perf(menubar): 降低绘制驻留并复用原生进程表与缩略图
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
@main struct NativeMetricDrawingChecks {
|
||||
@MainActor static func main() {
|
||||
_ = NSApplication.shared; NSApp.setActivationPolicy(.accessory)
|
||||
Task { @MainActor in
|
||||
let window = NSWindow(contentRect: NSRect(x: 40, y: 40, width: 300, height: 140), styleMask: [.borderless], backing: .buffered, defer: false)
|
||||
window.isReleasedWhenClosed = false
|
||||
let root = NSView(frame: NSRect(x: 0, y: 0, width: 300, height: 140))
|
||||
window.contentView = root
|
||||
let plot = NativePanelCurve.PlotView(); plot.frame = NSRect(x: 0, y: 0, width: 280, height: 60)
|
||||
root.addSubview(plot)
|
||||
let ring = NativeMetricRing.RingView(); ring.frame = NSRect(x: 0, y: 70, width: 28, height: 28)
|
||||
root.addSubview(ring)
|
||||
window.orderFrontRegardless()
|
||||
try? await Task.sleep(for: .milliseconds(100))
|
||||
let dates = (0..<4).map { Date(timeIntervalSinceReferenceDate: Double($0 * 2)) }
|
||||
func input(_ values: [Double?]) -> NativePanelCurve.Input {
|
||||
NativePanelCurve.Input(frame: PanelCurveFrame(dates: dates, series: [values], intervals: [2,2,2,2], boundaryDates: []), colors: [.red], scales: [1], maximumGap: 5)
|
||||
}
|
||||
let continuous = input([0.8,0.8,0.8,0.8])
|
||||
plot.configure(continuous)
|
||||
let image = bitmap(plot)
|
||||
precondition(redPixels(image, from: 0.4, to: 0.6) > 10, "Continuous curve must cross the middle")
|
||||
plot.needsDisplay = false; plot.configure(continuous)
|
||||
precondition(!plot.needsDisplay, "Identical inputs must not invalidate the plot")
|
||||
plot.configure(input([0.8,0.8,nil,0.8]))
|
||||
precondition(redPixels(bitmap(plot), from: 0.4, to: 0.6) == 0, "Missing values must leave a real gap")
|
||||
plot.configure(input([nil,nil,nil,nil]))
|
||||
precondition(redPixels(bitmap(plot)) == 0)
|
||||
var hovered = continuous; hovered.hoveredIndex = 1
|
||||
plot.configure(hovered)
|
||||
precondition(redPixels(bitmap(plot)) > 0)
|
||||
plot.appearance = NSAppearance(named: .darkAqua)
|
||||
precondition(redPixels(bitmap(plot)) > 0)
|
||||
ring.configure(NativeMetricRing.Input(value: 0, color: .red, lineWidth: 3, trackOpacity: 0.17, inset: 2))
|
||||
precondition(redPixels(bitmap(ring), opaque: true) == 0, "Zero ring must not draw a colored arc")
|
||||
ring.configure(NativeMetricRing.Input(value: 0.25, color: .red, lineWidth: 3, trackOpacity: 0.17, inset: 2))
|
||||
let quarter = redPixels(bitmap(ring), opaque: true)
|
||||
ring.configure(NativeMetricRing.Input(value: 1, color: .red, lineWidth: 3, trackOpacity: 0.17, inset: 2))
|
||||
let full = redPixels(bitmap(ring), opaque: true)
|
||||
precondition(quarter > 0 && full > quarter * 2, "Ring fraction must change the rendered arc")
|
||||
window.orderOut(nil); window.close()
|
||||
print("PASS: native curve pixels, real gaps, missing series, hover, appearance, duplicate-input invalidation and zero/quarter/full ring pixels")
|
||||
fflush(stdout); NSApp.terminate(nil)
|
||||
}
|
||||
NSApp.run()
|
||||
}
|
||||
@MainActor private static func bitmap(_ view: NSView) -> NSBitmapImageRep {
|
||||
let result = view.bitmapImageRepForCachingDisplay(in: view.bounds)!
|
||||
view.cacheDisplay(in: view.bounds, to: result)
|
||||
return result
|
||||
}
|
||||
private static func redPixels(_ image: NSBitmapImageRep, from: Double = 0, to: Double = 1, opaque: Bool = false) -> Int {
|
||||
var count = 0
|
||||
for x in Int(Double(image.pixelsWide) * from)..<Int(Double(image.pixelsWide) * to) {
|
||||
for y in 0..<image.pixelsHigh {
|
||||
guard let color = image.colorAt(x: x, y: y)?.usingColorSpace(.deviceRGB) else { continue }
|
||||
if color.redComponent > color.greenComponent + 0.15 && color.redComponent > color.blueComponent + 0.15 && color.alphaComponent > (opaque ? 0.8 : 0.01) { count += 1 }
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import Observation
|
||||
|
||||
@MainActor @Observable private final class State {
|
||||
var rows: [ProcessMetrics]
|
||||
var selection: ProcessIdentity?
|
||||
var sorting = [ProcessSort(key: .cpu)]
|
||||
var locale = Locale(identifier: "en")
|
||||
var insideDelegate = false
|
||||
var exits = 0
|
||||
init() {
|
||||
rows = (0..<500).map { index in
|
||||
ProcessMetrics(id: ProcessIdentity(pid: Int32(index + 1), seconds: 1, microseconds: 0),
|
||||
name: "worker-\(index)", path: nil, cpu: Double(index) / 100,
|
||||
residentBytes: 10_000_000, threads: 2, restricted: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
private struct Host: View {
|
||||
let state: State
|
||||
var body: some View {
|
||||
NativeProcessTable(rows: state.rows, selection: Binding(get: { state.selection }, set: {
|
||||
precondition(!state.insideDelegate, "Selection published inside an AppKit delegate callback")
|
||||
state.selection = $0
|
||||
}), sorting: Binding(get: { state.sorting }, set: {
|
||||
precondition(!state.insideDelegate, "Sort published inside an AppKit delegate callback")
|
||||
state.sorting = $0
|
||||
}), locale: state.locale, onExit: { state.exits += 1 }).frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
@MainActor private final class DelegateProbe: NSObject, NSTableViewDelegate {
|
||||
let state: State
|
||||
let target: NativeProcessTable.Coordinator
|
||||
init(_ state: State, _ target: NativeProcessTable.Coordinator) { self.state = state; self.target = target }
|
||||
func tableViewSelectionDidChange(_ notification: Notification) {
|
||||
state.insideDelegate = true
|
||||
target.tableViewSelectionDidChange(notification)
|
||||
state.insideDelegate = false
|
||||
}
|
||||
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
|
||||
state.insideDelegate = true
|
||||
target.tableView(tableView, sortDescriptorsDidChange: oldDescriptors)
|
||||
state.insideDelegate = false
|
||||
}
|
||||
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
|
||||
target.tableView(tableView, viewFor: tableColumn, row: row)
|
||||
}
|
||||
}
|
||||
@main struct NativeProcessTableChecks {
|
||||
@MainActor static func main() {
|
||||
_ = NSApplication.shared; NSApp.setActivationPolicy(.accessory)
|
||||
Task { @MainActor in
|
||||
let state = State()
|
||||
let window = NSWindow(contentRect: NSRect(x: 30, y: 30, width: 900, height: 260), styleMask: [.titled], backing: .buffered, defer: false)
|
||||
window.isReleasedWhenClosed = false
|
||||
let host = NSHostingView(rootView: Host(state: state))
|
||||
window.contentView = host; window.makeKeyAndOrderFront(nil)
|
||||
try? await Task.sleep(for: .milliseconds(200))
|
||||
let table = find(host)!
|
||||
let coordinator = table.delegate as! NativeProcessTable.Coordinator
|
||||
let probe = DelegateProbe(state, coordinator)
|
||||
table.delegate = probe
|
||||
precondition(table.numberOfRows == 500 && table.tableColumns.count == 6)
|
||||
precondition(table.frame.width >= table.enclosingScrollView!.contentSize.width - 1, "Native table must fill its viewport")
|
||||
precondition(coordinator.createdCells > 0 && coordinator.createdCells < 200, "Rows must be virtualized")
|
||||
let chosen = state.rows[10].id
|
||||
table.selectRowIndexes(IndexSet(integer: 10), byExtendingSelection: false)
|
||||
precondition(state.selection == nil, "Native selection must be deferred")
|
||||
await until { state.selection == chosen }
|
||||
state.rows.reverse()
|
||||
await until { table.selectedRow == 489 }
|
||||
precondition(state.selection == chosen, "Selection must follow identity after reordering")
|
||||
for index in 0..<12 {
|
||||
state.rows[0] = ProcessMetrics(id: state.rows[0].id, name: "updated-\(index)", path: nil, cpu: Double(index), residentBytes: nil, threads: nil, restricted: false)
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
let visible = table.rows(in: table.visibleRect)
|
||||
if visible.location != NSNotFound, visible.length > 0,
|
||||
let cell = table.view(atColumn: 1, row: visible.location, makeIfNecessary: false) as? NSTableCellView {
|
||||
precondition(cell.textField?.stringValue == state.rows[visible.location].name)
|
||||
} else { preconditionFailure("No visible native cell") }
|
||||
precondition(coordinator.createdCells < 250, "Refreshes must reuse visible cells")
|
||||
table.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
|
||||
await until { state.sorting == [ProcessSort(key: .name, order: .forward)] }
|
||||
let menu = coordinator.menu(row: 0)!
|
||||
precondition(menu.items.count == 3 && menu.items[0].representedObject as? String == String(state.rows[0].id.pid))
|
||||
precondition(menu.items[1].representedObject as? String == state.rows[0].name && !menu.items[2].isEnabled)
|
||||
state.rows.removeAll { $0.id == chosen }
|
||||
await until { table.numberOfRows == 499 && table.selectedRow == -1 }
|
||||
precondition(state.selection == chosen, "Filtering/removal must not invent a new selected identity")
|
||||
state.selection = nil
|
||||
state.locale = Locale(identifier: "zh-Hans")
|
||||
await until { table.tableColumns[1].title == "名称" }
|
||||
state.rows.removeAll(); await until { table.numberOfRows == 0 }
|
||||
precondition(window.makeFirstResponder(table))
|
||||
let escape = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime,
|
||||
windowNumber: window.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", isARepeat: false, keyCode: 53)!
|
||||
window.sendEvent(escape)
|
||||
await until { state.exits == 1 }
|
||||
window.orderOut(nil); window.close()
|
||||
print("PASS: real native table virtualization/reuse, deferred delegate writes, identity selection, sorting, copy menu, missing paths, removal, locale and in-window Esc event routing")
|
||||
fflush(stdout); NSApp.terminate(nil)
|
||||
}
|
||||
NSApp.run()
|
||||
}
|
||||
@MainActor private static func until(_ predicate: () -> Bool, line: UInt = #line) async {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||||
while !predicate() && ContinuousClock.now < deadline { try? await Task.sleep(for: .milliseconds(20)) }
|
||||
precondition(predicate(), "Timed out waiting for native table update at line \(line)")
|
||||
}
|
||||
@MainActor private static func find(_ view: NSView) -> NSTableView? {
|
||||
if let table = view as? NSTableView { return table }
|
||||
for child in view.subviews { if let table = find(child) { return table } }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
@main struct NetworkAddressChecks {
|
||||
static func main() {
|
||||
var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
func check(_ address: UnsafePointer<sockaddr>) {
|
||||
var original = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
let rc = getnameinfo(address, socklen_t(address.pointee.sa_len), &original, socklen_t(original.count), nil, 0, NI_NUMERICHOST)
|
||||
let expected = rc == 0 ? String(cString: original) : nil
|
||||
let value = NetworkMonitor.numericAddress(address, buffer: &buffer)
|
||||
precondition(value == expected, "Canonical numeric address / scope changed")
|
||||
}
|
||||
let loop = if_nametoindex("lo0")
|
||||
var v4 = sockaddr_in(); v4.sin_len = UInt8(MemoryLayout.size(ofValue: v4)); v4.sin_family = UInt8(AF_INET)
|
||||
precondition(inet_pton(AF_INET, "192.0.2.1", &v4.sin_addr) == 1)
|
||||
withUnsafePointer(to: &v4) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { check($0) } }
|
||||
for text in ["::1", "2001:db8::1", "::ffff:192.0.2.1", "fe80::1"] {
|
||||
var v6 = sockaddr_in6(); v6.sin6_len = UInt8(MemoryLayout.size(ofValue: v6)); v6.sin6_family = UInt8(AF_INET6)
|
||||
precondition(inet_pton(AF_INET6, text, &v6.sin6_addr) == 1)
|
||||
for scope in [UInt32(0), loop, UInt32.max] {
|
||||
v6.sin6_scope_id = scope
|
||||
withUnsafePointer(to: &v6) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
|
||||
check($0)
|
||||
var empty: [CChar] = []
|
||||
precondition(NetworkMonitor.numericAddress($0, buffer: &empty) == nil)
|
||||
} }
|
||||
}
|
||||
}
|
||||
var head: UnsafeMutablePointer<ifaddrs>?
|
||||
precondition(getifaddrs(&head) == 0)
|
||||
defer { freeifaddrs(head) }
|
||||
var cursor = head, count = 0
|
||||
while let entry = cursor {
|
||||
defer { cursor = entry.pointee.ifa_next }
|
||||
guard let address = entry.pointee.ifa_addr, [UInt8(AF_INET), UInt8(AF_INET6)].contains(address.pointee.sa_family) else { continue }
|
||||
check(UnsafePointer(address))
|
||||
count += 1
|
||||
}
|
||||
precondition(count > 0)
|
||||
print("PASS: sandbox IPv4/IPv6, known/unknown scopes, mapped addresses, empty buffer and canonical equivalence for", count, "live addresses (values omitted)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import AppKit
|
||||
|
||||
@main struct ProcessIconCacheChecks {
|
||||
@MainActor static func main() {
|
||||
var reads = 0, now: TimeInterval = 1
|
||||
let cache = ProcessIconCache(resolve: { _ in
|
||||
reads += 1
|
||||
return NSImage(size: NSSize(width: 1024, height: 1024), flipped: false) { bounds in
|
||||
NSColor.systemBlue.setFill(); bounds.fill(); return true
|
||||
}
|
||||
}, clock: { now })
|
||||
let first = cache.image(for: "/Applications/Example.app/Contents/MacOS/main")!
|
||||
let second = cache.image(for: "/Applications/Example.app/Contents/Helpers/worker")!
|
||||
precondition(first === second && reads == 1, "Executables in the same app must share a thumbnail")
|
||||
let bitmap = first.representations.first as! NSBitmapImageRep
|
||||
precondition(first.size == NSSize(width: 15, height: 15) && bitmap.pixelsWide == 30 && bitmap.pixelsHigh == 30)
|
||||
precondition(first.representations.count == 1 && cache.pixelBytes <= 4096)
|
||||
precondition(bitmap.colorAt(x: 15, y: 15)!.alphaComponent > 0.9, "Thumbnail must retain rendered pixels")
|
||||
now = 32
|
||||
let renewed = cache.image(for: "/Applications/Example.app/Contents/MacOS/main")!
|
||||
precondition(renewed !== first && reads == 2 && cache.count == 1)
|
||||
for index in 0..<200 { _ = cache.image(for: "/test/\(index)/worker") }
|
||||
precondition(cache.count == 128 && cache.pixelBytes <= ProcessIconCache.pixelLimit)
|
||||
let before = reads
|
||||
_ = cache.image(for: "/test/199/worker")
|
||||
precondition(reads == before, "Recent entry must survive eviction")
|
||||
_ = cache.image(for: "/test/0/worker")
|
||||
precondition(reads == before + 1, "Evicted entry must be resolved again")
|
||||
cache.removeAll()
|
||||
precondition(cache.count == 0 && cache.pixelBytes == 0)
|
||||
print("PASS: app-shared raster thumbnails, pixel content/dimensions, expiry, strict bounds, LRU and explicit clearing")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
enum PanelResourceAudit { static let omitted = "" }
|
||||
Reference in New Issue
Block a user