├── .DS_Store
├── image
├── .DS_Store
├── Icon
│ ├── batt.png
│ ├── batt 1.png
│ ├── batt 2.png
│ ├── batt 3.png
│ ├── batt 4.png
│ ├── batt 5.png
│ ├── batt 6.png
│ ├── batt 7.png
│ ├── a_batt_0.png
│ ├── a_batt_1.png
│ ├── a_batt_2.png
│ ├── a_batt_3.png
│ ├── a_batt_4.png
│ ├── a_batt_5.png
│ ├── a_batt_6.png
│ ├── ChatGPT Image 2025年4月20日 14_47_37.png
│ ├── ChatGPT Image 2025年4月20日 18_57_13.png
│ └── ChatGPT Image 2025年4月20日 19_06_11.png
├── capture0.png
└── capture1.png
├── systemLoad_Claude
├── power_info
├── Makefile
├── README.md
└── power_info.m
├── app
├── Assets.xcassets
│ ├── Contents.json
│ ├── AppIcon.appiconset
│ │ ├── a_batt_0.png
│ │ ├── a_batt_1.png
│ │ ├── a_batt_2.png
│ │ ├── a_batt_3.png
│ │ ├── a_batt_4.png
│ │ ├── a_batt_5.png
│ │ ├── a_batt_6.png
│ │ ├── a_batt_1 1.png
│ │ ├── a_batt_2 1.png
│ │ ├── a_batt_5 1.png
│ │ └── Contents.json
│ └── AccentColor.colorset
│ │ └── Contents.json
├── Preview Content
│ └── Preview Assets.xcassets
│ │ └── Contents.json
├── app-Bridging-Header.h
├── app.entitlements
├── powerInfo.h
├── zh-Hans.lproj
│ └── Localizable.strings
├── en.lproj
│ └── Localizable.strings
├── Battery.swift
├── appApp.swift
├── ContentView.swift
├── powerInfo.m
└── PowerFlowView.swift
├── BattGUI.xcodeproj
├── project.xcworkspace
│ ├── contents.xcworkspacedata
│ ├── xcuserdata
│ │ └── tsunami.xcuserdatad
│ │ │ ├── UserInterfaceState.xcuserstate
│ │ │ └── WorkspaceSettings.xcsettings
│ └── xcshareddata
│ │ └── WorkspaceSettings.xcsettings
├── xcuserdata
│ └── tsunami.xcuserdatad
│ │ └── xcschemes
│ │ └── xcschememanagement.plist
└── project.pbxproj
├── appTests
└── appTests.swift
├── .github
├── ISSUE_TEMPLATE
│ ├── feature_request.md
│ └── bug_report.md
└── PULL_REQUEST_TEMPLATE.md
├── appUITests
├── appUITestsLaunchTests.swift
└── appUITests.swift
├── CONTRIBUTING.md
├── README.md
└── LICENSE
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/.DS_Store
--------------------------------------------------------------------------------
/image/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/.DS_Store
--------------------------------------------------------------------------------
/image/Icon/batt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/batt.png
--------------------------------------------------------------------------------
/image/capture0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/capture0.png
--------------------------------------------------------------------------------
/image/capture1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/capture1.png
--------------------------------------------------------------------------------
/image/Icon/batt 1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/batt 1.png
--------------------------------------------------------------------------------
/image/Icon/batt 2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/batt 2.png
--------------------------------------------------------------------------------
/image/Icon/batt 3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/batt 3.png
--------------------------------------------------------------------------------
/image/Icon/batt 4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/batt 4.png
--------------------------------------------------------------------------------
/image/Icon/batt 5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/batt 5.png
--------------------------------------------------------------------------------
/image/Icon/batt 6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/batt 6.png
--------------------------------------------------------------------------------
/image/Icon/batt 7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/batt 7.png
--------------------------------------------------------------------------------
/image/Icon/a_batt_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/a_batt_0.png
--------------------------------------------------------------------------------
/image/Icon/a_batt_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/a_batt_1.png
--------------------------------------------------------------------------------
/image/Icon/a_batt_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/a_batt_2.png
--------------------------------------------------------------------------------
/image/Icon/a_batt_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/a_batt_3.png
--------------------------------------------------------------------------------
/image/Icon/a_batt_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/a_batt_4.png
--------------------------------------------------------------------------------
/image/Icon/a_batt_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/a_batt_5.png
--------------------------------------------------------------------------------
/image/Icon/a_batt_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/a_batt_6.png
--------------------------------------------------------------------------------
/systemLoad_Claude/power_info:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/systemLoad_Claude/power_info
--------------------------------------------------------------------------------
/app/Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "author" : "xcode",
4 | "version" : 1
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/app/Preview Content/Preview Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "author" : "xcode",
4 | "version" : 1
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/image/Icon/ChatGPT Image 2025年4月20日 14_47_37.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/ChatGPT Image 2025年4月20日 14_47_37.png
--------------------------------------------------------------------------------
/image/Icon/ChatGPT Image 2025年4月20日 18_57_13.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/ChatGPT Image 2025年4月20日 18_57_13.png
--------------------------------------------------------------------------------
/image/Icon/ChatGPT Image 2025年4月20日 19_06_11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/image/Icon/ChatGPT Image 2025年4月20日 19_06_11.png
--------------------------------------------------------------------------------
/app/Assets.xcassets/AppIcon.appiconset/a_batt_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/app/Assets.xcassets/AppIcon.appiconset/a_batt_0.png
--------------------------------------------------------------------------------
/app/Assets.xcassets/AppIcon.appiconset/a_batt_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/app/Assets.xcassets/AppIcon.appiconset/a_batt_1.png
--------------------------------------------------------------------------------
/app/Assets.xcassets/AppIcon.appiconset/a_batt_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/app/Assets.xcassets/AppIcon.appiconset/a_batt_2.png
--------------------------------------------------------------------------------
/app/Assets.xcassets/AppIcon.appiconset/a_batt_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/app/Assets.xcassets/AppIcon.appiconset/a_batt_3.png
--------------------------------------------------------------------------------
/app/Assets.xcassets/AppIcon.appiconset/a_batt_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/app/Assets.xcassets/AppIcon.appiconset/a_batt_4.png
--------------------------------------------------------------------------------
/app/Assets.xcassets/AppIcon.appiconset/a_batt_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/app/Assets.xcassets/AppIcon.appiconset/a_batt_5.png
--------------------------------------------------------------------------------
/app/Assets.xcassets/AppIcon.appiconset/a_batt_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/app/Assets.xcassets/AppIcon.appiconset/a_batt_6.png
--------------------------------------------------------------------------------
/app/Assets.xcassets/AppIcon.appiconset/a_batt_1 1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/app/Assets.xcassets/AppIcon.appiconset/a_batt_1 1.png
--------------------------------------------------------------------------------
/app/Assets.xcassets/AppIcon.appiconset/a_batt_2 1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/app/Assets.xcassets/AppIcon.appiconset/a_batt_2 1.png
--------------------------------------------------------------------------------
/app/Assets.xcassets/AppIcon.appiconset/a_batt_5 1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/app/Assets.xcassets/AppIcon.appiconset/a_batt_5 1.png
--------------------------------------------------------------------------------
/systemLoad_Claude/Makefile:
--------------------------------------------------------------------------------
1 | power_info:
2 | clang -o power_info power_info.m -framework Foundation -framework IOKit
3 |
4 | clean:
5 | rm -f power_info
6 |
--------------------------------------------------------------------------------
/app/app-Bridging-Header.h:
--------------------------------------------------------------------------------
1 | //
2 | // Use this file to import your target's public headers that you would like to expose to Swift.
3 | //
4 | #import "powerInfo.h"
5 |
--------------------------------------------------------------------------------
/BattGUI.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/app/Assets.xcassets/AccentColor.colorset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "colors" : [
3 | {
4 | "idiom" : "universal"
5 | }
6 | ],
7 | "info" : {
8 | "author" : "xcode",
9 | "version" : 1
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/BattGUI.xcodeproj/project.xcworkspace/xcuserdata/tsunami.xcuserdatad/UserInterfaceState.xcuserstate:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/clzoc/BattGUI/HEAD/BattGUI.xcodeproj/project.xcworkspace/xcuserdata/tsunami.xcuserdatad/UserInterfaceState.xcuserstate
--------------------------------------------------------------------------------
/BattGUI.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/app.entitlements:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | com.apple.security.app-sandbox
6 |
7 | com.apple.security.files.user-selected.read-only
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/appTests/appTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // appTests.swift
3 | // appTests
4 | //
5 | // Created by tsunami on 2025/3/22.
6 | //
7 |
8 | import Testing
9 | @testable import app
10 |
11 | struct appTests {
12 |
13 | @Test func example() async throws {
14 | // Write your test here and use APIs like `#expect(...)` to check expected conditions.
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/BattGUI.xcodeproj/project.xcworkspace/xcuserdata/tsunami.xcuserdatad/WorkspaceSettings.xcsettings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | BuildLocationStyle
6 | UseAppPreferences
7 | CustomBuildLocationType
8 | RelativeToDerivedData
9 | DerivedDataLocationStyle
10 | Default
11 | ShowSharedSchemesAutomaticallyEnabled
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/BattGUI.xcodeproj/xcuserdata/tsunami.xcuserdatad/xcschemes/xcschememanagement.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | SchemeUserState
6 |
7 | BattGUI.xcscheme_^#shared#^_
8 |
9 | orderHint
10 | 0
11 |
12 | app.xcscheme_^#shared#^_
13 |
14 | orderHint
15 | 0
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature Request
3 | about: Suggest an idea for this project
4 | title: "[Feature]: "
5 | labels: enhancement
6 | assignees: ''
7 |
8 | ---
9 |
10 | ## Description
11 |
12 |
13 | ## Why is this feature needed?
14 |
15 |
16 | ## Proposed Solution (Optional)
17 |
18 |
19 | ## Additional Context
20 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug Report
3 | about: Report a reproducible bug
4 | title: "[Bug]: "
5 | labels: bug
6 | assignees: ''
7 |
8 | ---
9 |
10 | ## Description
11 |
12 |
13 | ## Steps to Reproduce
14 |
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | ## Expected Behavior
21 |
22 |
23 | ## Actual Behavior
24 |
25 |
26 | ## Environment
27 |
28 | - **Operating System:** [e.g., macOS 14.4.1]
29 | - **App Version:** [e.g., 1.0.0]
30 | - **Xcode Version:** [e.g., 15.3]
31 |
32 | ## Additional Context
33 |
--------------------------------------------------------------------------------
/appUITests/appUITestsLaunchTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // appUITestsLaunchTests.swift
3 | // appUITests
4 | //
5 | // Created by tsunami on 2025/3/22.
6 | //
7 |
8 | import XCTest
9 |
10 | final class appUITestsLaunchTests: XCTestCase {
11 |
12 | override class var runsForEachTargetApplicationUIConfiguration: Bool {
13 | true
14 | }
15 |
16 | override func setUpWithError() throws {
17 | continueAfterFailure = false
18 | }
19 |
20 | @MainActor
21 | func testLaunch() throws {
22 | let app = XCUIApplication()
23 | app.launch()
24 |
25 | // Insert steps here to perform after app launch but before taking a screenshot,
26 | // such as logging into a test account or navigating somewhere in the app
27 |
28 | let attachment = XCTAttachment(screenshot: app.screenshot())
29 | attachment.name = "Launch Screen"
30 | attachment.lifetime = .keepAlways
31 | add(attachment)
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/app/powerInfo.h:
--------------------------------------------------------------------------------
1 | //
2 | // powerInfo.h
3 | // app
4 | //
5 | // Created by tsunami on 2025/4/19.
6 | //
7 | // power_info.h
8 | #import
9 |
10 | // Declare functions to be exposed to Swift
11 | float getRawSystemPower(void);
12 | float getAdapterPower(void);
13 | float getAdapterVoltage(void);
14 | float getAdapterAmperage(void);
15 | float getBatteryVoltage(void);
16 | float getBatteryAmperage(void);
17 | float getBatteryPower(void);
18 | NSString *_Nonnull getChargingStatus(void);
19 |
20 | // Class for interacting with the batt daemon socket
21 | // Function for interacting with the batt daemon socket
22 | // Sends a command value to the specified Unix domain socket path.
23 | // Returns the response string on success, nil on failure.
24 | // Populates the error pointer if an error occurs and the pointer is not NULL.
25 | NSString *_Nullable sendCommandToUnixSocket(NSInteger value, const char *_Nonnull socketPath, NSError *_Nullable *_Nullable error);
26 |
--------------------------------------------------------------------------------
/app/zh-Hans.lproj/Localizable.strings:
--------------------------------------------------------------------------------
1 | /*
2 | Localizable.strings
3 | app
4 |
5 | Created by Cline on [Current Date].
6 | */
7 |
8 | "limit.label" = "限制:";
9 | "enable.power.button" = "启用电源";
10 | "design.capacity.label" = "设计容量";
11 | "serial.number.label" = "序列号";
12 | "max.capacity.label" = "最大容量";
13 | "cycle.count.label" = "循环次数";
14 | "battery.temperature.label" = "电池温度";
15 | "battery.level.label" = "电量";
16 | "charging.status.label" = "正在充电";
17 | "yes" = "是";
18 | "no" = "否";
19 | "battery.power.label" = "电池功率";
20 | "battery.amperage.label" = "电池电流";
21 | "battery.voltage.label" = "电池电压";
22 | "system.load.label" = "系统负载";
23 | "adapter.input.power.label" = "电源适配器功率";
24 | "adapter.input.amperage.label" = "电源适配器电流";
25 | "adapter.input.voltage.label" = "电源适配器电压";
26 | // Error messages (optional, might not be user-facing)
27 | "executable.not.found.error" = "可执行文件未找到";
28 | "cannot.set.charge.limit.error" = "无法设置充电限制";
29 | "execution.failed.error" = "执行失败: %@";
30 | "initial.limit.distance.failed.error" = "执行初始限距失败: %@";
31 | "initial.limit.failed.error" = "执行初始限制失败: %@";
32 |
--------------------------------------------------------------------------------
/app/en.lproj/Localizable.strings:
--------------------------------------------------------------------------------
1 | /*
2 | Localizable.strings
3 | app
4 |
5 | Created by Cline on [Current Date].
6 | */
7 |
8 | "limit.label" = "Limit:";
9 | "enable.power.button" = "Enable Power";
10 | "design.capacity.label" = "Design Capacity";
11 | "serial.number.label" = "Serial Number";
12 | "max.capacity.label" = "Max Capacity";
13 | "cycle.count.label" = "Cycle Count";
14 | "battery.temperature.label" = "Temperature";
15 | "battery.level.label" = "Charge";
16 | "charging.status.label" = "Charging";
17 | "yes" = "Yes";
18 | "no" = "No";
19 | "battery.power.label" = "Battery Power";
20 | "battery.amperage.label" = "Battery Current";
21 | "battery.voltage.label" = "Battery Voltage";
22 | "system.load.label" = "System Load";
23 | "adapter.input.power.label" = "Adapter Power";
24 | "adapter.input.amperage.label" = "Adapter Current";
25 | "adapter.input.voltage.label" = "Adapter Voltage";
26 | // Error messages (optional, might not be user-facing)
27 | "executable.not.found.error" = "Executable file not found";
28 | "cannot.set.charge.limit.error" = "Cannot set charge limit";
29 | "execution.failed.error" = "Execution failed: %@"; // %@ is placeholder for error
30 | "initial.limit.distance.failed.error" = "Failed to set initial limit distance: %@";
31 | "initial.limit.failed.error" = "Failed to set initial limit: %@";
32 |
--------------------------------------------------------------------------------
/appUITests/appUITests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // appUITests.swift
3 | // appUITests
4 | //
5 | // Created by tsunami on 2025/3/22.
6 | //
7 |
8 | import XCTest
9 |
10 | final class appUITests: XCTestCase {
11 |
12 | override func setUpWithError() throws {
13 | // Put setup code here. This method is called before the invocation of each test method in the class.
14 |
15 | // In UI tests it is usually best to stop immediately when a failure occurs.
16 | continueAfterFailure = false
17 |
18 | // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
19 | }
20 |
21 | override func tearDownWithError() throws {
22 | // Put teardown code here. This method is called after the invocation of each test method in the class.
23 | }
24 |
25 | @MainActor
26 | func testExample() throws {
27 | // UI tests must launch the application that they test.
28 | let app = XCUIApplication()
29 | app.launch()
30 |
31 | // Use XCTAssert and related functions to verify your tests produce the correct results.
32 | }
33 |
34 | @MainActor
35 | func testLaunchPerformance() throws {
36 | if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
37 | // This measures how long it takes to launch your application.
38 | measure(metrics: [XCTApplicationLaunchMetric()]) {
39 | XCUIApplication().launch()
40 | }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contribution Guidelines
2 |
3 | ## Development Setup
4 |
5 | ### Prerequisites
6 | - Xcode 15+ with command line tools
7 | - Homebrew (for dependency management)
8 | - Swift 5.9+
9 |
10 | ### Environment Configuration
11 | ```bash
12 | # Install build dependencies
13 | brew install swiftlint sourcery
14 |
15 | # Clone repository
16 | git clone https://github.com/yourusername/power-suite.git
17 | cd power-suite
18 |
19 | # Install pre-commit hooks
20 | swiftlint install-hook
21 | ```
22 |
23 | ## Workflow
24 |
25 | 1. Create feature branch from `main`
26 | ```bash
27 | git checkout -b feat/new-power-metric
28 | ```
29 |
30 | 2. Implement changes following Swift style guide
31 | ```bash
32 | swiftlint autocorrect # Before committing
33 | ```
34 |
35 | 3. Update documentation when adding new features
36 |
37 | 4. Create pull request with:
38 | - Description of changes
39 | - Screenshots for UI changes
40 | - Updated unit tests
41 |
42 | ## Code Standards
43 |
44 | ### Swift
45 | - Follow Apple's Swift API Design Guidelines
46 | - Use SwiftLint with included .swiftlint.yml
47 | - Document public APIs using DocC format
48 |
49 | ### C Code
50 | - Follow Linux kernel coding style for CLI tools
51 | - Include Doxygen comments for complex functions
52 |
53 | ## Testing Requirements
54 | - 80%+ test coverage for core modules
55 | - Performance tests for battery monitoring
56 | - UI tests for power flow visualization
57 |
58 | ## Review Process
59 | - All PRs require 2 maintainer approvals
60 | - CI must pass SwiftPM tests and lint checks
61 | - Security-sensitive code requires audit
--------------------------------------------------------------------------------
/app/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "filename" : "a_batt_6.png",
5 | "idiom" : "mac",
6 | "scale" : "1x",
7 | "size" : "16x16"
8 | },
9 | {
10 | "filename" : "a_batt_5 1.png",
11 | "idiom" : "mac",
12 | "scale" : "2x",
13 | "size" : "16x16"
14 | },
15 | {
16 | "filename" : "a_batt_5.png",
17 | "idiom" : "mac",
18 | "scale" : "1x",
19 | "size" : "32x32"
20 | },
21 | {
22 | "filename" : "a_batt_4.png",
23 | "idiom" : "mac",
24 | "scale" : "2x",
25 | "size" : "32x32"
26 | },
27 | {
28 | "filename" : "a_batt_3.png",
29 | "idiom" : "mac",
30 | "scale" : "1x",
31 | "size" : "128x128"
32 | },
33 | {
34 | "filename" : "a_batt_2 1.png",
35 | "idiom" : "mac",
36 | "scale" : "2x",
37 | "size" : "128x128"
38 | },
39 | {
40 | "filename" : "a_batt_2.png",
41 | "idiom" : "mac",
42 | "scale" : "1x",
43 | "size" : "256x256"
44 | },
45 | {
46 | "filename" : "a_batt_1 1.png",
47 | "idiom" : "mac",
48 | "scale" : "2x",
49 | "size" : "256x256"
50 | },
51 | {
52 | "filename" : "a_batt_1.png",
53 | "idiom" : "mac",
54 | "scale" : "1x",
55 | "size" : "512x512"
56 | },
57 | {
58 | "filename" : "a_batt_0.png",
59 | "idiom" : "mac",
60 | "scale" : "2x",
61 | "size" : "512x512"
62 | }
63 | ],
64 | "info" : {
65 | "author" : "xcode",
66 | "version" : 1
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/systemLoad_Claude/README.md:
--------------------------------------------------------------------------------
1 | # Power Consumption Monitor for macOS
2 |
3 | A standalone command-line tool to monitor the current power consumption of your Mac.
4 |
5 | ## Overview
6 |
7 | This tool extracts the power consumption monitoring functionality from the Power Monitor Tool by SAP SE and provides it as a simple, standalone executable. It accesses the System Management Controller (SMC) to read the current power consumption in watts.
8 |
9 | ## Features
10 |
11 | - Display current power consumption in watts
12 | - Continuous monitoring with customizable interval
13 | - Multiple output formats (standard, verbose with timestamp, raw)
14 | - Simple command-line interface
15 |
16 | ## Requirements
17 |
18 | - macOS (tested on macOS Monterey and later)
19 | - Administrative privileges may be required to access the SMC
20 |
21 | ## Usage
22 |
23 | ```
24 | ./PowerConsumption [options]
25 | ```
26 |
27 | ### Options
28 |
29 | - `-h`: Display help message
30 | - `-c`: Continuous monitoring (press Ctrl+C to stop)
31 | - `-i `: Interval between measurements in seconds (default: 1, requires -c)
32 | - `-r`: Raw output (just the number, no text)
33 | - `-v`: Verbose output with timestamp
34 |
35 | ### Examples
36 |
37 | 1. Get current power consumption:
38 | ```
39 | ./PowerConsumption
40 | ```
41 |
42 | 2. Get current power consumption with timestamp:
43 | ```
44 | ./PowerConsumption -v
45 | ```
46 |
47 | 3. Monitor power consumption continuously with 5-second intervals:
48 | ```
49 | ./PowerConsumption -c -i 5
50 | ```
51 |
52 | 4. Get raw output (useful for scripts):
53 | ```
54 | ./PowerConsumption -r
55 | ```
56 |
57 | ## Building from Source
58 |
59 | ```
60 | clang -o PowerConsumption PowerConsumption.m -framework Foundation -framework IOKit
61 | ```
62 |
63 | ## License
64 |
65 | This tool is based on code from the Power Monitor Tool by SAP SE, which is licensed under the Apache License, Version 2.0.
66 |
67 | ## Acknowledgments
68 |
69 | - SAP SE for the original Power Monitor Tool
70 | - Apple for providing access to the SMC through IOKit
71 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | # Pull Request
2 |
3 | ## Description
4 |
5 |
6 | ## Type of Change
7 |
8 | - [ ] New feature (non-breaking change which adds functionality)
9 | - [ ] Bug fix (non-breaking change which fixes an issue)
10 | - [ ] Performance improvement
11 | - [ ] Code refactoring (no functional changes)
12 | - [ ] Documentation update
13 | - [ ] UI/UX improvement
14 | - [ ] Build/CI pipeline changes
15 | - [ ] Other (please describe):
16 |
17 | ## Related Issues
18 |
19 |
20 |
21 | ## Testing Performed
22 |
23 |
24 |
25 | ## Screenshots
26 |
27 |
28 |
29 | ## Checklist
30 |
31 |
32 | ### Development
33 | - [ ] Code follows Swift API Design Guidelines
34 | - [ ] SwiftLint has been run (`swiftlint autocorrect`)
35 | - [ ] C code follows Linux kernel coding style (if applicable)
36 | - [ ] Code is properly documented (DocC for Swift, Doxygen for C)
37 | - [ ] No new warnings or errors are introduced
38 |
39 | ### Testing
40 | - [ ] Added/updated unit tests (80%+ coverage for core modules)
41 | - [ ] Added/updated performance tests (for battery monitoring changes)
42 | - [ ] Added/updated UI tests (for power flow visualization changes)
43 | - [ ] All tests pass locally
44 |
45 | ### Documentation
46 | - [ ] Updated documentation for new/modified features
47 | - [ ] Comments added for complex code sections
48 |
49 | ### Review Requirements
50 | - [ ] PR requires 2 maintainer approvals
51 | - [ ] CI passes SwiftPM tests and lint checks
52 | - [ ] Security-sensitive code has been audited (if applicable)
53 |
54 | ## Additional Notes
55 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Power Management Suite
2 |
3 | []()
4 | [](https://www.gnu.org/licenses/gpl-3.0)
5 |
6 | A comprehensive power monitoring solution for macOS featuring:
7 |
8 | - 🖥 GUI application with real-time power flow visualization
9 | - 🔋 Detailed battery health analytics
10 | - ⚡️ CLI tools for low-level power monitoring
11 | - 📊 System load statistics collection
12 |
13 | - Initial app icon (This icon is open to creative reinterpretation by anyone.)
14 |
15 |
16 |
17 | ## Architecture Overview
18 |
19 | ```mermaid
20 | graph TD
21 | Suite[Power Management Suite] --> GUI{GUI Application}
22 |
23 | GUI --> App[appApp.swift]
24 | App --> CV[ContentView.swift]
25 | CV --> PFV[PowerFlowView.swift]
26 | CV --> BM[Battery.swift]
27 |
28 | BM --> OC[powerInfo.m Objective-C Bridge]
29 | OC --> SMC["SMC API (System Management Controller)"]
30 |
31 | PFV --> SW["SwiftUI Graphics Pipeline"]
32 | App --> SM[StatusBar Menu]
33 | SM --> POP["Popover Window (NSHostingView)"]
34 | SM --> MM[Menu Items]
35 |
36 | classDef swift fill:#F05138,color:white;
37 | classDef objc fill:#4381ff,color:white;
38 | classDef system fill:#666,color:white;
39 | classDef suite fill:#8e44ad,color:white;
40 |
41 | class Suite suite
42 | class App,CV,PFV,BM,SW,SM,POP,MM swift
43 | class OC objc
44 | class SMC system
45 | ```
46 |
47 | ## Features
48 |
49 | ### GUI Application
50 | - Real-time power flow visualization
51 | - Battery health monitoring (cycles, capacity, temperature)
52 | - Adapter power input tracking
53 | - System load/power consumption correlation
54 |
55 | ## Requirements
56 |
57 | - macOS 13 Ventura or newer
58 | - Xcode 15+
59 | - Administrative privileges for SMC access
60 |
61 | ## Installation
62 |
63 | ### DMG Installation
64 | 1. Download the latest `.dmg` package from our [Releases page](https://github.com/clzoc/BattGUI/releases)
65 | 2. Open the downloaded DMG file
66 | 3. Drag the application to your `Applications` folder
67 |
68 | ### Manual Installation (From Source)
69 | 1. Build the application:
70 | ```bash
71 | # Clone repository
72 | git clone https://github.com/clzoc/BattGUI.git
73 | cd power-suite
74 | xcodebuild -workspace app.xcodeproj/project.xcworkspace -scheme app
75 | ```
76 |
77 | 2. Install required components:
78 | ```bash
79 | sudo batt install --allow-non-root-access
80 | ```
81 |
82 | ### Alternative Installation
83 | 1. **GateKeeper Configuration**
84 | If you encounter security warnings:
85 | - Go to `System Settings` → `Privacy & Security` → scroll down to `Security`
86 | - Click "Open Anyway" next to the BattGUI warning
87 | - Confirm execution in the dialog
88 |
89 | 2. **Advanced Configuration (Admin required)**
90 | For system-level monitoring access:
91 | ```bash
92 | # Temporarily disable GateKeeper (resets after reboot)
93 | sudo spctl --master-disable
94 | ```
95 | ## Usage
96 |
97 | GUI Application:
98 | ```bash
99 | open app/build/Release/app.app
100 | ```
101 |
102 |
103 | ## Known Issues
104 |
105 | - **Adapter Voltage Detection**: Current implementation fixes adapter voltage at 20.00V due to missing SMC key in [VirtualSMC documentation](https://github.com/acidanthera/VirtualSMC/blob/master/Docs/SMCKeys.txt). Amperage is calculated using I = P / U. Contributions welcome to identify the correct SMC key.
106 |
107 | - **UI/UX Optimization**: Ongoing improvements to power management workflows including:
108 | - Enhanced real-time measurement visualization
109 | - Historical data trending
110 | - Customizable power profiles
111 |
112 | - **GUI Charge Limit Adjustment Permission Denied**: When attempting to adjust battery charge limit through the GUI, users encounter permission errors depending on installation method.
113 |
114 | ## Affected Components
115 | - `powerInfo.m` (Objective-C)
116 | - Unix domain socket: `/var/run/batt.sock`
117 | - GUI slider control
118 |
119 | ## Symptoms
120 | | Installation Method | Behavior | Command |
121 | |---------------------|----------|---------|
122 | | With `--allow-non-root-access` | ✅ Works correctly | `sudo batt install --allow-non-root-access` |
123 | | Default installation | ❌ "Permission denied" error | `sudo batt install` |
124 |
125 | ## Technical Details
126 | ### Root Cause
127 | The Unix domain socket (`/var/run/batt.sock`) implements strict permission controls:
128 | - Default mode: 600 (root-only)
129 | - With flag: 666 (world-readable/writable)
130 |
131 | ### Error Reproduction
132 | 1. Install without special flags
133 | 2. Launch GUI application
134 | 3. Attempt to move charge limit slider
135 | 4. Observe error in system logs:
136 |
137 | ## Contributing
138 | See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and guidelines.
139 |
140 | ## License
141 | GPLv3 (see [LICENSE](LICENSE))
142 |
--------------------------------------------------------------------------------
/app/Battery.swift:
--------------------------------------------------------------------------------
1 | // Power Management Suite - Battery Information Manager
2 | // Copyright (C) 2025
3 | //
4 | // This program is free software: you can redistribute it and/or modify
5 | // it under the terms of the GNU General Public License as published by
6 | // the Free Software Foundation, either version 3 of the License, or
7 | // (at your option) any later version.
8 | //
9 | // This program is distributed in the hope that it will be useful,
10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | // GNU General Public License for more details.
13 | //
14 | // You should have received a copy of the GNU General Public License
15 | // along with this program. If not, see .
16 |
17 | // Original file info:
18 | // Battery.swift
19 | // app
20 | //
21 | // Created by tsunami on 2025/4/1.
22 | //
23 |
24 | import Foundation
25 | import SwiftUI
26 |
27 | // Manages fetching and parsing battery and power information from system commands.
28 | //
29 | // This class acts as an `ObservableObject`, providing published properties
30 | // that SwiftUI views can observe to display real-time battery and power metrics.
31 | // It uses `ioreg` and the bundled `power_info` command-line tool to gather data.
32 | class BatteryInfoManager: ObservableObject {
33 | // The current maximum capacity of the battery in mAh (AppleRawMaxCapacity).
34 | @Published var batteryCapacity: Int = 0
35 | // The original design capacity of the battery in mAh.
36 | @Published var designCapacity: Int = 0
37 | // The number of charge cycles the battery has undergone.
38 | @Published var cycleCount: Int = 0
39 | // The battery's health percentage, calculated as `(batteryCapacity / designCapacity) * 100`.
40 | @Published var health: Double = 0.0
41 | // Indicates whether the battery is currently charging.
42 | @Published var isCharging: Bool = false
43 | // The current charge percentage of the battery (CurrentCapacity).
44 | @Published var batteryPercent: Int = 0
45 | // The voltage being supplied by the power adapter in Volts.
46 | @Published var voltage: Double = 0.0
47 | // The amperage being supplied by the power adapter in Amps.
48 | @Published var amperage: Double = 0.0
49 | // The current power consumption of the entire system in Watts.
50 | @Published var loadwatt: Double = 0.0
51 | // The power being drawn from the power adapter in Watts.
52 | @Published var inputwatt: Double = 0.0
53 | // The battery's internal temperature in degrees Celsius.
54 | @Published var temperature: Double = 0.0
55 | // The current power draw from/to the battery in Watts. Positive means charging, negative means discharging.
56 | @Published var batteryPower: Double = 0.0
57 | // The current voltage of the battery in Volts.
58 | @Published var batteryVoltage: Double = 0.0
59 | // The current amperage flow from/to the battery in Amps. Positive means charging, negative means discharging.
60 | @Published var batteryAmperage: Double = 0.0
61 | // The serial number of the battery.
62 | @Published var serialNumber: String = "--"
63 |
64 | @Published var batteryVoltage_mV: UInt16 = 0
65 | @Published var batteryAmperage_mA: Int16 = 0
66 |
67 | // Initializes the manager and triggers the first battery info update.
68 | init() {
69 | updateBatteryInfo()
70 | }
71 |
72 | // Asynchronously fetches and updates all battery information properties.
73 | //
74 | // This function runs the `power_info` tool and `ioreg` command,
75 | // captures their output, and then calls `parseBatteryInfo` on the main thread
76 | // to update the published properties.
77 | func updateBatteryInfo() {
78 | loadwatt = Double(getRawSystemPower())
79 | inputwatt = Double(getAdapterPower())
80 | amperage = Double(getAdapterAmperage())
81 | voltage = Double(getAdapterVoltage())
82 | batteryVoltage = Double(getBatteryVoltage())
83 | batteryAmperage = Double(getBatteryAmperage())
84 | batteryPower = Double(getBatteryPower())
85 | isCharging = getChargingStatus().contains("Charging")
86 | Task {
87 | let process = Process()
88 | process.executableURL = URL(fileURLWithPath: "/bin/zsh")
89 | process.arguments = ["-c", "ioreg -r -c AppleSmartBattery | grep -E 'DesignCapacity|CycleCount|Serial|Temperature|CurrentCapacity|AppleRawMaxCapacity' "]
90 | let pipe = Pipe()
91 | process.standardOutput = pipe
92 |
93 | do {
94 | try process.run()
95 | process.waitUntilExit()
96 | let data = pipe.fileHandleForReading.readDataToEndOfFile()
97 | let output = String(data: data, encoding: .utf8) ?? ""
98 |
99 | await parseBatteryInfo(from: output)
100 | } catch {
101 | print("Error: \(error)")
102 | }
103 | }
104 | }
105 |
106 | @MainActor
107 | private func parseBatteryInfo(from output: String) {
108 | // --- Parse Temperature (ioreg - VirtualTemperature seems more reliable than power_info's) ---
109 | if let match = output.range(of: "\"VirtualTemperature\" = ([0-9]+)", options: .regularExpression) {
110 | let valueStr = String(output[match]).components(separatedBy: "=").last?.trimmingCharacters(in: .whitespaces) ?? "0"
111 | let temperatureValue = Int(valueStr.trimmingCharacters(in: CharacterSet(charactersIn: "\" "))) ?? 0
112 | temperature = Double(temperatureValue) / 100.0
113 | }
114 |
115 | // --- Parse Serial Number (ioreg) ---
116 | if let match = output.range(of: "\"Serial\" = \"([^\"]+)\"", options: .regularExpression) {
117 | let fullMatch = String(output[match])
118 | let pattern = "\"Serial\" = \"([^\"]+)\""
119 | if let regex = try? NSRegularExpression(pattern: pattern),
120 | let nsMatch = regex.firstMatch(in: fullMatch, range: NSRange(fullMatch.startIndex..., in: fullMatch)),
121 | nsMatch.numberOfRanges > 1,
122 | let valueRange = Range(nsMatch.range(at: 1), in: fullMatch) {
123 | serialNumber = String(fullMatch[valueRange])
124 | }
125 | }
126 |
127 | // --- Parse Current Charge Percentage (ioreg) ---
128 | if let match = output.range(of: "\"CurrentCapacity\" = ([0-9]+)", options: .regularExpression) {
129 | let valueStr = String(output[match]).components(separatedBy: "=").last?.trimmingCharacters(in: .whitespaces) ?? "0"
130 | batteryPercent = Int(valueStr.trimmingCharacters(in: CharacterSet(charactersIn: "\" "))) ?? 0
131 | }
132 |
133 | // --- Parse Design Capacity (ioreg) ---
134 | if let match = output.range(of: "\"DesignCapacity\" = ([0-9]+)", options: .regularExpression) {
135 | let valueStr = String(output[match]).components(separatedBy: "=").last?.trimmingCharacters(in: .whitespaces) ?? "0"
136 | designCapacity = Int(valueStr.trimmingCharacters(in: CharacterSet(charactersIn: "\" "))) ?? 0
137 | }
138 |
139 | // --- Parse Current Max Capacity & Calculate Health (ioreg) ---
140 | if let match = output.range(of: "\"AppleRawMaxCapacity\" = ([0-9]+)", options: .regularExpression) {
141 | let valueStr = String(output[match]).components(separatedBy: "=").last?.trimmingCharacters(in: .whitespaces) ?? "0"
142 | batteryCapacity = Int(valueStr.trimmingCharacters(in: CharacterSet(charactersIn: "\" "))) ?? 0
143 | if designCapacity > 0 {
144 | health = (Double(batteryCapacity) / Double(designCapacity)) * 100
145 | }
146 | }
147 |
148 | // --- Parse Cycle Count (ioreg) ---
149 | if let match = output.range(of: "\"CycleCount\" = ([0-9]+)", options: .regularExpression) {
150 | let valueStr = String(output[match]).components(separatedBy: "=").last?.trimmingCharacters(in: .whitespaces) ?? "0"
151 | cycleCount = Int(valueStr.trimmingCharacters(in: CharacterSet(charactersIn: "\" "))) ?? 0
152 | }
153 |
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/app/appApp.swift:
--------------------------------------------------------------------------------
1 | // Power Management Suite - Main Application Entry Point
2 | // Copyright (C) 2025
3 | //
4 | // This program is free software: you can redistribute it and/or modify
5 | // it under the terms of the GNU General Public License as published by
6 | // the Free Software Foundation, either version 3 of the License, or
7 | // (at your option) any later version.
8 | //
9 | // This program is distributed in the hope that it will be useful,
10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | // GNU General Public License for more details.
13 | //
14 | // You should have received a copy of the GNU General Public License
15 | // along with this program. If not, see .
16 |
17 | // Original file info:
18 | //
19 | // appApp.swift
20 | // app
21 | //
22 | // Created by tsunami on 2025/3/22.
23 | //
24 |
25 | import SwiftUI
26 | import AppKit
27 | import Cocoa
28 |
29 | @main
30 | struct appApp: App {
31 | @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
32 | var body: some Scene {
33 | _EmptyScene()
34 | }
35 | }
36 |
37 | class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
38 | var window: NSWindow!
39 | var sbitem: NSStatusItem!
40 | var eventMonitor: Any?
41 | var highlightTimer: Timer?
42 |
43 | func applicationDidFinishLaunching(_ notification: Notification) {
44 | setupStatusBarItem()
45 | setupPopoverWindow()
46 | setupEventMonitor() // Keep existing call
47 | }
48 |
49 | // MARK: - Setup Methods
50 |
51 | private func setupStatusBarItem() {
52 | sbitem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
53 | guard let button = sbitem.button else { return }
54 |
55 | let config = NSImage.SymbolConfiguration(pointSize: 16, weight: .regular)
56 | if let originalImage = NSImage(systemSymbolName: "minus.plus.and.fluid.batteryblock", accessibilityDescription: "Battery Limit")?.withSymbolConfiguration(config) {
57 | // Create a new image with padding for visual centering in the status bar.
58 | let paddedImage = NSImage(size: NSSize(width: originalImage.size.width, height: originalImage.size.height + 4))
59 | paddedImage.lockFocus()
60 |
61 | // Draw the original image offset vertically (y: 2) to center it within the padded space.
62 | let drawRect = NSRect(
63 | x: 0,
64 | y: 2, // Vertical offset for centering
65 | width: originalImage.size.width,
66 | height: originalImage.size.height
67 | )
68 | originalImage.draw(in: drawRect)
69 |
70 | paddedImage.unlockFocus()
71 | paddedImage.isTemplate = true // Ensures proper appearance in light/dark mode
72 |
73 | button.image = paddedImage
74 | }
75 | button.target = self
76 | button.action = #selector(sbiClick)
77 | }
78 |
79 | private func setupPopoverWindow() {
80 |
81 | // Create the main content view using SwiftUI
82 | // Remove fixed frame to allow adaptive sizing
83 | // Inject the uiState into ContentView
84 | let swiftUIContentView = ContentView()
85 | // .frame(width: 300, height: 450, alignment: .top) // REMOVED
86 | .padding(0) // Add padding around the content
87 |
88 | // Host the SwiftUI view within an NSHostingView
89 | // NSHostingView will intrinsically size based on swiftUIContentView
90 | let hostingView = NSHostingView(rootView: swiftUIContentView)
91 | // hostingView.frame = NSRect(x: 0, y: 0, width: 300, height: 450) // REMOVED
92 | hostingView.autoresizingMask = [.width, .height] // Keep autoresizing
93 | // Restore layer setup for hostingView (though clipping is handled by backgroundView)
94 | hostingView.wantsLayer = true
95 | hostingView.layer?.cornerRadius = 16
96 | hostingView.layer?.cornerCurve = .continuous
97 | hostingView.layer?.masksToBounds = true // This might be redundant if backgroundView clips
98 |
99 | let intrinsicSize = hostingView.fittingSize
100 |
101 | // Create the visual effect view for the blurred background
102 | let visualEffectView = NSVisualEffectView()
103 | visualEffectView.material = .hudWindow
104 | visualEffectView.blendingMode = .behindWindow
105 | visualEffectView.state = .active
106 | visualEffectView.frame = hostingView.bounds
107 | visualEffectView.autoresizingMask = [.width, .height]
108 | visualEffectView.wantsLayer = true
109 | visualEffectView.layer?.cornerRadius = 16
110 | visualEffectView.layer?.cornerCurve = .continuous
111 | // visualEffectView.layer?.masksToBounds = true // Clipping handled by backgroundView
112 |
113 | // Add the hosting view as a subview of the visual effect view
114 | visualEffectView.addSubview(hostingView)
115 |
116 | // Re-add intermediate background view for clipping
117 | let backgroundView = NSView()
118 | backgroundView.wantsLayer = true
119 | backgroundView.layer?.backgroundColor = NSColor.clear.cgColor
120 | backgroundView.layer?.cornerRadius = 16
121 | backgroundView.layer?.cornerCurve = .continuous
122 | backgroundView.layer?.borderWidth = 0.5
123 | backgroundView.layer?.borderColor = NSColor.separatorColor.cgColor
124 | backgroundView.layer?.masksToBounds = true // Clip subviews (visualEffectView)
125 |
126 | backgroundView.addSubview(visualEffectView)
127 |
128 | // Create the NSPanel (popover window)
129 | // Initialize with zero rect, it will resize to fit contentView
130 | let panel = NSPanel(
131 | contentRect: .zero, // Use .zero rect
132 | styleMask: [.borderless, .nonactivatingPanel], // Borderless, doesn't activate app
133 | backing: .buffered,
134 | defer: false
135 | )
136 |
137 | // Configure the panel's appearance and behavior
138 | panel.isOpaque = false // Allows transparency
139 | panel.backgroundColor = .clear // Transparent background
140 | panel.level = .floating // Keep panel above other windows
141 | panel.isReleasedWhenClosed = false // Keep panel instance in memory
142 | // panel.hasShadow = true // Optional: Add a system shadow if desired
143 |
144 | // Set the intermediate background view as the panel's content view
145 | panel.contentView = backgroundView // Use backgroundView for clipping
146 |
147 | // Explicitly set the panel's content size based on the SwiftUI view's needs
148 | panel.setContentSize(intrinsicSize)
149 |
150 | // Assign the configured panel to the window property
151 | self.window = panel
152 |
153 | }
154 |
155 | func setupEventMonitor() {
156 | // Monitor global mouse clicks to close the popover when clicking outside
157 | eventMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown]) { [weak self] event in
158 | guard let self = self, self.window.isVisible else { return }
159 |
160 | // 检查点击是否在窗口范围外
161 | if let eventWindow = event.window, eventWindow == self.window {
162 | return // 点击在窗口内,不处理
163 | }
164 |
165 | // 点击在窗口外,关闭窗口
166 | self.closePopover()
167 | }
168 | }
169 |
170 | deinit {
171 | stopHighlightTimer()
172 | if let monitor = eventMonitor {
173 | NSEvent.removeMonitor(monitor)
174 | }
175 | }
176 |
177 | @objc
178 | func sbiClick() {
179 | if window.isVisible {
180 | closePopover()
181 | } else {
182 | showPopover()
183 | }
184 | }
185 |
186 | func showPopover() {
187 | guard let bt = sbitem.button else { return }
188 | guard let wo = bt.window else { return }
189 |
190 | // 高亮按钮
191 | startButtonHighlight()
192 |
193 | // 定位和显示窗口
194 | let x = wo.frame.midX - window.frame.width / 2
195 | let y = wo.frame.origin.y - 5
196 |
197 | window.setFrameTopLeftPoint(NSPoint(x: x, y: y))
198 | //window.makeKeyAndOrderFront(nil)
199 | window.orderFront(nil)
200 | }
201 |
202 | func closePopover() {
203 | // 停止高亮
204 | stopHighlightTimer()
205 |
206 | // 确保按钮取消高亮
207 | sbitem.button?.highlight(false)
208 |
209 | // 关闭窗口
210 | window.orderOut(nil)
211 | }
212 |
213 | // MARK: - Highlight Control
214 |
215 | private func startButtonHighlight() {
216 | // Stop any existing highlight timer
217 | stopHighlightTimer()
218 |
219 | // Immediately highlight the button
220 | sbitem.button?.highlight(true)
221 |
222 | // Use a timer to repeatedly ensure the button remains highlighted.
223 | // This is necessary because the non-activating panel might cause
224 | // the button to lose its highlight state otherwise.
225 | highlightTimer = Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) { [weak self] _ in
226 | self?.sbitem.button?.highlight(true)
227 | let cs = self?.window.contentView?.subviews[0].subviews[0].fittingSize
228 | let ws = self?.window.frame.size
229 | if cs != ws {
230 | self?.window.setContentSize(cs!)
231 | }
232 | }
233 | }
234 |
235 | private func stopHighlightTimer() {
236 | highlightTimer?.invalidate()
237 | highlightTimer = nil
238 | }
239 |
240 | // NSWindowDelegate
241 |
242 | func windowDidResignKey(_ notification: Notification) {
243 | // 窗口失去焦点时关闭
244 | if window.isVisible {
245 | closePopover()
246 | }
247 | }
248 |
249 | func applicationWillTerminate(_ notification: Notification) {
250 | // 清理资源
251 | stopHighlightTimer()
252 | if let monitor = eventMonitor {
253 | NSEvent.removeMonitor(monitor)
254 | }
255 | }
256 |
257 | }
258 |
259 | extension AppDelegate {
260 | private func setupQuitMenuItem() {
261 | let mainMenu = NSMenu()
262 | let appMenuItem = NSMenuItem()
263 | mainMenu.addItem(appMenuItem)
264 |
265 | let appMenu = NSMenu()
266 | let quitMenuItem = NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
267 | appMenu.addItem(quitMenuItem)
268 |
269 | appMenuItem.submenu = appMenu
270 | NSApplication.shared.mainMenu = mainMenu
271 | }
272 | }
273 |
--------------------------------------------------------------------------------
/app/ContentView.swift:
--------------------------------------------------------------------------------
1 | // Power Management Suite - Main Content View
2 | // Copyright (C) 2025
3 | //
4 | // This program is free software: you can redistribute it and/or modify
5 | // it under the terms of the GNU General Public License as published by
6 | // the Free Software Foundation, either version 3 of the License, or
7 | // (at your option) any later version.
8 | //
9 | // This program is distributed in the hope that it will be useful,
10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | // GNU General Public License for more details.
13 | //
14 | // You should have received a copy of the GNU General Public License
15 | // along with this program. If not, see .
16 |
17 | // Original file info:
18 | //
19 | // ContentView.swift
20 | // app
21 | //
22 | // Created by tsunami on 2025/3/22.
23 | //
24 |
25 | import SwiftUI
26 | import AppKit
27 |
28 | struct ContentView: View {
29 | // State for battery info and UI controls
30 | @StateObject private var batteryManager = BatteryInfoManager()
31 | @State private var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
32 | @State private var num: Float = 70
33 | @State private var iconwidth: CGFloat = 15
34 | @State private var debounceTask: Task?
35 | private let socketPath = "/var/run/batt.sock" // Define socket path constant
36 |
37 | private func quitApp() {
38 | NSApplication.shared.terminate(nil)
39 | }
40 |
41 | var body: some View {
42 | // Restore original VStack structure
43 | VStack(alignment: .leading, spacing: 0, content: {
44 | VStack(alignment: .center, spacing: 0) {
45 | HStack(alignment: .center, spacing: 0, content: {
46 | HStack(spacing: 0) {
47 | // Localized Text and flexible frame
48 | Text(LocalizedStringKey("limit.label")).font(.system(size: 13)).bold()
49 | Text(String(format: "%.0f", num)).font(.system(size: 13)).frame(width: 17, alignment: .trailing)
50 | Text("%").font(.system(size: 13))
51 | }.frame(minWidth: 70, idealWidth: 90, maxWidth: .infinity, minHeight: 30).background( // Use minWidth
52 | RoundedRectangle(cornerRadius: 10, style: .continuous)
53 | .fill(.ultraThickMaterial) // Changed to transparent
54 | ).padding(EdgeInsets(top: 10, leading: 10, bottom: 0, trailing: 0))
55 |
56 | Spacer()
57 |
58 | // Button(action: {}) {
59 | // HStack {
60 | // // Localized Text and flexible frame
61 | // Text(LocalizedStringKey("enable.power.button")).font(.system(size: 13)).bold()
62 | // }.frame(minWidth: 70, idealWidth: 90, maxWidth: .infinity, minHeight: 30).background( // Use minWidth
63 | // RoundedRectangle(cornerRadius: 10, style: .continuous)
64 | // .fill(.ultraThickMaterial) // Changed to transparent
65 | // )
66 | // }.padding(EdgeInsets(top: 10, leading: 0, bottom: 0, trailing: 0)).buttonStyle(PlainButtonStyle())
67 | //
68 | // Spacer()
69 |
70 | Button(action: { quitApp() }) {
71 | HStack {
72 | Image(systemName: "xmark.circle")
73 | .imageScale(.large)
74 | .foregroundColor(.black)
75 | }.frame(width: 30, height: 30).background(
76 | RoundedRectangle(cornerRadius: 10, style: .continuous)
77 | .fill(.ultraThickMaterial) // Changed to transparent
78 | )
79 | }.padding(EdgeInsets(top: 10, leading: 0, bottom: 0, trailing: 10)).buttonStyle(PlainButtonStyle())
80 | })
81 |
82 | Slider(value: $num, in: 10...99, onEditingChanged: {editing in
83 | if !editing {
84 | debounceTask?.cancel()
85 | // Use Task for background execution, no need for .detached unless specific priority is crucial
86 | debounceTask = Task {
87 | // Define error pointer for C function
88 | var nsError: NSError?
89 |
90 | // Call the C function with the defined path as a C string
91 | let result = sendCommandToUnixSocket(Int(num), socketPath.cString(using: .utf8)!, &nsError)
92 |
93 | // Switch back to the main thread to handle UI or print logs
94 | await MainActor.run {
95 | if let error = nsError {
96 | // An error occurred during the socket operation
97 | // Use localized string with formatting
98 | print(String(format: NSLocalizedString("socket.command.failed.error", comment: "Error message when socket command fails"), error.localizedDescription))
99 | // TODO: Add UI feedback for the error (e.g., show an alert)
100 | } else if let response = result {
101 | // Successfully sent command and got response
102 | print("Socket command successful. Response: \(response)")
103 | // Optional: Parse response using extractSet(from: response) if needed
104 | if let limitSet = extractSet(from: response) {
105 | print("Successfully set limit to \(limitSet)%")
106 | // TODO: Add UI feedback for success if desired
107 | } else {
108 | // Use localized string if available, otherwise generic message
109 | // Consider adding a specific localized string for this case
110 | print(NSLocalizedString("limit.set.confirmation.parse.error", comment: "Could not parse confirmation from daemon response: \(response)"))
111 | // TODO: Add UI feedback for parsing failure if desired
112 | }
113 | } else {
114 | // Should not happen if ObjC code is correct and no error is set, but handle defensively
115 | print(NSLocalizedString("socket.command.unknown.error", comment: "Unknown error during socket command"))
116 | // TODO: Add UI feedback for this unexpected case
117 | }
118 | }
119 | }
120 | }
121 | })
122 | .padding(EdgeInsets(top: 10, leading: 10, bottom: 5, trailing: 10)) // Added bottom padding
123 |
124 | // --- Power Flow Visualization ---
125 | PowerFlowView(
126 | inputPower: batteryManager.inputwatt,
127 | batteryPower: batteryManager.batteryPower,
128 | systemLoad: batteryManager.loadwatt
129 | )
130 | .frame(minWidth: 300)
131 | .padding(EdgeInsets(top: 5, leading: 10, bottom: 0, trailing: 10))
132 | .animation(.easeIn, value: batteryManager.batteryPower)
133 | // --- End Power Flow Visualization ---
134 | }
135 |
136 | Divider().padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
137 |
138 | VStack(alignment: .leading, content: {
139 | HStack(alignment: .center, content: {
140 | Image(systemName: Icons.designcapacity).frame(width: iconwidth, alignment: .center)
141 | Text(LocalizedStringKey("design.capacity.label")).font(.system(size: 13)).bold() // Localized
142 | Spacer()
143 | Text("\(batteryManager.designCapacity) mAh").font(.system(size: 13))
144 | Text("100%").font(.system(size: 13)).frame(width: 40, alignment: .trailing)
145 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 1, trailing: 15))
146 | HStack(content: {
147 | Image(systemName: Icons.serial).frame(width: iconwidth, alignment: .center)
148 | Text(LocalizedStringKey("serial.number.label")).font(.system(size: 13)).bold() // Localized
149 | Spacer()
150 | Text(batteryManager.serialNumber).font(.system(size: 13)).frame(alignment: .trailing)
151 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 0, trailing: 15))
152 | })
153 |
154 | Divider().padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
155 |
156 | VStack(alignment: .leading, content: {
157 | HStack(alignment: .center, content: {
158 | Image(systemName: Icons.maxcapacity).frame(width: iconwidth, alignment: .center)
159 | Text(LocalizedStringKey("max.capacity.label")).font(.system(size: 13)).bold() // Localized
160 | Spacer()
161 | Text("\(batteryManager.batteryCapacity) mAh").font(.system(size: 13))
162 | Text(String(format: "%.0f%%", batteryManager.health)).font(.system(size: 13)).frame(width: 40, alignment: .trailing)
163 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 1, trailing: 15))
164 | HStack(alignment: .center, content: {
165 | Image(systemName: Icons.cyclecount).frame(width: iconwidth, alignment: .center)
166 | Text(LocalizedStringKey("cycle.count.label")).font(.system(size: 13)).bold() // Localized
167 | Spacer()
168 | Text("\(batteryManager.cycleCount)").font(.system(size: 13)).frame(width: 40, alignment: .trailing)
169 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 1, trailing: 15))
170 | HStack(content: {
171 | Image(systemName: Icons.flame).frame(width: iconwidth, alignment: .center)
172 | Text(LocalizedStringKey("battery.temperature.label")).font(.system(size: 13)).bold() // Localized
173 | Spacer()
174 | Text(String(format: "%.2f", batteryManager.temperature) + " °C").font(.system(size: 13)).frame(alignment: .trailing)
175 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 1, trailing: 15))
176 | HStack(content: {
177 | Image(systemName: Icons.levelcapacity).frame(width: iconwidth, alignment: .center)
178 | Text(LocalizedStringKey("battery.level.label")).font(.system(size: 13)).bold() // Localized
179 | Spacer()
180 | Text(String(format: "%d%%", batteryManager.batteryPercent)).font(.system(size: 13)).frame(alignment: .trailing)
181 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 0, trailing: 15))
182 | })
183 |
184 | Divider().padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
185 |
186 | VStack(alignment: .leading, content: {
187 | HStack(content: {
188 | Image(systemName: Icons.charge).frame(width: iconwidth, alignment: .center)
189 | Text(LocalizedStringKey("charging.status.label")).font(.system(size: 13)).bold() // Localized
190 | Spacer()
191 | // Localized Yes/No
192 | Text(batteryManager.isCharging ? LocalizedStringKey("yes") : LocalizedStringKey("no")).font(.system(size: 13)).frame(alignment: .trailing)
193 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 1, trailing: 15))
194 | HStack(content: {
195 | Image(systemName: Icons.iconLight).frame(width: iconwidth, alignment: .center)
196 | Text(LocalizedStringKey("battery.power.label")).font(.system(size: 13)).bold() // Localized
197 | Spacer()
198 | Text(String(format: "%.2f", batteryManager.batteryPower < 0 ? batteryManager.batteryPower * -1 : batteryManager.batteryPower) + " W").font(.system(size: 13)).frame(alignment: .trailing)
199 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 1, trailing: 15))
200 | HStack(content: {
201 | Image(systemName: Icons.normLight).frame(width: iconwidth, alignment: .center)
202 | Text(LocalizedStringKey("battery.amperage.label")).font(.system(size: 13)).bold() // Localized
203 | Spacer()
204 | Text(String(format: "%.3f", batteryManager.batteryAmperage < 0 ? batteryManager.batteryAmperage * -1 : batteryManager.batteryAmperage) + " A").font(.system(size: 13)).frame(alignment: .trailing)
205 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 1, trailing: 15))
206 | HStack(content: {
207 | Image(systemName: Icons.slash).frame(width: iconwidth, alignment: .center)
208 | Text(LocalizedStringKey("battery.voltage.label")).font(.system(size: 13)).bold() // Localized
209 | Spacer()
210 | Text(String(format: "%.2f", batteryManager.batteryVoltage) + " V").font(.system(size: 13)).frame(alignment: .trailing)
211 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 0, trailing: 15))
212 | })
213 |
214 | Divider().padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
215 |
216 | VStack(alignment: .leading, content: {
217 | HStack(content: {
218 | Image(systemName: Icons.iconLight).frame(width: iconwidth, alignment: .center)
219 | Text(LocalizedStringKey("system.load.label")).font(.system(size: 13)).bold() // Localized
220 | Spacer()
221 | Text(String(format: "%.2f", batteryManager.loadwatt) + " W").font(.system(size: 13)).frame(alignment: .trailing)
222 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 1, trailing: 15))
223 | HStack(content: {
224 | Image(systemName: Icons.iconLight).frame(width: iconwidth, alignment: .center)
225 | Text(LocalizedStringKey("adapter.input.power.label")).font(.system(size: 13)).bold() // Localized
226 | Spacer()
227 | Text(String(format: "%.2f", batteryManager.inputwatt) + " W").font(.system(size: 13)).frame(alignment: .trailing)
228 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 1, trailing: 15))
229 | HStack(content: {
230 | Image(systemName: Icons.normLight).frame(width: iconwidth, alignment: .center)
231 | Text(LocalizedStringKey("adapter.input.amperage.label")).font(.system(size: 13)).bold() // Localized
232 | Spacer()
233 | Text(String(format: "%.3f", batteryManager.amperage) + " A").font(.system(size: 13)).frame(alignment: .trailing)
234 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 1, trailing: 15))
235 | HStack(content: {
236 | Image(systemName: Icons.slash).frame(width: iconwidth, alignment: .center)
237 | Text(LocalizedStringKey("adapter.input.voltage.label")).font(.system(size: 13)).bold() // Localized
238 | Spacer()
239 | Text(String(format: "%.2f", batteryManager.voltage) + " V").font(.system(size: 13)).frame(alignment: .trailing)
240 | }).padding(EdgeInsets(top: 0, leading: 15, bottom: 10, trailing: 15))
241 | })
242 | })
243 | // Restore .onReceive here
244 | .onReceive(timer) { _ in
245 | batteryManager.updateBatteryInfo()
246 | }
247 | }
248 |
249 | }
250 |
251 | func extractGet(from input: String) -> Int? {
252 | let pattern = #"Upper limit:\s+(\d+)%"#
253 |
254 | guard let regex = try? NSRegularExpression(pattern: pattern) else {
255 | return nil
256 | }
257 |
258 | let nsRange = NSRange(input.startIndex.. Int? {
269 | let pattern = #"charging limit to\s+(\d+)%"#
270 |
271 | // 创建正则表达式,因为确定模式有效,所以使用 try!
272 | let regex = try! NSRegularExpression(pattern: pattern)
273 |
274 | let nsRange = NSRange(input.startIndex..
10 | *
11 | * This program is free software: you can redistribute it and/or modify
12 | * it under the terms of the GNU General Public License as published by
13 | * the Free Software Foundation, either version 3 of the License, or
14 | * (at your option) any later version.
15 | *
16 | * This program is distributed in the hope that it will be useful,
17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | * GNU General Public License for more details.
20 | *
21 | * You should have received a copy of the GNU General Public License
22 | * along with this program. If not, see .
23 | *
24 | * --- Acknowledgments ---
25 | * This tool incorporates code originally from the Power Monitor Tool by SAP SE,
26 | * which was licensed under the Apache License, Version 2.0.
27 | * See original notice below (preserved for attribution):
28 | *
29 | * Original file info:
30 | * PowerConsumption.m
31 | * Standalone tool to get current power consumption on macOS
32 | * Extracted from Power Monitor Tool by SAP SE
33 | * Original code licensed under Apache License, Version 2.0
34 | */
35 |
36 | #import
37 | #import
38 | #import
39 |
40 | // Structure to communicate with the SMC
41 | typedef struct {
42 | uint32_t key;
43 | char unused0[24];
44 | uint32_t size;
45 | char unused1[10];
46 | char command;
47 | char unused2[5];
48 | float value;
49 | char unused3[28];
50 | } AppleSMCData_Float; // Renamed for clarity
51 |
52 | // Structure for reading 16-bit integer SMC values
53 | typedef struct {
54 | uint32_t key;
55 | char unused0[24];
56 | uint32_t size;
57 | char unused1[10];
58 | char command;
59 | char unused2[5];
60 | uint16_t value; // Changed to uint16_t
61 | char unused3[30]; // Adjusted padding size
62 | } AppleSMCData_Int16;
63 |
64 | // Enum for Battery Status
65 | typedef enum {
66 | BATTERY_STATUS_IDLE,
67 | BATTERY_STATUS_CHARGING,
68 | BATTERY_STATUS_DISCHARGING,
69 | BATTERY_STATUS_FAILED
70 | } BatteryStatus;
71 |
72 | // Struct to hold battery info
73 | typedef struct {
74 | BatteryStatus status;
75 | float powerWatts; // Positive for charging, negative for discharging
76 | } BatteryInfo;
77 |
78 |
79 | // Helper function to read a signed fixed-point 7.8 value from SMC (e.g., temperature)
80 | BOOL getSMCSignedFixedPoint78Value(uint32_t key, float* outValue) {
81 | BOOL success = NO;
82 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
83 |
84 | if (smc) {
85 | io_connect_t conn = IO_OBJECT_NULL;
86 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
87 |
88 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
89 | // sp78 is 2 bytes, so use the Int16 structure
90 | AppleSMCData_Int16 inStruct, outStruct;
91 | size_t outStructSize = sizeof(AppleSMCData_Int16);
92 |
93 | bzero(&inStruct, sizeof(AppleSMCData_Int16));
94 | bzero(&outStruct, sizeof(AppleSMCData_Int16));
95 |
96 | inStruct.command = 5; // read command
97 | inStruct.size = 2; // Size for sp78
98 | inStruct.key = key;
99 |
100 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Int16), &outStruct, &outStructSize);
101 | IOServiceClose(conn);
102 |
103 | if (result == kIOReturnSuccess) {
104 | // Convert sp78 raw value (signed int16) to float
105 | // sp78: 1 sign bit, 7 integer bits, 8 fractional bits
106 | *outValue = (float)((int16_t)outStruct.value) / 256.0f; // Divide by 2^8
107 | success = YES;
108 | }
109 | }
110 | IOObjectRelease(smc);
111 | }
112 | return success;
113 | }
114 |
115 |
116 | // Helper function to read a 16-bit integer value from SMC
117 | BOOL getSMCUInt16Value(uint32_t key, uint16_t* outValue) { // Changed to uint16_t output
118 | BOOL success = NO;
119 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
120 |
121 | if (smc) {
122 | io_connect_t conn = IO_OBJECT_NULL;
123 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
124 |
125 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
126 | AppleSMCData_Int16 inStruct, outStruct; // Still use Int16 struct for 2 bytes
127 | size_t outStructSize = sizeof(AppleSMCData_Int16);
128 |
129 | bzero(&inStruct, sizeof(AppleSMCData_Int16));
130 | bzero(&outStruct, sizeof(AppleSMCData_Int16));
131 |
132 | inStruct.command = 5; // read command
133 | inStruct.size = 2; // Size for ui16/si16
134 | inStruct.key = key;
135 |
136 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Int16), &outStruct, &outStructSize);
137 | IOServiceClose(conn);
138 |
139 | if (result == kIOReturnSuccess) {
140 | // Value is in outStruct.value (as uint16_t)
141 | *outValue = outStruct.value;
142 | success = YES;
143 | }
144 | }
145 | IOObjectRelease(smc);
146 | }
147 | return success;
148 | }
149 |
150 | // Helper function to read a signed 8-bit integer value from SMC
151 | BOOL getSMCSInt8Value(uint32_t key, int8_t* outValue) {
152 | BOOL success = NO;
153 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
154 |
155 | if (smc) {
156 | io_connect_t conn = IO_OBJECT_NULL;
157 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
158 |
159 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
160 | // Use Int16 struct but only read/expect 1 byte
161 | AppleSMCData_Int16 inStruct, outStruct;
162 | size_t outStructSize = sizeof(AppleSMCData_Int16);
163 |
164 | bzero(&inStruct, sizeof(AppleSMCData_Int16));
165 | bzero(&outStruct, sizeof(AppleSMCData_Int16));
166 |
167 | inStruct.command = 5; // read command
168 | inStruct.size = 1; // Size for si8
169 | inStruct.key = key;
170 |
171 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Int16), &outStruct, &outStructSize);
172 | IOServiceClose(conn);
173 |
174 | if (result == kIOReturnSuccess) {
175 | // Value is in the lower byte of outStruct.value
176 | *outValue = (int8_t)(outStruct.value & 0xFF);
177 | success = YES;
178 | }
179 | }
180 | IOObjectRelease(smc);
181 | }
182 | return success;
183 | }
184 |
185 |
186 | // Helper function to read a signed 16-bit integer value from SMC
187 | BOOL getSMCSInt16Value(uint32_t key, int16_t* outValue) { // Specific function for signed
188 | BOOL success = NO;
189 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
190 |
191 | if (smc) {
192 | io_connect_t conn = IO_OBJECT_NULL;
193 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
194 |
195 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
196 | AppleSMCData_Int16 inStruct, outStruct; // Use Int16 struct for 2 bytes
197 | size_t outStructSize = sizeof(AppleSMCData_Int16);
198 |
199 | bzero(&inStruct, sizeof(AppleSMCData_Int16));
200 | bzero(&outStruct, sizeof(AppleSMCData_Int16));
201 |
202 | inStruct.command = 5; // read command
203 | inStruct.size = 2; // Size for si16
204 | inStruct.key = key;
205 |
206 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Int16), &outStruct, &outStructSize);
207 | IOServiceClose(conn);
208 |
209 | if (result == kIOReturnSuccess) {
210 | // Value is in outStruct.value (as uint16_t), cast to int16_t
211 | *outValue = (int16_t)outStruct.value;
212 | success = YES;
213 | }
214 | }
215 | IOObjectRelease(smc);
216 | }
217 | return success;
218 | }
219 |
220 |
221 | // Function to get the current power consumption (using original float struct)
222 | float getRawSystemPower(void)
223 | {
224 | float returnValue = 0;
225 |
226 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
227 |
228 | if (smc) {
229 |
230 | io_connect_t conn = IO_OBJECT_NULL;
231 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
232 |
233 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
234 |
235 | AppleSMCData_Float inStruct, outStruct; // Use float struct
236 | size_t outStructSize = sizeof(AppleSMCData_Float);
237 |
238 | bzero(&inStruct, sizeof(AppleSMCData_Float));
239 | bzero(&outStruct, sizeof(AppleSMCData_Float));
240 |
241 | inStruct.command = 5; // read command
242 | inStruct.size = 4;
243 | inStruct.key = ('P' << 24) + ('S' << 16) + ('T' << 8) + 'R'; // PSTR key
244 |
245 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Float), &outStruct, &outStructSize);
246 | IOServiceClose(conn);
247 |
248 | if (result == kIOReturnSuccess) {
249 | returnValue = outStruct.value;
250 | }
251 | }
252 |
253 | IOObjectRelease(smc);
254 | }
255 |
256 | return returnValue;
257 | }
258 |
259 | // Function to get the current power input from the adapter
260 | float getAdapterPower(void)
261 | {
262 | float returnValue = 0;
263 |
264 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
265 |
266 | if (smc) {
267 |
268 | io_connect_t conn = IO_OBJECT_NULL;
269 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
270 |
271 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
272 |
273 | AppleSMCData_Float inStruct, outStruct; // Use float struct
274 | size_t outStructSize = sizeof(AppleSMCData_Float);
275 |
276 | bzero(&inStruct, sizeof(AppleSMCData_Float));
277 | bzero(&outStruct, sizeof(AppleSMCData_Float));
278 |
279 | inStruct.command = 5; // read command
280 | inStruct.size = 4; // Assuming float or similar sp format handled by the struct/call
281 | inStruct.key = ('P' << 24) + ('D' << 16) + ('T' << 8) + 'R'; // PDTR key for DC-In total power
282 |
283 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Float), &outStruct, &outStructSize);
284 | IOServiceClose(conn);
285 |
286 | if (result == kIOReturnSuccess) {
287 | // Assuming the value is returned correctly as a float or interpretable as such
288 | returnValue = outStruct.value;
289 | }
290 | }
291 |
292 | IOObjectRelease(smc);
293 | }
294 |
295 | return returnValue;
296 | }
297 |
298 | // Function to get battery info (status and power)
299 | BatteryInfo getBatteryInfo(void) {
300 | BatteryInfo info;
301 | info.status = BATTERY_STATUS_FAILED; // Default to failed
302 | info.powerWatts = 0.0f;
303 |
304 | int16_t voltage_mV = 0;
305 | int16_t current_mA = 0; // Signed, positive=charging, negative=discharging
306 |
307 | // Define keys
308 | uint32_t voltageKey = ('B' << 24) + ('0' << 16) + ('A' << 8) + 'V'; // B0AV (ui16)
309 | uint32_t currentKey = ('B' << 24) + ('0' << 16) + ('A' << 8) + 'C'; // B0AC (si16)
310 |
311 | uint16_t raw_voltage_mV = 0; // Use uint16_t for B0AV
312 | BOOL voltageSuccess = getSMCUInt16Value(voltageKey, &raw_voltage_mV);
313 | voltage_mV = (int16_t)raw_voltage_mV; // Cast for calculation, sign irrelevant here
314 |
315 | BOOL currentSuccess = getSMCSInt16Value(currentKey, ¤t_mA); // Use signed helper for B0AC
316 |
317 | if (voltageSuccess && currentSuccess) {
318 | // Calculate power: P(W) = V(V) * I(A) = (mV / 1000) * (mA / 1000)
319 | info.powerWatts = ( (float)voltage_mV / 1000.0f ) * ( (float)current_mA / 1000.0f );
320 |
321 | // Determine status based on current
322 | if (current_mA > 50) { // Add a small threshold to avoid noise around zero
323 | info.status = BATTERY_STATUS_CHARGING;
324 | } else if (current_mA < -50) {
325 | info.status = BATTERY_STATUS_DISCHARGING;
326 | } else {
327 | info.status = BATTERY_STATUS_IDLE; // Near zero current
328 | }
329 | }
330 | // If only one succeeded, status remains FAILED, power remains 0.
331 |
332 | return info;
333 | } // <-- ADDED MISSING CLOSING BRACE FOR getBatteryInfo
334 |
335 | // Function to get battery temperature (tries multiple keys)
336 | float getBatteryTemperature(void) {
337 | float temperature = -999.0f; // Indicate failure
338 | BOOL success = NO;
339 |
340 | // Define potential keys
341 | uint32_t keysToTry[] = {
342 | ('T' << 24) + ('B' << 16) + ('0' << 8) + 'T', // TB0T
343 | ('T' << 24) + ('B' << 16) + ('1' << 8) + 'T', // TB1T
344 | ('T' << 24) + ('B' << 16) + ('2' << 8) + 'T', // TB2T
345 | ('T' << 24) + ('B' << 16) + ('3' << 8) + 'T', // TB3T
346 | ('T' << 24) + ('C' << 16) + ('0' << 8) + 'B' // TC0B (Another possible battery temp key)
347 | };
348 | int numKeys = sizeof(keysToTry) / sizeof(keysToTry[0]);
349 |
350 | for (int i = 0; i < numKeys; ++i) {
351 | success = getSMCSignedFixedPoint78Value(keysToTry[i], &temperature);
352 | // If the SMC call itself succeeded, return the value immediately.
353 | if (success) {
354 | return temperature; // Found a valid reading
355 | }
356 | }
357 |
358 | // If loop finishes without returning, all SMC calls failed for these keys.
359 | return -999.0f; // Return failure indicator
360 | }
361 |
362 | // Function to get battery cycle count
363 | uint16_t getBatteryCycleCount(void) {
364 | uint16_t cycles = 0xFFFF; // Indicate failure
365 | uint32_t cycleKey = ('B' << 24) + ('0' << 16) + ('C' << 8) + 'T'; // B0CT (ui16)
366 | getSMCUInt16Value(cycleKey, &cycles);
367 | return cycles;
368 | }
369 |
370 | // Function to get adapter voltage (Reads DVR as ui16)
371 | float getAdapterVoltage(void) {
372 | int8_t activePort = 0; // Default to port 0
373 | uint32_t winnerPortKey = ('A' << 24) + ('C' << 16) + ('-' << 8) + 'W'; // AC-W (si8)
374 | getSMCSInt8Value(winnerPortKey, &activePort);
375 |
376 | // Ensure port index is within a reasonable range (e.g., 0-4)
377 | if (activePort < 0 || activePort > 4) {
378 | activePort = 0;
379 | }
380 |
381 | uint16_t voltage_mV = 0;
382 | float voltage_V = 0.0f; // Indicate failure
383 | // Construct key dynamically: DVR
384 | uint32_t voltageKey = ('D' << 24) + ((uint32_t)('0' + activePort) << 16) + ('V' << 8) + 'R';
385 |
386 | if (getSMCUInt16Value(voltageKey, &voltage_mV)) {
387 | voltage_V = (float)voltage_mV / 1000.0f;
388 | }
389 | // Return -1.0f if read failed, otherwise the voltage (likely 20.000)
390 | return voltage_V;
391 | }
392 |
393 | // Function to get adapter amperage (Calculated from Real-Time Power and Reported Voltage)
394 | float getAdapterAmperage(void) {
395 | float power = getAdapterPower(); // Get real-time power (PDTR)
396 | float voltage = getAdapterVoltage(); // Get reported voltage (DVR)
397 |
398 | float current_A = 0.000f; // Indicate failure
399 |
400 | // Check if both readings were likely successful and voltage is usable
401 | // Use PDTR / DVR as DIR seems to report max rated current, not real-time.
402 | if (power >= 0 && voltage > 0.01f) { // Allow power to be 0
403 | current_A = power / voltage; // Calculate Amps = Watts / Volts
404 | }
405 |
406 | return current_A;
407 | }
408 |
409 | float getBatteryVoltage(void) {
410 | float bv = 0.00f;
411 |
412 | uint16_t batteryVoltage_mV = 0;
413 | BOOL batteryVoltageSuccess = getSMCUInt16Value(('B' << 24) + ('0' << 16) + ('A' << 8) + 'V', &batteryVoltage_mV);
414 |
415 | if (batteryVoltageSuccess) {
416 | bv = (float) batteryVoltage_mV / 1000;
417 | }
418 | return bv;
419 | }
420 |
421 | float getBatteryAmperage(void) {
422 | float ba = 0.000f;
423 |
424 | int16_t batteryAmperage_mA = 0;
425 | BOOL batteryAmperageSuccess = getSMCSInt16Value(('B' << 24) + ('0' << 16) + ('A' << 8) + 'C', &batteryAmperage_mA);
426 |
427 | if (batteryAmperageSuccess) {
428 | ba = (float) batteryAmperage_mA / 1000;
429 | }
430 | return ba;
431 | }
432 |
433 | float getBatteryPower(void) {
434 | float bp = 0.00f;
435 | bp = getBatteryVoltage() * getBatteryAmperage();
436 | //NSString *s = getChargingStatus()
437 | // if (s == "Idle") {
438 | // bp = bp * -1;
439 | // }
440 | return bp;
441 | }
442 |
443 | NSString* getChargingStatus(void) {
444 | NSString *myString = @"This is a string to return.";
445 | float ba = getBatteryAmperage();
446 | if (ba > 0.05) {
447 | myString = @"Charging";
448 | } else {
449 | myString = @"Idle";
450 | }
451 | return myString;
452 | }
453 |
454 | #import "powerInfo.h"
455 | #import
456 | #import
457 | #import // For errno
458 |
459 | // Define an error domain for our custom errors
460 | NSString * const PowerInfoErrorDomain = @"com.yourcompany.BattGUI.PowerInfoErrorDomain"; // Replace with your actual domain
461 |
462 | // Implementation for sending command to Unix domain socket
463 | NSString * _Nullable sendCommandToUnixSocket(NSInteger value, const char * _Nonnull socketPath, NSError * _Nullable * _Nullable error) {
464 | // Declare all variables at the top to avoid goto issues
465 | int sockfd = -1;
466 | struct sockaddr_un addr;
467 | char buffer[1024];
468 | ssize_t bytesSent = 0; // Initialize to avoid potential uninitialized reads if goto happens early
469 | ssize_t bytesRead = 0;
470 | NSString *responseString = nil;
471 | NSError *localError = nil;
472 | NSString *valueString = nil;
473 | NSString *requestBody = nil;
474 | NSString *requestString = nil;
475 | const char *requestBytes = NULL;
476 | size_t requestLength = 0;
477 | NSMutableData *responseData = nil; // Initialize later
478 |
479 | // 1. Create Socket
480 | sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
481 | if (sockfd == -1) {
482 | localError = [NSError errorWithDomain:PowerInfoErrorDomain
483 | code:errno // Use POSIX error code
484 | userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create socket: %s", strerror(errno)]}];
485 | perror("socket error");
486 | goto cleanup; // Use goto for centralized cleanup
487 | }
488 |
489 | // 2. Set up Address Structure
490 | memset(&addr, 0, sizeof(addr));
491 | addr.sun_family = AF_UNIX;
492 | if (strlen(socketPath) >= sizeof(addr.sun_path)) {
493 | localError = [NSError errorWithDomain:PowerInfoErrorDomain
494 | code:ENAMETOOLONG
495 | userInfo:@{NSLocalizedDescriptionKey: @"Socket path is too long."}];
496 | goto cleanup;
497 | }
498 | strncpy(addr.sun_path, socketPath, sizeof(addr.sun_path) - 1);
499 |
500 | // 3. Connect to Socket
501 | if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
502 | localError = [NSError errorWithDomain:PowerInfoErrorDomain
503 | code:errno
504 | userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to connect to socket '%s': %s", socketPath, strerror(errno)]}];
505 | perror("connect error");
506 | goto cleanup;
507 | }
508 |
509 | // 4. Construct HTTP PUT Request
510 | valueString = [NSString stringWithFormat:@"%ld", (long)value]; // Assign here
511 | requestBody = valueString; // Assign here
512 | requestString = [NSString stringWithFormat: // Assign here
513 | @"PUT /limit HTTP/1.1\r\n"
514 | @"Host: localhost\r\n"
515 | @"Content-Type: text/plain\r\n" // Assuming plain text is okay
516 | @"Content-Length: %lu\r\n"
517 | @"Connection: close\r\n" // Close connection after response
518 | @"\r\n"
519 | @"%@",
520 | (unsigned long)[requestBody length], requestBody]; // Corrected argument order
521 |
522 | requestBytes = [requestString UTF8String]; // Assign here
523 | requestLength = strlen(requestBytes); // Assign here
524 |
525 | // 5. Send Request
526 | bytesSent = write(sockfd, requestBytes, requestLength);
527 | if (bytesSent == -1) {
528 | localError = [NSError errorWithDomain:PowerInfoErrorDomain
529 | code:errno
530 | userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write to socket: %s", strerror(errno)]}];
531 | perror("write error");
532 | goto cleanup;
533 | }
534 | if (bytesSent < requestLength) {
535 | localError = [NSError errorWithDomain:PowerInfoErrorDomain
536 | code:EIO // Generic I/O error
537 | userInfo:@{NSLocalizedDescriptionKey: @"Partial write to socket."}];
538 | fprintf(stderr, "Partial write to socket\n");
539 | goto cleanup;
540 | }
541 |
542 | // 6. Read Response
543 | responseData = [NSMutableData data]; // Initialize here
544 | while ((bytesRead = read(sockfd, buffer, sizeof(buffer) - 1)) > 0) {
545 | // buffer[bytesRead] = '\0'; // Null-termination not needed for appending data
546 | [responseData appendBytes:buffer length:bytesRead];
547 | }
548 |
549 | if (bytesRead == -1) {
550 | // Read error might occur if server closes connection immediately. Check errno.
551 | // EAGAIN/EWOULDBLOCK are not expected for blocking sockets.
552 | // ECONNRESET might be okay if data was received before reset.
553 | if (errno != ECONNRESET || [responseData length] == 0) {
554 | localError = [NSError errorWithDomain:PowerInfoErrorDomain
555 | code:errno
556 | userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read from socket: %s", strerror(errno)]}];
557 | perror("read error");
558 | goto cleanup;
559 | }
560 | // If ECONNRESET and we got data, proceed.
561 | perror("read warning (ECONNRESET after receiving data)");
562 | }
563 |
564 | // Convert response data to string
565 | if ([responseData length] > 0) {
566 | responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
567 | if (!responseString) {
568 | localError = [NSError errorWithDomain:PowerInfoErrorDomain
569 | code:NSPropertyListReadCorruptError // Or a more specific encoding error code
570 | userInfo:@{NSLocalizedDescriptionKey: @"Failed to decode response data as UTF-8."}];
571 | fprintf(stderr, "Failed to decode response as UTF-8\n");
572 | // Fall through to cleanup, responseString is already nil
573 | }
574 | } else {
575 | // No data read, assume success with empty response if no other error occurred.
576 | responseString = @"";
577 | }
578 |
579 | cleanup:
580 | // 7. Close Socket if it was opened
581 | if (sockfd != -1) {
582 | close(sockfd);
583 | }
584 |
585 | // 8. Assign error if pointer provided and localError exists
586 | if (error && localError) {
587 | *error = localError;
588 | }
589 |
590 | // Return nil if an error occurred, otherwise the response string
591 | return (localError == nil) ? responseString : nil;
592 | }
593 |
--------------------------------------------------------------------------------
/systemLoad_Claude/power_info.m:
--------------------------------------------------------------------------------
1 | /*
2 | * Power Management Suite - System Power Information Tool (power_info)
3 | * Copyright (C) 2025
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | *
18 | * --- Acknowledgments ---
19 | * This tool incorporates code originally from the Power Monitor Tool by SAP SE,
20 | * which was licensed under the Apache License, Version 2.0.
21 | * See original notice below (preserved for attribution):
22 | *
23 | * Original file info:
24 | * PowerConsumption.m
25 | * Standalone tool to get current power consumption on macOS
26 | * Extracted from Power Monitor Tool by SAP SE
27 | * Original code licensed under Apache License, Version 2.0
28 | */
29 |
30 | #import
31 | #import
32 | #import
33 |
34 | // Structure to communicate with the SMC
35 | typedef struct {
36 | uint32_t key;
37 | char unused0[24];
38 | uint32_t size;
39 | char unused1[10];
40 | char command;
41 | char unused2[5];
42 | float value;
43 | char unused3[28];
44 | } AppleSMCData_Float; // Renamed for clarity
45 |
46 | // Structure for reading 16-bit integer SMC values
47 | typedef struct {
48 | uint32_t key;
49 | char unused0[24];
50 | uint32_t size;
51 | char unused1[10];
52 | char command;
53 | char unused2[5];
54 | uint16_t value; // Changed to uint16_t
55 | char unused3[30]; // Adjusted padding size
56 | } AppleSMCData_Int16;
57 |
58 | // Enum for Battery Status
59 | typedef enum {
60 | BATTERY_STATUS_IDLE,
61 | BATTERY_STATUS_CHARGING,
62 | BATTERY_STATUS_DISCHARGING,
63 | BATTERY_STATUS_FAILED
64 | } BatteryStatus;
65 |
66 | // Struct to hold battery info
67 | typedef struct {
68 | BatteryStatus status;
69 | float powerWatts; // Positive for charging, negative for discharging
70 | } BatteryInfo;
71 |
72 |
73 | // Helper function to read a signed fixed-point 7.8 value from SMC (e.g., temperature)
74 | BOOL getSMCSignedFixedPoint78Value(uint32_t key, float* outValue) {
75 | BOOL success = NO;
76 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
77 |
78 | if (smc) {
79 | io_connect_t conn = IO_OBJECT_NULL;
80 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
81 |
82 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
83 | // sp78 is 2 bytes, so use the Int16 structure
84 | AppleSMCData_Int16 inStruct, outStruct;
85 | size_t outStructSize = sizeof(AppleSMCData_Int16);
86 |
87 | bzero(&inStruct, sizeof(AppleSMCData_Int16));
88 | bzero(&outStruct, sizeof(AppleSMCData_Int16));
89 |
90 | inStruct.command = 5; // read command
91 | inStruct.size = 2; // Size for sp78
92 | inStruct.key = key;
93 |
94 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Int16), &outStruct, &outStructSize);
95 | IOServiceClose(conn);
96 |
97 | if (result == kIOReturnSuccess) {
98 | // Convert sp78 raw value (signed int16) to float
99 | // sp78: 1 sign bit, 7 integer bits, 8 fractional bits
100 | *outValue = (float)((int16_t)outStruct.value) / 256.0f; // Divide by 2^8
101 | success = YES;
102 | }
103 | }
104 | IOObjectRelease(smc);
105 | }
106 | return success;
107 | }
108 |
109 |
110 | // Helper function to read a 16-bit integer value from SMC
111 | BOOL getSMCUInt16Value(uint32_t key, uint16_t* outValue) { // Changed to uint16_t output
112 | BOOL success = NO;
113 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
114 |
115 | if (smc) {
116 | io_connect_t conn = IO_OBJECT_NULL;
117 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
118 |
119 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
120 | AppleSMCData_Int16 inStruct, outStruct; // Still use Int16 struct for 2 bytes
121 | size_t outStructSize = sizeof(AppleSMCData_Int16);
122 |
123 | bzero(&inStruct, sizeof(AppleSMCData_Int16));
124 | bzero(&outStruct, sizeof(AppleSMCData_Int16));
125 |
126 | inStruct.command = 5; // read command
127 | inStruct.size = 2; // Size for ui16/si16
128 | inStruct.key = key;
129 |
130 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Int16), &outStruct, &outStructSize);
131 | IOServiceClose(conn);
132 |
133 | if (result == kIOReturnSuccess) {
134 | // Value is in outStruct.value (as uint16_t)
135 | *outValue = outStruct.value;
136 | success = YES;
137 | }
138 | }
139 | IOObjectRelease(smc);
140 | }
141 | return success;
142 | }
143 |
144 | // Helper function to read a signed 8-bit integer value from SMC
145 | BOOL getSMCSInt8Value(uint32_t key, int8_t* outValue) {
146 | BOOL success = NO;
147 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
148 |
149 | if (smc) {
150 | io_connect_t conn = IO_OBJECT_NULL;
151 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
152 |
153 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
154 | // Use Int16 struct but only read/expect 1 byte
155 | AppleSMCData_Int16 inStruct, outStruct;
156 | size_t outStructSize = sizeof(AppleSMCData_Int16);
157 |
158 | bzero(&inStruct, sizeof(AppleSMCData_Int16));
159 | bzero(&outStruct, sizeof(AppleSMCData_Int16));
160 |
161 | inStruct.command = 5; // read command
162 | inStruct.size = 1; // Size for si8
163 | inStruct.key = key;
164 |
165 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Int16), &outStruct, &outStructSize);
166 | IOServiceClose(conn);
167 |
168 | if (result == kIOReturnSuccess) {
169 | // Value is in the lower byte of outStruct.value
170 | *outValue = (int8_t)(outStruct.value & 0xFF);
171 | success = YES;
172 | }
173 | }
174 | IOObjectRelease(smc);
175 | }
176 | return success;
177 | }
178 |
179 |
180 | // Helper function to read a signed 16-bit integer value from SMC
181 | BOOL getSMCSInt16Value(uint32_t key, int16_t* outValue) { // Specific function for signed
182 | BOOL success = NO;
183 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
184 |
185 | if (smc) {
186 | io_connect_t conn = IO_OBJECT_NULL;
187 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
188 |
189 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
190 | AppleSMCData_Int16 inStruct, outStruct; // Use Int16 struct for 2 bytes
191 | size_t outStructSize = sizeof(AppleSMCData_Int16);
192 |
193 | bzero(&inStruct, sizeof(AppleSMCData_Int16));
194 | bzero(&outStruct, sizeof(AppleSMCData_Int16));
195 |
196 | inStruct.command = 5; // read command
197 | inStruct.size = 2; // Size for si16
198 | inStruct.key = key;
199 |
200 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Int16), &outStruct, &outStructSize);
201 | IOServiceClose(conn);
202 |
203 | if (result == kIOReturnSuccess) {
204 | // Value is in outStruct.value (as uint16_t), cast to int16_t
205 | *outValue = (int16_t)outStruct.value;
206 | success = YES;
207 | }
208 | }
209 | IOObjectRelease(smc);
210 | }
211 | return success;
212 | }
213 |
214 |
215 | // Function to get the current power consumption (using original float struct)
216 | float getRawSystemPower(void)
217 | {
218 | float returnValue = 0;
219 |
220 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
221 |
222 | if (smc) {
223 |
224 | io_connect_t conn = IO_OBJECT_NULL;
225 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
226 |
227 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
228 |
229 | AppleSMCData_Float inStruct, outStruct; // Use float struct
230 | size_t outStructSize = sizeof(AppleSMCData_Float);
231 |
232 | bzero(&inStruct, sizeof(AppleSMCData_Float));
233 | bzero(&outStruct, sizeof(AppleSMCData_Float));
234 |
235 | inStruct.command = 5; // read command
236 | inStruct.size = 4;
237 | inStruct.key = ('P' << 24) + ('S' << 16) + ('T' << 8) + 'R'; // PSTR key
238 |
239 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Float), &outStruct, &outStructSize);
240 | IOServiceClose(conn);
241 |
242 | if (result == kIOReturnSuccess) {
243 | returnValue = outStruct.value;
244 | }
245 | }
246 |
247 | IOObjectRelease(smc);
248 | }
249 |
250 | return returnValue;
251 | }
252 |
253 | // Function to get the current power input from the adapter
254 | float getAdapterPower(void)
255 | {
256 | float returnValue = 0;
257 |
258 | io_service_t smc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"));
259 |
260 | if (smc) {
261 |
262 | io_connect_t conn = IO_OBJECT_NULL;
263 | IOReturn result = IOServiceOpen(smc, mach_task_self(), 1, &conn);
264 |
265 | if (result == kIOReturnSuccess && conn != IO_OBJECT_NULL) {
266 |
267 | AppleSMCData_Float inStruct, outStruct; // Use float struct
268 | size_t outStructSize = sizeof(AppleSMCData_Float);
269 |
270 | bzero(&inStruct, sizeof(AppleSMCData_Float));
271 | bzero(&outStruct, sizeof(AppleSMCData_Float));
272 |
273 | inStruct.command = 5; // read command
274 | inStruct.size = 4; // Assuming float or similar sp format handled by the struct/call
275 | inStruct.key = ('P' << 24) + ('D' << 16) + ('T' << 8) + 'R'; // PDTR key for DC-In total power
276 |
277 | result = IOConnectCallStructMethod(conn, 2, &inStruct, sizeof(AppleSMCData_Float), &outStruct, &outStructSize);
278 | IOServiceClose(conn);
279 |
280 | if (result == kIOReturnSuccess) {
281 | // Assuming the value is returned correctly as a float or interpretable as such
282 | returnValue = outStruct.value;
283 | }
284 | }
285 |
286 | IOObjectRelease(smc);
287 | }
288 |
289 | return returnValue;
290 | }
291 |
292 | // Function to get battery info (status and power)
293 | BatteryInfo getBatteryInfo(void) {
294 | BatteryInfo info;
295 | info.status = BATTERY_STATUS_FAILED; // Default to failed
296 | info.powerWatts = 0.0f;
297 |
298 | int16_t voltage_mV = 0;
299 | int16_t current_mA = 0; // Signed, positive=charging, negative=discharging
300 |
301 | // Define keys
302 | uint32_t voltageKey = ('B' << 24) + ('0' << 16) + ('A' << 8) + 'V'; // B0AV (ui16)
303 | uint32_t currentKey = ('B' << 24) + ('0' << 16) + ('A' << 8) + 'C'; // B0AC (si16)
304 |
305 | uint16_t raw_voltage_mV = 0; // Use uint16_t for B0AV
306 | BOOL voltageSuccess = getSMCUInt16Value(voltageKey, &raw_voltage_mV);
307 | voltage_mV = (int16_t)raw_voltage_mV; // Cast for calculation, sign irrelevant here
308 |
309 | BOOL currentSuccess = getSMCSInt16Value(currentKey, ¤t_mA); // Use signed helper for B0AC
310 |
311 | if (voltageSuccess && currentSuccess) {
312 | // Calculate power: P(W) = V(V) * I(A) = (mV / 1000) * (mA / 1000)
313 | info.powerWatts = ( (float)voltage_mV / 1000.0f ) * ( (float)current_mA / 1000.0f );
314 |
315 | // Determine status based on current
316 | if (current_mA > 50) { // Add a small threshold to avoid noise around zero
317 | info.status = BATTERY_STATUS_CHARGING;
318 | } else if (current_mA < -50) {
319 | info.status = BATTERY_STATUS_DISCHARGING;
320 | } else {
321 | info.status = BATTERY_STATUS_IDLE; // Near zero current
322 | }
323 | }
324 | // If only one succeeded, status remains FAILED, power remains 0.
325 |
326 | return info;
327 | } // <-- ADDED MISSING CLOSING BRACE FOR getBatteryInfo
328 |
329 | // Function to get battery temperature (tries multiple keys)
330 | float getBatteryTemperature(void) {
331 | float temperature = -999.0f; // Indicate failure
332 | BOOL success = NO;
333 |
334 | // Define potential keys
335 | uint32_t keysToTry[] = {
336 | ('T' << 24) + ('B' << 16) + ('0' << 8) + 'T', // TB0T
337 | ('T' << 24) + ('B' << 16) + ('1' << 8) + 'T', // TB1T
338 | ('T' << 24) + ('B' << 16) + ('2' << 8) + 'T', // TB2T
339 | ('T' << 24) + ('B' << 16) + ('3' << 8) + 'T', // TB3T
340 | ('T' << 24) + ('C' << 16) + ('0' << 8) + 'B' // TC0B (Another possible battery temp key)
341 | };
342 | int numKeys = sizeof(keysToTry) / sizeof(keysToTry[0]);
343 |
344 | for (int i = 0; i < numKeys; ++i) {
345 | success = getSMCSignedFixedPoint78Value(keysToTry[i], &temperature);
346 | // If the SMC call itself succeeded, return the value immediately.
347 | if (success) {
348 | return temperature; // Found a valid reading
349 | }
350 | }
351 |
352 | // If loop finishes without returning, all SMC calls failed for these keys.
353 | return -999.0f; // Return failure indicator
354 | }
355 |
356 | // Function to get battery cycle count
357 | uint16_t getBatteryCycleCount(void) {
358 | uint16_t cycles = 0xFFFF; // Indicate failure
359 | uint32_t cycleKey = ('B' << 24) + ('0' << 16) + ('C' << 8) + 'T'; // B0CT (ui16)
360 | getSMCUInt16Value(cycleKey, &cycles);
361 | return cycles;
362 | }
363 |
364 | // Function to get adapter voltage (Reads DVR as ui16)
365 | float getAdapterVoltage(void) {
366 | int8_t activePort = 0; // Default to port 0
367 | uint32_t winnerPortKey = ('A' << 24) + ('C' << 16) + ('-' << 8) + 'W'; // AC-W (si8)
368 | getSMCSInt8Value(winnerPortKey, &activePort);
369 |
370 | // Ensure port index is within a reasonable range (e.g., 0-4)
371 | if (activePort < 0 || activePort > 4) {
372 | activePort = 0;
373 | }
374 |
375 | uint16_t voltage_mV = 0;
376 | float voltage_V = -1.0f; // Indicate failure
377 | // Construct key dynamically: DVR
378 | uint32_t voltageKey = ('D' << 24) + ((uint32_t)('0' + activePort) << 16) + ('V' << 8) + 'R';
379 |
380 | if (getSMCUInt16Value(voltageKey, &voltage_mV)) {
381 | voltage_V = (float)voltage_mV / 1000.0f;
382 | }
383 | // Return -1.0f if read failed, otherwise the voltage (likely 20.000)
384 | return voltage_V;
385 | }
386 |
387 | // Function to get adapter amperage (Calculated from Real-Time Power and Reported Voltage)
388 | float getAdapterAmperage(void) {
389 | float power = getAdapterPower(); // Get real-time power (PDTR)
390 | float voltage = getAdapterVoltage(); // Get reported voltage (DVR)
391 |
392 | float current_A = -1.0f; // Indicate failure
393 |
394 | // Check if both readings were likely successful and voltage is usable
395 | // Use PDTR / DVR as DIR seems to report max rated current, not real-time.
396 | if (power >= 0 && voltage > 0.1f) { // Allow power to be 0
397 | current_A = power / voltage; // Calculate Amps = Watts / Volts
398 | }
399 |
400 | return current_A;
401 | }
402 |
403 |
404 | void printUsage(const char* programName) {
405 | printf("Usage: %s [options]\n", programName);
406 | printf("Options:\n");
407 | printf(" -h Display this help message\n");
408 | printf(" -c Continuous monitoring (press Ctrl+C to stop)\n");
409 | printf(" -i Interval between measurements in seconds (default: 1, requires -c)\n");
410 | printf(" -r Raw output (just the number, no text)\n");
411 | printf(" -v Verbose output with timestamp\n");
412 | }
413 |
414 | int main(int argc, const char * argv[]) {
415 | @autoreleasepool {
416 | // Default settings
417 | BOOL continuousMode = NO;
418 | BOOL rawOutput = NO;
419 | BOOL verboseOutput = NO;
420 | int interval = 1; // Default interval in seconds
421 |
422 | // Parse command line arguments
423 | int opt;
424 | while ((opt = getopt(argc, (char *const *)argv, "hci:rv")) != -1) {
425 | switch (opt) {
426 | case 'h':
427 | printUsage(argv[0]);
428 | return EXIT_SUCCESS;
429 | case 'c':
430 | continuousMode = YES;
431 | break;
432 | case 'i':
433 | interval = atoi(optarg);
434 | if (interval < 1) interval = 1;
435 | break;
436 | case 'r':
437 | rawOutput = YES;
438 | break;
439 | case 'v':
440 | verboseOutput = YES;
441 | break;
442 | default:
443 | printUsage(argv[0]);
444 | return EXIT_FAILURE;
445 | }
446 | }
447 |
448 | // Single measurement mode
449 | if (!continuousMode) {
450 | // --- Get All Metrics ---
451 | float systemPower = getRawSystemPower();
452 | float adapterPower = getAdapterPower();
453 | float adapterVoltage = getAdapterVoltage();
454 | float adapterAmperage = getAdapterAmperage();
455 | BatteryInfo batteryInfo = getBatteryInfo();
456 |
457 | // Get raw battery V/A again for direct display
458 | uint16_t batteryVoltage_mV = 0;
459 | int16_t batteryAmperage_mA = 0;
460 | BOOL batteryVoltageSuccess = getSMCUInt16Value(('B' << 24) + ('0' << 16) + ('A' << 8) + 'V', &batteryVoltage_mV);
461 | BOOL batteryAmperageSuccess = getSMCSInt16Value(('B' << 24) + ('0' << 16) + ('A' << 8) + 'C', &batteryAmperage_mA);
462 |
463 | // --- Success Flags ---
464 | BOOL systemSuccess = systemPower > 0;
465 | BOOL adapterPowerSuccess = adapterPower > 0;
466 | BOOL adapterVoltageSuccess = adapterVoltage >= 0;
467 | BOOL adapterAmperageSuccess = adapterAmperage >= 0;
468 | BOOL batteryInfoSuccess = batteryInfo.status != BATTERY_STATUS_FAILED; // Covers calculated power/status
469 | // Use the direct V/A success flags for their display
470 |
471 | // --- Format Strings ---
472 | const char* batteryStatusStr;
473 | switch (batteryInfo.status) {
474 | case BATTERY_STATUS_CHARGING: batteryStatusStr = "Charging"; break;
475 | case BATTERY_STATUS_DISCHARGING: batteryStatusStr = "Discharging"; break;
476 | case BATTERY_STATUS_IDLE: batteryStatusStr = "Idle"; break;
477 | default: batteryStatusStr = "Failed"; break;
478 | }
479 |
480 | printf("sys_power=%s adapter_power=%s adapter_voltage=%s adapter_amperage=%s battery_power=%s battery_voltage=%s battery_amperage=%s battery_status=%s\n",
481 | systemSuccess ? [[NSString stringWithFormat:@"%.2fW", systemPower] UTF8String] : "Failed",
482 | adapterPowerSuccess ? [[NSString stringWithFormat:@"%.2fW", adapterPower] UTF8String] : "Failed",
483 | adapterVoltageSuccess ? [[NSString stringWithFormat:@"%.3fV", adapterVoltage] UTF8String] : "Failed", // Changed to %.3fV
484 | adapterAmperageSuccess ? [[NSString stringWithFormat:@"%.3fA", adapterAmperage] UTF8String] : "Failed",
485 | batteryInfoSuccess ? [[NSString stringWithFormat:@"%.2fW", batteryInfo.powerWatts] UTF8String] : "N/A",
486 | batteryVoltageSuccess ? [[NSString stringWithFormat:@"%.3fV", (float)batteryVoltage_mV / 1000.0f] UTF8String] : "Failed",
487 | batteryAmperageSuccess ? [[NSString stringWithFormat:@"%.3fA", (float)batteryAmperage_mA / 1000.0f] UTF8String] : "Failed",
488 | batteryStatusStr
489 | );
490 |
491 | // Exit successfully if system power reading worked (as a basic check)
492 | return systemSuccess ? EXIT_SUCCESS : EXIT_FAILURE;
493 | }
494 |
495 | // Continuous monitoring mode
496 | if (!rawOutput) {
497 | printf("Continuous power monitoring (Ctrl+C to stop)\n");
498 | if (interval > 1) {
499 | printf("Interval: %d seconds\n", interval);
500 | }
501 | printf("-------------------------------------------\n");
502 | }
503 |
504 | NSDateFormatter *dateFormatter = nil;
505 | if (verboseOutput) {
506 | dateFormatter = [[NSDateFormatter alloc] init];
507 | [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
508 | }
509 |
510 | while (1) {
511 | // --- Get All Metrics ---
512 | float systemPower = getRawSystemPower();
513 | float adapterPower = getAdapterPower();
514 | float adapterVoltage = getAdapterVoltage();
515 | float adapterAmperage = getAdapterAmperage();
516 | BatteryInfo batteryInfo = getBatteryInfo();
517 |
518 | // Get raw battery V/A again for direct display
519 | uint16_t batteryVoltage_mV = 0;
520 | int16_t batteryAmperage_mA = 0;
521 | BOOL batteryVoltageSuccess = getSMCUInt16Value(('B' << 24) + ('0' << 16) + ('A' << 8) + 'V', &batteryVoltage_mV);
522 | BOOL batteryAmperageSuccess = getSMCSInt16Value(('B' << 24) + ('0' << 16) + ('A' << 8) + 'C', &batteryAmperage_mA);
523 |
524 | // --- Success Flags ---
525 | BOOL systemSuccess = systemPower > 0;
526 | BOOL adapterPowerSuccess = adapterPower > 0;
527 | BOOL adapterVoltageSuccess = adapterVoltage >= 0;
528 | BOOL adapterAmperageSuccess = adapterAmperage >= 0;
529 | BOOL batteryInfoSuccess = batteryInfo.status != BATTERY_STATUS_FAILED; // Covers calculated power/status
530 | // Use the direct V/A success flags for their display
531 |
532 | // --- Format Strings ---
533 | const char* batteryStatusStr;
534 | switch (batteryInfo.status) {
535 | case BATTERY_STATUS_CHARGING: batteryStatusStr = "Charging"; break;
536 | case BATTERY_STATUS_DISCHARGING: batteryStatusStr = "Discharging"; break;
537 | case BATTERY_STATUS_IDLE: batteryStatusStr = "Idle"; break;
538 | default: batteryStatusStr = "Failed"; break;
539 | }
540 |
541 | printf("sys_power=%s adapter_power=%s adapter_voltage=%s adapter_amperage=%s battery_power=%s battery_voltage=%s battery_amperage=%s battery_status=%s\n",
542 | systemSuccess ? [[NSString stringWithFormat:@"%.2fW", systemPower] UTF8String] : "Failed",
543 | adapterPowerSuccess ? [[NSString stringWithFormat:@"%.2fW", adapterPower] UTF8String] : "Failed",
544 | adapterVoltageSuccess ? [[NSString stringWithFormat:@"%.2fV", adapterVoltage] UTF8String] : "Failed", // Changed to %.3fV
545 | adapterAmperageSuccess ? [[NSString stringWithFormat:@"%.3fA", adapterAmperage] UTF8String] : "Failed",
546 | batteryInfoSuccess ? [[NSString stringWithFormat:@"%.2fW", batteryInfo.powerWatts] UTF8String] : "N/A",
547 | batteryVoltageSuccess ? [[NSString stringWithFormat:@"%.3fV", (float)batteryVoltage_mV / 1000.0f] UTF8String] : "Failed",
548 | batteryAmperageSuccess ? [[NSString stringWithFormat:@"%.3fA", (float)batteryAmperage_mA / 1000.0f] UTF8String] : "Failed",
549 | batteryStatusStr
550 | );
551 |
552 | fflush(stdout); // Ensure output is immediate
553 | sleep(interval);
554 | }
555 | }
556 | }
557 | // Removed extra closing brace here
558 |
--------------------------------------------------------------------------------
/app/PowerFlowView.swift:
--------------------------------------------------------------------------------
1 | // Power Management Suite - Power Flow Visualization View
2 | // Copyright (C) 2025
3 | //
4 | // This program is free software: you can redistribute it and/or modify
5 | // it under the terms of the GNU General Public License as published by
6 | // the Free Software Foundation, either version 3 of the License, or
7 | // (at your option) any later version.
8 | //
9 | // This program is distributed in the hope that it will be useful,
10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | // GNU General Public License for more details.
13 | //
14 | // You should have received a copy of the GNU General Public License
15 | // along with this program. If not, see .
16 |
17 | import SwiftUI
18 | /// A `PreferenceKey` used to measure and report the width of the middle flow section
19 | /// in the `PowerFlowView`. This allows the animation width to adapt dynamically.
20 | struct WidthPreferenceKey: PreferenceKey {
21 | /// The default width value.
22 | static var defaultValue: CGFloat = 0
23 | /// Combines multiple reported width values, using the maximum.
24 | static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
25 | // Use the maximum width reported, in case of multiple reports (though unlikely here)
26 | value = max(value, nextValue())
27 | }
28 | }
29 |
30 | /// A SwiftUI `View` that visualizes the flow of power between the power adapter,
31 | /// the battery, and the system load (laptop).
32 | ///
33 | /// It displays icons for each component and uses animated, shaped connectors
34 | /// to represent the direction and magnitude of power flow.
35 | struct PowerFlowView: View {
36 | /// The power currently being supplied by the adapter in Watts.
37 | let inputPower: Double
38 | /// The power flowing into (+) or out of (-) the battery in Watts.
39 | let batteryPower: Double
40 | /// The power currently being consumed by the system in Watts.
41 | let systemLoad: Double
42 |
43 | // MARK: - Configuration Constants
44 | /// The size of the icons used (power plug, battery, laptop).
45 | private let iconSize: CGFloat = 15
46 | /// The standard height of the flow connector sections.
47 | private let flowHeight: CGFloat = 40
48 | /// The spacing between the main view components (icons and flow).
49 | private let spacing: CGFloat = 5
50 | /// The corner radius used for the squircle shapes.
51 | private let cornerRadius: CGFloat = 12
52 |
53 | // MARK: - Color Constants (Currently Unused - Consider Applying)
54 | /// Color intended for battery charging flow.
55 | private let batteryChargeColor: Color = .green
56 | /// Color intended for battery discharging flow.
57 | private let batteryDischargeColor: Color = .orange
58 | /// Color intended for system load flow.
59 | private let systemLoadColor: Color = .red
60 |
61 | // MARK: - State Variables
62 | /// The measured width of the middle flow section, used for animations. Updated via `WidthPreferenceKey`.
63 | @State private var middleSectionWidth: CGFloat = 10 // Default non-zero width
64 |
65 | /// State flag to control the animation highlight on the charging-related icons/flows.
66 | @State private var animateCharge = false
67 | /// State flag to control the animation highlight on the load-related icons/flows.
68 | @State private var animateLoad = false
69 | /// State variable controlling the animated width of the flow gradient.
70 | @State private var animateFlowWidth: CGFloat = 0
71 | /// State variable controlling the color of the animated flow gradient.
72 | @State private var animateFlowColor = Color.yellow.opacity(0.8)
73 | /// Timer responsible for driving the repeating flow animation cycle.
74 | @State private var animationTimer: Timer? = nil
75 |
76 | /// The main body of the power flow visualization view.
77 | var body: some View {
78 | HStack(spacing: spacing) {
79 | VStack(alignment: .leading, spacing: flowHeight, content: {
80 | if inputPower > 0.01 {
81 | ZStack {
82 | // corners: [TL, TR, BR, BL]
83 | generateSquircle(width: iconSize + 20, height: batteryPower > 0 ? flowHeight * 1.5 : flowHeight, radius: cornerRadius, corners: [true, false, false, true])
84 | .fill(.ultraThickMaterial)
85 | Image(systemName: "powerplug.portrait")
86 | .font(.system(size: iconSize))
87 | .foregroundColor(animateCharge ? Color.yellow : Color.black)
88 | .offset(x: 1, y: 0)
89 | }
90 | .frame(width: iconSize + 20, height: batteryPower > 0 ? flowHeight * 1.5 : flowHeight) // Apply frame to the ZStack, conditional height
91 | }
92 |
93 | if batteryPower < 0 {
94 | ZStack {
95 | // corners: [TL, TR, BR, BL]
96 | generateSquircle(width: iconSize + 20, height: flowHeight, radius: cornerRadius, corners: [true, false, false, true])
97 | .fill(.ultraThickMaterial)
98 | Image(systemName: batteryPower > 0 ? "battery.100.bolt" : (batteryPower < 0 ? "battery.75" : "battery.100")) // Simple icon logic
99 | .font(.system(size: iconSize))
100 | .foregroundColor(animateCharge ? Color.orange : Color.black)
101 | .offset(x: 1, y: 0)
102 | }
103 | .frame(width: iconSize + 20, height: flowHeight) // Apply frame to the ZStack
104 | }
105 | })
106 |
107 | // Middle Flow Section - Measure width using PreferenceKey
108 | Group {
109 | if inputPower > 0.01 {
110 | if batteryPower == 0 {
111 | ZStack {
112 | ZStack(alignment: .leading, content: {
113 | Rectangle()
114 | .fill(.ultraThickMaterial)
115 | .frame(height: flowHeight)
116 | .background(GeometryReader { geometry in
117 | Color.clear.preference(key: WidthPreferenceKey.self, value: geometry.size.width)
118 | })
119 | Rectangle()
120 | .fill(
121 | LinearGradient(
122 | gradient: Gradient(colors: [Color.clear, animateFlowColor]),
123 | startPoint: .leading,
124 | endPoint: .trailing
125 | )
126 | )
127 | .blur(radius: 1.5)
128 | .offset(x: 0)
129 | .frame(width: animateFlowWidth, height: flowHeight)
130 | })
131 | Text(String(format: "%.2f", inputPower) + " W").font(.system(size: 13)).frame(alignment: .trailing)
132 | }
133 | } else if batteryPower > 0 {
134 | VStack(alignment: .center, spacing: 0) {
135 | ZStack {
136 | ZStack(alignment: .leading, content: {
137 | Rectangle()
138 | .fill(.ultraThickMaterial)
139 | .frame(width: middleSectionWidth, height: flowHeight * 1.5)
140 | .clipShape(
141 | flowShape(width: middleSectionWidth, height: flowHeight * 1.5,
142 | startLength: flowHeight * 0.75, endLength: flowHeight, direction: 1)
143 | )
144 | Rectangle()
145 | .fill(
146 | LinearGradient(
147 | gradient: Gradient(colors: [Color.clear, animateFlowColor]),
148 | startPoint: .leading,
149 | endPoint: .trailing
150 | )
151 | )
152 | .blur(radius: 1.5)
153 | .offset(x: 0)
154 | .frame(width: animateFlowWidth, height: flowHeight * 1.5)
155 | .clipShape(
156 | flowShape(width: middleSectionWidth, height: flowHeight * 1.5,
157 | startLength: flowHeight * 0.75, endLength: flowHeight, direction: 1)
158 | )
159 | })
160 | Text(String(format: "%.2f", batteryPower) + " W").font(.system(size: 13)).frame(alignment: .trailing)
161 |
162 | }
163 |
164 | ZStack {
165 | ZStack(alignment: .leading, content: {
166 | Rectangle()
167 | .fill(.ultraThickMaterial)
168 | .frame(width: middleSectionWidth, height: flowHeight * 1.5)
169 | .clipShape(
170 | flowShape(width: middleSectionWidth, height: flowHeight * 1.5,
171 | startLength: flowHeight * 0.75, endLength: flowHeight, direction: 0)
172 | )
173 | Rectangle()
174 | .fill(
175 | LinearGradient(
176 | gradient: Gradient(colors: [Color.clear, animateFlowColor]),
177 | startPoint: .leading,
178 | endPoint: .trailing
179 | )
180 | )
181 | .blur(radius: 1.5)
182 | .offset(x: 0)
183 | .frame(width: animateFlowWidth, height: flowHeight * 1.5)
184 | .clipShape(
185 | flowShape(width: middleSectionWidth, height: flowHeight * 1.5,
186 | startLength: flowHeight * 0.75, endLength: flowHeight, direction: 0)
187 | )
188 | })
189 | Text(String(format: "%.2f", systemLoad) + " W").font(.system(size: 13)).frame(alignment: .trailing)
190 | }
191 | }
192 | // .background(GeometryReader { geometry in
193 | // Color.clear.preference(key: WidthPreferenceKey.self, value: geometry.size.width)
194 | // })
195 | } else { // batteryPower < 0
196 | // Similar pattern for negative battery power
197 | VStack(alignment: .center, spacing: 0) {
198 | ZStack {
199 | ZStack(alignment: .leading, content: {
200 | Rectangle()
201 | .fill(.ultraThickMaterial)
202 | .frame(width: middleSectionWidth, height: flowHeight * 1.5)
203 | .clipShape(
204 | flowShape(width: middleSectionWidth, height: flowHeight * 1.5,
205 | startLength: flowHeight, endLength: flowHeight * 0.75, direction: 0)
206 | )
207 | Rectangle()
208 | .fill(
209 | LinearGradient(
210 | gradient: Gradient(colors: [Color.clear, animateFlowColor]),
211 | startPoint: .leading,
212 | endPoint: .trailing
213 | )
214 | )
215 | .blur(radius: 1.5)
216 | .offset(x: 0)
217 | .frame(width: animateFlowWidth, height: flowHeight * 1.5)
218 | .clipShape(
219 | flowShape(width: middleSectionWidth, height: flowHeight * 1.5,
220 | startLength: flowHeight, endLength: flowHeight * 0.75, direction: 0)
221 | )
222 | })
223 | Text(String(format: "%.2f", inputPower) + " W").font(.system(size: 13)).frame(alignment: .trailing)
224 | }
225 |
226 | ZStack {
227 | ZStack(alignment: .leading, content: {
228 | Rectangle()
229 | .fill(.ultraThickMaterial)
230 | .frame(width: middleSectionWidth, height: flowHeight * 1.5)
231 | .clipShape(
232 | flowShape(width: middleSectionWidth, height: flowHeight * 1.5,
233 | startLength: flowHeight, endLength: flowHeight * 0.75, direction: 1)
234 | )
235 | Rectangle()
236 | .fill(
237 | LinearGradient(
238 | gradient: Gradient(colors: [Color.clear, animateFlowColor]),
239 | startPoint: .leading,
240 | endPoint: .trailing
241 | )
242 | )
243 | .blur(radius: 1.5)
244 | .offset(x: 0)
245 | .frame(width: animateFlowWidth, height: flowHeight * 1.5)
246 | .clipShape(
247 | flowShape(width: middleSectionWidth, height: flowHeight * 1.5,
248 | startLength: flowHeight, endLength: flowHeight * 0.75, direction: 1)
249 | )
250 | })
251 | Text(String(format: "%.2f", batteryPower * -1) + " W").font(.system(size: 13)).frame(alignment: .trailing)
252 | }
253 | }
254 | // .background(GeometryReader { geometry in
255 | // Color.clear.preference(key: WidthPreferenceKey.self, value: geometry.size.width)
256 | // })
257 | }
258 | } else {
259 | ZStack {
260 | ZStack(alignment: .leading, content: {
261 | Rectangle()
262 | .fill(.ultraThickMaterial)
263 | .frame(height: flowHeight)
264 | .background(GeometryReader { geometry in
265 | Color.clear.preference(key: WidthPreferenceKey.self, value: geometry.size.width)
266 | })
267 | Rectangle()
268 | .fill(
269 | LinearGradient(
270 | gradient: Gradient(colors: [Color.clear, animateFlowColor]),
271 | startPoint: .leading,
272 | endPoint: .trailing
273 | )
274 | )
275 | .blur(radius: 1.5)
276 | .offset(x: 0)
277 | .frame(width: animateFlowWidth, height: flowHeight)
278 | })
279 | Text(String(format: "%.2f", batteryPower * -1) + " W").font(.system(size: 13)).frame(alignment: .trailing)
280 | }
281 | }
282 | }
283 |
284 | VStack(alignment: .trailing, spacing: flowHeight, content: {
285 | // Battery Icon (conditional)
286 | if batteryPower > 0 {
287 | ZStack {
288 | // corners: [TL, TR, BR, BL]
289 | generateSquircle(width: iconSize + 20, height: flowHeight, radius: cornerRadius, corners: [false, true, true, false])
290 | .fill(.ultraThickMaterial)
291 |
292 | Image(systemName: batteryPower > 0 ? "battery.100.bolt" : (batteryPower < 0 ? "battery.75" : "battery.100")) // Simple icon logic
293 | .font(.system(size: iconSize))
294 | .foregroundColor(animateLoad ? Color.green : Color.black)
295 | .offset(x: -1, y: 0)
296 | }
297 | .frame(width: iconSize + 20, height: flowHeight) // Apply frame to the ZStack
298 | }
299 |
300 | // System Load Icon (Laptop)
301 | ZStack {
302 | // corners: [TL, TR, BR, BL]
303 | generateSquircle(width: iconSize + 20, height: (batteryPower < 0 && inputPower > 0.01) ? flowHeight * 1.5 : flowHeight, radius: cornerRadius, corners: [false, true, true, false])
304 | .fill(.ultraThickMaterial)
305 |
306 | Image(systemName: "laptopcomputer")
307 | .font(.system(size: iconSize))
308 | .foregroundColor(animateLoad ? Color.blue : Color.black)
309 | .offset(x: -1, y: 0)
310 | }
311 | .frame(width: iconSize + 20, height: (batteryPower < 0 && inputPower > 0.01) ? flowHeight * 1.5 : flowHeight) // Apply frame to the ZStack
312 | }).frame(width: iconSize + 20)
313 |
314 | }
315 | // Replace the problematic onAppear block with this macOS-compatible version
316 | .onAppear {
317 | // Force width calculation on initial appearance
318 | DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
319 | // Use the available space if not already set
320 | if middleSectionWidth <= 10 {
321 | // Use NSScreen instead of UIScreen for macOS
322 | let screenWidth = NSScreen.main?.frame.width ?? 800 // Default fallback
323 | // Estimate the parent width (adjust multiplier as needed)
324 | let parentWidth = screenWidth * 0.4 - ((iconSize + 20) * 2) - (spacing * 2)
325 | middleSectionWidth = max(parentWidth, 50) // Ensure minimum width
326 | }
327 | }
328 |
329 | DispatchQueue.main.async {
330 | animateFlowWidth = 0
331 | animateFlowColor = Color.yellow.opacity(0.8)
332 | withAnimation(.easeOut(duration: 1.0)) {
333 | animateCharge = true
334 | animateLoad = false
335 | }
336 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
337 | withAnimation(.easeIn(duration: 1.0)) {
338 | animateCharge = false
339 | }
340 | withAnimation(.linear(duration: 1.0)) {
341 | animateFlowWidth = middleSectionWidth / 2
342 | }
343 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
344 | withAnimation(.easeOut(duration: 0.5)) {
345 | animateFlowColor = Color.blue.opacity(0.8)
346 | }
347 | withAnimation(.linear(duration: 1.0)) {
348 | animateFlowWidth = middleSectionWidth
349 | }
350 | }
351 | DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
352 | // Only toggle if the timer hasn't been invalidated yet
353 | withAnimation(.easeOut(duration: 1.0)) {
354 | animateFlowColor = Color.clear
355 | animateLoad = true
356 | }
357 | }
358 | }
359 | }
360 |
361 | // Create a repeating animation cycle with no delay between expansions
362 | animationTimer = Timer.scheduledTimer(withTimeInterval: 4.0, repeats: true) { _ in
363 | // Immediately start the next expansion animation
364 | DispatchQueue.main.async {
365 | animateFlowWidth = 0
366 | animateFlowColor = Color.yellow.opacity(0.8)
367 | withAnimation(.easeOut(duration: 1.0)) {
368 | animateCharge = true
369 | animateLoad = false
370 | }
371 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
372 | withAnimation(.easeIn(duration: 1.0)) {
373 | animateCharge = false
374 | }
375 | withAnimation(.linear(duration: 1.0)) {
376 | animateFlowWidth = middleSectionWidth / 2
377 | }
378 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
379 | withAnimation(.easeOut(duration: 0.5)) {
380 | animateFlowColor = Color.blue.opacity(0.8)
381 | }
382 | withAnimation(.linear(duration: 1.0)) {
383 | animateFlowWidth = middleSectionWidth
384 | }
385 | }
386 | DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
387 | // Only toggle if the timer hasn't been invalidated yet
388 | withAnimation(.easeOut(duration: 1.0)) {
389 | animateFlowColor = Color.clear
390 | animateLoad = true
391 | }
392 | }
393 | }
394 | }
395 | }
396 | }
397 | .onDisappear {
398 | // Clean up timer when view disappears
399 | animationTimer?.invalidate()
400 | animationTimer = nil
401 | }
402 | // Keep the existing onPreferenceChange
403 | .onPreferenceChange(WidthPreferenceKey.self) { width in
404 | if width > 10 { // Avoid updating with very small values
405 | self.middleSectionWidth = width
406 | }
407 | }
408 | }
409 | }
410 |
411 | // DocC comments for generateSquircle are already present. Skipping this block.
412 | func generateSquircle(width: CGFloat, height: CGFloat, radius: CGFloat, corners: [Bool]) -> Path {
413 | precondition(corners.count == 4, "Corners array must contain exactly 4 boolean values (TL, TR, BR, BL)")
414 | var path = Path() // Changed from NSBezierPath
415 |
416 | // --- Constants defining the reference squircle shape ---
417 | // These likely represent control point offsets for a reference radius
418 | let f5: CGFloat = 63.0000 // Outer edge offset?
419 | let f4: CGFloat = 36.7519 // Control point offset?
420 | let f3: CGFloat = 23.6278 // Control point offset?
421 | let f2: CGFloat = 14.4275 // Endpoint offset?
422 | let f1: CGFloat = 6.6844 // Endpoint offset?
423 | let f0: CGFloat = 0.0 // Origin/Zero offset
424 |
425 | // Constants for the middle curve segment's control points
426 | let a0: CGFloat = 11.457
427 | let a1: CGFloat = 8.843
428 |
429 | let refRadius: CGFloat = 35 // The radius for which the above constants were defined
430 |
431 | // --- Scale constants based on desired radius ---
432 | let ratio: CGFloat = radius / refRadius // Avoid division by zero if radius is 0? Consider max(radius, 0.001) / refRadius
433 |
434 | let s0 = f0 * ratio
435 | let s1 = f1 * ratio
436 | let s2 = f2 * ratio
437 | let s3 = f3 * ratio
438 | let s4 = f4 * ratio
439 | let s5 = f5 * ratio
440 |
441 | let s6 = a0 * ratio // Scaled a0
442 | let s7 = a1 * ratio // Scaled a1
443 |
444 | // --- Calculate coordinates relative to width/height ---
445 | // 's' prefix usually means relative to origin (0,0)
446 | // 'w' prefix means relative to width (x-axis)
447 | // 'h' prefix means relative to height (y-axis)
448 | let w0 = width - s0
449 | let w1 = width - s1
450 | let w2 = width - s2
451 | let w3 = width - s3
452 | let w4 = width - s4
453 | let w5 = width - s5
454 | let w6 = width - s6 // width - scaled a0
455 | let w7 = width - s7 // width - scaled a1
456 |
457 | let h0 = height - s0
458 | let h1 = height - s1
459 | let h2 = height - s2
460 | let h3 = height - s3
461 | let h4 = height - s4
462 | let h5 = height - s5
463 | let h6 = height - s6 // height - scaled a0
464 | let h7 = height - s7 // height - scaled a1
465 |
466 | // --- Construct the Path ---
467 | // Start at bottom-left edge, just above the corner
468 | path.move(to: CGPoint(x: s0, y: s5)) // Changed from NSPoint
469 |
470 | let tl = corners[0]
471 | let tr = corners[1]
472 | let br = corners[2]
473 | let bl = corners[3]
474 | if bl {
475 | // Bottom-left corner (3 curves)
476 | path.addCurve(to: CGPoint(x: s1, y: s2), control1: CGPoint(x: s0, y: s4), control2: CGPoint(x: s0, y: s3)) // Changed from NSPoint & path.curve
477 | path.addCurve(to: CGPoint(x: s2, y: s1), control1: CGPoint(x: s7, y: s6), control2: CGPoint(x: s6, y: s7)) // Changed from NSPoint & path.curve
478 | path.addCurve(to: CGPoint(x: s5, y: s0), control1: CGPoint(x: s3, y: s0), control2: CGPoint(x: s4, y: s0)) // Changed from NSPoint & path.curve
479 | } else {
480 | path.addLine(to: CGPoint(x: s0, y: s0))
481 | path.addLine(to: CGPoint(x: s5, y: s0))
482 | }
483 |
484 | // Bottom edge
485 | path.addLine(to: CGPoint(x: w5, y: s0)) // Changed from NSPoint & path.line
486 |
487 | if br {
488 | // Bottom-right corner (3 curves)
489 | path.addCurve(to: CGPoint(x: w2, y: s1), control1: CGPoint(x: w4, y: s0), control2: CGPoint(x: w3, y: s0)) // Changed from NSPoint & path.curve
490 | path.addCurve(to: CGPoint(x: w1, y: s2), control1: CGPoint(x: w6, y: s7), control2: CGPoint(x: w7, y: s6)) // Changed from NSPoint & path.curve
491 | path.addCurve(to: CGPoint(x: w0, y: s5), control1: CGPoint(x: w0, y: s3), control2: CGPoint(x: w0, y: s4)) // Changed from NSPoint & path.curve
492 | } else {
493 | path.addLine(to: CGPoint(x: w0, y: s0))
494 | path.addLine(to: CGPoint(x: w0, y: s5))
495 | }
496 |
497 | // Right edge
498 | path.addLine(to: CGPoint(x: w0, y: h5)) // Changed from NSPoint & path.line
499 |
500 | if tr {
501 | // Top-right corner (3 curves)
502 | path.addCurve(to: CGPoint(x: w1, y: h2), control1: CGPoint(x: w0, y: h4), control2: CGPoint(x: w0, y: h3)) // Changed from NSPoint & path.curve
503 | path.addCurve(to: CGPoint(x: w2, y: h1), control1: CGPoint(x: w7, y: h6), control2: CGPoint(x: w6, y: h7)) // Changed from NSPoint & path.curve
504 | path.addCurve(to: CGPoint(x: w5, y: h0), control1: CGPoint(x: w3, y: h0), control2: CGPoint(x: w4, y: h0)) // Changed from NSPoint & path.curve
505 | } else {
506 | path.addLine(to: CGPoint(x: w0, y: h0))
507 | path.addLine(to: CGPoint(x: w5, y: h0))
508 | }
509 |
510 | // Top edge
511 | path.addLine(to: CGPoint(x: s5, y: h0)) // Changed from NSPoint & path.line
512 |
513 | if tl {
514 | // Top-left corner (3 curves)
515 | path.addCurve(to: CGPoint(x: s2, y: h1), control1: CGPoint(x: s4, y: h0), control2: CGPoint(x: s3, y: h0)) // Changed from NSPoint & path.curve
516 | path.addCurve(to: CGPoint(x: s1, y: h2), control1: CGPoint(x: s6, y: h7), control2: CGPoint(x: s7, y: h6)) // Changed from NSPoint & path.curve
517 | path.addCurve(to: CGPoint(x: s0, y: h5), control1: CGPoint(x: s0, y: h3), control2: CGPoint(x: s0, y: h4)) // Changed from NSPoint & path.curve
518 | } else {
519 | path.addLine(to: CGPoint(x: s0, y: h0))
520 | path.addLine(to: CGPoint(x: s0, y: h5))
521 | }
522 |
523 | path.closeSubpath() // Changed from path.close()
524 | return path
525 | }
526 |
527 | /// Creates a custom `Path` shape used for the flowing connectors between power components.
528 | ///
529 | /// This shape resembles a trapezoid with curved top and bottom edges, allowing it to smoothly
530 | /// connect sections of potentially different heights.
531 | ///
532 | /// - Parameters:
533 | /// - width: The width of the flow shape.
534 | /// - height: The total height of the flow shape.
535 | /// - startLength: The height of the vertical edge on the starting side (left).
536 | /// - endLength: The height of the vertical edge on the ending side (right).
537 | /// - direction: Determines the orientation of the curves. `0` for top curve, `1` for bottom curve.
538 | /// - Returns: A `Path` representing the flow connector shape.
539 | func flowShape(width: CGFloat, height: CGFloat, startLength: CGFloat, endLength: CGFloat, direction: Int) -> Path {
540 | var path = Path()
541 | if direction == 0 { // Top curve connects (0,0) to (width, height - endLength)
542 | path.move(to: CGPoint(x: 0, y: 0))
543 | let controlPoint1_x: CGFloat = width * 0.3 // Adjust control points for smoother curve
544 | let controlPoint1_y: CGFloat = 0
545 | let controlPoint2_x: CGFloat = width * 0.7
546 | let controlPoint2_y: CGFloat = height - endLength
547 | path.addCurve(to: CGPoint(x: width, y: height - endLength), control1: CGPoint(x: controlPoint1_x, y: controlPoint1_y), control2: CGPoint(x: controlPoint2_x, y: controlPoint2_y))
548 | path.addLine(to: CGPoint(x: width, y: height)) // Line down to bottom-right
549 | let controlPoint3_x: CGFloat = width * 0.7
550 | let controlPoint3_y: CGFloat = height
551 | let controlPoint4_x: CGFloat = width * 0.3
552 | let controlPoint4_y: CGFloat = startLength
553 | path.addCurve(to: CGPoint(x: 0, y: startLength), control1: CGPoint(x: controlPoint3_x, y: controlPoint3_y), control2: CGPoint(x: controlPoint4_x, y: controlPoint4_y)) // Curve back to start height
554 | path.closeSubpath()
555 | } else { // Bottom curve connects (0, height - startLength) to (width, 0)
556 | path.move(to: CGPoint(x: 0, y: height - startLength))
557 | let controlPoint1_x: CGFloat = width * 0.3
558 | let controlPoint1_y: CGFloat = height - startLength
559 | let controlPoint2_x: CGFloat = width * 0.7
560 | let controlPoint2_y: CGFloat = 0
561 | path.addCurve(to: CGPoint(x: width, y: 0), control1: CGPoint(x: controlPoint1_x, y: controlPoint1_y), control2: CGPoint(x: controlPoint2_x, y: controlPoint2_y))
562 | path.addLine(to: CGPoint(x: width, y: endLength)) // Line down to end height on right
563 | let controlPoint3_x: CGFloat = width * 0.7
564 | let controlPoint3_y: CGFloat = endLength
565 | let controlPoint4_x: CGFloat = width * 0.3
566 | let controlPoint4_y: CGFloat = height
567 | path.addCurve(to: CGPoint(x: 0, y: height), control1: CGPoint(x: controlPoint3_x, y: controlPoint3_y), control2: CGPoint(x: controlPoint4_x, y: controlPoint4_y)) // Curve back to bottom-left
568 | path.closeSubpath()
569 | }
570 | return path
571 | }
572 |
573 | /// Provides previews for the `PowerFlowView` in different power states.
574 | struct PowerFlowView_Previews: PreviewProvider {
575 | static var previews: some View {
576 | Group {
577 | // Example 1: Charging
578 | VStack {
579 | Text("Charging").font(.caption)
580 | PowerFlowView(inputPower: 60.5, batteryPower: 20.1, systemLoad: 40.4)
581 | }
582 | .padding()
583 | .background(Color(NSColor.windowBackgroundColor))
584 | .previewDisplayName("Charging")
585 |
586 | // Example 2: Discharging (On Battery)
587 | VStack {
588 | Text("Discharging (On Battery)").font(.caption)
589 | PowerFlowView(inputPower: 0, batteryPower: -15.2, systemLoad: 15.2)
590 | }
591 | .padding()
592 | .background(Color(NSColor.windowBackgroundColor))
593 | .previewDisplayName("Discharging")
594 |
595 | // Example 3: Adapter Powering System Only (Battery Full/Idle)
596 | VStack {
597 | Text("Adapter Powering System (Battery Idle)").font(.caption)
598 | PowerFlowView(inputPower: 30.0, batteryPower: 0, systemLoad: 30.0)
599 | }
600 | .padding()
601 | .background(Color(NSColor.windowBackgroundColor))
602 | .previewDisplayName("Adapter Only")
603 |
604 | // Example 4: Adapter + Battery Powering System (High Load)
605 | VStack {
606 | Text("Adapter + Battery Powering System").font(.caption)
607 | PowerFlowView(inputPower: 90.0, batteryPower: -10.0, systemLoad: 100.0)
608 | }
609 | .padding()
610 | .background(Color(NSColor.windowBackgroundColor))
611 | .previewDisplayName("Adapter + Battery")
612 | }
613 | .previewLayout(.sizeThatFits)
614 | }
615 | }
616 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic pattern
54 | of such abuse occurs in the area of products for individuals to use,
55 | which is precisely where it is most unacceptable. Therefore, we have
56 | designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work for
115 | making modifications to it. "Object code" means any non-source form of
116 | a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not permitted; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is released
218 | under this License and any conditions added under section 7. This
219 | requirement modifies the requirement in section 4 to "keep intact
220 | all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no permission
227 | to license the work in any other way, but it does not invalidate
228 | such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate". An aggregate does not cause this License to apply to the
240 | other parts of the aggregate.
241 |
242 | 6. Conveying Non-Source Forms.
243 |
244 | You may convey a covered work in object code form under the terms of
245 | sections 4 and 5, provided that you also convey the
246 | machine-readable Corresponding Source under the terms of this License,
247 | in one of these ways:
248 |
249 | a) Convey the object code in, or embodied in, a physical product
250 | (including a physical distribution medium), accompanied by the
251 | Corresponding Source fixed on a durable physical medium
252 | customarily used for software interchange.
253 |
254 | b) Convey the object code in, or embodied in, a physical product
255 | (including a physical distribution medium), accompanied by a
256 | written offer, valid for at least three years and valid for as
257 | long as you offer spare parts or customer support for that product
258 | model, to give anyone who possesses the object code either (1) a
259 | copy of the Corresponding Source for all the software in the
260 | product that is covered by this License, on a durable physical
261 | medium customarily used for software interchange, for a price no
262 | more than your reasonable cost of physically performing this
263 | conveyance of source, or (2) access to copy the
264 | Corresponding Source from a network server at no charge.
265 |
266 | c) Convey individual copies of the object code with a copy of the
267 | written offer to provide the Corresponding Source. This
268 | alternative is allowed only occasionally and noncommercially, and
269 | only if you received the object code with such an offer, in accord
270 | with subsection 6b.
271 |
272 | d) Convey the object code by offering access from a designated
273 | place (gratis or for a fee), and offer equivalent access to the
274 | Corresponding Source in the same way through the same place at no
275 | further charge. You need not require recipients to copy the
276 | Corresponding Source along with the object code. If the place to
277 | copy the object code is a network server, the Corresponding Source
278 | may be on a different server (operated by you or a third party)
279 | that supports equivalent copying facilities, provided you maintain
280 | clear directions next to the object code saying where to find the
281 | Corresponding Source. Regardless of what server hosts the
282 | Corresponding Source, you remain obligated to ensure that it is
283 | available for as long as needed to satisfy these requirements.
284 |
285 | e) Convey the object code using peer-to-peer transmission, provided
286 | you inform other peers where the object code and Corresponding
287 | Source of the work are being offered to the general public at no
288 | charge under subsection 6d.
289 |
290 | A separable portion of the object code, whose source code is excluded
291 | from the Corresponding Source as a System Library, need not be
292 | included in conveying the object code work.
293 |
294 | A "User Product" is either (1) a "consumer product", which means any
295 | tangible personal property which is normally used for personal, family,
296 | or household purposes, or (2) anything designed or sold for incorporation
297 | into a dwelling. In determining whether a product is a consumer product,
298 | doubtful cases shall be resolved in favor of coverage. For a particular
299 | product received by a particular user, "normally used" refers to a
300 | typical or common use of that class of product, regardless of the status
301 | of the particular user or of the way in which the particular user
302 | actually uses, or expects or is expected to use, the product. A product
303 | is a consumer product regardless of whether the product has substantial
304 | commercial, industrial or non-consumer uses, unless such uses represent
305 | the only significant mode of use of the product.
306 |
307 | "Installation Information" for a User Product means any methods,
308 | procedures, authorization keys, or other information required to install
309 | and execute modified versions of a covered work in that User Product from
310 | a modified version of its Corresponding Source. The information must
311 | suffice to ensure that the continued functioning of the modified object
312 | code is in no case prevented or interfered with solely because
313 | modification has been made.
314 |
315 | If you convey an object code work under this section in, or with, or
316 | specifically for use in, a User Product, and the conveying occurs as
317 | part of a transaction in which the right of possession and use of the
318 | User Product is transferred to the recipient in perpetuity or for a
319 | fixed term (regardless of how the transaction is characterized), the
320 | Corresponding Source conveyed under this section must be accompanied
321 | by the Installation Information. But this requirement does not apply
322 | if neither you nor any third party retains the ability to install
323 | modified object code on the User Product (for example, the work has
324 | been installed in ROM).
325 |
326 | The requirement to provide Installation Information does not include a
327 | requirement to continue to provide support service, warranty, or updates
328 | for a work that has been modified or installed by the recipient, or for
329 | the User Product in which it has been modified or installed. Access to a
330 | network may be denied when the modification itself materially and
331 | adversely affects the operation of the network or violates the rules and
332 | protocols for communication across the network.
333 |
334 | Corresponding Source conveyed, and Installation Information provided,
335 | in accord with this section must be in a format that is publicly
336 | documented (and with an implementation available to the public in
337 | source code form), and must require no special password or key for
338 | unpacking, reading or copying.
339 |
340 | 7. Additional Terms.
341 |
342 | "Additional permissions" are terms that supplement the terms of this
343 | License by making exceptions from one or more of its conditions.
344 | Additional permissions that are applicable to the entire Program shall
345 | be treated as though they were included in this License, to the extent
346 | that they are valid under applicable law. If additional permissions
347 | apply only to part of the Program, that part may be used separately
348 | under those permissions, but the entire Program remains governed by
349 | this License without regard to the additional permissions.
350 |
351 | When you convey a copy of a covered work, you may at your option
352 | remove any additional permissions from that copy, or from any part of
353 | it. (Additional permissions may be written to require their own
354 | removal in certain cases when you modify the work.) You may place
355 | additional permissions on material, added by you to a covered work,
356 | for which you have or can give appropriate copyright permission.
357 |
358 | Notwithstanding any other provision of this License, for material you
359 | add to a covered work, you may (if authorized by the copyright holders of
360 | that material) supplement the terms of this License with terms:
361 |
362 | a) Disclaiming warranty or limiting liability differently from the
363 | terms of sections 15 and 16 of this License; or
364 |
365 | b) Requiring preservation of specified reasonable legal notices or
366 | author attributions in that material or in the Appropriate Legal
367 | Notices displayed by works containing it; or
368 |
369 | c) Prohibiting misrepresentation of the origin of that material, or
370 | requiring that modified versions of such material be marked in
371 | reasonable ways as different from the original version; or
372 |
373 | d) Limiting the use for publicity purposes of names of licensors or
374 | authors of the material; or
375 |
376 | e) Declining to grant rights under trademark law for use of some
377 | trade names, trademarks, or service marks; or
378 |
379 | f) Requiring indemnification of licensors and authors of that
380 | material by anyone who conveys the material (or modified versions of
381 | it) with contractual assumptions of liability to the recipient, for
382 | any liability that these contractual assumptions directly impose on
383 | those licensors and authors.
384 |
385 | All other non-permissive additional terms are considered "further
386 | restrictions" within the meaning of section 10. If the Program as you
387 | received it, or any part of it, contains a notice stating that it is
388 | governed by this License along with a term that is a further
389 | restriction, you may remove that term. If a license document contains
390 | a further restriction but permits relicensing or conveying under this
391 | License, you may add to a covered work material governed by the terms
392 | of that license document, provided that the further restriction does
393 | not survive such relicensing or conveying.
394 |
395 | If you add terms to a covered work in accord with this section, you
396 | must place, in the relevant source files, a statement of the
397 | additional terms that apply to those files, or a notice indicating
398 | where to find the applicable terms.
399 |
400 | Additional terms, permissive or non-permissive, may be stated in the
401 | form of a separately written license, or stated as exceptions;
402 | the above requirements apply either way.
403 |
404 | 8. Termination.
405 |
406 | You may not propagate or modify a covered work except as expressly
407 | provided under this License. Any attempt otherwise to propagate or
408 | modify it is void, and will automatically terminate your rights under
409 | this License (including any patent licenses granted under the third
410 | paragraph of section 11).
411 |
412 | However, if you cease all violation of this License, then your
413 | license from a particular copyright holder is reinstated (a)
414 | provisionally, unless and until the copyright holder explicitly and
415 | finally terminates your license, and (b) permanently, if the copyright
416 | holder fails to notify you of the violation by some reasonable means
417 | prior to 60 days after the cessation.
418 |
419 | Moreover, your license from a particular copyright holder is
420 | reinstated permanently if the copyright holder notifies you of the
421 | violation by some reasonable means, this is the first time you have
422 | received notice of violation of this License (for any work) from that
423 | copyright holder, and you cure the violation prior to 30 days after
424 | your receipt of the notice.
425 |
426 | Termination of your rights under this section does not terminate the
427 | licenses of parties who have received copies or rights from you under
428 | this License. If your rights have been terminated and not permanently
429 | reinstated, you do not qualify to receive new licenses for the same
430 | material under section 10.
431 |
432 | 9. Acceptance Not Required for Having Copies.
433 |
434 | You are not required to accept this License in order to receive or
435 | run a copy of the Program. Ancillary propagation of a covered work
436 | occurring solely as a consequence of using peer-to-peer transmission
437 | to receive a copy likewise does not require acceptance. However,
438 | nothing other than this License grants you permission to propagate or
439 | modify any covered work. These actions infringe copyright if you do
440 | not accept this License. Therefore, by modifying or propagating a
441 | covered work, you indicate your acceptance of this License to do so.
442 |
443 | 10. Automatic Licensing of Downstream Recipients.
444 |
445 | Each time you convey a covered work, the recipient automatically
446 | receives a license from the original licensors, to run, modify and
447 | propagate that work, subject to this License. You are not responsible
448 | for enforcing compliance by third parties with this License.
449 |
450 | An "entity transaction" is a transaction transferring control of an
451 | organization, or substantially all assets of one, or subdividing an
452 | organization, or merging organizations. If propagation of a covered
453 | work results from an entity transaction, each party to that
454 | transaction who receives a copy of the work also receives whatever
455 | licenses to the work the party's predecessor in interest had or could
456 | give under the previous paragraph, plus a right to possession of the
457 | Corresponding Source of the work from the predecessor in interest, if
458 | the predecessor has it or can get it with reasonable efforts.
459 |
460 | You may not impose any further restrictions on the exercise of the
461 | rights granted or affirmed under this License. For example, you may
462 | not impose a license fee, royalty, or other charge for exercise of
463 | rights granted under this License, and you may not initiate litigation
464 | (including a cross-claim or counterclaim in a lawsuit) alleging that
465 | any patent claim is infringed by making, using, selling, offering for
466 | sale, or importing the Program or any portion of it.
467 |
468 | 11. Patents.
469 |
470 | A "contributor" is a copyright holder who authorizes use under this
471 | License of the Program or a work on which the Program is based. The
472 | work thus licensed is called the contributor's "contributor version".
473 |
474 | A contributor's "essential patent claims" are all patent claims
475 | owned or controlled by the contributor, whether already acquired or
476 | hereafter acquired, that would be infringed by some manner, permitted
477 | by this License, of making, using, or selling its contributor version,
478 | but do not include claims that would be infringed only as a
479 | consequence of further modification of the contributor version. For
480 | purposes of this definition, "control" includes the right to grant
481 | patent sublicenses in a manner consistent with the requirements of
482 | this License.
483 |
484 | Each contributor grants you a non-exclusive, worldwide, royalty-free
485 | patent license under the contributor's essential patent claims, to
486 | make, use, sell, offer for sale, import and otherwise run, modify and
487 | propagate the contents of its contributor version.
488 |
489 | In the following three paragraphs, a "patent license" is any express
490 | agreement or commitment, however denominated, not to enforce a patent
491 | (such as an express permission to practice a patent or covenant not to
492 | sue for patent infringement). To "grant" such a patent license to a
493 | party means to make such an agreement or commitment not to enforce a
494 | patent against the party.
495 |
496 | If you convey a covered work, knowingly relying on a patent license,
497 | and the Corresponding Source of the work is not available for anyone
498 | to copy, free of charge and under the terms of this License, through a
499 | publicly available network server or other readily accessible means,
500 | then you must either (1) cause the Corresponding Source to be so
501 | available, or (2) arrange to deprive yourself of the benefit of the
502 | patent license for this particular work, or (3) arrange, in a manner
503 | consistent with the requirements of this License, to extend the patent
504 | license to downstream recipients. "Knowingly relying" means you have
505 | actual knowledge that, but for the patent license, your conveying the
506 | covered work in a country, or your recipient's use of the covered work
507 | in a country, would infringe one or more identifiable patents in that
508 | country that you have reason to believe are valid.
509 |
510 | If, pursuant to or in connection with a single transaction or
511 | arrangement, you convey, or propagate by procuring conveyance of, a
512 | covered work, and grant a patent license to some of the parties
513 | receiving the covered work authorizing them to use, propagate, modify
514 | or convey a specific copy of the covered work, then the patent license
515 | you grant is automatically extended to all recipients of the covered
516 | work and works based on it.
517 |
518 | A patent license is "discriminatory" if it does not include within
519 | the scope of its coverage, prohibits the exercise of, or is
520 | conditioned on the non-exercise of one or more of the rights that are
521 | specifically granted under this License. You may not convey a covered
522 | work if you are a party to an arrangement with a third party who is
523 | in the business of distributing software, under which you make payment
524 | to the third party based on the extent of your activity of conveying
525 | the work, and under which the third party grants, to any of the
526 | parties who would receive the covered work from you, a discriminatory
527 | patent license (a) in connection with copies of the covered work
528 | conveyed by you (or copies made from those copies), or (b) primarily
529 | for and in connection with specific products or compilations that
530 | contain the covered work, unless you entered into that arrangement,
531 | or that patent license was granted, prior to 28 March 2007.
532 |
533 | Nothing in this License shall be construed as excluding or limiting
534 | any implied license or other defenses to infringement that may
535 | otherwise be available to you under applicable patent law.
536 |
537 | 12. No Surrender of Others' Freedom.
538 |
539 | If conditions are imposed on you (whether by court order, agreement or
540 | otherwise) that contradict the conditions of this License, they do not
541 | excuse you from the conditions of this License. If you cannot convey a
542 | covered work so as to satisfy simultaneously your obligations under this
543 | License and any other pertinent obligations, then as a consequence you may
544 | not convey it at all. For example, if you agree to terms that obligate you
545 | to collect a royalty for further conveying from those to whom you convey
546 | the Program, the only way you could satisfy both those terms and this
547 | License would be to refrain entirely from conveying the Program.
548 |
549 | 13. Use with the GNU Affero General Public License.
550 |
551 | Notwithstanding any other provision of this License, you have
552 | permission to link or combine any covered work with a work licensed
553 | under version 3 of the GNU Affero General Public License into a single
554 | combined work, and to convey the resulting work. The terms of this
555 | License will continue to apply to the part which is the covered work,
556 | but the special requirements of the GNU Affero General Public License,
557 | section 13, concerning interaction through a network will apply to the
558 | combination as such.
559 |
560 | 14. Revised Versions of this License.
561 |
562 | The Free Software Foundation may publish revised and/or new versions of
563 | the GNU General Public License from time to time. Such new versions will
564 | be similar in spirit to the present version, but may differ in detail to
565 | address new problems or concerns.
566 |
567 | Each version is given a distinguishing version number. If the
568 | Program specifies that a certain numbered version of the GNU General
569 | Public License "or any later version" applies to it, you have the
570 | option of following the terms and conditions either of that numbered
571 | version or of any later version published by the Free Software
572 | Foundation. If the Program does not specify a version number of the
573 | GNU General Public License, you may choose any version ever published
574 | by the Free Software Foundation.
575 |
576 | If the Program specifies that a proxy can decide which future
577 | versions of the GNU General Public License can be used, that proxy's
578 | public statement of acceptance of a version permanently authorizes you
579 | to choose that version for the Program.
580 |
581 | Later license versions may give you additional or different
582 | permissions. However, no additional obligations are imposed on any
583 | author or copyright holder as a result of your choosing to follow a
584 | later version.
585 |
586 | 15. Disclaimer of Warranty.
587 |
588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
591 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
592 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
593 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
594 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
595 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
596 |
597 | 16. Limitation of Liability.
598 |
599 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
600 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
601 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
602 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
603 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
604 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
605 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
606 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
607 | SUCH DAMAGES.
608 |
609 | 17. Interpretation of Sections 15 and 16.
610 |
611 | If the disclaimer of warranty and limitation of liability provided
612 | above cannot be given local legal effect according to their terms,
613 | reviewing courts shall apply local law that most closely approximates
614 | an absolute waiver of all civil liability in connection with the
615 | Program, unless a warranty or assumption of liability accompanies a
616 | copy of the Program in return for a fee.
617 |
618 | END OF TERMS AND CONDITIONS
619 |
620 | How to Apply These Terms to Your New Programs
621 |
622 | If you develop a new program, and you want it to be of the greatest
623 | possible use to the public, the best way to achieve this is to make it
624 | free software which everyone can redistribute and change under these terms.
625 |
626 | To do so, attach the following notices to the program. It is safest
627 | to attach them to the start of each source file to most effectively
628 | state the exclusion of warranty; and each file should have at least
629 | the "copyright" line and a pointer to where the full notice is found.
630 |
631 |
632 | Copyright (C)
633 |
634 | This program is free software: you can redistribute it and/or modify
635 | it under the terms of the GNU General Public License as published by
636 | the Free Software Foundation, either version 3 of the License, or
637 | (at your option) any later version.
638 |
639 | This program is distributed in the hope that it will be useful,
640 | but WITHOUT ANY WARRANTY; without even the implied warranty of
641 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
642 | GNU General Public License for more details.
643 |
644 | You should have received a copy of the GNU General Public License
645 | along with this program. If not, see .
646 |
647 | Also add information on how to contact you by electronic and paper mail.
648 |
649 | If the program does terminal interaction, make it output a short
650 | notice like this when it starts in an interactive mode:
651 |
652 | Copyright (C)
653 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
654 | This is free software, and you are welcome to redistribute it
655 | under certain conditions; type `show c' for details.
656 |
657 | The hypothetical commands `show w' and `show c' should show the appropriate
658 | parts of the General Public License. Of course, your program's commands
659 | might be different; for a GUI interface, you would use an "about box".
660 |
661 | You should also get your employer (if you work as a programmer) or school,
662 | if any, to sign a "copyright disclaimer" for the program, if necessary.
663 | For more information on this, and how to apply and follow the GNU GPL, see
664 | .
665 |
666 | The GNU General Public License does not permit incorporating your program
667 | into proprietary programs. If your program is a subroutine library, you
668 | may consider it more useful to permit linking proprietary applications with
669 | the library. If this is what you want to do, use the GNU Lesser General
670 | Public License instead of this License. But first, please read
671 | .
--------------------------------------------------------------------------------