Repository Public
1import Foundation2import SheetCore3import SheetUI4import Statistics5import WhatIf6import AnalysisKit78extension CellAddress {9 var modelCell: ModelCell { ModelCell(sheet: sheet, cell: cell) }10}1112/// Small helpers shared by the What-If tools.13enum WhatIfSupport {14 /// "Model!B5"15 static func label(_ c: CellAddress, in wb: Workbook) -> String { c.modelCell.label(in: wb) }1617 /// Display name of an input or output cell: the text label immediately to its left when there is one, else its address.18 static func name(_ c: CellAddress, in wb: Workbook) -> String {19 guard c.sheet >= 0, c.sheet < wb.sheets.count else { return c.cell.a1 }20 if c.cell.col > 0, case .text(let s) = wb.sheets[c.sheet].value(c.cell.row, c.cell.col - 1) {21 let t = s.trimmingCharacters(in: .whitespaces)22 if !t.isEmpty { return t }23 }24 return label(c, in: wb)25 }2627 /// "Unit price (Model!B4)" or just the address when the cell has no label.28 static func nameWithAddress(_ c: CellAddress, in wb: Workbook) -> String {29 let n = name(c, in: wb), l = label(c, in: wb)30 return n == l ? l : "\(n) (\(l))"31 }3233 static func cell(_ c: CellAddress, in wb: Workbook) -> Cell? {34 guard c.sheet >= 0, c.sheet < wb.sheets.count else { return nil }35 return wb.sheets[c.sheet].cell(c.cell.row, c.cell.col)36 }3738 static func isFormula(_ c: CellAddress, in wb: Workbook) -> Bool { cell(c, in: wb)?.formula != nil }3940 /// "=B4*B5" for a formula cell, nil otherwise.41 static func formulaText(_ c: CellAddress, in wb: Workbook) -> String? {42 cell(c, in: wb)?.formula.map { "=" + $0.expr.formulaText() }43 }4445 /// Number format of the cell (used to show results the way the model shows them).46 static func format(_ c: CellAddress, in wb: Workbook) -> CellFormat {47 guard c.sheet >= 0, c.sheet < wb.sheets.count else { return .auto }48 let code = wb.styles[wb.sheets[c.sheet].styleID(c.cell.row, c.cell.col)].numberFormat49 if code == "General" || code.isEmpty { return .auto }50 if code.hasSuffix("%") {51 let decimals = code.split(separator: ".").count > 1 ? code.split(separator: ".")[1].filter { $0 == "0" }.count : 052 return .percent(decimals)53 }54 // plain fixed-decimal codes ("0.00", "#,##0", "#,##0.00") map to the panel's own fixed format55 let body = code.hasPrefix("#,##") ? String(code.dropFirst(4)) : code56 if body == "0" { return .fixed(0) }57 if body.hasPrefix("0."), body.dropFirst(2).allSatisfy({ $0 == "0" }) { return .fixed(body.count - 2) }58 return .code(code)59 }6061 /// Short axis labels for the bins of a histogram (decimals chosen from the bin width).62 static func binLabels(edges: [Double], locale: Locale) -> [String] {63 guard edges.count > 1 else { return [] }64 let width = abs(edges[1] - edges[0])65 let decimals = width >= 1 || width == 0 ? 0 : min(6, Int(ceil(-log10(width))) + 1)66 return zip(edges, edges.dropFirst()).map { Fmt.fixed(($0 + $1) / 2, decimals, locale: locale) }67 }6869 /// The changing cell of a what-if tool must hold a plain number (or be empty), never a formula.70 static func requireInput(_ c: CellAddress, in wb: Workbook) throws {71 if isFormula(c, in: wb) { throw ToolError(L("%@ contains a formula. The changing cell must contain a value.", label(c, in: wb))) }72 switch cell(c, in: wb)?.value ?? .blank {73 case .number, .blank: return74 default: throw ToolError(L("%@ must contain a number.", label(c, in: wb)))75 }76 }7778 static func requireFormula(_ c: CellAddress, in wb: Workbook) throws {79 if !isFormula(c, in: wb) { throw ToolError(L("%@ does not contain a formula, so it cannot react to the changing cell.", label(c, in: wb))) }80 }8182 /// Values typed as a list ("0.05; 0.06") or given as a reference to cells ("B3:B8"); the cells are read from the model.83 static func values(_ text: String, input: ToolInput, model: CalcEngine, field: String) throws -> [Double] {84 let t = text.trimmingCharacters(in: .whitespaces)85 guard !t.isEmpty else { throw ToolError(L("Enter the values for “%@” (a typed list or a range).", field)) }86 if let list = FormValues.numberList(t, locale: input.locale) { return list }87 guard let cells = RangeReader.cells(t, workbook: model.workbook, sheet: input.activeSheet) else {88 throw ToolError(L("“%@” is neither a list of numbers nor a range.", t))89 }90 let numbers = cells.compactMap { c -> Double? in model.workbook.sheets[c.sheet].value(c.cell.row, c.cell.col).numberValue }91 guard !numbers.isEmpty else { throw ToolError(L("The range “%@” contains no numbers.", t)) }92 return numbers93 }9495 /// An isolated, recalculated copy of the live model (what `ToolInput.model` is for declarative tools).96 @MainActor static func snapshot(_ session: WorkbookSession) -> CalcEngine {97 let live = session.engine98 live.lock.lock()99 let copy = live.workbook.clone()100 let trust = live.pendingCount == 0101 live.lock.unlock()102 let engine = CalcEngine(workbook: copy, registry: live.registry, trustCachedValues: trust)103 engine.maxDepth = live.maxDepth104 if !trust { engine.recalculate() }105 return engine106 }107108}109