Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Monitor9// File : App/Sources/Features/HistoryView.swift10// Description : Stored history: time-range selection, metric comparison,11// min/max band, gaps, bookmarks, chart and CSV export.12// Module : Features13// Repository : https://git.spboucher.ai/orix-monitor14// Created : 2026-11-2115// Last Modified : 2026-11-2116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : Proprietary, all rights reserved (see license file)82// License File : LICENSE83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import AppKit91import Charts92import ORIXMonitorCore93import SwiftUI94import UniformTypeIdentifiers9596enum HistoryRange: String, CaseIterable, Identifiable {97 case hour, sixHours, day, week, month, year98 var id: String { rawValue }99100 var seconds: TimeInterval {101 switch self {102 case .hour: 3600103 case .sixHours: 6 * 3600104 case .day: 86400105 case .week: 7 * 86400106 case .month: 30 * 86400107 case .year: 365 * 86400108 }109 }110111 var title: LocalizedStringKey {112 switch self {113 case .hour: "1 hour"114 case .sixHours: "6 hours"115 case .day: "24 hours"116 case .week: "7 days"117 case .month: "30 days"118 case .year: "1 year"119 }120 }121}122123struct HistoryView: View {124 @Environment(MonitorModel.self) private var model125 @Environment(\.colorBlindSafe) private var safe126 @State private var range: HistoryRange = .hour127 @State private var primary: MetricID = .cpuTotal128 @State private var secondary: MetricID?129 @State private var series: [Series] = []130 @State private var bookmarks: [StoredEvent] = []131 @State private var loadedAt = Date()132 @State private var hover: Date?133134 var body: some View {135 let f = model.format136 Page {137 PageHeader(title: "History", subtitle: historySubtitle, family: .system, symbol: "chart.xyaxis.line")138 HStack(spacing: ORIX.Space.sm) {139 Picker("Metric", selection: $primary) { metricOptions }.frame(maxWidth: 260)140 .accessibilityIdentifier("history.metric")141 Picker("Compare with", selection: $secondary) {142 Text("Nothing").tag(MetricID?.none)143 metricOptions144 }145 .frame(maxWidth: 280)146 Spacer()147 Picker("Range", selection: $range) { ForEach(HistoryRange.allCases) { Text($0.title).tag($0) } }148 .pickerStyle(.segmented).labelsHidden().fixedSize()149 .accessibilityIdentifier("history.range")150 Button { Task { await load() } } label: { Label("Reload", systemImage: "arrow.clockwise") }.help("Reload from the store")151 }152 ForEach(series, id: \.metric) { s in chartCard(s, f: f) }153 if series.isEmpty { ProgressView().frame(maxWidth: .infinity, minHeight: 200) }154 Card("Bookmarks in this range") {155 if bookmarks.isEmpty {156 Text("No bookmark. Use the bookmark button in the toolbar to mark a moment worth coming back to.").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)157 }158 ForEach(bookmarks) { b in159 HStack {160 Image(systemName: "bookmark.fill").foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)161 Text(f.date(b.date)).font(ORIX.Typeface.value)162 Text(b.payload["note"].flatMap { $0.isEmpty ? nil : $0 } ?? L("No note")).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)163 Spacer()164 Button { model.deleteEvent(b.id) } label: { Image(systemName: "trash") }.buttonStyle(.borderless).accessibilityLabel(Text("Delete bookmark"))165 }166 }167 }168 Card("How history is kept") {169 let r = model.settings.retention170 Text(String(format: L("Every sample is kept for %1$@, one-minute summaries (minimum, average, maximum) for %2$@ and one-hour summaries for %3$@. Longer ranges are drawn from the coarser tiers. History only covers periods when ORIX Monitor was running; those holes are shaded, never filled in."),171 f.duration(r.raw), f.duration(r.minute), f.duration(r.hour)))172 .font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)173 }174 }175 .task(id: "\(range.rawValue)|\(primary.rawValue)|\(secondary?.rawValue ?? 0)|\(model.eventsRevision)") { await load() }176 }177178 private var historySubtitle: String {179 guard let stats = model.storeStatistics, let earliest = stats.earliest else { return L("Collected locally since ORIX Monitor was first opened") }180 return String(format: L("Collected locally since %@"), model.format.date(earliest))181 }182183 @ViewBuilder private var metricOptions: some View {184 ForEach(MetricFamily.allCases, id: \.self) { family in185 let metrics = MetricID.allCases.filter { $0.family == family }186 if !metrics.isEmpty {187 Section(familyName(family)) {188 ForEach(metrics, id: \.self) { Text(L(MetricCatalog.descriptor($0).name)).tag(MetricID?.some($0)).tag($0) }189 }190 }191 }192 }193194 private func familyName(_ family: MetricFamily) -> String {195 switch family {196 case .cpu: L("CPU")197 case .gpu: L("GPU")198 case .memory: L("Memory")199 case .disk: L("Disk")200 case .network: L("Network")201 case .power: L("Power")202 case .thermal: L("Thermal")203 case .system: L("System")204 }205 }206207 private func load() async {208 guard let store = model.store else { return }209 let now = Date()210 let from = now.addingTimeInterval(-range.seconds)211 var loaded = [await store.series(primary, from: from, to: now, maxPoints: 480, now: now)]212 if let secondary, secondary != primary { loaded.append(await store.series(secondary, from: from, to: now, maxPoints: 480, now: now)) }213 let marks = await store.events(kinds: [.bookmark], from: from, to: now)214 series = loaded215 bookmarks = marks216 loadedAt = now217 }218219 private func chartCard(_ s: Series, f: ValueFormatter) -> some View {220 let d = MetricCatalog.descriptor(s.metric)221 let color = s.metric.family.color(colorBlindSafe: safe)222 let from = loadedAt.addingTimeInterval(-range.seconds)223 let format: (Double) -> String = { AlertText.formatted($0, metric: s.metric, formatter: f) }224 let nearest = hover.flatMap { h in s.points.min { abs($0.time - h.timeIntervalSince1970) < abs($1.time - h.timeIntervalSince1970) } }225 return Card(LocalizedStringKey(L(d.name)), family: s.metric.family, quality: d.quality) {226 HStack(spacing: ORIX.Space.lg) {227 stat("Minimum", s.minimum.map(format))228 stat("Average", s.average.map(format))229 stat("Maximum", s.maximum.map(format))230 stat("Samples", String(s.sampleCount))231 stat("Resolution", f.duration(s.step))232 stat("Gaps", s.gaps.isEmpty ? L("None") : "\(s.gaps.count) · \(f.duration(s.gaps.reduce(0) { $0 + $1.duration }))")233 Spacer()234 Menu {235 Button("Export Chart as PNG…") { exportPNG(s, f: f) }236 Button("Export Data as CSV…") { exportCSV(s) }237 } label: { Label("Export", systemImage: "square.and.arrow.up") }238 .menuStyle(.borderlessButton).fixedSize()239 }240 if let nearest {241 Text("\(f.date(nearest.date)) — \(L("Average")) \(format(nearest.avg)) · \(L("Minimum")) \(format(nearest.min)) · \(L("Maximum")) \(format(nearest.max))")242 .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)243 } else {244 Text("Move the pointer over the chart to read a point.").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)245 }246 HistoryChart(series: s, from: from, to: loadedAt, color: color, bookmarks: bookmarks.map(\.date), hover: $hover, format: format)247 .frame(height: 230)248 if s.points.isEmpty {249 Text("No stored sample in this range yet.").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)250 }251 }252 }253254 private func stat(_ label: LocalizedStringKey, _ value: String?) -> some View {255 VStack(alignment: .leading, spacing: 1) {256 Text(label).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary)257 Text(value ?? "—").font(ORIX.Typeface.value)258 }259 .accessibilityElement(children: .combine)260 }261262 @MainActor private func exportPNG(_ s: Series, f: ValueFormatter) {263 let d = MetricCatalog.descriptor(s.metric)264 let view = VStack(alignment: .leading, spacing: 8) {265 Text(L(d.name)).font(.system(size: 16, weight: .bold))266 Text("\(f.date(loadedAt.addingTimeInterval(-range.seconds))) → \(f.date(loadedAt)) · \(d.source)").font(.system(size: 11)).foregroundStyle(.secondary)267 HistoryChart(series: s, from: loadedAt.addingTimeInterval(-range.seconds), to: loadedAt, color: s.metric.family.color(colorBlindSafe: safe),268 bookmarks: bookmarks.map(\.date), hover: .constant(nil), format: { AlertText.formatted($0, metric: s.metric, formatter: f) })269 .frame(width: 1100, height: 420)270 }271 .padding(24).background(ORIX.Palette.surface).environment(\.colorScheme, model.settings.appearance.scheme ?? .light)272 let renderer = ImageRenderer(content: view)273 renderer.scale = 2274 guard let image = renderer.nsImage, let tiff = image.tiffRepresentation, let png = NSBitmapImageRep(data: tiff)?.representation(using: .png, properties: [:]) else { return }275 save(png, name: "ORIX-Monitor-\(s.metric.key)-\(range.rawValue).png", type: .png)276 }277278 private func exportCSV(_ s: Series) {279 let iso = ISO8601DateFormatter()280 var text = "metric,unit,tier,bucket_seconds,timestamp_iso8601,min,avg,max,samples\n"281 let d = MetricCatalog.descriptor(s.metric)282 for p in s.points { text += "\(s.metric.key),\(d.unit.rawValue),\(s.tier.rawValue),\(s.step),\(iso.string(from: p.date)),\(p.min),\(p.avg),\(p.max),\(p.count)\n" }283 save(Data(text.utf8), name: "ORIX-Monitor-\(s.metric.key)-\(range.rawValue).csv", type: .commaSeparatedText)284 }285286 private func save(_ data: Data, name: String, type: UTType) {287 let panel = NSSavePanel()288 panel.nameFieldStringValue = name289 panel.allowedContentTypes = [type]290 if panel.runModal() == .OK, let url = panel.url { try? data.write(to: url) }291 }292}293294/// Average line over a min–max band. Lines break at gaps; gaps are shaded.295struct HistoryChart: View {296 var series: Series297 var from: Date298 var to: Date299 var color: Color300 var bookmarks: [Date]301 @Binding var hover: Date?302 var format: (Double) -> String303304 /// Points tagged with a segment index that changes at every gap, so the line is not drawn across missing data.305 private var segments: [(point: SeriesPoint, segment: Int)] {306 var result: [(SeriesPoint, Int)] = []307 var segment = 0308 var previous: Double?309 for p in series.points {310 if let previous, p.time - previous > series.step * 2.5 { segment += 1 }311 result.append((p, segment))312 previous = p.time313 }314 return result315 }316317 var body: some View {318 Chart {319 ForEach(Array(series.gaps.enumerated()), id: \.offset) { _, gap in320 RectangleMark(xStart: .value("Start", Date(timeIntervalSince1970: gap.start)), xEnd: .value("End", Date(timeIntervalSince1970: gap.end)))321 .foregroundStyle(ORIX.Palette.textTertiary.opacity(0.10))322 }323 ForEach(segments, id: \.point.time) { item in324 AreaMark(x: .value("Time", item.point.date), yStart: .value("Minimum", item.point.min), yEnd: .value("Maximum", item.point.max), series: .value("Segment", "band\(item.segment)"))325 .foregroundStyle(color.opacity(0.18))326 LineMark(x: .value("Time", item.point.date), y: .value("Average", item.point.avg), series: .value("Segment", "line\(item.segment)"))327 .foregroundStyle(color)328 .lineStyle(StrokeStyle(lineWidth: 1.6, lineCap: .round, lineJoin: .round))329 }330 ForEach(bookmarks, id: \.self) { date in331 RuleMark(x: .value("Bookmark", date)).foregroundStyle(ORIX.Palette.accentSecondary).lineStyle(StrokeStyle(lineWidth: 1, dash: [3, 3]))332 .annotation(position: .top, alignment: .center) { Image(systemName: "bookmark.fill").font(.system(size: 8)).foregroundStyle(ORIX.Palette.accentSecondary) }333 }334 if let hover { RuleMark(x: .value("Pointer", hover)).foregroundStyle(ORIX.Palette.textTertiary).lineStyle(StrokeStyle(lineWidth: 1)) }335 }336 .chartXScale(domain: from...to)337 .chartYAxis {338 AxisMarks(position: .leading, values: .automatic(desiredCount: 5)) { value in339 AxisGridLine().foregroundStyle(ORIX.Palette.hairline)340 AxisValueLabel { if let v = value.as(Double.self) { Text(format(v)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary) } }341 }342 }343 .chartXAxis {344 AxisMarks(values: .automatic(desiredCount: 6)) { _ in345 AxisGridLine().foregroundStyle(ORIX.Palette.hairline.opacity(0.5))346 AxisValueLabel().font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)347 }348 }349 .chartOverlay { proxy in350 GeometryReader { geometry in351 Rectangle().fill(.clear).contentShape(Rectangle())352 .onContinuousHover { phase in353 switch phase {354 case .active(let location):355 if let frame = proxy.plotFrame { hover = proxy.value(atX: location.x - geometry[frame].origin.x) }356 case .ended: hover = nil357 }358 }359 }360 }361 .accessibilityElement(children: .ignore)362 .accessibilityLabel(Text(L(MetricCatalog.descriptor(series.metric).name)))363 .accessibilityValue(Text(summary))364 }365366 private var summary: String {367 guard let min = series.minimum, let avg = series.average, let max = series.maximum else { return L("No stored sample in this range yet.") }368 return "\(L("Minimum")) \(format(min)), \(L("Average")) \(format(avg)), \(L("Maximum")) \(format(max)). \(series.gaps.count) \(L("Gaps"))."369 }370}371