Repository Public
1import Foundation2import SwiftUI3import SheetCore4import SheetUI56/// Thread-safe cancellation flag shared by a running tool and its panel.7public final class CancelFlag: @unchecked Sendable {8 private var value = false9 private let lock = NSLock()10 public init() {}11 public func cancel() { lock.lock(); value = true; lock.unlock() }12 public var isCancelled: Bool { lock.lock(); defer { lock.unlock() }; return value }13}1415/// Everything a tool needs, captured on the main actor so `run` can execute on a background thread.16public struct ToolInput: Sendable {17 public var values: FormValues18 /// Data read for every visible range field.19 public var frames: [String: DataFrame]20 /// Cells resolved for every visible cell / cells field.21 public var cellLists: [String: [CellAddress]]22 /// A private recalculated copy of the workbook (only when the tool declares `needsModel`).23 /// The live workbook, its undo and redo stacks are never touched by work done on it.24 public var model: CalcEngine?25 public var activeSheet: Int26 public var date1904: Bool27 public var locale: Locale28 /// Reports progress in 0…1 (throttled by the panel).29 public var progress: @Sendable (Double) -> Void30 public var isCancelled: @Sendable () -> Bool3132 public init(values: FormValues, frames: [String: DataFrame] = [:], cellLists: [String: [CellAddress]] = [:], model: CalcEngine? = nil,33 activeSheet: Int = 0, date1904: Bool = false, locale: Locale = .current,34 progress: @escaping @Sendable (Double) -> Void = { _ in }, isCancelled: @escaping @Sendable () -> Bool = { false }) {35 self.values = values; self.frames = frames; self.cellLists = cellLists; self.model = model36 self.activeSheet = activeSheet; self.date1904 = date1904; self.locale = locale37 self.progress = progress; self.isCancelled = isCancelled38 }3940 public func frame(_ id: String = "data") throws -> DataFrame {41 guard let f = frames[id] else { throw ToolError(L("Choose a data range first.")) }42 return f43 }4445 /// The column chosen in a column field.46 public func column(_ id: String, in range: String = "data") throws -> DataColumn {47 let f = try frame(range)48 guard let i = values.columnIndex(id), i >= 0, i < f.columns.count else { throw ToolError(L("Choose a column for every required field.")) }49 return f.columns[i]50 }5152 public func optionalColumn(_ id: String, in range: String = "data") -> DataColumn? {53 guard let f = frames[range], let i = values.columnIndex(id), i >= 0, i < f.columns.count else { return nil }54 return f.columns[i]55 }5657 /// The columns chosen in a multi-column field, in sheet order.58 public func columns(_ id: String, in range: String = "data", atLeast minimum: Int = 1) throws -> [DataColumn] {59 let f = try frame(range)60 let picked = values.columnIndices(id).filter { $0 >= 0 && $0 < f.columns.count }.sorted().map { f.columns[$0] }61 guard picked.count >= minimum else {62 throw ToolError(minimum <= 1 ? L("Choose at least one column.") : L("Choose at least %d columns.", minimum))63 }64 return picked65 }6667 public func cell(_ id: String) throws -> CellAddress {68 guard let c = cellLists[id]?.first else { throw ToolError(L("Enter a cell reference for every required field.")) }69 return c70 }7172 public func cells(_ id: String) throws -> [CellAddress] {73 guard let c = cellLists[id], !c.isEmpty else { throw ToolError(L("Enter a cell reference for every required field.")) }74 return c75 }7677 public func requireModel() throws -> CalcEngine {78 guard let model else { throw ToolError(L("The workbook model is not available.")) }79 return model80 }8182 /// Throws when the user cancelled.83 public func checkCancelled() throws { if isCancelled() { throw CancellationError() } }84}8586/// Context handed to a tool's custom form section.87@MainActor public struct ToolFormContext {88 public let session: WorkbookSession89 public let values: Binding<FormValues>90 public init(session: WorkbookSession, values: Binding<FormValues>) { self.session = session; self.values = values }91}9293/// One analysis or tool of a studio: a declarative form, a pure `run`, and its documentation.94public struct ToolDescriptor: Identifiable, Sendable {95 public var id: String96 public var title: String97 /// Group heading in the studio list.98 public var group: String99 public var systemImage: String100 public var summary: String101 public var fields: [FormField]102 /// Documented caveats and method notes shown in the info popover.103 public var info: [String]104 /// "Assumptions & conventions" disclosure (exact conventions used by the computation).105 public var conventions: [String]106 /// Ask for an isolated copy of the workbook model in `ToolInput.model`.107 public var needsModel: Bool108 /// Title of the run button (default "Run").109 public var runTitle: String?110 /// Runs off the main actor. Must only read `input`.111 public var run: @Sendable (ToolInput) throws -> ToolResult112 /// Extra controls placed under the declarative form (state lives in `FormValues`).113 public var extraForm: (@MainActor @Sendable (ToolFormContext) -> AnyView)?114 /// Replaces the whole panel (form, run, results) for tools that are editors rather than computations.115 public var customPanel: (@MainActor @Sendable (WorkbookSession) -> AnyView)?116 /// Fills the form for the preview's demo workbook (`--tool <id>`).117 public var demo: (@MainActor @Sendable (WorkbookSession, inout FormValues) -> Void)?118119 public init(id: String, title: String, group: String, systemImage: String, summary: String, fields: [FormField],120 info: [String] = [], conventions: [String] = [], needsModel: Bool = false, runTitle: String? = nil,121 run: @escaping @Sendable (ToolInput) throws -> ToolResult) {122 self.id = id; self.title = title; self.group = group; self.systemImage = systemImage; self.summary = summary123 self.fields = fields; self.info = info; self.conventions = conventions; self.needsModel = needsModel; self.runTitle = runTitle124 self.run = run125 }126127 public func field(_ id: String) -> FormField? { fields.first { $0.id == id } }128}129130/// Builds a `ToolInput` from the live session.131@MainActor public enum ToolInputResolver {132 /// Reads the frame of one range field (nil when the text is empty or not a reference).133 public static func frame(_ value: RangeValue, session: WorkbookSession) -> DataFrame? {134 guard let area = RangeReader.resolve(value.text, workbook: session.workbook, sheet: session.sheetIndex) else { return nil }135 return RangeReader.read(engine: session.engine, area: area, hasHeader: value.hasHeader)136 }137138 public static func resolve(_ tool: ToolDescriptor, values: FormValues, session: WorkbookSession,139 progress: @escaping @Sendable (Double) -> Void = { _ in },140 isCancelled: @escaping @Sendable () -> Bool = { false }) throws -> ToolInput {141 var frames = [String: DataFrame]()142 var cellLists = [String: [CellAddress]]()143 for f in tool.fields where f.isVisible(values) {144 switch f.kind {145 case .range:146 let rv = values.range(f.id)147 guard !rv.text.trimmingCharacters(in: .whitespaces).isEmpty else { throw ToolError(L("Enter a range for “%@”.", f.label)) }148 guard let frame = frame(rv, session: session) else { throw ToolError(L("“%@” is not a valid range.", rv.text)) }149 guard frame.rowCount > 0 else { throw ToolError(L("The range “%@” contains no data rows.", rv.text)) }150 frames[f.id] = frame151 case .cell, .cells:152 let text = values.text(f.id).trimmingCharacters(in: .whitespaces)153 if text.isEmpty { continue }154 guard let list = RangeReader.cells(text, workbook: session.workbook, sheet: session.sheetIndex) else {155 throw ToolError(L("“%@” is not a valid cell reference.", text))156 }157 if case .cell = f.kind, list.count != 1 { throw ToolError(L("“%@” must be a single cell.", f.label)) }158 cellLists[f.id] = list159 default: break160 }161 }162 var model: CalcEngine?163 if tool.needsModel {164 let live = session.engine165 live.lock.lock()166 let copy = live.workbook.clone()167 let trust = live.pendingCount == 0168 live.lock.unlock()169 let engine = CalcEngine(workbook: copy, registry: live.registry, trustCachedValues: trust)170 engine.maxDepth = live.maxDepth171 if !trust { engine.recalculate() }172 model = engine173 }174 return ToolInput(values: values, frames: frames, cellLists: cellLists, model: model, activeSheet: session.sheetIndex,175 date1904: session.workbook.date1904, locale: session.locale, progress: progress, isCancelled: isCancelled)176 }177178 /// Presets the range fields from the current selection (or the data region around the active cell) and179 /// chooses default columns. Called when a tool is opened and after "Use Selection".180 public static func preset(_ tool: ToolDescriptor, values: inout FormValues, session: WorkbookSession, force: Bool = false) {181 for f in tool.fields {182 guard case .range(let preset) = f.kind, preset else { continue }183 var rv = values.range(f.id)184 if rv.text.isEmpty || force {185 let area = selectionArea(session)186 rv.text = area.range.a1187 rv.hasHeader = RangeReader.guessHeader(workbook: session.workbook, area: area)188 values[f.id] = .range(rv)189 }190 }191 applyColumnDefaults(tool, values: &values, session: session, reset: force)192 }193194 /// The selection, or the contiguous data region around the active cell when a single cell is selected.195 public static func selectionArea(_ session: WorkbookSession) -> AreaRef {196 var rg = session.selection.primary197 if rg.isSingleCell { rg = session.currentRegion(around: session.selection.active) }198 return AreaRef(sheet: session.sheetIndex, range: rg)199 }200201 /// Gives column fields a sensible default (and drops choices that no longer exist) after their range changed.202 public static func applyColumnDefaults(_ tool: ToolDescriptor, values: inout FormValues, session: WorkbookSession, reset: Bool = false) {203 var cache = [String: DataFrame?]()204 func frameFor(_ id: String) -> DataFrame? {205 if let f = cache[id] { return f }206 let f = frame(values.range(id), session: session)207 cache[id] = f208 return f209 }210 var used = [String: Set<Int>]()211 for f in tool.fields {212 switch f.kind {213 case .column(let range, let numericOnly, let optional, let defaultIndex):214 guard let frame = frameFor(range) else { values[f.id] = .column(nil); continue }215 let eligible = frame.columns.filter { !numericOnly || $0.isNumeric }.map(\.index)216 var current = values.columnIndex(f.id)217 if reset || current.map({ !eligible.contains($0) }) ?? true {218 if let d = defaultIndex, eligible.contains(d) { current = d }219 else if optional { current = nil }220 else { current = eligible.first { !(used[range] ?? []).contains($0) } ?? eligible.first }221 }222 if let c = current { used[range, default: []].insert(c) }223 values[f.id] = .column(current)224 case .columns(let range, let numericOnly, let defaultAll):225 guard let frame = frameFor(range) else { values[f.id] = .columns([]); continue }226 let eligible = frame.columns.filter { !numericOnly || $0.isNumeric }.map(\.index)227 var current = values.columnIndices(f.id).filter { eligible.contains($0) }228 if (current.isEmpty || reset) && defaultAll { current = eligible.filter { !(used[range] ?? []).contains($0) } }229 values[f.id] = .columns(current)230 default: break231 }232 }233 }234}235