Files
RedLintu16andClaude Opus 5.5 64ec524ba0 CrossSound for Apple platforms
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 13:28:34 -07:00

371 lines
13 KiB
Swift
Executable File

// ConsoleView — port of lib/screens/console_screen.dart (LogConsoleScreen).
//
// The in-app debug console over CSLog: initial render from the ring-buffer
// snapshot (CSLog.shared.lines), then live lines from CSLog.shared.tail().
// The Dart screen polled FileLogger every 300ms because per-line setState
// couldn't keep up with log bursts; natively the AsyncStream pushes per line
// and SwiftUI coalesces renders per runloop turn, which does the same
// smoothing without the poll timer.
//
// Colors come from the RwPalette environment like every other screen, so a
// loaded theme restyles the console too: the Dart console's fixed dark scheme
// (0xFF11141A canvas, white washes, terminal green, per-category message
// colors) is mapped onto the semantic tokens — bg/bg2 for canvas and wells,
// contentText for log bodies, red for errors and the active accent, info for
// FairPlay, warn for Widevine/DRM. Only the typeface stays a terminal's:
// log text is monospaced so stamps and columns line up.
//
// MARK: Skipped — ConsoleOverlayButton (the floating draggable launcher that
// lived above Flutter's Navigator, with its long-press-to-hide and
// edge-snapping). The native app reaches the console through
// AppDestination.console instead, so there is no overlay layer to port.
// MARK: Skipped — the Dart "native" line marker (⟟) and FileLogger merge:
// Flutter merged Dart-side and EventChannel lines from two sources; natively
// CSLog is the ONE source, so every line is "native" and the marker means
// nothing.
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
@MainActor
public struct ConsoleView: View {
/// One rendered log line. Lines can repeat verbatim (retries, loops), so
/// ForEach needs a stable id that survives head-trimming and filtering — a
/// monotonic counter, not the string or its array index.
private struct LogRow: Identifiable {
let id: Int
let text: String
}
@Environment(\.rw) private var p
@State private var rows: [LogRow] = []
@State private var nextId = 0
@State private var filter = ""
@State private var autoScroll = true
/// Transient confirmation ("Copied N lines") — the Dart SnackBar's job.
@State private var note: String?
/// Monotonic token so an old dismiss task can't hide a newer note.
@State private var noteToken = 0
/// Stable scroll anchor BELOW the rows: scrollTo targets this, never the
/// last row's id, which changes on every appended line.
private let bottomID = "console-bottom"
public init() {}
@ObserveInjection var inject
public var body: some View {
let shown = filteredRows
VStack(spacing: 0) {
header(shown: shown.count, total: rows.count)
filterBar
if shown.isEmpty {
emptyState
} else {
logList(shown)
}
}
.background(p.bg)
.overlay(alignment: .bottom) { noteView }
.task { await pump() }
.enableInjection()
}
// MARK: - Live feed
/// Snapshot + tail, for the life of the screen (.task cancels on pop, which
/// terminates the stream and unregisters the CSLog continuation).
private func pump() async {
// Subscribe BEFORE snapshotting: a line logged between the two calls then
// shows up twice (already in the snapshot AND buffered in the stream)
// instead of falling into a gap — for a debug console a duplicate is
// recoverable, a silently missing error line is not. The replay guard
// below drops those buffered duplicates again.
let stream = CSLog.shared.tail()
let snapshot = CSLog.shared.lines
reset(to: snapshot)
// Replay guard: the buffered duplicates are, in order, a suffix of the
// snapshot — so each one is IN the snapshot, and there can be at most
// snapshot.count of them. Dedupe against the whole snapshot (a fixed
// 8-line window missed bursts longer than 8) and only for the first
// snapshot.count events; the phase also ends at the first non-duplicate,
// since the duplicates form a prefix of the stream. Past either bound
// nothing is ever dropped. Residual edge: a genuinely NEW line arriving
// inside that brief replay window is still swallowed when its text
// exactly repeats some snapshot line — telling the two apart would need
// sequence numbers from CSLog, not line text.
let snapshotSet = Set(snapshot)
var replaysLeft = snapshot.count
for await line in stream {
if replaysLeft > 0 {
replaysLeft -= 1
if snapshotSet.contains(line) { continue }
replaysLeft = 0
}
append(line)
}
}
private func reset(to lines: [String]) {
rows = lines.map { line in
defer { nextId += 1 }
return LogRow(id: nextId, text: line)
}
}
private func append(_ line: String) {
rows.append(LogRow(id: nextId, text: line))
nextId += 1
// CSLog's own ring holds 2000; the view keeps a little more scrollback
// for a long-open console but still bounds memory.
if rows.count > 4000 {
rows.removeFirst(rows.count - 4000)
}
}
private var filteredRows: [LogRow] {
let q = filter.trimmingCharacters(in: .whitespaces).lowercased()
guard !q.isEmpty else { return rows }
// Match the message part only: the stored row starts with the
// "HH:mm:ss.SSS" stamp, so filtering the whole text made numeric queries
// ("40", "12") hit nearly every line through the timestamps.
return rows.filter { Self.split($0.text).message.lowercased().contains(q) }
}
// MARK: - Header (title + counts + the Dart RwAction row)
private func header(shown: Int, total: Int) -> some View {
HStack(spacing: 8) {
VStack(alignment: .leading, spacing: 2) {
Text("Debug Console")
.font(.system(size: 15, weight: .bold, design: .monospaced))
.foregroundStyle(p.text)
Text("\(shown)/\(total) lines")
.font(.system(size: 11, design: .monospaced).monospacedDigit())
.foregroundStyle(p.textMuted)
}
Spacer(minLength: RwSizes.gap)
headerButton(
icon: "arrow.down.to.line",
active: autoScroll,
help: autoScroll ? "Auto-scroll: on" : "Auto-scroll: off"
) {
autoScroll.toggle()
}
headerButton(icon: "doc.on.doc", active: false, help: "Copy all") {
copyAll()
}
headerButton(icon: "trash", active: false, help: "Clear view") {
clearView()
}
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, 10)
}
private func headerButton(
icon: String, active: Bool, help: String, action: @escaping () -> Void
) -> some View {
Button(action: action) {
LitPalette { p in
Image(systemName: icon)
// On is the active state: the hover colour, flipping on hover
// (BareButtons.swift). No wash or well: buttons draw no background.
.font(.system(size: 14, weight: .semibold))
.foregroundStyle(p.red)
.frame(width: 32, height: 32)
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow(active: active))
.help(help)
}
// MARK: - Filter
private var filterBar: some View {
HStack(spacing: 6) {
Image(systemName: "magnifyingglass")
.font(.system(size: 12))
.foregroundStyle(p.iconInactive)
filterTextField
if !filter.isEmpty {
Button {
filter = ""
} label: {
Image(systemName: "xmark.circle.fill")
.font(.system(size: 13))
.foregroundStyle(p.iconInactive)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
}
.padding(.horizontal, 8)
.padding(.vertical, 6)
// An outline, not a well: no field draws a fill (Outlined.swift).
.outlined(p.hair)
.padding(.horizontal, RwSizes.pagePadding)
.padding(.bottom, 6)
}
@ViewBuilder
private var filterTextField: some View {
let field = TextField("Filter (e.g. fairplay, drm, error)…", text: $filter)
.textFieldStyle(.plain)
.font(.system(size: 13, design: .monospaced))
.foregroundStyle(p.contentText)
.autocorrectionDisabled()
#if os(macOS)
field
#else
field.textInputAutocapitalization(.never)
#endif
}
// MARK: - Log list
private var emptyState: some View {
Text(filter.trimmingCharacters(in: .whitespaces).isEmpty
? "No log lines yet"
: "No lines match the filter")
.font(.system(size: 13, design: .monospaced))
.foregroundStyle(p.textMuted)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private func logList(_ shown: [LogRow]) -> some View {
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 2) {
ForEach(shown) { row in
lineView(row.text)
}
Color.clear
.frame(height: 1)
.id(bottomID)
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, 4)
}
.onAppear {
// Land at the tail like a real terminal — the newest line is what a
// debug session opened the console for.
proxy.scrollTo(bottomID, anchor: .bottom)
}
.onChange(of: rows.count) {
if autoScroll { proxy.scrollTo(bottomID, anchor: .bottom) }
}
.onChange(of: autoScroll) {
// Turning auto-scroll back ON jumps to the tail immediately instead
// of waiting for the next line (same feel as the Dart toggle).
if autoScroll { proxy.scrollTo(bottomID, anchor: .bottom) }
}
}
}
private func lineView(_ line: String) -> some View {
let parts = Self.split(line)
return (Text(parts.stamp.map { "\($0) " } ?? "")
.foregroundStyle(p.textSubtle)
+ Text(parts.message)
.foregroundStyle(color(for: parts.message)))
.font(.system(size: 12, design: .monospaced))
.lineSpacing(2)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
/// CSLog prefixes every buffered line with "HH:mm:ss.SSS " — split it back
/// out so the timestamp can render dimmed like the Dart console (which got
/// the time as a separate field). A cheap shape check, not a date parse: a
/// line that doesn't match renders whole in the message color.
private static func split(_ line: String) -> (stamp: String?, message: String) {
guard line.count > 13 else { return (nil, line) }
let stamp = String(line.prefix(12))
let chars = Array(stamp)
guard chars[2] == ":", chars[5] == ":", chars[8] == "." else { return (nil, line) }
return (stamp, String(line.dropFirst(13)))
}
/// The Dart _colorFor rules, in order — errors outrank the DRM tags so a
/// "[fairplay] license FAILED" line reads as a failure, not as FairPlay.
/// Palette tokens stand in for the Dart hex colors: red for errors, the
/// two status tones for the DRM tags, contentText (not the brand red) for
/// the ordinary body so a wall of log stays readable.
private func color(for message: String) -> RwColor {
let m = message.lowercased()
if m.contains("error") || m.contains("exception") || m.contains("failed") {
return p.red
}
if m.contains("fairplay") { return p.info }
if m.contains("[drm]") || m.contains("widevine") { return p.warn }
return p.contentText
}
// MARK: - Actions
/// Copies the UNFILTERED buffer, like Dart's exportText — a filtered copy
/// would silently hand over an incomplete repro log.
private func copyAll() {
copyToPasteboard(rows.map(\.text).joined(separator: "\n"))
flash("Copied \(rows.count) lines")
}
/// CSLog has no clear() — its ring keeps feeding Console.app and any later
/// console session. This clears the VIEW so a burst can be watched from a
/// clean slate; reopening the screen resyncs from the full buffer.
private func clearView() {
rows.removeAll()
flash("View cleared")
}
private func flash(_ text: String) {
noteToken += 1
let token = noteToken
withAnimation { note = text }
Task {
try? await Task.sleep(for: .seconds(2))
if noteToken == token {
withAnimation { note = nil }
}
}
}
@ViewBuilder
private var noteView: some View {
if let note {
// The notice look (Outlined.swift): primary, 2pt primary edge, no fill.
Text(note)
.font(.system(size: 12, weight: .medium, design: .monospaced))
.foregroundStyle(p.red)
.padding(.horizontal, RwSizes.gap)
.padding(.vertical, 8)
.noticeChrome()
.padding(.bottom, RwSizes.pagePadding)
.transition(.move(edge: .bottom).combined(with: .opacity))
}
}
/// Same helper TrackRow keeps privately — small enough to duplicate rather
/// than grow a shared clipboard layer for two call sites.
private func copyToPasteboard(_ string: String) {
#if canImport(UIKit)
UIPasteboard.general.string = string
#elseif canImport(AppKit)
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(string, forType: .string)
#endif
}
}