Repository Public
1//2// VQuant iOS3// File: VQuant/Next/ChartDrawing.swift4// Description: Drawings on the price chart, anchored in data space (each point is a time and a price, never a pixel)5// and stored in the symbol's synced `chart` object with the same types as the web client: trend line,6// horizontal line, rectangle, Fibonacci retracement, note, measure — plus free strokes for the Pencil.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10//1112import PencilKit13import SwiftUI14import VQuantKit15import VQuantUI1617enum DrawTool: String, CaseIterable, Identifiable {18 case trend, hline, rect, fib, text, measure, pencil19 var id: String { rawValue }20 var label: String {21 switch self { case .trend: "Ligne de tendance"; case .hline: "Ligne horizontale"; case .rect: "Rectangle"; case .fib: "Fibonacci"; case .text: "Note"; case .measure: "Mesure"; case .pencil: "Tracé libre" }22 }23 var systemImage: String {24 switch self { case .trend: "line.diagonal"; case .hline: "minus"; case .rect: "rectangle"; case .fib: "line.3.horizontal"; case .text: "text.bubble"; case .measure: "ruler"; case .pencil: "pencil.tip" }25 }26 var pointsNeeded: Int { self == .hline || self == .text ? 1 : 2 }27}2829enum ChartDrawingMath {30 static let fibLevels: [Double] = [0, 0.236, 0.382, 0.5, 0.618, 0.786, 1]31 /// Fibonacci retracement of the move from A to B: level 0 at B, level 1 at A (the web's convention).32 static func fib(a: Double, b: Double) -> [(ratio: Double, price: Double)] { fibLevels.map { ($0, b + (a - b) * $0) } }3334 struct Measure: Equatable { var deltaPrice: Double; var deltaPct: Double?; var bars: Int; var days: Int }35 static func measure(_ a: VQChart.Drawing.Point, _ b: VQChart.Drawing.Point, times: [Double]) -> Measure {36 let bars = Int((ChartTime.index(of: b.t, times: times) - ChartTime.index(of: a.t, times: times)).rounded())37 return Measure(deltaPrice: b.p - a.p, deltaPct: a.p > 0 ? b.p / a.p - 1 : nil, bars: bars, days: Int(((b.t - a.t) / 86_400).rounded()))38 }3940 /// Price levels the drawings mark, for the question sent to the agent.41 static func levels(_ drawings: [VQChart.Drawing]) -> [(kind: String, price: Double)] {42 var out: [(String, Double)] = []43 for d in drawings {44 let p = d.points45 switch d.type {46 case "hline": if let a = p.first { out.append(("Ligne horizontale", a.p)) }47 case "trend", "ray": if p.count == 2 { out.append(("Ligne de tendance, début", p[0].p)); out.append(("Ligne de tendance, fin", p[1].p)) }48 case "rect": if p.count == 2 { out.append(("Rectangle, haut", max(p[0].p, p[1].p))); out.append(("Rectangle, bas", min(p[0].p, p[1].p))) }49 case "fib": if p.count == 2 { for l in fib(a: p[0].p, b: p[1].p) { out.append(("Fibonacci \(VQFormat.number(l.ratio * 100, decimals: 1)) %", l.price)) } }50 default: break51 }52 }53 return out54 }55}5657extension PriceChartScene {58 func times(intraday: Bool) -> [Double] { bars.map { ChartTime.t($0, intraday: intraday) } }59 func screen(_ pt: VQChart.Drawing.Point, times: [Double]) -> CGPoint {60 let i = ChartTime.index(of: pt.t, times: times)61 return CGPoint(x: layout.plot.minX + CGFloat(viewport.x(index: i, width: plotWidth)), y: y(pt.p))62 }63 func data(at p: CGPoint, times: [Double]) -> VQChart.Drawing.Point {64 let slot = viewport.slot(width: plotWidth)65 let index = slot > 0 ? viewport.start + Double(p.x - layout.plot.minX) / slot - 0.5 : 066 let span = yRange.upperBound - yRange.lowerBound67 let h = Double(layout.plot.height)68 let price = h > 0 ? yRange.upperBound - Double(p.y - layout.plot.minY) / h * span : yRange.lowerBound69 return VQChart.Drawing.Point(t: ChartTime.time(at: index, times: times).rounded(), p: price)70 }71}7273/// Draws the drawings of a chart at their time and price, and — while a tool is selected — turns touches (finger,74/// trackpad or Pencil) into new drawings.75struct DrawingLayer: View {76 let scene: PriceChartScene77 let drawings: [VQChart.Drawing]78 var tool: DrawTool?79 var selected: String?80 var onAdd: (VQChart.Drawing) -> Void81 var onSelect: (String?) -> Void82 @State private var draft: [VQChart.Drawing.Point] = []8384 var body: some View {85 let times = scene.times(intraday: scene.intraday)86 Canvas { ctx, _ in87 var clipped = ctx88 clipped.clip(to: Path(scene.layout.plot))89 for d in drawings { draw(d, in: &clipped, times: times, highlighted: d.id == selected) }90 if let tool, !draft.isEmpty { draw(VQChart.Drawing(id: "draft", type: tool.rawValue, points: draft), in: &clipped, times: times, highlighted: true) }91 }92 .contentShape(Rectangle())93 .gesture(tool == nil ? nil : DragGesture(minimumDistance: 0, coordinateSpace: .local)94 .onChanged { v in95 guard let tool, scene.layout.plot.contains(v.startLocation) else { return }96 let p = scene.data(at: clamp(v.location), times: times)97 if tool == .pencil { if draft.last.map({ abs($0.t - p.t) + abs($0.p - p.p) > 0 }) ?? true { draft.append(p) } }98 else if tool.pointsNeeded == 1 { draft = [p] }99 else { draft = [scene.data(at: clamp(v.startLocation), times: times), p] }100 }101 .onEnded { _ in102 guard let tool else { return }103 defer { draft = [] }104 if tool == .pencil { if draft.count > 1 { onAdd(VQChart.Drawing(id: VQObjectID.make(), type: "pencil", points: Self.thin(draft, to: 160))) }; return }105 guard draft.count == tool.pointsNeeded else { return }106 if tool.pointsNeeded == 2, draft[0] == draft[1] { return } // a tap is not a two-point drawing107 onAdd(VQChart.Drawing(id: VQObjectID.make(), type: tool.rawValue, points: draft))108 })109 .simultaneousGesture(tool != nil ? nil : SpatialTapGesture().onEnded { v in onSelect(hit(v.location, times: times)) })110 .allowsHitTesting(tool != nil || !drawings.isEmpty)111 .accessibilityElement(children: .ignore)112 .accessibilityLabel("Tracés du graphique")113 .accessibilityValue(drawings.isEmpty ? "Aucun tracé" : "\(drawings.count) tracé\(drawings.count > 1 ? "s" : "") ancré\(drawings.count > 1 ? "s" : "") au temps et au prix")114 }115116 private func clamp(_ p: CGPoint) -> CGPoint {117 let r = scene.layout.plot118 return CGPoint(x: min(max(p.x, r.minX), r.maxX), y: min(max(p.y, r.minY), r.maxY))119 }120121 /// Keeps at most `n` points of a free stroke (every k-th, plus the last).122 static func thin(_ pts: [VQChart.Drawing.Point], to n: Int) -> [VQChart.Drawing.Point] {123 guard pts.count > n, n > 2 else { return pts }124 let k = Int((Double(pts.count) / Double(n)).rounded(.up))125 var out = stride(from: 0, to: pts.count, by: k).map { pts[$0] }126 if out.last != pts.last, let l = pts.last { out.append(l) }127 return out128 }129130 private func hit(_ p: CGPoint, times: [Double]) -> String? {131 let tol: CGFloat = 18132 for d in drawings.reversed() {133 let pts = d.points.map { scene.screen($0, times: times) }134 guard let a = pts.first else { continue }135 switch d.type {136 case "hline": if abs(p.y - a.y) <= tol { return d.id }137 case "text": if abs(p.y - a.y) <= tol && p.x >= a.x - tol && p.x <= a.x + 160 { return d.id }138 case "rect": if pts.count == 2, CGRect(x: min(a.x, pts[1].x), y: min(a.y, pts[1].y), width: abs(a.x - pts[1].x), height: abs(a.y - pts[1].y)).insetBy(dx: -tol, dy: -tol).contains(p) { return d.id }139 case "fib": if pts.count == 2, ChartDrawingMath.fib(a: d.points[0].p, b: d.points[1].p).contains(where: { abs(scene.y($0.price) - p.y) <= tol }) { return d.id }140 default:141 for (u, v) in zip(pts, pts.dropFirst()) where Self.distance(p, u, v) <= tol { return d.id }142 }143 }144 return nil145 }146 static func distance(_ p: CGPoint, _ a: CGPoint, _ b: CGPoint) -> CGFloat {147 let dx = b.x - a.x, dy = b.y - a.y148 let len2 = dx * dx + dy * dy149 guard len2 > 0 else { return hypot(p.x - a.x, p.y - a.y) }150 let t = max(0, min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2))151 return hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy))152 }153154 private func draw(_ d: VQChart.Drawing, in ctx: inout GraphicsContext, times: [Double], highlighted: Bool) {155 let pts = d.points.map { scene.screen($0, times: times) }156 guard let a = pts.first else { return }157 let color = Theme.orange158 let width: CGFloat = highlighted ? 2.4 : 1.6159 let plot = scene.layout.plot160 func label(_ s: String, at p: CGPoint, anchor: UnitPoint = .bottomLeading) {161 let t = ctx.resolve(Text(s).font(.caption2.monospacedDigit().weight(.semibold)).foregroundStyle(color))162 let size = t.measure(in: CGSize(width: 260, height: 60))163 let origin = CGPoint(x: min(max(plot.minX + 2, p.x + 4), plot.maxX - size.width - 2), y: max(plot.minY + size.height + 2, p.y - 3))164 ctx.fill(Path(roundedRect: CGRect(x: origin.x - 2, y: origin.y - size.height - 1, width: size.width + 4, height: size.height + 2), cornerRadius: 3), with: .color(Theme.surface.opacity(0.85)))165 ctx.draw(t, at: origin, anchor: .bottomLeading)166 }167 switch d.type {168 case "hline":169 var l = Path(); l.move(to: CGPoint(x: plot.minX, y: a.y)); l.addLine(to: CGPoint(x: plot.maxX, y: a.y))170 ctx.stroke(l, with: .color(color), style: StrokeStyle(lineWidth: width, dash: [6, 4]))171 label(Fmt.price(d.points[0].p), at: CGPoint(x: plot.minX, y: a.y))172 case "text":173 ctx.fill(Path(ellipseIn: CGRect(x: a.x - 3, y: a.y - 3, width: 6, height: 6)), with: .color(color))174 label(d.text?.isEmpty == false ? d.text! : "Note", at: a)175 case "rect":176 guard pts.count == 2 else { return }177 let r = CGRect(x: min(a.x, pts[1].x), y: min(a.y, pts[1].y), width: abs(a.x - pts[1].x), height: abs(a.y - pts[1].y))178 ctx.fill(Path(r), with: .color(color.opacity(0.10)))179 ctx.stroke(Path(r), with: .color(color), lineWidth: width)180 case "fib":181 guard pts.count == 2 else { return }182 let x0 = min(a.x, pts[1].x), x1 = max(max(a.x, pts[1].x), x0 + 60)183 for l in ChartDrawingMath.fib(a: d.points[0].p, b: d.points[1].p) {184 let y = scene.y(l.price)185 var line = Path(); line.move(to: CGPoint(x: x0, y: y)); line.addLine(to: CGPoint(x: min(x1, plot.maxX), y: y))186 ctx.stroke(line, with: .color(color.opacity(l.ratio == 0 || l.ratio == 1 ? 1 : 0.7)), lineWidth: l.ratio == 0.5 ? width : 1)187 label("\(VQFormat.number(l.ratio * 100, decimals: 1)) % · \(Fmt.price(l.price))", at: CGPoint(x: x0, y: y))188 }189 case "measure":190 guard pts.count == 2 else { return }191 var l = Path(); l.move(to: a); l.addLine(to: pts[1])192 ctx.stroke(l, with: .color(color), style: StrokeStyle(lineWidth: width, dash: [2, 3]))193 let m = ChartDrawingMath.measure(d.points[0], d.points[1], times: times)194 label("\(Fmt.signed(m.deltaPrice)) · \(m.deltaPct.map { Fmt.fraction($0) } ?? "—") · \(m.bars) barres · \(m.days) j", at: pts[1])195 default: // trend, ray, pencil and types this version does not know: a polyline196 guard pts.count > 1 else { return }197 var l = Path(); l.move(to: a); for p in pts.dropFirst() { l.addLine(to: p) }198 ctx.stroke(l, with: .color(color), style: StrokeStyle(lineWidth: width, lineCap: .round, lineJoin: .round))199 if highlighted, d.type == "trend" { for p in pts { ctx.fill(Path(ellipseIn: CGRect(x: p.x - 4, y: p.y - 4, width: 8, height: 8)), with: .color(color)) } }200 }201 }202}203204/// The working chart of a symbol as a synced object: reads and writes its drawings and view settings.205@MainActor206struct ChartObject {207 let model: AppModel208 let symbol: String209 var id: String { model.next.sync.chartId(symbol) }210 var object: VQObject<VQChart>? { model.next.sync.charts[id] }211 var drawings: [VQChart.Drawing] { object?.data.drawings ?? [] }212 var isPending: Bool { model.next.sync.charts.pendingIDs.contains(id) }213214 func mutate(_ change: @escaping @Sendable (inout VQChart) -> Void) {215 let id = self.id, symbol = self.symbol, sync = model.next.sync216 Task {217 await sync.edit(VQChart.self, id: id, create: VQChart(symbol: symbol), change)218 await sync.charts.refresh()219 }220 }221 func add(_ d: VQChart.Drawing) { mutate { var l = $0.drawings; l.append(d); $0.drawings = l } }222 func remove(_ drawingId: String) { mutate { $0.drawings = $0.drawings.filter { $0.id != drawingId } } }223 func setText(_ drawingId: String, _ text: String) { mutate { var l = $0.drawings; if let i = l.firstIndex(where: { $0.id == drawingId }) { l[i].text = text }; $0.drawings = l } }224 func clear() { mutate { $0.drawings = [] } }225}226227/// The full chart of a symbol: bars of the data layer with their provenance, the drawing tools, and "Demander à228/// l’agent" on exactly what is on screen. Used full screen on the iPhone, as a destination, a window or a workspace229/// panel on the iPad.230struct ChartWorkstation: View {231 let symbol: String232 var name: String?233 var compact = false234 var onClose: (() -> Void)?235 @Environment(AppModel.self) private var model236 @Environment(\.colorScheme) private var scheme237 @Environment(\.horizontalSizeClass) private var sizeClass238 @State private var loader = ChartLoader()239 @State private var range: ChartRange = .year240 @State private var inspected: Bar?241 @State private var tool: DrawTool?242 @State private var selected: String?243 @State private var visible: Range<Int> = 0..<0244 @State private var share: ChartScreen.ShareItem?245 @State private var noteText = ""246 @State private var editingNote: String?247 @State private var confirmClear = false248 @State private var legacy: PKDrawing?249 @State private var showLegacy = false250 @State private var plotSize = CGSize.zero251252 private var chart: ChartObject { ChartObject(model: model, symbol: symbol) }253254 var body: some View {255 VStack(spacing: 8) {256 if !compact {257 Picker("Période", selection: $range) { ForEach(ChartRange.allCases) { Text($0.rawValue).tag($0) } }.pickerStyle(.segmented)258 .accessibilityIdentifier("workstation-range")259 }260 ZStack {261 if loader.bars.isEmpty {262 StateView(kind: loader.isLoading ? .loading : .failed, title: loader.isLoading ? "Chargement…" : "Graphique indisponible", message: loader.error)263 } else {264 PriceChartView(bars: loader.bars, configuration: model.preferences.chartConfiguration, intraday: range.isIntraday, interactive: tool == nil,265 overlay: { scene in266 AnyView(DrawingLayer(scene: scene, drawings: chart.drawings, tool: tool, selected: selected, onAdd: { d in267 chart.add(d)268 if d.type == "text" { noteText = ""; editingNote = d.id }269 if tool != .pencil { tool = nil }270 selected = d.id271 }, onSelect: { selected = $0 }))272 }, onViewport: { visible = $0 }) { inspected = $0 }273 if showLegacy, let legacy { LegacyAnnotationOverlay(drawing: legacy).allowsHitTesting(false) }274 }275 }276 .background(GeometryReader { g in Color.clear.onAppear { plotSize = g.size }.onChange(of: g.size) { _, s in plotSize = s } })277 .symbolDrop { s in model.router.open(.chart(s), compact: sizeClass == .compact) }278 if !compact { toolbarRow; footer }279 }280 .padding(compact ? 6 : 12)281 .background(Theme.background)282 .navigationTitle("\(symbol.replacingOccurrences(of: "^", with: "")) · \(range.rawValue)")283 .navigationBarTitleDisplayMode(.inline)284 .toolbar {285 if let onClose { ToolbarItem(placement: .cancellationAction) { Button("Fermer", action: onClose).accessibilityIdentifier("chart-close") } }286 ToolbarItemGroup(placement: .primaryAction) {287 Button { ask() } label: { Label("Demander à l’agent", systemImage: "sparkles") }288 .disabled(loader.bars.isEmpty).requiresNetwork(model.network.isOnline).accessibilityIdentifier("chart-ask")289 Menu {290 OpenWindowButton(route: .chart(symbol))291 Button { exportImage() } label: { Label("Partager l’image", systemImage: "photo") }292 Button { exportCSV() } label: { Label("Exporter en CSV", systemImage: "tablecells") }293 } label: { Label("Partager", systemImage: "square.and.arrow.up") }294 .disabled(loader.bars.isEmpty).accessibilityIdentifier("chart-share")295 }296 }297 .task(id: range) { await loader.load(symbol, range: range, market: model.market) }298 .onAppear { if !compact { range = model.preferences.chartRange }; legacy = ChartAnnotationStore.load(symbol) }299 .sheet(item: $share) { ActivityView(items: [$0.url]) }300 .alert("Note", isPresented: Binding(get: { editingNote != nil }, set: { if !$0 { editingNote = nil } })) {301 TextField("Texte de la note", text: $noteText)302 Button("Enregistrer") { if let id = editingNote { chart.setText(id, noteText) } }303 Button("Annuler", role: .cancel) {}304 }305 .confirmationDialog("Effacer tous les tracés de \(symbol) ?", isPresented: $confirmClear, titleVisibility: .visible) {306 Button("Effacer les tracés", role: .destructive) { chart.clear(); selected = nil }307 } message: { Text("Ils sont retirés du graphique du compte, sur tous vos appareils.") }308 .accessibilityElement(children: .contain).accessibilityIdentifier("chart-workstation")309 }310311 /// Drawing tools. One row that scrolls on the iPhone; every button is at least 44 pt.312 private var toolbarRow: some View {313 ScrollView(.horizontal, showsIndicators: false) {314 HStack(spacing: 6) {315 ChartOptionsMenu()316 Divider().frame(height: 24)317 ForEach(DrawTool.allCases) { t in318 Button { tool = tool == t ? nil : t; selected = nil } label: {319 Image(systemName: t.systemImage).frame(width: 48, height: 48)320 .background(tool == t ? Theme.surface2 : .clear, in: RoundedRectangle(cornerRadius: 8))321 .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(tool == t ? Theme.orange : .clear, lineWidth: 1))322 .contentShape(Rectangle())323 }324 .buttonStyle(.plain).hoverEffect(.highlight)325 .accessibilityLabel(t.label).accessibilityAddTraits(tool == t ? [.isSelected] : [])326 .accessibilityIdentifier("draw-\(t.rawValue)")327 }328 Divider().frame(height: 24)329 if let s = selected {330 Button(role: .destructive) { chart.remove(s); selected = nil } label: { Label("Supprimer le tracé", systemImage: "trash").labelStyle(.iconOnly).frame(width: 44, height: 44) }331 .accessibilityIdentifier("draw-delete")332 }333 if !chart.drawings.isEmpty {334 Button { confirmClear = true } label: { Label("Tout effacer", systemImage: "eraser").labelStyle(.iconOnly).frame(width: 44, height: 44) }.accessibilityIdentifier("draw-clear")335 }336 }337 }338 .accessibilityElement(children: .contain).accessibilityLabel("Outils de tracé")339 }340341 @ViewBuilder private var footer: some View {342 VStack(alignment: .leading, spacing: 6) {343 HStack(spacing: 8) {344 if let p = model.market.provenance(symbol, range: range) { BarProvenanceLine(provenance: p) }345 else if case .cache(let t)? = loader.origin { FreshnessBadge(freshness: .cached(savedAt: t), compact: true) }346 Spacer(minLength: 4)347 if !chart.drawings.isEmpty {348 Text("\(chart.drawings.count) tracé\(chart.drawings.count > 1 ? "s" : "")" + (chart.isPending ? " · en attente d’envoi" : " · synchronisé\(chart.drawings.count > 1 ? "s" : "")"))349 .font(.caption).foregroundStyle(chart.isPending ? Theme.orange : Theme.textSecondary).accessibilityIdentifier("drawing-count")350 }351 }352 if let t = tool { Text(hint(t)).font(.caption).foregroundStyle(Theme.orange) }353 else if let b = inspected {354 Text("\(range.isIntraday ? Fmt.dateTime(b.date) : Fmt.day(b.date)) · O \(Fmt.price(b.open)) H \(Fmt.price(b.high)) B \(Fmt.price(b.low)) C \(Fmt.price(b.close))")355 .font(.mono(.caption)).foregroundStyle(Theme.textSecondary).lineLimit(1).minimumScaleFactor(0.7)356 }357 if legacy != nil { legacyNotice }358 }359 }360361 private func hint(_ t: DrawTool) -> String {362 switch t {363 case .hline, .text: "Touchez le graphique pour poser : \(t.label.lowercased())."364 case .pencil: "Dessinez au doigt ou au Pencil. Le tracé est ancré au temps et au prix : il suit le zoom et le défilement."365 default: "Faites glisser entre deux points pour tracer : \(t.label.lowercased())."366 }367 }368369 /// Annotations made with 1.0 were a drawing tied to the screen. They cannot be placed in time and price without370 /// knowing the view they were made on, so the person decides: show them over the current view and anchor them there.371 private var legacyNotice: some View {372 VStack(alignment: .leading, spacing: 6) {373 Text("Des annotations de la version 1.0 existent pour \(symbol). Elles étaient liées à l’écran, pas au prix : choisissez la période et le zoom où elles tombent juste, puis ancrez-les.")374 .font(.caption).foregroundStyle(Theme.textSecondary)375 HStack {376 Toggle("Afficher", isOn: $showLegacy).toggleStyle(.button).accessibilityIdentifier("legacy-show")377 Button("Ancrer à cette vue") { anchorLegacy() }.disabled(!showLegacy || loader.bars.isEmpty).accessibilityIdentifier("legacy-anchor")378 Button("Supprimer", role: .destructive) { ChartAnnotationStore.remove(symbol); legacy = nil; showLegacy = false }379 }380 .font(.caption).buttonStyle(.bordered)381 }382 .padding(10).background(Theme.surface2.opacity(0.6), in: RoundedRectangle(cornerRadius: 10))383 .accessibilityIdentifier("legacy-annotations")384 }385386 /// Converts each stroke shown over the chart into a free drawing anchored at the time and price under it.387 private func anchorLegacy() {388 guard let legacy, plotSize.width > 10 else { return }389 let layout = ChartLayout(size: plotSize, panels: model.preferences.chartConfiguration.panels, axisWidth: 54, xAxisHeight: 18)390 let scene = PriceChartScene(bars: loader.bars, data: ChartData(bars: loader.bars, configuration: model.preferences.chartConfiguration), configuration: model.preferences.chartConfiguration,391 intraday: range.isIntraday, previousClose: nil, viewport: ChartViewport(count: loader.bars.count, start: Double(visible.lowerBound), length: Double(max(1, visible.count))), layout: layout, crosshair: nil)392 let times = scene.times(intraday: range.isIntraday)393 let strokes = LegacyAnnotationOverlay.polylines(legacy).map { line in394 VQChart.Drawing(id: VQObjectID.make(), type: "pencil", points: DrawingLayer.thin(line.map { scene.data(at: $0, times: times) }, to: 160))395 }.filter { $0.points.count > 1 }396 chart.mutate { c in var l = c.drawings; l.append(contentsOf: strokes); c.drawings = l }397 ChartAnnotationStore.archive(symbol)398 self.legacy = nil; showLegacy = false399 }400401 /// The question carries exactly what is on screen: symbol, interval, the dates of the visible window, the402 /// indicators shown and the price levels the drawings mark.403 private func ask() {404 let window = loader.bars.indices.contains(visible.lowerBound) && visible.upperBound <= loader.bars.count && !visible.isEmpty ? Array(loader.bars[visible]) : loader.bars405 guard let first = window.first, let last = window.last else { return }406 model.router.compose(mode: .research, draft: Self.question(symbol: symbol, range: range, first: first, last: last, count: window.count, configuration: model.preferences.chartConfiguration,407 levels: ChartDrawingMath.levels(chart.drawings), provider: model.market.provenance(symbol, range: range)?.provider))408 onClose?()409 }410411 static func question(symbol: String, range: ChartRange, first: Bar, last: Bar, count: Int, configuration: ChartConfiguration, levels: [(kind: String, price: Double)], provider: String?) -> String {412 let iso: (Date) -> String = { range.isIntraday ? ISO8601.string($0) : MarketDate.day($0) }413 var parts = ["Analyse \(symbol) sur la fenêtre que je regarde : du \(iso(first.date)) au \(iso(last.date)) (\(count) barres, intervalle \(ChartTime.interval(range))\(provider.map { ", données \($0)" } ?? ""))."]414 parts.append("Clôture de \(Fmt.price(first.close)) à \(Fmt.price(last.close)).")415 let ind = ChartOverlay.allCases.filter { configuration.overlays.contains($0) }.map(\.label) + ChartPanel.allCases.filter { configuration.panels.contains($0) }.map(\.label)416 if !ind.isEmpty { parts.append("Indicateurs affichés : \(ind.joined(separator: ", ")).") }417 if !levels.isEmpty { parts.append("Niveaux que j’ai tracés : " + levels.prefix(16).map { "\($0.kind) à \(Fmt.price($0.price))" }.joined(separator: " ; ") + ".") }418 parts.append("Que montrent ces niveaux et ces indicateurs sur cette période, et qu’est-ce qui les invaliderait ?")419 return parts.joined(separator: " ")420 }421422 private func exportImage() {423 let p = model.market.provenance(symbol, range: range)424 let subtitle = "\(range.rawValue) · \(loader.bars.count) observations · source VQuant (\(VQFreshness.providerName(p?.provider) ?? "FMP")) · \(Fmt.dateTime(Date()))"425 guard let data = ChartSnapshot.png(bars: loader.bars, configuration: model.preferences.chartConfiguration, intraday: range.isIntraday,426 title: [symbol, name].compactMap { $0 }.joined(separator: " — "), subtitle: subtitle, colorScheme: scheme) else { return }427 write(data, name: "VQuant-\(symbol)-\(range.rawValue).png")428 }429 private func exportCSV() { write(Data(CSVExport.bars(loader.bars, intraday: range.isIntraday).utf8), name: "VQuant-\(symbol)-\(range.rawValue).csv") }430 private func write(_ data: Data, name: String) {431 let safe = name.replacingOccurrences(of: "^", with: "").replacingOccurrences(of: "/", with: "-")432 let url = FileManager.default.temporaryDirectory.appendingPathComponent(safe)433 do { try data.write(to: url, options: .atomic); share = .init(url: url) } catch {}434 }435}436437/// Where the bars come from: provider, adjustment actually applied, observations, gaps — as the data layer states.438struct BarProvenanceLine: View {439 let provenance: VQBarSeries.Provenance440 var body: some View {441 HStack(spacing: 8) {442 if let f = provenance.freshness { ProvenanceChip(f) }443 else { ProvenanceChip(kind: .historical, provider: provenance.provider, asOf: provenance.retrievedAt) }444 Text(detail).font(.caption2).foregroundStyle(Theme.textSecondary).lineLimit(2)445 }446 .accessibilityElement(children: .combine)447 .accessibilityAddTraits(.isStaticText)448 .accessibilityIdentifier("bar-provenance")449 }450 private var detail: String {451 var parts: [String] = []452 if let o = provenance.observations { parts.append("\(o) obs.") }453 if let a = provenance.adjust { parts.append(a == "split_div" ? "ajusté fractionnements et dividendes" : a == "split" ? "ajusté des fractionnements" : "non ajusté") }454 if let f = provenance.fallbackFrom { parts.append("repli depuis \(f)") }455 if let g = provenance.gaps, g.missingSessions > 0 { parts.append("\(g.missingSessions) séance\(g.missingSessions > 1 ? "s" : "") manquante\(g.missingSessions > 1 ? "s" : "")") }456 if provenance.truncated { parts.append("série tronquée") }457 return parts.joined(separator: " · ")458 }459}460461/// The 1.0 annotation of a symbol (a PencilKit drawing tied to the screen), shown as it was drawn.462struct LegacyAnnotationOverlay: View {463 let drawing: PKDrawing464 var body: some View {465 Canvas { ctx, _ in466 for line in Self.polylines(drawing) where line.count > 1 {467 var p = Path(); p.move(to: line[0]); for q in line.dropFirst() { p.addLine(to: q) }468 ctx.stroke(p, with: .color(Theme.info), style: StrokeStyle(lineWidth: 2, lineCap: .round, dash: [5, 4]))469 }470 }471 .accessibilityLabel("Annotations de la version 1.0, liées à l’écran")472 }473 static func polylines(_ d: PKDrawing) -> [[CGPoint]] {474 d.strokes.map { s in s.path.interpolatedPoints(by: .distance(6)).map { $0.location.applying(s.transform) } }475 }476}477