Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ public final class CmuxResolvedIconImageView: NSView {

private struct RenderKey: Equatable {
private let source: SourceKey
private let fallbackSource: SourceKey?
private let canReuseRenderedImage: Bool
private let width: CGFloat
private let height: CGFloat
Expand All @@ -106,7 +107,12 @@ public final class CmuxResolvedIconImageView: NSView {

init(request: CmuxResolvedIconRequest, appearance: NSAppearance) {
self.source = SourceKey(request.source)
self.fallbackSource = request.fallbackSource.map(SourceKey.init)
// Any mutable source disables key reuse. This applies to the
// fallback as well: the public request can carry an NSImage whose
// representations change in place between updates.
self.canReuseRenderedImage = source.canReuseRenderedImage
&& (fallbackSource?.canReuseRenderedImage ?? true)
self.width = request.size.width
self.height = request.size.height
self.tint = request.tintColor
Expand All @@ -121,6 +127,7 @@ public final class CmuxResolvedIconImageView: NSView {

func matchesRequestAndAppearance(_ other: RenderKey) -> Bool {
source == other.source &&
fallbackSource == other.fallbackSource &&
width == other.width &&
height == other.height &&
symbolWeight == other.symbolWeight &&
Expand Down Expand Up @@ -148,6 +155,7 @@ public final class CmuxResolvedIconImageView: NSView {
case systemSymbol(name: String, accessibilityDescription: String?)
case asset(name: String, bundle: ObjectIdentifier)
case image(ObjectIdentifier)
case workspaceIcon(String)

init(_ source: CmuxResolvedIconSource) {
switch source {
Expand All @@ -157,13 +165,17 @@ public final class CmuxResolvedIconImageView: NSView {
self = .asset(name: name, bundle: ObjectIdentifier(bundle))
case .image(let image):
self = .image(ObjectIdentifier(image))
case .workspaceIcon(let type):
self = .workspaceIcon(type.identifier)
}
}

var canReuseRenderedImage: Bool {
switch self {
case .systemSymbol, .asset:
return true
case .workspaceIcon:
return true
case .image:
return false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,44 +32,54 @@ public final class CmuxResolvedIconRenderer {
}
var output: NSImage?
var failure = CmuxResolvedIconRenderFailure.sourceUnavailable
var sources = [request.source]
if let fallbackSource = request.fallbackSource {
sources.append(fallbackSource)
}
appearance.performAsCurrentDrawingAppearance {
guard let sourceImage = resolvedSourceImage(for: request),
let bitmap = bitmapRepresentation(size: imageSize) else {
failure = .sourceUnavailable
return
}
bitmap.size = imageSize
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap)
defer { NSGraphicsContext.restoreGraphicsState() }
for source in sources {
guard let sourceImage = resolvedSourceImage(for: source, request: request),
let bitmap = bitmapRepresentation(size: imageSize) else {
continue
}
bitmap.size = imageSize
guard let graphicsContext = NSGraphicsContext(bitmapImageRep: bitmap) else {
continue
}
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = graphicsContext

NSColor.clear.setFill()
NSRect(origin: .zero, size: imageSize).fill()
NSGraphicsContext.current?.imageInterpolation = .high
NSColor.clear.setFill()
NSRect(origin: .zero, size: imageSize).fill()
NSGraphicsContext.current?.imageInterpolation = .high

let drawRect = drawingRect(for: sourceImage.size, in: imageSize)
sourceImage.draw(
in: drawRect,
from: .zero,
operation: .sourceOver,
fraction: 1,
respectFlipped: true,
hints: nil
)
let drawRect = drawingRect(for: sourceImage.size, in: imageSize)
sourceImage.draw(
in: drawRect,
from: .zero,
operation: .sourceOver,
fraction: 1,
respectFlipped: true,
hints: nil
)

if let tintColor = request.tintColor {
tintColor.setFill()
NSRect(origin: .zero, size: imageSize).fill(using: .sourceAtop)
}
guard containsVisiblePixels(in: bitmap) else {
failure = .blankOutput
if let tintColor = request.tintColor {
tintColor.setFill()
NSRect(origin: .zero, size: imageSize).fill(using: .sourceAtop)
}
let isVisible = containsVisiblePixels(in: bitmap)
NSGraphicsContext.restoreGraphicsState()
guard isVisible else {
failure = .blankOutput
continue
}
let rendered = NSImage(size: imageSize)
rendered.addRepresentation(bitmap)
rendered.cacheMode = .never
rendered.isTemplate = false
output = rendered
return
}
let rendered = NSImage(size: imageSize)
rendered.addRepresentation(bitmap)
rendered.cacheMode = .never
rendered.isTemplate = false
output = rendered
}
if let output {
return .success(output)
Expand All @@ -87,8 +97,11 @@ public final class CmuxResolvedIconRenderer {
return representation.representation(using: .png, properties: [:])
}

private func resolvedSourceImage(for request: CmuxResolvedIconRequest) -> NSImage? {
switch request.source {
private func resolvedSourceImage(
for source: CmuxResolvedIconSource,
request: CmuxResolvedIconRequest
) -> NSImage? {
switch source {
case .systemSymbol(let name, let accessibilityDescription):
guard let baseImage = NSImage(
systemSymbolName: name,
Expand All @@ -112,6 +125,8 @@ public final class CmuxResolvedIconRenderer {
case .image(let image):
image.recache()
return copiedImage(image)
case .workspaceIcon(let type):
return copiedImage(NSWorkspace.shared.icon(for: type))
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ public import AppKit
public struct CmuxResolvedIconRequest {
/// The source image to resolve and draw.
public let source: CmuxResolvedIconSource
/// Optional source used when the primary source is unavailable or draws
/// no visible pixels during an AppKit lifecycle transition.
public let fallbackSource: CmuxResolvedIconSource?
/// Final icon size in points.
public let size: NSSize
/// Optional explicit tint. When set, the source alpha is used as the mask.
Expand All @@ -17,6 +20,7 @@ public struct CmuxResolvedIconRequest {
/// Creates an icon render request.
/// - Parameters:
/// - source: Source image to resolve.
/// - fallbackSource: Source to try when `source` is unavailable or blank.
/// - size: Final icon size in points.
/// - tintColor: Optional tint applied while drawing under the effective appearance.
/// - symbolWeight: SF Symbol weight for symbol sources.
Expand All @@ -26,9 +30,11 @@ public struct CmuxResolvedIconRequest {
size: NSSize,
tintColor: NSColor? = nil,
symbolWeight: NSFont.Weight = .regular,
accessibilityDescription: String? = nil
accessibilityDescription: String? = nil,
fallbackSource: CmuxResolvedIconSource? = nil
) {
self.source = source
self.fallbackSource = fallbackSource
self.size = size
self.tintColor = tintColor
self.symbolWeight = symbolWeight
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
public import AppKit
public import Foundation
public import UniformTypeIdentifiers

/// Source image for a small cmux UI icon that must be resolved through AppKit.
@MainActor
Expand All @@ -10,4 +11,10 @@ public enum CmuxResolvedIconSource {
case asset(name: String, bundle: Bundle)
/// An already-created image. The renderer copies it before sizing or drawing.
case image(NSImage)
/// A Finder/system image resolved by `NSWorkspace` for a Uniform Type.
///
/// Resolving this source inside the renderer keeps the workspace image out
/// of SwiftUI's view construction and gives the image view a stable source
/// identity without sharing a mutable `NSImage` singleton.
case workspaceIcon(UTType)
}
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,83 @@ import Testing
#expect(renderedImage(in: view) == nil)
}

/// A concrete fallback keeps an icon visible when the primary provider
/// returns a transparent bitmap during its first AppKit draw.
@Test func rendererUsesFallbackAfterBlankPrimaryOutput() throws {
let renderer = CmuxResolvedIconRenderer()
let blankSource = NSImage(size: NSSize(width: 16, height: 16))
blankSource.addRepresentation(transparentBitmapRepresentation(pixels: 16))
let visibleFallback = NSImage(size: NSSize(width: 16, height: 16))
visibleFallback.addRepresentation(solidBitmapRepresentation(color: .systemBlue, pixels: 16))
let appearance = try #require(NSAppearance(named: .aqua))

let result = renderer.render(
for: CmuxResolvedIconRequest(
source: .image(blankSource),
size: NSSize(width: 16, height: 16),
fallbackSource: .image(visibleFallback)
),
appearance: appearance
)

guard case .success(let image) = result else {
Issue.record("A visible fallback should recover a blank primary icon")
return
}
#expect(visiblePixelCount(in: image) > 0)
}

/// Workspace-backed fallbacks resolve lazily in the renderer and retain
/// Finder's concrete folder artwork without sharing a mutable NSImage.
@Test func rendererUsesWorkspaceIconFallback() throws {
let renderer = CmuxResolvedIconRenderer()
let appearance = try #require(NSAppearance(named: .aqua))

let result = renderer.render(
for: CmuxResolvedIconRequest(
source: .systemSymbol(name: "not.a.real.symbol", accessibilityDescription: nil),
size: NSSize(width: 16, height: 16),
tintColor: .secondaryLabelColor,
fallbackSource: .workspaceIcon(.folder)
),
appearance: appearance
)

guard case .success(let image) = result else {
Issue.record("The workspace folder fallback should render visible pixels")
return
}
#expect(visiblePixelCount(in: image) > 0)
}

/// A mutable fallback is re-read instead of being hidden behind a stable
/// primary-source cache key.
@Test func imageViewRerendersWhenFallbackImageChangesInPlace() throws {
let view = CmuxResolvedIconImageView(frame: NSRect(x: 0, y: 0, width: 16, height: 16))
view.appearance = NSAppearance(named: .aqua)
let fallbackImage = NSImage(size: NSSize(width: 16, height: 16))
let representation = solidBitmapRepresentation(color: .systemRed, pixels: 16)
fallbackImage.addRepresentation(representation)
let request = CmuxResolvedIconRequest(
source: .asset(name: "missing-icon", bundle: .main),
size: NSSize(width: 16, height: 16),
fallbackSource: .image(fallbackImage)
)

view.apply(request)
let firstImage = try #require(renderedImage(in: view))
let firstPixel = try #require(centerPixelColor(in: firstImage))
#expect(firstPixel.redComponent > firstPixel.blueComponent)

fill(representation, color: .systemBlue, operation: .copy)
view.apply(request)
let updatedImage = try #require(renderedImage(in: view))
let updatedPixel = try #require(centerPixelColor(in: updatedImage))

#expect(updatedImage !== firstImage)
#expect(updatedPixel.blueComponent > updatedPixel.redComponent)
}

private func solidBitmapRepresentation(color: NSColor, pixels: Int) -> NSBitmapImageRep {
let representation = NSBitmapImageRep(
bitmapDataPlanes: nil,
Expand Down
38 changes: 35 additions & 3 deletions Sources/RenderableSystemSymbol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,12 @@ enum RenderableSystemSymbol {
guard let bitmap = materializedBitmap(source, size: size, pixelScale: pixelScale) else {
return nil
}
// A symbol provider can resolve successfully while still drawing
// a transparent bitmap during an AppKit window/appearance pass.
// Never put that transient result in the process-wide cache.
guard containsVisiblePixels(in: bitmap) else {
return nil
}
image.addRepresentation(bitmap)
}
image.cacheMode = .never
Expand Down Expand Up @@ -293,6 +299,22 @@ enum RenderableSystemSymbol {
return bitmap
}

/// Reports whether a bitmap contains any visible symbol pixels.
///
/// This is intentionally shared by materialization and tests so a blank
/// first draw cannot become a reusable cached image.
@MainActor
static func containsVisiblePixels(in bitmap: NSBitmapImageRep) -> Bool {
for y in 0..<bitmap.pixelsHigh {
for x in 0..<bitmap.pixelsWide {
if let color = bitmap.colorAt(x: x, y: y), color.alphaComponent > 0.01 {
return true
}
}
}
return false
}

static func symbolImageSize(_ naturalSize: NSSize, fallbackDimension: CGFloat) -> NSSize {
let fallbackDimension = clampedRasterPointSize(fallbackDimension)
guard naturalSize.width.isFinite,
Expand Down Expand Up @@ -380,9 +402,19 @@ struct CmuxSystemSymbolImage: View {
.renderingMode(.template)
.frame(width: rasterSize, height: rasterSize, alignment: alignment)
} else {
Color.clear
.frame(width: rasterSize, height: rasterSize, alignment: alignment)
.accessibilityHidden(true)
// Keep a lazy SwiftUI provider as a one-pass fallback when the
// concrete AppKit draw was transiently blank. The materialized
// cache remains untouched, so a later body/lifecycle pass can
// retry instead of reusing a blank bitmap.
if RenderableSystemSymbol.isRenderable(systemName) {
Image(systemName: systemName)
.font(.system(size: rasterSize, weight: weight ?? .regular))
.frame(width: rasterSize, height: rasterSize, alignment: alignment)
} else {
Color.clear
.frame(width: rasterSize, height: rasterSize, alignment: alignment)
.accessibilityHidden(true)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
}
Loading