Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Charting/ChartInteraction.swift3// Description: The AppKit view above the chart canvas: crosshair tracking, pan and zoom (drag, scroll, pinch, keyboard), and the drawing gestures — create with the active tool, select, move, resize by a handle, delete, cancel — all undoable through the window's undo manager.4import SwiftUI5import VQuantCore67/// Transparent view above the canvas: pointer tracking for the crosshair, drag and two-finger scroll to pan, pinch8/// and vertical scroll to zoom around the pointer, double-click to fit, arrow keys and +/− from the keyboard; with a9/// drawing tool active a click or a drag creates a drawing; with the pointer, drawings are selected, moved, resized.10struct ChartInteraction: NSViewRepresentable {11 let model: ChartModel1213 func makeNSView(context: Context) -> InteractionView { let v = InteractionView(); v.model = model; return v }14 func updateNSView(_ v: InteractionView, context: Context) { v.model = model }1516 final class InteractionView: NSView {17 var model: ChartModel?18 private var tracking: NSTrackingArea?1920 private enum Drag {21 case pan(lastX: CGFloat)22 /// second anchor follows the pointer; `moved` says the press became a drag23 case create(origin: CGPoint, moved: Bool)24 case handle(id: String, index: Int)25 case move(original: ChartDrawing, origin: CGPoint, originIndex: Double, originPrice: Double)26 }27 private var drag: Drag?2829 override var isFlipped: Bool { true }30 override var acceptsFirstResponder: Bool { true }31 override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }3233 override func updateTrackingAreas() {34 if let tracking { removeTrackingArea(tracking) }35 let t = NSTrackingArea(rect: bounds, options: [.mouseMoved, .mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect, .cursorUpdate], owner: self)36 addTrackingArea(t); tracking = t37 }3839 private var plotWidth: CGFloat { max(1, bounds.width - ChartLayout.axisWidth) }40 private func barsPerPoint() -> Double { guard let m = model else { return 0 }; return m.count / Double(plotWidth) }41 private func location(_ e: NSEvent) -> CGPoint { convert(e.locationInWindow, from: nil) }4243 /// The projection of the frame last drawn (nil until the chart has drawn once).44 private var projection: ChartProjection? {45 guard let m = model, let s = m.scale, !m.times.isEmpty else { return nil }46 return ChartProjection(start: m.start, step: plotWidth / CGFloat(m.count), times: m.times, stepSeconds: m.stepSeconds, scale: s)47 }48 private func inPricePanel(_ p: CGPoint) -> Bool {49 guard let s = model?.scale else { return false }50 return p.x >= 0 && p.x <= plotWidth && p.y >= s.minY && p.y <= s.maxY51 }52 private func clampToPanel(_ p: CGPoint) -> CGPoint {53 guard let s = model?.scale else { return p }54 return CGPoint(x: min(max(p.x, 0), plotWidth), y: min(max(p.y, s.minY), s.maxY))55 }5657 /// The topmost drawing under the pointer.58 private func drawing(at p: CGPoint, _ proj: ChartProjection) -> ChartDrawing? {59 guard let m = model, inPricePanel(p), let s = m.scale else { return nil }60 let sp = ScreenPoint(x: Double(p.x), y: Double(p.y))61 return m.drawings.last { d in62 DrawingMath.hit(d.kind, proj.screen(d), sp, width: Double(plotWidth), height: Double(s.maxY), textWidth: d.kind == .text ? Double(ChartDrawingRender.noteWidth(d.text ?? "")) : 140)63 }64 }6566 private func hover(_ e: NSEvent) {67 guard let m = model else { return }68 let p = location(e)69 guard p.x >= 0, p.x <= plotWidth, !m.bars.isEmpty else { clear(); return }70 let i = Int((m.start + Double(p.x) * barsPerPoint()).rounded(.down))71 guard m.bars.indices.contains(i) else { clear(); return }72 m.hover = (i, m.scale?.value(atY: p.y))73 if m.linked { ChartLink.shared.source = m.id; ChartLink.shared.time = m.bars[i].time }74 }75 private func clear() {76 guard let m = model else { return }77 m.hover = nil78 if ChartLink.shared.source == m.id { ChartLink.shared.time = nil; ChartLink.shared.source = nil }79 }80 private func updateCursor(_ p: CGPoint) {81 guard let m = model else { return }82 if m.tool != nil, inPricePanel(p) { NSCursor.crosshair.set() }83 else if let proj = projection, drawing(at: p, proj) != nil { NSCursor.openHand.set() }84 else { NSCursor.arrow.set() }85 }8687 override func cursorUpdate(with e: NSEvent) { updateCursor(location(e)) }88 override func mouseMoved(with e: NSEvent) {89 hover(e)90 let p = location(e)91 updateCursor(p)92 // click-click creation: after a first click the second anchor follows the pointer until the next click93 if let m = model, var d = m.draft, drag == nil, let proj = projection, d.points.count == 2 {94 d.points[1] = proj.dataPoint(at: clampToPanel(p)); m.draft = d95 }96 }97 override func mouseExited(with e: NSEvent) { clear(); NSCursor.arrow.set() }9899 override func mouseDown(with e: NSEvent) {100 window?.makeFirstResponder(self)101 guard let m = model else { return }102 let p = location(e)103 if let tool = m.tool {104 guard inPricePanel(p), let proj = projection else { return }105 let dp = proj.dataPoint(at: p)106 if var d = m.draft, d.points.count == 2 { // the second click of a click-click creation107 d.points[1] = dp; finish(d); return108 }109 let d = ChartDrawing(id: ChartModel.newDrawingID(), kind: tool, points: tool.pointsNeeded == 1 ? [dp] : [dp, dp], color: m.drawingColor, text: nil)110 if tool.pointsNeeded == 1 { finish(d) } else { m.draft = d; m.selection = nil; drag = .create(origin: p, moved: false) }111 return112 }113 guard let proj = projection else { if e.clickCount == 2 { m.fit() } else { drag = .pan(lastX: p.x) }; return }114 // a handle of the selected drawing first, then any drawing, then the chart itself115 if let id = m.selection, let d = m.drawings.first(where: { $0.id == id }),116 let h = DrawingMath.handle(Array(proj.screen(d).prefix(d.kind.pointsNeeded)), at: ScreenPoint(x: Double(p.x), y: Double(p.y))) {117 m.beginEdit(); drag = .handle(id: id, index: h); return118 }119 if let d = drawing(at: p, proj) {120 m.selection = d.id121 if e.clickCount == 2, d.kind == .text { m.editingText = d.id; return }122 m.beginEdit()123 drag = .move(original: d, origin: p, originIndex: proj.index(atX: p.x), originPrice: proj.scale.price(atY: p.y))124 NSCursor.closedHand.set()125 return126 }127 if m.editingText != nil { m.editingText = nil }128 m.selection = nil129 if e.clickCount == 2 { m.fit(); return }130 drag = .pan(lastX: p.x)131 }132133 override func mouseDragged(with e: NSEvent) {134 guard let m = model else { return }135 let p = location(e)136 switch drag {137 case .pan(let last):138 m.pan(bars: -Double(p.x - last) * barsPerPoint()); drag = .pan(lastX: p.x)139 case .create(let origin, let moved):140 guard let proj = projection, var d = m.draft else { break }141 d.points[1] = proj.dataPoint(at: clampToPanel(p)); m.draft = d142 if !moved, hypot(p.x - origin.x, p.y - origin.y) > 4 { drag = .create(origin: origin, moved: true) }143 case .handle(let id, let index):144 guard let proj = projection, var d = m.drawings.first(where: { $0.id == id }), d.points.indices.contains(index) else { break }145 d.points[index] = proj.dataPoint(at: clampToPanel(p)); m.updateDuringEdit(d)146 case .move(let original, _, let originIndex, let originPrice):147 guard let proj = projection else { break }148 let bars = proj.index(atX: p.x) - originIndex149 let price = proj.scale.price(atY: p.y)150 let moved = proj.scale.log && originPrice > 0 && price > 0151 ? DrawingMath.translate(original, bars: bars, priceRatio: price / originPrice, times: m.times, step: m.stepSeconds)152 : DrawingMath.translate(original, bars: bars, price: price - originPrice, times: m.times, step: m.stepSeconds)153 m.updateDuringEdit(moved)154 case nil: break155 }156 hover(e)157 }158159 override func mouseUp(with e: NSEvent) {160 guard let m = model else { drag = nil; return }161 switch drag {162 case .create(_, let moved):163 // a drag creates the drawing at release; a plain click leaves the second anchor following the pointer164 if moved, let d = m.draft { finish(d) }165 case .handle: m.endEdit(undo: undoManager, action: "Resize Drawing")166 case .move: m.endEdit(undo: undoManager, action: "Move Drawing"); updateCursor(location(e))167 default: break168 }169 drag = nil170 }171172 /// Adds a completed drawing (one undo step) and returns to the pointer; a note opens its text field.173 private func finish(_ d: ChartDrawing) {174 guard let m = model else { return }175 m.draft = nil; m.tool = nil; drag = nil176 m.add(d, undo: undoManager)177 if d.kind == .text { m.editingText = d.id }178 NSCursor.arrow.set()179 }180181 override func scrollWheel(with e: NSEvent) {182 guard let m = model else { return }183 let precise = e.hasPreciseScrollingDeltas184 let dx = Double(e.scrollingDeltaX) * (precise ? 1 : 8), dy = Double(e.scrollingDeltaY) * (precise ? 1 : 8)185 if abs(dx) > abs(dy) { m.pan(bars: -dx * barsPerPoint()) }186 else if dy != 0 {187 let p = location(e)188 m.zoom(factor: exp(dy * 0.006), anchor: Double(min(max(p.x / plotWidth, 0), 1)))189 }190 hover(e)191 }192 override func magnify(with e: NSEvent) {193 let p = location(e)194 model?.zoom(factor: 1 + Double(e.magnification), anchor: Double(min(max(p.x / plotWidth, 0), 1)))195 }196 override func keyDown(with e: NSEvent) {197 guard let m = model else { return super.keyDown(with: e) }198 switch e.keyCode {199 case 123: m.pan(bars: -max(1, m.count * 0.1)) // ←200 case 124: m.pan(bars: max(1, m.count * 0.1)) // →201 case 126: m.zoom(factor: 1.25, anchor: 0.5) // ↑202 case 125: m.zoom(factor: 0.8, anchor: 0.5) // ↓203 case 51, 117: // ⌫, ⌦204 if let id = m.selection { m.delete(id, undo: undoManager) } else { super.keyDown(with: e) }205 case 53: // esc: the creation in progress, then the tool, then the selection206 if m.draft != nil { m.draft = nil; drag = nil }207 else if m.tool != nil { m.tool = nil; NSCursor.arrow.set() }208 else if m.selection != nil { m.selection = nil }209 else { super.keyDown(with: e) }210 default:211 switch e.charactersIgnoringModifiers {212 case "+", "=": m.zoom(factor: 1.25, anchor: 0.5)213 case "-": m.zoom(factor: 0.8, anchor: 0.5)214 case "0": m.fit()215 default: super.keyDown(with: e)216 }217 }218 }219 }220}221