@legios/quartermaster 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1276 -0
- package/bin/qm +66 -0
- package/bin/qm-barra +63 -0
- package/bin/qm-barra.swift +1253 -0
- package/bin/qm-indicator +2063 -0
- package/bin/qm-tray +41 -0
- package/bin/qm-tray.ps1 +1241 -0
- package/bin/qm-web +137 -0
- package/dist/adapters/cache-cuota.js +45 -0
- package/dist/adapters/cache-cuota.js.map +1 -0
- package/dist/adapters/cache-endpoint.js +66 -0
- package/dist/adapters/cache-endpoint.js.map +1 -0
- package/dist/adapters/codex.js +462 -0
- package/dist/adapters/codex.js.map +1 -0
- package/dist/adapters/credenciales.js +88 -0
- package/dist/adapters/credenciales.js.map +1 -0
- package/dist/adapters/cuota.js +73 -0
- package/dist/adapters/cuota.js.map +1 -0
- package/dist/adapters/historial.js +103 -0
- package/dist/adapters/historial.js.map +1 -0
- package/dist/adapters/opencode.js +214 -0
- package/dist/adapters/opencode.js.map +1 -0
- package/dist/adapters/transcripciones.js +129 -0
- package/dist/adapters/transcripciones.js.map +1 -0
- package/dist/adapters/utilizacion.js +151 -0
- package/dist/adapters/utilizacion.js.map +1 -0
- package/dist/cli/demo-h1.js +60 -0
- package/dist/cli/demo-h1.js.map +1 -0
- package/dist/cli/preflight.js +39 -0
- package/dist/cli/preflight.js.map +1 -0
- package/dist/cli/qm.js +779 -0
- package/dist/cli/qm.js.map +1 -0
- package/dist/core/config.js +63 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/perfiles.js +139 -0
- package/dist/core/perfiles.js.map +1 -0
- package/dist/core/proyeccion.js +83 -0
- package/dist/core/proyeccion.js.map +1 -0
- package/dist/core/tipos.js +101 -0
- package/dist/core/tipos.js.map +1 -0
- package/dist/render/barras.js +62 -0
- package/dist/render/barras.js.map +1 -0
- package/dist/render/tablero.html +664 -0
- package/package.json +59 -0
- package/src/render/tablero.html +664 -0
|
@@ -0,0 +1,1253 @@
|
|
|
1
|
+
// qm en la barra de menú de macOS.
|
|
2
|
+
//
|
|
3
|
+
// Es la contraparte de `bin/qm-indicator` (GNOME) para la otra mitad de las
|
|
4
|
+
// máquinas. Vale la misma regla que allá y que en el tablero web: DIBUJA y nada
|
|
5
|
+
// más. Le pide el JSON a `qm` por stdout y no sabe qué es una credencial, un
|
|
6
|
+
// llavero ni un endpoint.
|
|
7
|
+
//
|
|
8
|
+
// Las tres cosas que lo hacen algo más que un reloj son las mismas que en GNOME,
|
|
9
|
+
// con los mecanismos que da esta plataforma:
|
|
10
|
+
//
|
|
11
|
+
// · Se entera solo. Vigila el .claude.json de cada perfil con
|
|
12
|
+
// DispatchSource.makeFileSystemObjectSource, así que cuando Claude Code
|
|
13
|
+
// refresca la cuota el número cambia en el acto. El sondeo de 5 min queda
|
|
14
|
+
// de red de seguridad. Claude Code reescribe el archivo por rename, que
|
|
15
|
+
// mata el descriptor: por eso el vigía se vuelve a armar solo.
|
|
16
|
+
// · Avisa sin que lo mires. Notifica al cruzar 80 % y 95 %, y cuando la
|
|
17
|
+
// proyección pasa a decir que tocás el techo ANTES del reinicio — que es el
|
|
18
|
+
// momento útil, no cuando ya chocaste.
|
|
19
|
+
// · No repite. Cada aviso se recuerda por (perfil, barra, reinicio, umbral),
|
|
20
|
+
// así que una ventana avisa una vez y vuelve a avisar en la siguiente.
|
|
21
|
+
//
|
|
22
|
+
// Se compila sin Xcode: `swiftc` viene con las Command Line Tools, y AppKit
|
|
23
|
+
// alcanza para un NSStatusItem. `bin/qm-barra` lo compila si hace falta.
|
|
24
|
+
|
|
25
|
+
import AppKit
|
|
26
|
+
import Foundation
|
|
27
|
+
|
|
28
|
+
// Red de seguridad para Claude: ahí manda el vigía de archivos.
|
|
29
|
+
// Para Codex NO hay vigía —no deja nada en disco— así que este sondeo es lo
|
|
30
|
+
// único que mueve su número, y por eso la cadencia se adapta (ver `cadencia`).
|
|
31
|
+
let SEGUNDOS_SONDEO: TimeInterval = 300
|
|
32
|
+
// Coalescer escrituras: Claude Code reescribe .claude.json varias veces seguidas.
|
|
33
|
+
let DEBOUNCE: TimeInterval = 1.5
|
|
34
|
+
/// Piso para cualquier cadencia que salga a la RED.
|
|
35
|
+
///
|
|
36
|
+
/// La primera versión bajaba a 20 s cuando una barra pasaba el 90 %, y como
|
|
37
|
+
/// además refrescaba todas las cuentas en cada vuelta daban ~360 pedidos por
|
|
38
|
+
/// hora, sostenidos mientras la barra siguiera alta. Claude Code pide la cuota
|
|
39
|
+
/// del orden de una vez por sesión. Un endpoint no documentado que además
|
|
40
|
+
/// puede desaparecer sin aviso no es lugar para eso, y la diferencia real es
|
|
41
|
+
/// chica: a 1,6 puntos por minuto, 60 s son 1,6 puntos de atraso.
|
|
42
|
+
///
|
|
43
|
+
/// La lectura del disco no tiene piso: es gratis y la dispara el vigía.
|
|
44
|
+
let MINIMO_RED: TimeInterval = 60
|
|
45
|
+
let UMBRALES = [80, 95]
|
|
46
|
+
let ANCHO_BARRA = 12
|
|
47
|
+
let VIEJO_SEGUNDOS = 6 * 3600
|
|
48
|
+
|
|
49
|
+
/// La raíz del repo. El binario compilado vive en ~/.cache, así que derivarla
|
|
50
|
+
/// de argv[0] daría ~/.cache y ahí no hay ningún bin/qm: el lanzador, que sí
|
|
51
|
+
/// sabe dónde está el repo, la pasa por entorno. Lo de argv[0] queda para
|
|
52
|
+
/// cuando alguien corre el binario a mano desde el repo.
|
|
53
|
+
let RAIZ: URL = {
|
|
54
|
+
if let r = ProcessInfo.processInfo.environment["QM_RAIZ"], !r.isEmpty {
|
|
55
|
+
return URL(fileURLWithPath: r)
|
|
56
|
+
}
|
|
57
|
+
return URL(fileURLWithPath: CommandLine.arguments[0])
|
|
58
|
+
.resolvingSymlinksInPath().deletingLastPathComponent().deletingLastPathComponent()
|
|
59
|
+
}()
|
|
60
|
+
|
|
61
|
+
/// `qm` al lado del repo; si no está, el que haya instalado `make instalar`.
|
|
62
|
+
func rutaQm() -> String {
|
|
63
|
+
let candidato = RAIZ.appendingPathComponent("bin/qm").path
|
|
64
|
+
if FileManager.default.isExecutableFile(atPath: candidato) { return candidato }
|
|
65
|
+
return (NSHomeDirectory() as NSString).appendingPathComponent(".local/bin/qm")
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// La paleta de estado, la misma del tablero y validada contra los dos fondos
|
|
69
|
+
/// que puede tener la barra. El color va en la MARCA, nunca en el texto: el
|
|
70
|
+
/// número se queda con el color de etiqueta del sistema, que se adapta solo.
|
|
71
|
+
enum Nivel {
|
|
72
|
+
case ok, atento, aviso, critico
|
|
73
|
+
var color: NSColor {
|
|
74
|
+
switch self {
|
|
75
|
+
case .ok: return NSColor(srgbRed: 0.047, green: 0.639, blue: 0.047, alpha: 1) // #0ca30c
|
|
76
|
+
case .atento: return NSColor(srgbRed: 0.980, green: 0.698, blue: 0.098, alpha: 1) // #fab219
|
|
77
|
+
case .aviso: return NSColor(srgbRed: 0.925, green: 0.514, blue: 0.353, alpha: 1) // #ec835a
|
|
78
|
+
case .critico: return NSColor(srgbRed: 0.816, green: 0.231, blue: 0.231, alpha: 1) // #d03b3b
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/// El color con que se identifica cada cuenta.
|
|
84
|
+
///
|
|
85
|
+
/// Deliberadamente lejos de la paleta de estado: los colores de estado están
|
|
86
|
+
/// reservados y no pueden significar además «esta es la cuenta 2». Por eso acá
|
|
87
|
+
/// no hay ni verde ni ámbar ni rojo — azul, violeta y magenta no se confunden
|
|
88
|
+
/// con «vas bien» ni con «te frenaste».
|
|
89
|
+
func colorCuenta(_ i: Int) -> NSColor {
|
|
90
|
+
let claro: [NSColor] = [
|
|
91
|
+
NSColor(srgbRed: 0.165, green: 0.471, blue: 0.839, alpha: 1), // #2a78d6
|
|
92
|
+
NSColor(srgbRed: 0.290, green: 0.227, blue: 0.655, alpha: 1), // #4a3aa7
|
|
93
|
+
NSColor(srgbRed: 0.910, green: 0.482, blue: 0.643, alpha: 1), // #e87ba4
|
|
94
|
+
]
|
|
95
|
+
let oscuro: [NSColor] = [
|
|
96
|
+
NSColor(srgbRed: 0.224, green: 0.529, blue: 0.898, alpha: 1), // #3987e5
|
|
97
|
+
NSColor(srgbRed: 0.565, green: 0.522, blue: 0.914, alpha: 1), // #9085e9
|
|
98
|
+
NSColor(srgbRed: 0.835, green: 0.318, blue: 0.506, alpha: 1), // #d55181
|
|
99
|
+
]
|
|
100
|
+
return NSColor(name: nil) { ap in
|
|
101
|
+
let tabla = ap.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua ? oscuro : claro
|
|
102
|
+
return tabla[i % tabla.count]
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/// La marca de cada producto, dibujada: SF Symbols no trae ni la de Claude ni
|
|
107
|
+
/// la de Codex. El asterisco es la forma de la de Claude; los chevrones, código.
|
|
108
|
+
func glifoProducto(_ producto: String, _ color: NSColor, _ lado: CGFloat) -> NSImage {
|
|
109
|
+
NSImage(size: NSSize(width: lado, height: lado), flipped: false) { r in
|
|
110
|
+
let c = NSPoint(x: r.midX, y: r.midY)
|
|
111
|
+
let t = NSBezierPath()
|
|
112
|
+
t.lineWidth = 1.3
|
|
113
|
+
t.lineCapStyle = .round
|
|
114
|
+
if producto == "opencode" {
|
|
115
|
+
// Un rombo: ni asterisco ni chevrones, y se distingue de los dos a
|
|
116
|
+
// 9 px, que es lo único que se le pide a un glifo de barra.
|
|
117
|
+
let r0 = lado * 0.34
|
|
118
|
+
t.move(to: NSPoint(x: c.x, y: c.y + r0))
|
|
119
|
+
t.line(to: NSPoint(x: c.x + r0, y: c.y))
|
|
120
|
+
t.line(to: NSPoint(x: c.x, y: c.y - r0))
|
|
121
|
+
t.line(to: NSPoint(x: c.x - r0, y: c.y))
|
|
122
|
+
t.close()
|
|
123
|
+
} else if producto == "codex" {
|
|
124
|
+
// Los chevrones necesitan aire en el medio: pegados, y con la punta
|
|
125
|
+
// redondeada, a 10 px se fusionan y el glifo se lee como una «o».
|
|
126
|
+
let a = lado * 0.30, hueco = lado * 0.20
|
|
127
|
+
t.move(to: NSPoint(x: c.x - hueco, y: c.y + a))
|
|
128
|
+
t.line(to: NSPoint(x: c.x - hueco - a * 0.85, y: c.y))
|
|
129
|
+
t.line(to: NSPoint(x: c.x - hueco, y: c.y - a))
|
|
130
|
+
t.move(to: NSPoint(x: c.x + hueco, y: c.y + a))
|
|
131
|
+
t.line(to: NSPoint(x: c.x + hueco + a * 0.85, y: c.y))
|
|
132
|
+
t.line(to: NSPoint(x: c.x + hueco, y: c.y - a))
|
|
133
|
+
} else {
|
|
134
|
+
let r0 = lado * 0.36
|
|
135
|
+
for k in 0..<3 {
|
|
136
|
+
let ang = Double(k) * Double.pi / 3
|
|
137
|
+
t.move(to: NSPoint(x: c.x + r0 * CGFloat(cos(ang)), y: c.y + r0 * CGFloat(sin(ang))))
|
|
138
|
+
t.line(to: NSPoint(x: c.x - r0 * CGFloat(cos(ang)), y: c.y - r0 * CGFloat(sin(ang))))
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
color.setStroke()
|
|
142
|
+
t.stroke()
|
|
143
|
+
return true
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
func nivelDe(_ pct: Int, preocupa: Bool) -> Nivel {
|
|
148
|
+
if pct >= 95 { return .critico }
|
|
149
|
+
if preocupa || pct >= 80 { return .aviso }
|
|
150
|
+
if pct >= 60 { return .atento }
|
|
151
|
+
return .ok
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ── formato ──────────────────────────────────────────────────────────────
|
|
155
|
+
/// `.claude-teams` -> `teams`; el perfil por defecto -> `main`.
|
|
156
|
+
func corto(_ nombre: String) -> String {
|
|
157
|
+
var n = nombre
|
|
158
|
+
if n.hasPrefix(".claude") { n.removeFirst(".claude".count) }
|
|
159
|
+
while n.hasPrefix("-") { n.removeFirst() }
|
|
160
|
+
return n.isEmpty ? "main" : n
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/// La escalera de duración del proyecto.
|
|
164
|
+
///
|
|
165
|
+
/// El canon es `duracion()` en src/render/barras.ts —por donde pasa todo lo que
|
|
166
|
+
/// imprime el CLI— y está congelado en test/fixtures/duraciones.json.
|
|
167
|
+
/// `make gate-duraciones` corre las cuatro implementaciones y las compara.
|
|
168
|
+
///
|
|
169
|
+
/// Antes esta decía "ya", "1h" y "1d0h" donde el CLI decía "vencido", "1h00m" y
|
|
170
|
+
/// "1d". Eran dos convenciones conviviendo, y sobrevivieron porque nadie había
|
|
171
|
+
/// comparado una GUI contra el CLI.
|
|
172
|
+
func duracion(_ segundos: Int) -> String {
|
|
173
|
+
if segundos < 0 { return "vencido" }
|
|
174
|
+
let h = segundos / 3600, m = (segundos % 3600) / 60
|
|
175
|
+
if h >= 24 { return h % 24 == 0 ? "\(h / 24)d" : "\(h / 24)d\(h % 24)h" }
|
|
176
|
+
if h > 0 { return String(format: "%dh%02dm", h, m) }
|
|
177
|
+
if m > 0 { return "\(m)m" }
|
|
178
|
+
return "\(segundos)s"
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
func barraTexto(_ pct: Int) -> String {
|
|
182
|
+
let llenos = max(0, min(ANCHO_BARRA, Int((Double(pct) / 100.0 * Double(ANCHO_BARRA)).rounded())))
|
|
183
|
+
return String(repeating: "█", count: llenos) + String(repeating: "░", count: ANCHO_BARRA - llenos)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ── el dato ──────────────────────────────────────────────────────────────
|
|
187
|
+
struct Ventana {
|
|
188
|
+
let clave: String
|
|
189
|
+
let alcance: String?
|
|
190
|
+
let porcentaje: Int
|
|
191
|
+
let severidad: String
|
|
192
|
+
let activa: Bool
|
|
193
|
+
let reinicia: Date?
|
|
194
|
+
let grupo: String?
|
|
195
|
+
/// Lo decide qm, no acá.
|
|
196
|
+
let preocupa: Bool
|
|
197
|
+
|
|
198
|
+
var nombre: String { alcance == nil ? clave : "\(clave) (\(alcance!))" }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
struct Proyeccion {
|
|
202
|
+
let ritmo: Double
|
|
203
|
+
let techo: Date
|
|
204
|
+
let chocas: Bool
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/// Lo que hay que decir de una cuenta arriba: la sesión de 5 h, la barra que
|
|
208
|
+
/// frena antes, y dos banderas que NO son lo mismo.
|
|
209
|
+
///
|
|
210
|
+
/// `viejo` califica al número —este 23 es de hace rato— así que viaja pegado a
|
|
211
|
+
/// él, como `~23`. `alerta` es del estado de la cuenta, y ese NO se escribe al
|
|
212
|
+
/// lado del número de la sesión: el aviso puede ser de la barra semanal, y un
|
|
213
|
+
/// `23!` diría que lo alarmante es la sesión, que es falso. La alerta la lleva
|
|
214
|
+
/// el color del medidor de la derecha, que es justamente el de esa barra.
|
|
215
|
+
/// Dos números por cuenta, cada uno SIEMPRE con el mismo significado:
|
|
216
|
+
/// el medidor es la semanal y el número es la sesión de 5 h.
|
|
217
|
+
///
|
|
218
|
+
/// Antes el medidor mostraba «la que frena antes», que a veces era la semanal y
|
|
219
|
+
/// a veces la sesión — y cuando era la sesión, dibujaba lo mismo que ya decía
|
|
220
|
+
/// el número al lado. Un encoding que cambia de significado según el dato no se
|
|
221
|
+
/// puede leer de un vistazo, que es lo único que hace la barra de menú.
|
|
222
|
+
struct Trozo {
|
|
223
|
+
let nombre: String
|
|
224
|
+
let producto: String
|
|
225
|
+
let indice: Int
|
|
226
|
+
/// La ventana corta: «¿puedo seguir ahora?». Va como número.
|
|
227
|
+
let sesion: Int?
|
|
228
|
+
let sesionAlerta: Bool
|
|
229
|
+
/// La peor de las semanales: «¿llego al final?». Va como medidor.
|
|
230
|
+
let semanal: Int?
|
|
231
|
+
let semanalAlerta: Bool
|
|
232
|
+
let viejo: Bool
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
struct PerfilVista {
|
|
236
|
+
/// claude | codex. Lo único que distingue una cuenta de otra.
|
|
237
|
+
let producto: String
|
|
238
|
+
let nombre: String
|
|
239
|
+
let directorio: String
|
|
240
|
+
let cuenta: String?
|
|
241
|
+
let plan: String?
|
|
242
|
+
let credencial: String
|
|
243
|
+
let hayNumero: Bool
|
|
244
|
+
let frase: String?
|
|
245
|
+
/// Ya filtradas por qm: las que vale la pena mostrar.
|
|
246
|
+
let mostrar: [Ventana]
|
|
247
|
+
/// Las muestras recientes de la barra que frena, ya recortadas por qm.
|
|
248
|
+
let historia: [(t: Double, pct: Int)]
|
|
249
|
+
/// La que frena antes, la sesión y la semanal — resueltas por qm.
|
|
250
|
+
let frena: Ventana?
|
|
251
|
+
let sesion: Ventana?
|
|
252
|
+
let semanal: Ventana?
|
|
253
|
+
let edadSegundos: Int?
|
|
254
|
+
let proyeccion: Proyeccion?
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Las reglas del núcleo no se reimplementan acá: `qm` manda `mostrar`, `frena`,
|
|
258
|
+
// `sesion` y `semanal` ya resueltas. Este archivo dibuja y nada más.
|
|
259
|
+
|
|
260
|
+
let fechaISO: ISO8601DateFormatter = {
|
|
261
|
+
let f = ISO8601DateFormatter()
|
|
262
|
+
f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
263
|
+
return f
|
|
264
|
+
}()
|
|
265
|
+
|
|
266
|
+
func fecha(_ s: Any?) -> Date? {
|
|
267
|
+
guard let t = s as? String else { return nil }
|
|
268
|
+
return fechaISO.date(from: t) ?? ISO8601DateFormatter().date(from: t)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// ── leer a qm ────────────────────────────────────────────────────────────
|
|
272
|
+
enum Lectura {
|
|
273
|
+
case ok([PerfilVista])
|
|
274
|
+
/// Silencio es el bug: si no hay número, hay una frase.
|
|
275
|
+
case falla(String)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
func leer() -> Lectura {
|
|
279
|
+
let p = Process()
|
|
280
|
+
p.executableURL = URL(fileURLWithPath: rutaQm())
|
|
281
|
+
// --breve no toca las transcripciones: ~150 ms en vez de un segundo.
|
|
282
|
+
p.arguments = ["--json", "--breve"]
|
|
283
|
+
let salida = Pipe(), errores = Pipe()
|
|
284
|
+
p.standardOutput = salida
|
|
285
|
+
p.standardError = errores
|
|
286
|
+
do { try p.run() } catch {
|
|
287
|
+
return .falla("no pude correr qm: \(error.localizedDescription)")
|
|
288
|
+
}
|
|
289
|
+
let datos = salida.fileHandleForReading.readDataToEndOfFile()
|
|
290
|
+
let feo = String(data: errores.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
|
|
291
|
+
p.waitUntilExit()
|
|
292
|
+
|
|
293
|
+
// 3 es «alguna barra pasó el umbral», no un error.
|
|
294
|
+
if p.terminationStatus != 0 && p.terminationStatus != 3 && datos.isEmpty {
|
|
295
|
+
let primera = feo.split(separator: "\n").first.map(String.init) ?? "sin detalle"
|
|
296
|
+
return .falla("qm salió \(p.terminationStatus): \(primera)")
|
|
297
|
+
}
|
|
298
|
+
guard let raiz = (try? JSONSerialization.jsonObject(with: datos)) as? [String: Any],
|
|
299
|
+
let crudos = raiz["perfiles"] as? [[String: Any]] else {
|
|
300
|
+
return .falla("qm no devolvió JSON")
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
let perfiles: [PerfilVista] = crudos.map { p in
|
|
304
|
+
let cuota = p["cuota"] as? [String: Any] ?? [:]
|
|
305
|
+
let hayNumero = (cuota["estado"] as? String) == "ok"
|
|
306
|
+
func aVentana(_ v: [String: Any]) -> Ventana {
|
|
307
|
+
Ventana(clave: v["clave"] as? String ?? "?",
|
|
308
|
+
alcance: v["alcance"] as? String,
|
|
309
|
+
porcentaje: v["porcentaje"] as? Int ?? 0,
|
|
310
|
+
severidad: v["severidad"] as? String ?? "normal",
|
|
311
|
+
activa: v["activa"] as? Bool ?? false,
|
|
312
|
+
reinicia: fecha(v["reinicia"]),
|
|
313
|
+
grupo: v["grupo"] as? String,
|
|
314
|
+
preocupa: v["preocupa"] as? Bool ?? false)
|
|
315
|
+
}
|
|
316
|
+
let mostrar = (cuota["mostrar"] as? [[String: Any]] ?? []).map(aVentana)
|
|
317
|
+
let historia: [(t: Double, pct: Int)] = (cuota["historia"] as? [[String: Any]] ?? []).compactMap {
|
|
318
|
+
guard let t = $0["t"] as? Double, let p = $0["porcentaje"] as? Int else { return nil }
|
|
319
|
+
return (t, p)
|
|
320
|
+
}
|
|
321
|
+
let una = { (k: String) -> Ventana? in (cuota[k] as? [String: Any]).map(aVentana) }
|
|
322
|
+
var proy: Proyeccion? = nil
|
|
323
|
+
if let pr = p["proyeccion"] as? [String: Any], (pr["estado"] as? String) == "sube",
|
|
324
|
+
let techo = fecha(pr["techo"]) {
|
|
325
|
+
proy = Proyeccion(ritmo: pr["ritmoPuntosPorHora"] as? Double ?? 0,
|
|
326
|
+
techo: techo,
|
|
327
|
+
chocas: pr["chocasAntesDelReinicio"] as? Bool ?? false)
|
|
328
|
+
}
|
|
329
|
+
return PerfilVista(
|
|
330
|
+
producto: p["producto"] as? String ?? "claude",
|
|
331
|
+
nombre: p["perfil"] as? String ?? "?",
|
|
332
|
+
directorio: p["directorio"] as? String ?? "",
|
|
333
|
+
cuenta: p["cuenta"] as? String,
|
|
334
|
+
plan: p["plan"] as? String,
|
|
335
|
+
credencial: p["credencial"] as? String ?? "?",
|
|
336
|
+
hayNumero: hayNumero,
|
|
337
|
+
frase: cuota["frase"] as? String,
|
|
338
|
+
mostrar: mostrar, historia: historia,
|
|
339
|
+
frena: una("frena"), sesion: una("sesion"), semanal: una("semanal"),
|
|
340
|
+
edadSegundos: cuota["edadSegundos"] as? Int,
|
|
341
|
+
proyeccion: proy)
|
|
342
|
+
}
|
|
343
|
+
return .ok(perfiles)
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ── avisos ───────────────────────────────────────────────────────────────
|
|
347
|
+
/// Sin bundle no hay UNUserNotificationCenter, y osascript sí anda: es la vía
|
|
348
|
+
// que no obliga a empaquetar una .app para decir una frase.
|
|
349
|
+
func notificar(titulo: String, cuerpo: String) {
|
|
350
|
+
let limpio: (String) -> String = { $0.replacingOccurrences(of: "\"", with: "'") }
|
|
351
|
+
let p = Process()
|
|
352
|
+
p.executableURL = URL(fileURLWithPath: "/usr/bin/osascript")
|
|
353
|
+
p.arguments = ["-e", "display notification \"\(limpio(cuerpo))\" with title \"\(limpio(titulo))\""]
|
|
354
|
+
try? p.run()
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
// ── el menú, dibujado ────────────────────────────────────────────────────
|
|
359
|
+
/// Una cuenta adentro del menú, dibujada con el mismo lenguaje que el item de
|
|
360
|
+
/// arriba: medidores de verdad, no bloques `█░` de una tipografía monoespaciada.
|
|
361
|
+
///
|
|
362
|
+
/// Es una NSView y no un NSMenuItem con texto porque el menú es donde se
|
|
363
|
+
/// contesta la pregunta completa —qué barra, cuánto, cuándo se reinicia, a qué
|
|
364
|
+
/// ritmo— y eso pide una grilla, no un renglón.
|
|
365
|
+
/// La cabecera del menú: la respuesta de una línea.
|
|
366
|
+
///
|
|
367
|
+
/// Es la misma pregunta que contesta el héroe del tablero —«qué me frena
|
|
368
|
+
/// primero, en toda la máquina»— y faltaba acá: había que leer las tres
|
|
369
|
+
/// cuentas y compararlas uno mismo. Cuando esa barra está llena, además dice
|
|
370
|
+
/// **cuándo te liberás**, que es lo único que importa una vez que te frenaste.
|
|
371
|
+
final class VistaResumen: NSView {
|
|
372
|
+
private let cuenta: String
|
|
373
|
+
private let barra: String
|
|
374
|
+
private let pct: Int
|
|
375
|
+
private let nivel: Nivel
|
|
376
|
+
private let reinicia: Date?
|
|
377
|
+
|
|
378
|
+
init?(_ perfiles: [PerfilVista]) {
|
|
379
|
+
var mejor: (PerfilVista, Ventana, Int)? = nil
|
|
380
|
+
var i = 0
|
|
381
|
+
for p in perfiles where p.hayNumero {
|
|
382
|
+
if let v = p.frena, mejor == nil || v.porcentaje > mejor!.1.porcentaje {
|
|
383
|
+
mejor = (p, v, i)
|
|
384
|
+
}
|
|
385
|
+
i += 1
|
|
386
|
+
}
|
|
387
|
+
guard let (p, v, _) = mejor else { return nil }
|
|
388
|
+
cuenta = corto(p.nombre)
|
|
389
|
+
barra = v.nombre
|
|
390
|
+
pct = v.porcentaje
|
|
391
|
+
nivel = nivelDe(v.porcentaje, preocupa: v.preocupa || (p.proyeccion?.chocas ?? false))
|
|
392
|
+
reinicia = v.reinicia
|
|
393
|
+
super.init(frame: NSRect(x: 0, y: 0, width: 340, height: 74))
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
required init?(coder: NSCoder) { nil }
|
|
397
|
+
|
|
398
|
+
override func draw(_ dirtyRect: NSRect) {
|
|
399
|
+
let m: CGFloat = 15
|
|
400
|
+
// El anillo, igual que el del tablero.
|
|
401
|
+
let lado: CGFloat = 44
|
|
402
|
+
let centro = NSPoint(x: m + lado / 2, y: bounds.height / 2)
|
|
403
|
+
let radio = lado / 2 - 3
|
|
404
|
+
let pista = NSBezierPath()
|
|
405
|
+
pista.appendArc(withCenter: centro, radius: radio, startAngle: 0, endAngle: 360)
|
|
406
|
+
pista.lineWidth = 5
|
|
407
|
+
nivel.color.withAlphaComponent(0.18).setStroke()
|
|
408
|
+
pista.stroke()
|
|
409
|
+
|
|
410
|
+
let arco = NSBezierPath()
|
|
411
|
+
arco.appendArc(withCenter: centro, radius: radio, startAngle: 90,
|
|
412
|
+
endAngle: 90 - 360 * CGFloat(min(100, max(0, pct))) / 100, clockwise: true)
|
|
413
|
+
arco.lineWidth = 5
|
|
414
|
+
arco.lineCapStyle = .round
|
|
415
|
+
nivel.color.setStroke()
|
|
416
|
+
arco.stroke()
|
|
417
|
+
|
|
418
|
+
let x = m + lado + 14
|
|
419
|
+
let esc = { (t: String, y: CGFloat, f: NSFont, c: NSColor) in
|
|
420
|
+
NSAttributedString(string: t, attributes: [.font: f, .foregroundColor: c])
|
|
421
|
+
.draw(at: NSPoint(x: x, y: y))
|
|
422
|
+
}
|
|
423
|
+
esc("LO PRIMERO QUE TE FRENA", bounds.height - 22, .systemFont(ofSize: 9, weight: .semibold),
|
|
424
|
+
.tertiaryLabelColor)
|
|
425
|
+
let cifra = NSAttributedString(string: "\(pct)%", attributes: [
|
|
426
|
+
.font: NSFont.systemFont(ofSize: 20, weight: .semibold), .foregroundColor: NSColor.labelColor,
|
|
427
|
+
])
|
|
428
|
+
cifra.draw(at: NSPoint(x: x, y: bounds.height - 44))
|
|
429
|
+
// El nombre va a la derecha de la cifra, en su línea de base.
|
|
430
|
+
NSAttributedString(string: " \(cuenta) · \(barra)", attributes: [
|
|
431
|
+
.font: NSFont.systemFont(ofSize: 11.5), .foregroundColor: NSColor.secondaryLabelColor,
|
|
432
|
+
]).draw(at: NSPoint(x: x + cifra.size().width, y: bounds.height - 40))
|
|
433
|
+
|
|
434
|
+
// Cuando ya te frenó, lo que importa no es cuándo "reinicia": es cuándo
|
|
435
|
+
// volvés a poder trabajar. Es la misma fecha y una pregunta distinta.
|
|
436
|
+
let falta = reinicia.map { Int($0.timeIntervalSinceNow) }
|
|
437
|
+
let texto: String
|
|
438
|
+
if pct >= 95, let f = falta { texto = "libre en \(duracion(f))" }
|
|
439
|
+
else if let f = falta { texto = "reinicia en \(duracion(f))" }
|
|
440
|
+
else { texto = "sin reinicio informado" }
|
|
441
|
+
esc(texto, 12, .systemFont(ofSize: 11, weight: pct >= 95 ? .medium : .regular),
|
|
442
|
+
pct >= 95 ? nivel.color : .tertiaryLabelColor)
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/// La clave de la barra que frena, para saber a cuál pegarle la curva.
|
|
447
|
+
private func peor_clave(_ p: PerfilVista) -> String? { p.frena?.nombre }
|
|
448
|
+
|
|
449
|
+
final class VistaCuenta: NSView {
|
|
450
|
+
private let titulo: String
|
|
451
|
+
private let sub: String
|
|
452
|
+
private let icono: NSImage?
|
|
453
|
+
private let barras: [(nombre: String, pct: Int, nivel: Nivel, activa: Bool, pie: String)]
|
|
454
|
+
private let historia: [(t: Double, pct: Int)]
|
|
455
|
+
private let claveQueFrena: String?
|
|
456
|
+
private let frase: String?
|
|
457
|
+
private let ritmo: String?
|
|
458
|
+
private let ritmoRojo: Bool
|
|
459
|
+
|
|
460
|
+
private static let ANCHO: CGFloat = 340
|
|
461
|
+
private static let MARGEN: CGFloat = 15
|
|
462
|
+
// Un renglón de barra = nombre (14) + medidor (8) + pie (13). Si esta
|
|
463
|
+
// cuenta no coincide con lo que dibuja draw(), los renglones se pisan.
|
|
464
|
+
private static let ALTO_BARRA: CGFloat = 35
|
|
465
|
+
// 6 de aire + 16 de curva + 12 para los rótulos de abajo. Si esto no
|
|
466
|
+
// coincide con lo que dibuja draw(), los rótulos se comen el renglón
|
|
467
|
+
// siguiente — que fue exactamente lo que pasó.
|
|
468
|
+
private static let ALTO_CURVA: CGFloat = 34
|
|
469
|
+
|
|
470
|
+
init(_ p: PerfilVista, icono: NSImage?) {
|
|
471
|
+
self.titulo = corto(p.nombre)
|
|
472
|
+
var partes: [String] = []
|
|
473
|
+
if let c = p.cuenta { partes.append(c) }
|
|
474
|
+
if let pl = p.plan { partes.append(pl) }
|
|
475
|
+
self.sub = partes.joined(separator: " · ")
|
|
476
|
+
self.icono = icono
|
|
477
|
+
self.historia = p.historia
|
|
478
|
+
self.claveQueFrena = peor_clave(p)
|
|
479
|
+
|
|
480
|
+
let visibles = p.mostrar
|
|
481
|
+
let cual = p.frena
|
|
482
|
+
let chocas = p.proyeccion?.chocas ?? false
|
|
483
|
+
self.barras = p.hayNumero ? visibles.map { v in
|
|
484
|
+
var pie = v.reinicia.map { "reinicia en \(duracion(Int($0.timeIntervalSinceNow)))" } ?? ""
|
|
485
|
+
if let e = p.edadSegundos, v.clave == cual?.clave {
|
|
486
|
+
pie += pie.isEmpty ? "" : " · "
|
|
487
|
+
pie += "cache de hace \(duracion(e))" + (e >= VIEJO_SEGUNDOS ? " · viejo" : "")
|
|
488
|
+
}
|
|
489
|
+
return (v.nombre, v.porcentaje,
|
|
490
|
+
nivelDe(v.porcentaje, preocupa: v.preocupa || (chocas && v.clave == cual?.clave)),
|
|
491
|
+
v.activa, pie)
|
|
492
|
+
} : []
|
|
493
|
+
// Silencio es el bug: si no hay número, hay una frase.
|
|
494
|
+
self.frase = p.hayNumero ? nil : (p.frase ?? "sin cuota")
|
|
495
|
+
if let pr = p.proyeccion {
|
|
496
|
+
self.ritmo = String(format: "%.1f pts/h · 100 %% en %@%@", pr.ritmo,
|
|
497
|
+
duracion(Int(pr.techo.timeIntervalSinceNow)),
|
|
498
|
+
pr.chocas ? " — antes del reinicio" : "")
|
|
499
|
+
self.ritmoRojo = pr.chocas
|
|
500
|
+
} else {
|
|
501
|
+
self.ritmo = nil
|
|
502
|
+
self.ritmoRojo = false
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
var alto = VistaCuenta.MARGEN + 16 + 15 + 6
|
|
506
|
+
alto += CGFloat(barras.count) * VistaCuenta.ALTO_BARRA
|
|
507
|
+
if historia.count >= 3 { alto += VistaCuenta.ALTO_CURVA }
|
|
508
|
+
if frase != nil { alto += 34 }
|
|
509
|
+
if ritmo != nil { alto += 16 }
|
|
510
|
+
alto += 12
|
|
511
|
+
super.init(frame: NSRect(x: 0, y: 0, width: VistaCuenta.ANCHO, height: alto))
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
required init?(coder: NSCoder) { nil }
|
|
515
|
+
|
|
516
|
+
private func escribir(_ t: String, _ x: CGFloat, _ y: CGFloat, _ f: NSFont, _ c: NSColor,
|
|
517
|
+
derecha: CGFloat? = nil) {
|
|
518
|
+
let a = NSAttributedString(string: t, attributes: [.font: f, .foregroundColor: c])
|
|
519
|
+
a.draw(at: NSPoint(x: derecha == nil ? x : derecha! - a.size().width, y: y))
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/// Las dos horas de muestras, dibujadas. El eje Y va del mínimo al máximo
|
|
523
|
+
/// de la serie y no de 0 a 100: lo que interesa acá es la PENDIENTE, y a
|
|
524
|
+
/// escala completa una subida de tres puntos se ve plana.
|
|
525
|
+
private func dibujarCurva(_ caja: NSRect, _ nivel: Nivel) {
|
|
526
|
+
guard historia.count >= 3 else { return }
|
|
527
|
+
let ts = historia.map(\.t), ps = historia.map { Double($0.pct) }
|
|
528
|
+
let t0 = ts.min()!, t1 = ts.max()!
|
|
529
|
+
let p0 = ps.min()!, p1 = ps.max()!
|
|
530
|
+
guard t1 > t0 else { return }
|
|
531
|
+
let rango = max(1, p1 - p0)
|
|
532
|
+
|
|
533
|
+
let x = { (t: Double) in caja.minX + caja.width * CGFloat((t - t0) / (t1 - t0)) }
|
|
534
|
+
let y = { (p: Double) in caja.minY + caja.height * CGFloat((p - p0) / rango) }
|
|
535
|
+
|
|
536
|
+
// Un piso tenue, para que se vea que es un área y no una raya suelta.
|
|
537
|
+
let area = NSBezierPath()
|
|
538
|
+
area.move(to: NSPoint(x: x(ts[0]), y: caja.minY))
|
|
539
|
+
for (i, t) in ts.enumerated() { area.line(to: NSPoint(x: x(t), y: y(ps[i]))) }
|
|
540
|
+
area.line(to: NSPoint(x: x(ts[ts.count - 1]), y: caja.minY))
|
|
541
|
+
area.close()
|
|
542
|
+
nivel.color.withAlphaComponent(0.14).setFill()
|
|
543
|
+
area.fill()
|
|
544
|
+
|
|
545
|
+
let linea = NSBezierPath()
|
|
546
|
+
linea.lineWidth = 1.5
|
|
547
|
+
linea.lineJoinStyle = .round
|
|
548
|
+
linea.move(to: NSPoint(x: x(ts[0]), y: y(ps[0])))
|
|
549
|
+
for (i, t) in ts.enumerated().dropFirst() { linea.line(to: NSPoint(x: x(t), y: y(ps[i]))) }
|
|
550
|
+
nivel.color.setStroke()
|
|
551
|
+
linea.stroke()
|
|
552
|
+
|
|
553
|
+
// El punto de ahora, que es el que se mira.
|
|
554
|
+
let fin = NSRect(x: x(ts[ts.count - 1]) - 2.5, y: y(ps[ps.count - 1]) - 2.5, width: 5, height: 5)
|
|
555
|
+
nivel.color.setFill()
|
|
556
|
+
NSBezierPath(ovalIn: fin).fill()
|
|
557
|
+
|
|
558
|
+
let horas = (t1 - t0) / 3_600_000
|
|
559
|
+
escribir(String(format: "%.0f%%", p0), caja.minX, caja.minY - 11, .systemFont(ofSize: 9), .tertiaryLabelColor)
|
|
560
|
+
escribir(horas >= 1 ? String(format: "últimas %.1f h", horas) : "última hora",
|
|
561
|
+
0, caja.minY - 11, .systemFont(ofSize: 9), .tertiaryLabelColor, derecha: caja.maxX)
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
override func draw(_ dirtyRect: NSRect) {
|
|
565
|
+
let m = VistaCuenta.MARGEN
|
|
566
|
+
let der = bounds.width - m
|
|
567
|
+
var y = bounds.height - m - 16
|
|
568
|
+
|
|
569
|
+
// Cabecera: ícono, nombre y, debajo, cuenta y plan.
|
|
570
|
+
if let ic = icono {
|
|
571
|
+
ic.draw(in: NSRect(x: m, y: y + 1, width: 13, height: 13))
|
|
572
|
+
}
|
|
573
|
+
escribir(titulo, m + 19, y, .systemFont(ofSize: 13, weight: .semibold), .labelColor)
|
|
574
|
+
y -= 15
|
|
575
|
+
escribir(sub, m + 19, y, .systemFont(ofSize: 10.5), .tertiaryLabelColor)
|
|
576
|
+
y -= 6
|
|
577
|
+
|
|
578
|
+
if let f = frase {
|
|
579
|
+
let a = NSAttributedString(string: f, attributes: [
|
|
580
|
+
.font: NSFont.systemFont(ofSize: 11), .foregroundColor: NSColor.secondaryLabelColor,
|
|
581
|
+
])
|
|
582
|
+
a.draw(with: NSRect(x: m, y: y - 26, width: der - m, height: 32),
|
|
583
|
+
options: [.usesLineFragmentOrigin])
|
|
584
|
+
return
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
for b in barras {
|
|
588
|
+
y -= 14
|
|
589
|
+
let nombre = b.activa ? "\(b.nombre) ▸" : b.nombre
|
|
590
|
+
escribir(nombre, m, y, .systemFont(ofSize: 11, weight: b.activa ? .medium : .regular),
|
|
591
|
+
b.activa ? .labelColor : .secondaryLabelColor)
|
|
592
|
+
escribir("\(b.pct)%", 0, y, .monospacedDigitSystemFont(ofSize: 11.5, weight: .semibold),
|
|
593
|
+
.labelColor, derecha: der)
|
|
594
|
+
y -= 8
|
|
595
|
+
// El medidor: pista tenue y relleno con el color del estado.
|
|
596
|
+
let pista = NSRect(x: m, y: y, width: der - m, height: 4)
|
|
597
|
+
NSColor.labelColor.withAlphaComponent(0.14).setFill()
|
|
598
|
+
NSBezierPath(roundedRect: pista, xRadius: 2, yRadius: 2).fill()
|
|
599
|
+
let ancho = max(4, (der - m) * CGFloat(min(100, max(0, b.pct))) / 100)
|
|
600
|
+
b.nivel.color.setFill()
|
|
601
|
+
NSBezierPath(roundedRect: NSRect(x: m, y: y, width: ancho, height: 4),
|
|
602
|
+
xRadius: 2, yRadius: 2).fill()
|
|
603
|
+
y -= 13
|
|
604
|
+
escribir(b.pie, m, y, .systemFont(ofSize: 10), .tertiaryLabelColor)
|
|
605
|
+
|
|
606
|
+
// La curva va pegada a la barra que frena: es de ella.
|
|
607
|
+
if b.nombre == claveQueFrena, historia.count >= 3 {
|
|
608
|
+
y -= VistaCuenta.ALTO_CURVA
|
|
609
|
+
dibujarCurva(NSRect(x: m, y: y + 14, width: der - m, height: 16), b.nivel)
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
if let r = ritmo {
|
|
614
|
+
y -= 16
|
|
615
|
+
escribir(r, m, y, .systemFont(ofSize: 10.5, weight: ritmoRojo ? .medium : .regular),
|
|
616
|
+
ritmoRojo ? Nivel.critico.color : .tertiaryLabelColor)
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// ── la barra ─────────────────────────────────────────────────────────────
|
|
622
|
+
final class Barra: NSObject, NSApplicationDelegate {
|
|
623
|
+
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
|
|
624
|
+
var vigias: [DispatchSourceFileSystemObject] = []
|
|
625
|
+
var vigilando: Set<String> = []
|
|
626
|
+
/// Los avisos ya dados. **Se persisten**: eran de memoria nomás, así que
|
|
627
|
+
/// cada arranque volvía a notificar todo lo que ya estaba cruzado — y
|
|
628
|
+
/// arrancar pasa seguido (reinstalar, actualizar, reiniciar sesión). Un
|
|
629
|
+
/// aviso marca un cruce; repetirlo en cada arranque es ruido y enseña a
|
|
630
|
+
/// ignorarlos, que es lo contrario de lo que tienen que hacer.
|
|
631
|
+
var avisados: Set<String> = Barra.leerAvisados()
|
|
632
|
+
|
|
633
|
+
static var rutaAvisados: String {
|
|
634
|
+
let base = ProcessInfo.processInfo.environment["XDG_CACHE_HOME"]
|
|
635
|
+
?? (NSHomeDirectory() as NSString).appendingPathComponent(".cache")
|
|
636
|
+
return (base as NSString).appendingPathComponent("quartermaster/avisados.json")
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
static func leerAvisados() -> Set<String> {
|
|
640
|
+
guard let d = FileManager.default.contents(atPath: rutaAvisados),
|
|
641
|
+
let a = try? JSONDecoder().decode([String].self, from: d) else { return [] }
|
|
642
|
+
return Set(a)
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
func guardarAvisados() {
|
|
646
|
+
// Las claves llevan el minuto de reinicio, así que envejecen solas; se
|
|
647
|
+
// recorta igual para que el archivo no crezca para siempre.
|
|
648
|
+
let recorte = Array(avisados.suffix(300))
|
|
649
|
+
let url = URL(fileURLWithPath: Barra.rutaAvisados)
|
|
650
|
+
try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(),
|
|
651
|
+
withIntermediateDirectories: true)
|
|
652
|
+
try? JSONEncoder().encode(recorte).write(to: url)
|
|
653
|
+
}
|
|
654
|
+
var pendiente: DispatchWorkItem?
|
|
655
|
+
var reloj: Timer?
|
|
656
|
+
/// Sin esto macOS le aplica App Nap —es una app sin ventanas— y los timers
|
|
657
|
+
/// se corren minutos. Medido: un sondeo de 5 min que no disparó en 7.
|
|
658
|
+
var actividad: NSObjectProtocol?
|
|
659
|
+
/// Lo último que se vio, para decidir cada cuánto volver a mirar.
|
|
660
|
+
var ultimas: [Trozo] = []
|
|
661
|
+
var avisoBarraLlena = false
|
|
662
|
+
/// `perfil|barra` -> [minuto de reinicio, porcentaje] de la última vuelta.
|
|
663
|
+
/// Persistido: es lo que permite notar que una ventana se dio vuelta.
|
|
664
|
+
var previos: [String: [Int]] = Barra.leerPrevios()
|
|
665
|
+
|
|
666
|
+
static var rutaPrevios: String {
|
|
667
|
+
(Barra.rutaAvisados as NSString).deletingLastPathComponent + "/previos.json"
|
|
668
|
+
}
|
|
669
|
+
static func leerPrevios() -> [String: [Int]] {
|
|
670
|
+
guard let d = FileManager.default.contents(atPath: rutaPrevios),
|
|
671
|
+
let m = try? JSONDecoder().decode([String: [Int]].self, from: d) else { return [:] }
|
|
672
|
+
return m
|
|
673
|
+
}
|
|
674
|
+
func guardarPrevios() {
|
|
675
|
+
let url = URL(fileURLWithPath: Barra.rutaPrevios)
|
|
676
|
+
try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(),
|
|
677
|
+
withIntermediateDirectories: true)
|
|
678
|
+
try? JSONEncoder().encode(previos).write(to: url)
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
func applicationDidFinishLaunching(_ n: Notification) {
|
|
682
|
+
// Con autosaveName el sistema recuerda dónde lo dejó el usuario: en una
|
|
683
|
+
// barra llena, cmd-arrastrar el item a un hueco es LA salida, y sin
|
|
684
|
+
// esto se perdería en cada arranque.
|
|
685
|
+
item.autosaveName = "quartermaster"
|
|
686
|
+
item.button?.title = "qm…"
|
|
687
|
+
item.menu = NSMenu()
|
|
688
|
+
actividad = ProcessInfo.processInfo.beginActivity(
|
|
689
|
+
options: [.userInitiated, .idleSystemSleepDisabled],
|
|
690
|
+
reason: "mirar la cuota a tiempo")
|
|
691
|
+
refrescar()
|
|
692
|
+
calentarCodex()
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/// Cada cuánto volver a preguntar por Codex.
|
|
696
|
+
///
|
|
697
|
+
/// Un intervalo fijo de 5 minutos es inservible para una barra que sube
|
|
698
|
+
/// 1,6 puntos por minuto: se llega al 100 % dos veces adentro de una sola
|
|
699
|
+
/// espera. La cadencia sale de lo que ya sabemos —cuán alto está y cuánto
|
|
700
|
+
/// falta para el techo según la proyección—, que es exactamente para lo que
|
|
701
|
+
/// existe la proyección.
|
|
702
|
+
func cadencia() -> TimeInterval {
|
|
703
|
+
let alto = ultimas.map { max($0.sesion ?? 0, $0.semanal ?? 0) }.max() ?? 0
|
|
704
|
+
var segundos: TimeInterval = SEGUNDOS_SONDEO
|
|
705
|
+
if alto >= 90 { segundos = MINIMO_RED }
|
|
706
|
+
else if alto >= 75 { segundos = 120 }
|
|
707
|
+
else if alto >= 50 { segundos = 240 }
|
|
708
|
+
if let m = minutosAlTecho, m <= 30 { segundos = min(segundos, MINIMO_RED) }
|
|
709
|
+
else if let m = minutosAlTecho, m <= 90 { segundos = min(segundos, 120) }
|
|
710
|
+
return max(MINIMO_RED, segundos)
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
var minutosAlTecho: Double? = nil
|
|
714
|
+
|
|
715
|
+
func programar() {
|
|
716
|
+
reloj?.invalidate()
|
|
717
|
+
let t = Timer(timeInterval: cadencia(), repeats: false) { _ in
|
|
718
|
+
// Codex primero: su número no está en ningún disco hasta que
|
|
719
|
+
// alguien lo pide, y el refresco de abajo lee del cache.
|
|
720
|
+
self.calentarCodex()
|
|
721
|
+
}
|
|
722
|
+
// Sin tolerancia y en modo común: si no, el sistema los agrupa y los
|
|
723
|
+
// corre, que es la mitad de lo que pasó acá.
|
|
724
|
+
t.tolerance = 0
|
|
725
|
+
RunLoop.main.add(t, forMode: .common)
|
|
726
|
+
reloj = t
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/// Refresca las dos puntas —el endpoint de cada perfil de Claude y el de
|
|
730
|
+
/// Codex— y deja los números en el cache de qm, para que las lecturas de la
|
|
731
|
+
/// barra —que son `--breve`— sigan tardando milisegundos y encuentren algo
|
|
732
|
+
/// reciente. Si falla, no pasa nada: se sigue mostrando lo viejo, con su
|
|
733
|
+
/// edad a la vista.
|
|
734
|
+
///
|
|
735
|
+
/// Para Claude hace falta porque Claude Code refresca su propio cache
|
|
736
|
+
/// cuando quiere: medido, 83 minutos sin tocarlo mientras reescribía el
|
|
737
|
+
/// archivo cada 20 s, con la sesión 11 puntos abajo de la realidad.
|
|
738
|
+
func calentarCodex() {
|
|
739
|
+
DispatchQueue.global(qos: .utility).async {
|
|
740
|
+
let p = Process()
|
|
741
|
+
p.executableURL = URL(fileURLWithPath: rutaQm())
|
|
742
|
+
// Sólo las cuentas que se mueven. Refrescar una que va al 9 % es
|
|
743
|
+
// gastar un pedido para confirmar que no pasó nada.
|
|
744
|
+
let vale = self.ultimas.filter { max($0.sesion ?? 0, $0.semanal ?? 0) >= 40 }.map(\.nombre)
|
|
745
|
+
p.arguments = vale.isEmpty || vale.count == self.ultimas.count
|
|
746
|
+
? ["--calentar"]
|
|
747
|
+
: ["--calentar", "--cuentas=" + vale.joined(separator: ",")]
|
|
748
|
+
p.standardOutput = FileHandle.nullDevice
|
|
749
|
+
p.standardError = FileHandle.nullDevice
|
|
750
|
+
try? p.run()
|
|
751
|
+
p.waitUntilExit()
|
|
752
|
+
DispatchQueue.main.async { self.refrescar() }
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// Vigilancia de archivos ----------------------------------------------
|
|
757
|
+
/// Un vigía por .claude.json: es donde aparece la cuota nueva. El perfil
|
|
758
|
+
/// por defecto lo guarda al lado del directorio y los demás adentro, así
|
|
759
|
+
/// que se prueban las dos formas.
|
|
760
|
+
func vigilar(_ perfiles: [PerfilVista]) {
|
|
761
|
+
var rutas: Set<String> = []
|
|
762
|
+
for p in perfiles where !p.directorio.isEmpty {
|
|
763
|
+
rutas.insert((p.directorio as NSString).appendingPathComponent(".claude.json"))
|
|
764
|
+
rutas.insert(p.directorio + ".json")
|
|
765
|
+
}
|
|
766
|
+
for ruta in rutas where !vigilando.contains(ruta) {
|
|
767
|
+
armar(ruta)
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
func armar(_ ruta: String) {
|
|
772
|
+
let fd = open(ruta, O_EVTONLY)
|
|
773
|
+
guard fd >= 0 else { return }
|
|
774
|
+
vigilando.insert(ruta)
|
|
775
|
+
let v = DispatchSource.makeFileSystemObjectSource(
|
|
776
|
+
fileDescriptor: fd, eventMask: [.write, .extend, .delete, .rename], queue: .main)
|
|
777
|
+
v.setEventHandler { [weak self] in
|
|
778
|
+
guard let self else { return }
|
|
779
|
+
let evento = v.data
|
|
780
|
+
self.pedirRefresco()
|
|
781
|
+
// Claude Code reescribe por rename: el descriptor viejo ya no mira
|
|
782
|
+
// nada. Sin re-armar, el vigía se muere después del primer cambio.
|
|
783
|
+
if evento.contains(.delete) || evento.contains(.rename) {
|
|
784
|
+
v.cancel()
|
|
785
|
+
self.vigilando.remove(ruta)
|
|
786
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.armar(ruta) }
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
v.setCancelHandler { close(fd) }
|
|
790
|
+
v.resume()
|
|
791
|
+
vigias.append(v)
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
func pedirRefresco() {
|
|
795
|
+
pendiente?.cancel()
|
|
796
|
+
let t = DispatchWorkItem { [weak self] in self?.refrescar() }
|
|
797
|
+
pendiente = t
|
|
798
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + DEBOUNCE, execute: t)
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// Datos y dibujo -------------------------------------------------------
|
|
802
|
+
@objc func refrescar() {
|
|
803
|
+
DispatchQueue.global(qos: .utility).async {
|
|
804
|
+
let r = leer()
|
|
805
|
+
DispatchQueue.main.async { self.pintar(r) }
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
func pintar(_ lectura: Lectura) {
|
|
810
|
+
let menu = NSMenu()
|
|
811
|
+
menu.autoenablesItems = false
|
|
812
|
+
|
|
813
|
+
switch lectura {
|
|
814
|
+
case .falla(let porque):
|
|
815
|
+
item.button?.attributedTitle = comoRenglones("qm ✕")
|
|
816
|
+
item.button?.image = icono("exclamationmark.triangle.fill")
|
|
817
|
+
agregar(menu, porque, activo: false)
|
|
818
|
+
|
|
819
|
+
case .ok(let perfiles):
|
|
820
|
+
vigilar(perfiles)
|
|
821
|
+
// Por cuenta: la sesión (la ventana corta) y la barra que frena
|
|
822
|
+
// antes. Son dos preguntas distintas —«¿puedo seguir ahora?» y
|
|
823
|
+
// «¿llego al viernes?»— y el título tiene que contestar las dos.
|
|
824
|
+
var piezas: [Trozo] = []
|
|
825
|
+
var iCuenta = 0
|
|
826
|
+
var peorPct = 0
|
|
827
|
+
|
|
828
|
+
if let resumen = VistaResumen(perfiles) {
|
|
829
|
+
let fila = NSMenuItem()
|
|
830
|
+
fila.view = resumen
|
|
831
|
+
menu.addItem(fila)
|
|
832
|
+
menu.addItem(.separator())
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
for p in perfiles {
|
|
836
|
+
let visibles = p.mostrar
|
|
837
|
+
|
|
838
|
+
// El menú lo dibuja VistaCuenta: acá sólo se junta lo que va
|
|
839
|
+
// arriba, en el item.
|
|
840
|
+
let fila = NSMenuItem()
|
|
841
|
+
fila.view = VistaCuenta(p, icono: glifoProducto(p.producto, colorCuenta(iCuenta), 13))
|
|
842
|
+
if p.hayNumero { iCuenta += 1 }
|
|
843
|
+
menu.addItem(fila)
|
|
844
|
+
menu.addItem(.separator())
|
|
845
|
+
|
|
846
|
+
if p.hayNumero, let cual = p.frena {
|
|
847
|
+
let viejo = (p.edadSegundos ?? 0) >= VIEJO_SEGUNDOS
|
|
848
|
+
// El `!` no es sólo severidad: también avisa que a este
|
|
849
|
+
// ritmo tocás el techo ANTES del reinicio.
|
|
850
|
+
let chocas = p.proyeccion?.chocas ?? false
|
|
851
|
+
let esLaProyectada = { (v: Ventana) in chocas && v.clave == cual.clave }
|
|
852
|
+
|
|
853
|
+
let ses = p.sesion
|
|
854
|
+
let sem = p.semanal
|
|
855
|
+
|
|
856
|
+
piezas.append(Trozo(
|
|
857
|
+
nombre: corto(p.nombre), producto: p.producto, indice: piezas.count,
|
|
858
|
+
sesion: ses?.porcentaje,
|
|
859
|
+
sesionAlerta: ses.map { $0.preocupa || esLaProyectada($0) } ?? false,
|
|
860
|
+
semanal: sem?.porcentaje,
|
|
861
|
+
semanalAlerta: sem.map { $0.preocupa || esLaProyectada($0) } ?? false,
|
|
862
|
+
viejo: viejo))
|
|
863
|
+
peorPct = max(peorPct, cual.porcentaje)
|
|
864
|
+
revisarAvisos(p, visibles)
|
|
865
|
+
revisarLiberadas(p, visibles)
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
ultimas = piezas
|
|
870
|
+
minutosAlTecho = perfiles.compactMap { p -> Double? in
|
|
871
|
+
guard let pr = p.proyeccion, pr.chocas else { return nil }
|
|
872
|
+
return pr.techo.timeIntervalSinceNow / 60
|
|
873
|
+
}.min()
|
|
874
|
+
item.button?.imagePosition = piezas.isEmpty ? .noImage : .imageOnly
|
|
875
|
+
item.button?.attributedTitle = NSAttributedString(string: "")
|
|
876
|
+
// El número de la sesión es lo que se viene a mirar, así que es lo
|
|
877
|
+
// ÚLTIMO que se cae. Antes la escalera lo tiraba primero y el item
|
|
878
|
+
// quedaba mudo justo en la parte que importa; la identidad se
|
|
879
|
+
// recupera del orden y del menú, el número no se recupera de nada.
|
|
880
|
+
probarCaras(piezas.isEmpty ? []
|
|
881
|
+
: [(true, true), (false, true), (true, false)], piezas)
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
if let i = CommandLine.arguments.firstIndex(of: "--captura"),
|
|
885
|
+
i + 1 < CommandLine.arguments.count {
|
|
886
|
+
let ruta = CommandLine.arguments[i + 1]
|
|
887
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
|
|
888
|
+
self.capturar(ruta)
|
|
889
|
+
NSApp.terminate(nil)
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
menu.addItem(.separator())
|
|
894
|
+
agregar(menu, "Abrir el tablero…", accion: #selector(abrirTablero))
|
|
895
|
+
agregar(menu, "Refrescar ahora", accion: #selector(refrescar))
|
|
896
|
+
agregar(menu, "Salir", accion: #selector(salir))
|
|
897
|
+
item.menu = menu
|
|
898
|
+
|
|
899
|
+
// Recién acá se sabe cómo viene la mano, así que recién acá se puede
|
|
900
|
+
// decidir cada cuánto volver a mirar. Programarlo en el arranque —con
|
|
901
|
+
// `ultimas` todavía vacío— dejaba la cadencia clavada en 5 minutos, que
|
|
902
|
+
// fue exactamente el bug: Codex llegó al 100 % adentro de una espera.
|
|
903
|
+
programar()
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
func comoRenglones(_ texto: String) -> NSAttributedString {
|
|
907
|
+
NSAttributedString(string: texto, attributes: [
|
|
908
|
+
.font: NSFont.monospacedDigitSystemFont(ofSize: 11.5, weight: .regular),
|
|
909
|
+
.foregroundColor: NSColor.labelColor,
|
|
910
|
+
])
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/// La barra de menú de una Mac con muesca tiene mucho menos lugar del que
|
|
914
|
+
/// aparenta: los items se acomodan de derecha a izquierda y el sistema
|
|
915
|
+
/// esconde —sin decir nada, y con `isVisible` en true— al que caería abajo
|
|
916
|
+
/// de la muesca. Medido acá: quedaban ~137 puntos, y el item con glifos,
|
|
917
|
+
/// medidores y números pedía 158.
|
|
918
|
+
///
|
|
919
|
+
/// Por eso la cara no se elige, se mide: entero, después sin glifos, y
|
|
920
|
+
/// recién al final sin números.
|
|
921
|
+
func probarCaras(_ caras: [(glifos: Bool, numeros: Bool)], _ piezas: [Trozo]) {
|
|
922
|
+
guard let boton = item.button, !caras.isEmpty else { return }
|
|
923
|
+
func intentar(_ i: Int) {
|
|
924
|
+
boton.image = medidores(piezas, glifos: caras[i].glifos, numeros: caras[i].numeros)
|
|
925
|
+
DispatchQueue.main.async {
|
|
926
|
+
if !self.tapadoPorLaMuesca() { self.revisarSiSeVe(); return }
|
|
927
|
+
if i + 1 < caras.count { intentar(i + 1); return }
|
|
928
|
+
// Ninguna entró. Antes se quedaba en la última —la que no tiene
|
|
929
|
+
// números— y el item terminaba mudo justo en la parte que se
|
|
930
|
+
// viene a mirar, aunque igual estuviera tapado. Si va a estar
|
|
931
|
+
// tapado de todos modos, que esté tapada la versión completa:
|
|
932
|
+
// en cuanto el usuario lo cmd-arrastra a un hueco, está todo.
|
|
933
|
+
boton.image = self.medidores(piezas, glifos: caras[0].glifos, numeros: caras[0].numeros)
|
|
934
|
+
self.revisarSiSeVe()
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
intentar(0)
|
|
938
|
+
}
|
|
939
|
+
/// El sistema esconde un item que no entra en la barra —y deja `isVisible`
|
|
940
|
+
/// en true igual, así que no se entera nadie. Un número que no se ve es el
|
|
941
|
+
/// mismo bug que el silencio, así que se avisa una vez.
|
|
942
|
+
func revisarSiSeVe() {
|
|
943
|
+
guard let v = item.button?.window else { return }
|
|
944
|
+
// Antes esto miraba `minX < 0`, y estaba mal: en una pantalla ubicada a
|
|
945
|
+
// la izquierda de la principal las coordenadas globales SON negativas y
|
|
946
|
+
// el item se ve perfecto. Lo que importa es si cae fuera de su propia
|
|
947
|
+
// pantalla, o abajo de la muesca.
|
|
948
|
+
let suya = v.screen ?? NSScreen.main
|
|
949
|
+
let afuera = suya.map { v.frame.minX < $0.frame.minX || v.frame.maxX > $0.frame.maxX } ?? false
|
|
950
|
+
let escondido = afuera || tapadoPorLaMuesca()
|
|
951
|
+
// A stderr, siempre: es lo único que explica por qué no se ve nada.
|
|
952
|
+
let pant = v.screen ?? NSScreen.main
|
|
953
|
+
FileHandle.standardError.write(
|
|
954
|
+
("[qm-barra] titulo=\(item.button?.attributedTitle.string.replacingOccurrences(of: "\n", with: " / ") ?? "?") "
|
|
955
|
+
+ "ancho=\(v.frame.width) x=\(v.frame.minX)..\(v.frame.maxX) "
|
|
956
|
+
+ "muescaDerechaMinX=\(pant?.auxiliaryTopRightArea?.minX ?? -1) "
|
|
957
|
+
+ "pantalla=\(pant?.frame.width ?? -1) escondido=\(escondido)\n").data(using: .utf8)!)
|
|
958
|
+
// Una sola vez por corrida. Antes se re-armaba al volver a entrar, así
|
|
959
|
+
// que un item que oscila entre visible y tapado avisaba en cada vuelta.
|
|
960
|
+
if escondido, !avisoBarraLlena {
|
|
961
|
+
avisoBarraLlena = true
|
|
962
|
+
notificar(titulo: "quartermaster",
|
|
963
|
+
cuerpo: "el número está, pero macOS no tiene lugar en la barra: "
|
|
964
|
+
+ "cmd-arrastrá el item a un hueco, o mirá el tablero con qm-web")
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
func tapadoPorLaMuesca() -> Bool {
|
|
969
|
+
guard let ventana = item.button?.window else { return false }
|
|
970
|
+
let pantalla = ventana.screen ?? NSScreen.main
|
|
971
|
+
guard let pantalla, pantalla.safeAreaInsets.top > 0,
|
|
972
|
+
let derecha = pantalla.auxiliaryTopRightArea else { return false }
|
|
973
|
+
return ventana.frame.minX < derecha.minX
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
@discardableResult
|
|
977
|
+
func agregar(_ menu: NSMenu, _ titulo: String, accion: Selector? = nil, activo: Bool = true) -> NSMenuItem {
|
|
978
|
+
let it = NSMenuItem(title: titulo, action: accion, keyEquivalent: "")
|
|
979
|
+
it.target = self
|
|
980
|
+
it.isEnabled = activo && accion != nil
|
|
981
|
+
menu.addItem(it)
|
|
982
|
+
return it
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
/// El item de la barra, dibujado.
|
|
986
|
+
///
|
|
987
|
+
/// Un medidor vertical por cuenta, en el orden del menú, lleno hasta la
|
|
988
|
+
/// barra que la frena antes y pintado por severidad. Es lo que hace que
|
|
989
|
+
/// tres cuentas entren en el ancho de una palabra, y además es la forma en
|
|
990
|
+
/// que se leen las cosas en una barra de menú de macOS: una marca chica y
|
|
991
|
+
/// callada, no un renglón de texto.
|
|
992
|
+
///
|
|
993
|
+
/// Adentro de cada medidor, una muesca más clara marca dónde va la sesión:
|
|
994
|
+
/// así el mismo dibujo contesta «¿puedo seguir ahora?» y «¿llego al final
|
|
995
|
+
/// de la semana?» sin ocupar el doble.
|
|
996
|
+
func medidores(_ piezas: [Trozo], glifos: Bool, numeros: Bool) -> NSImage {
|
|
997
|
+
let alto: CGFloat = 22, altoBarra: CGFloat = 15
|
|
998
|
+
let ancho: CGFloat = 3, entreGrupos: CGFloat = 5
|
|
999
|
+
let ladoGlifo: CGFloat = glifos ? 9 : 0, aireGlifo: CGFloat = glifos ? 2 : 0
|
|
1000
|
+
let aireNumero: CGFloat = 3
|
|
1001
|
+
// Un solo medidor por cuenta, no dos. Con el glifo adentro, el par no
|
|
1002
|
+
// entraba (158 pt contra los ~137 que deja la muesca) y la escalera
|
|
1003
|
+
// terminaba tirando los números — justo lo que hay que mostrar. Y la
|
|
1004
|
+
// barra de sesión pasó a ser redundante: el número YA es la sesión.
|
|
1005
|
+
// El medidor queda para la que frena antes, que es la que no tiene
|
|
1006
|
+
// número y necesita alguna forma de verse.
|
|
1007
|
+
let par = ancho
|
|
1008
|
+
|
|
1009
|
+
let fuente = NSFont.monospacedDigitSystemFont(ofSize: 10, weight: .medium)
|
|
1010
|
+
// El número de cada cuenta es el de la SESIÓN de 5 h: es el que
|
|
1011
|
+
// contesta «¿puedo seguir trabajando ahora?». La semanal se sigue
|
|
1012
|
+
// viendo —es la barra de la derecha, con su color— sin gastar dígitos.
|
|
1013
|
+
func texto(_ t: Trozo) -> NSAttributedString? {
|
|
1014
|
+
guard numeros, let s = t.sesion else { return nil }
|
|
1015
|
+
// El número es la sesión, así que lleva el estado DE LA SESIÓN. Se
|
|
1016
|
+
// tiñe recién cuando aprieta: si se pintara siempre, el color
|
|
1017
|
+
// dejaría de querer decir algo.
|
|
1018
|
+
let n = nivelDe(s, preocupa: t.sesionAlerta)
|
|
1019
|
+
let color: NSColor = (n == .aviso || n == .critico) ? n.color : .labelColor
|
|
1020
|
+
return NSAttributedString(string: "\(t.viejo ? "~" : "")\(s)", attributes: [
|
|
1021
|
+
.font: fuente, .foregroundColor: color,
|
|
1022
|
+
])
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
var anchos: [CGFloat] = []
|
|
1026
|
+
for t in piezas {
|
|
1027
|
+
let n = texto(t)
|
|
1028
|
+
anchos.append(ladoGlifo + aireGlifo + par + (n == nil ? 0 : aireNumero + ceil(n!.size().width)))
|
|
1029
|
+
}
|
|
1030
|
+
let total = anchos.reduce(0, +) + CGFloat(max(0, piezas.count - 1)) * entreGrupos
|
|
1031
|
+
|
|
1032
|
+
let img = NSImage(size: NSSize(width: max(total, 4), height: alto), flipped: false) { _ in
|
|
1033
|
+
let base = (alto - altoBarra) / 2
|
|
1034
|
+
let radio = ancho / 2
|
|
1035
|
+
|
|
1036
|
+
func barra(_ x: CGFloat, _ pct: Int, _ color: NSColor) {
|
|
1037
|
+
let pista = NSRect(x: x, y: base, width: ancho, height: altoBarra)
|
|
1038
|
+
NSColor.labelColor.withAlphaComponent(0.16).setFill()
|
|
1039
|
+
NSBezierPath(roundedRect: pista, xRadius: radio, yRadius: radio).fill()
|
|
1040
|
+
let h = max(ancho, altoBarra * CGFloat(min(100, max(0, pct))) / 100)
|
|
1041
|
+
color.setFill()
|
|
1042
|
+
NSBezierPath(roundedRect: NSRect(x: x, y: base, width: ancho, height: h),
|
|
1043
|
+
xRadius: radio, yRadius: radio).fill()
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
var x: CGFloat = 0
|
|
1047
|
+
for (i, t) in piezas.enumerated() {
|
|
1048
|
+
// El glifo dice QUÉ suscripción es: la forma, el producto; el
|
|
1049
|
+
// color, cuál de ellas. La identidad va acá y nunca en los
|
|
1050
|
+
// medidores, que están reservados para el estado.
|
|
1051
|
+
if glifos {
|
|
1052
|
+
glifoProducto(t.producto, colorCuenta(t.indice), ladoGlifo)
|
|
1053
|
+
.draw(in: NSRect(x: x, y: (alto - ladoGlifo) / 2, width: ladoGlifo, height: ladoGlifo))
|
|
1054
|
+
}
|
|
1055
|
+
let xb = x + ladoGlifo + aireGlifo
|
|
1056
|
+
// El medidor es SIEMPRE la semanal. Si la cuenta no informa
|
|
1057
|
+
// ninguna, queda la pista vacía: mejor un hueco honesto que
|
|
1058
|
+
// dibujar ahí otra cosa.
|
|
1059
|
+
barra(xb, t.semanal ?? 0,
|
|
1060
|
+
t.semanal == nil ? NSColor.labelColor.withAlphaComponent(0.16)
|
|
1061
|
+
: nivelDe(t.semanal!, preocupa: t.semanalAlerta).color)
|
|
1062
|
+
if let n = texto(t) {
|
|
1063
|
+
n.draw(at: NSPoint(x: xb + par + aireNumero, y: (alto - n.size().height) / 2))
|
|
1064
|
+
}
|
|
1065
|
+
x += anchos[i] + entreGrupos
|
|
1066
|
+
}
|
|
1067
|
+
return true
|
|
1068
|
+
}
|
|
1069
|
+
img.isTemplate = false
|
|
1070
|
+
img.accessibilityDescription = piezas
|
|
1071
|
+
.map { t in
|
|
1072
|
+
let a = t.sesion.map { "sesión \($0) por ciento" } ?? "sin sesión"
|
|
1073
|
+
let b = t.semanal.map { "semana \($0) por ciento" } ?? "sin semanal"
|
|
1074
|
+
return "\(t.nombre): \(a), \(b)\(t.sesionAlerta || t.semanalAlerta ? ", con aviso" : "")"
|
|
1075
|
+
}
|
|
1076
|
+
.joined(separator: "; ")
|
|
1077
|
+
return img
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
/// El ícono de cada cuenta. SF Symbols no trae ni el de Claude ni el de
|
|
1081
|
+
/// Codex, así que se usan los dos que más se les parecen y que además se
|
|
1082
|
+
/// distinguen de un vistazo: el asterisco —que es la forma de la marca de
|
|
1083
|
+
/// Claude— y los chevrones de código para Codex.
|
|
1084
|
+
func iconoProducto(_ producto: String) -> NSImage? {
|
|
1085
|
+
let simbolo = producto == "codex" ? "chevron.left.forwardslash.chevron.right" : "asterisk"
|
|
1086
|
+
guard let img = NSImage(systemSymbolName: simbolo, accessibilityDescription: producto) else { return nil }
|
|
1087
|
+
img.isTemplate = true
|
|
1088
|
+
img.size = NSSize(width: 13, height: 13)
|
|
1089
|
+
return img
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
func icono(_ nombre: String) -> NSImage? {
|
|
1093
|
+
let img = NSImage(systemSymbolName: nombre, accessibilityDescription: "quartermaster")
|
|
1094
|
+
img?.isTemplate = true
|
|
1095
|
+
return img
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
// Avisos ---------------------------------------------------------------
|
|
1099
|
+
/// El aviso que faltaba: **cuándo volvés a poder trabajar**.
|
|
1100
|
+
///
|
|
1101
|
+
/// Todo lo demás avisa que te estás quedando sin cuota. Nada avisaba lo
|
|
1102
|
+
/// contrario, y es la mitad útil de la pregunta: si te frenaste, lo que
|
|
1103
|
+
/// querés saber es cuándo se liberó, y hasta ahora eso había que ir a
|
|
1104
|
+
/// mirarlo. Se dispara cuando una barra que estaba apretada cambia de
|
|
1105
|
+
/// ventana —cambia su minuto de reinicio— y vuelve abajo.
|
|
1106
|
+
func revisarLiberadas(_ p: PerfilVista, _ visibles: [Ventana]) {
|
|
1107
|
+
for v in visibles {
|
|
1108
|
+
let clave = "\(p.nombre)|\(v.nombre)"
|
|
1109
|
+
let minuto = v.reinicia.map { Int($0.timeIntervalSince1970 / 60) } ?? 0
|
|
1110
|
+
defer { previos[clave] = [minuto, v.porcentaje] }
|
|
1111
|
+
guard let antes = previos[clave], antes.count == 2 else { continue }
|
|
1112
|
+
let (minutoAntes, pctAntes) = (antes[0], antes[1])
|
|
1113
|
+
// Ventana nueva, y en la anterior estabas contra el techo.
|
|
1114
|
+
if minuto != minutoAntes, pctAntes >= 80, v.porcentaje < pctAntes {
|
|
1115
|
+
notificar(titulo: "quartermaster · \(corto(p.nombre))",
|
|
1116
|
+
cuerpo: "\(v.nombre) se reinició: estabas \(pctAntes) % y ahora vas \(v.porcentaje) %")
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
guardarPrevios()
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
func revisarAvisos(_ p: PerfilVista, _ visibles: [Ventana]) {
|
|
1123
|
+
for v in visibles {
|
|
1124
|
+
// La clave incluye el reinicio: una ventana avisa una vez, y la
|
|
1125
|
+
// siguiente ventana vuelve a avisar.
|
|
1126
|
+
let ventana = v.reinicia.map { String(Int($0.timeIntervalSince1970 / 60)) } ?? "sin-reinicio"
|
|
1127
|
+
for u in UMBRALES where v.porcentaje >= u {
|
|
1128
|
+
let clave = "\(p.nombre)|\(v.nombre)|\(ventana)|\(u)"
|
|
1129
|
+
if avisados.insert(clave).inserted {
|
|
1130
|
+
guardarAvisados()
|
|
1131
|
+
notificar(titulo: "quartermaster · \(corto(p.nombre))",
|
|
1132
|
+
cuerpo: "\(v.nombre) al \(v.porcentaje) %"
|
|
1133
|
+
+ (v.reinicia.map { " · reinicia en \(duracion(Int($0.timeIntervalSinceNow)))" } ?? ""))
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
// El aviso que de verdad sirve: enterarte ANTES de chocar, no después.
|
|
1138
|
+
if let pr = p.proyeccion, pr.chocas, let cual = p.frena {
|
|
1139
|
+
let ventana = cual.reinicia.map { String(Int($0.timeIntervalSince1970 / 60)) } ?? "sin-reinicio"
|
|
1140
|
+
let clave = "\(p.nombre)|\(cual.nombre)|\(ventana)|choque"
|
|
1141
|
+
if avisados.insert(clave).inserted {
|
|
1142
|
+
guardarAvisados()
|
|
1143
|
+
notificar(titulo: "quartermaster · \(corto(p.nombre))",
|
|
1144
|
+
cuerpo: "vas a tocar el techo de \(cual.nombre) en "
|
|
1145
|
+
+ "\(duracion(Int(pr.techo.timeIntervalSinceNow))), antes del reinicio")
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
/// El item se dibuja a sí mismo en un PNG.
|
|
1151
|
+
///
|
|
1152
|
+
/// Existe porque `screencapture` no sirve para verlo: con varias pantallas
|
|
1153
|
+
/// la barra de menú se muda a la que tenga el foco, y encima el sistema
|
|
1154
|
+
/// puede esconder el item sin avisar. Esto renderiza el botón tal cual
|
|
1155
|
+
/// quedó, sobre los dos fondos que puede tocarle, y no depende de qué
|
|
1156
|
+
/// pantalla esté mirando nadie. Diseñar a ciegas fue el error.
|
|
1157
|
+
func capturar(_ ruta: String) {
|
|
1158
|
+
guard let boton = item.button else { return }
|
|
1159
|
+
let escala: CGFloat = 4
|
|
1160
|
+
let caja = boton.bounds
|
|
1161
|
+
for (sufijo, fondo, apariencia) in [
|
|
1162
|
+
("-oscuro", NSColor(white: 0.07, alpha: 1), NSAppearance(named: .darkAqua)),
|
|
1163
|
+
("-claro", NSColor(white: 0.96, alpha: 1), NSAppearance(named: .aqua)),
|
|
1164
|
+
] {
|
|
1165
|
+
boton.appearance = apariencia
|
|
1166
|
+
boton.layoutSubtreeIfNeeded()
|
|
1167
|
+
guard let rep = boton.bitmapImageRepForCachingDisplay(in: caja) else { continue }
|
|
1168
|
+
boton.cacheDisplay(in: caja, to: rep)
|
|
1169
|
+
|
|
1170
|
+
let ancho = Int(caja.width * escala), alto = Int(caja.height * escala)
|
|
1171
|
+
guard let lienzo = NSBitmapImageRep(
|
|
1172
|
+
bitmapDataPlanes: nil, pixelsWide: ancho, pixelsHigh: alto,
|
|
1173
|
+
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
|
|
1174
|
+
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0) else { continue }
|
|
1175
|
+
NSGraphicsContext.saveGraphicsState()
|
|
1176
|
+
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: lienzo)
|
|
1177
|
+
fondo.setFill()
|
|
1178
|
+
NSRect(x: 0, y: 0, width: ancho, height: alto).fill()
|
|
1179
|
+
NSImage(size: caja.size, flipped: false) { r in rep.draw(in: r); return true }
|
|
1180
|
+
.draw(in: NSRect(x: 0, y: 0, width: ancho, height: alto))
|
|
1181
|
+
NSGraphicsContext.restoreGraphicsState()
|
|
1182
|
+
|
|
1183
|
+
let destino = ruta.replacingOccurrences(of: ".png", with: "\(sufijo).png")
|
|
1184
|
+
try? lienzo.representation(using: .png, properties: [:])?
|
|
1185
|
+
.write(to: URL(fileURLWithPath: destino))
|
|
1186
|
+
}
|
|
1187
|
+
// Y el menú, que es donde se contesta la pregunta entera. Mismo motivo:
|
|
1188
|
+
// no hay forma de mirarlo con screencapture.
|
|
1189
|
+
let vistas = (item.menu?.items ?? []).compactMap { $0.view }
|
|
1190
|
+
if !vistas.isEmpty {
|
|
1191
|
+
let ancho = vistas.map(\.frame.width).max() ?? 340
|
|
1192
|
+
let altoTotal = vistas.map(\.frame.height).reduce(0, +) + CGFloat(vistas.count - 1)
|
|
1193
|
+
for (sufijo, fondo, apariencia) in [
|
|
1194
|
+
("-menu-oscuro", NSColor(white: 0.13, alpha: 1), NSAppearance(named: .darkAqua)),
|
|
1195
|
+
("-menu-claro", NSColor(white: 0.98, alpha: 1), NSAppearance(named: .aqua)),
|
|
1196
|
+
] {
|
|
1197
|
+
guard let lienzo = NSBitmapImageRep(
|
|
1198
|
+
bitmapDataPlanes: nil, pixelsWide: Int(ancho * escala), pixelsHigh: Int(altoTotal * escala),
|
|
1199
|
+
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
|
|
1200
|
+
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0) else { continue }
|
|
1201
|
+
NSGraphicsContext.saveGraphicsState()
|
|
1202
|
+
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: lienzo)
|
|
1203
|
+
NSGraphicsContext.current?.cgContext.scaleBy(x: escala, y: escala)
|
|
1204
|
+
fondo.setFill()
|
|
1205
|
+
NSRect(x: 0, y: 0, width: ancho, height: altoTotal).fill()
|
|
1206
|
+
var y = altoTotal
|
|
1207
|
+
for v in vistas {
|
|
1208
|
+
v.appearance = apariencia
|
|
1209
|
+
y -= v.frame.height
|
|
1210
|
+
guard let rep = v.bitmapImageRepForCachingDisplay(in: v.bounds) else { continue }
|
|
1211
|
+
v.cacheDisplay(in: v.bounds, to: rep)
|
|
1212
|
+
NSImage(size: v.bounds.size, flipped: false) { r in rep.draw(in: r); return true }
|
|
1213
|
+
.draw(in: NSRect(x: 0, y: y, width: v.frame.width, height: v.frame.height))
|
|
1214
|
+
y -= 1
|
|
1215
|
+
NSColor.labelColor.withAlphaComponent(0.10).setFill()
|
|
1216
|
+
NSRect(x: 0, y: y, width: ancho, height: 1).fill()
|
|
1217
|
+
}
|
|
1218
|
+
NSGraphicsContext.restoreGraphicsState()
|
|
1219
|
+
try? lienzo.representation(using: .png, properties: [:])?
|
|
1220
|
+
.write(to: URL(fileURLWithPath: ruta.replacingOccurrences(of: ".png", with: "\(sufijo).png")))
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
FileHandle.standardError.write("[qm-barra] capturado ancho=\(caja.width) alto=\(caja.height) filas=\(vistas.count)\n".data(using: .utf8)!)
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
// Acciones -------------------------------------------------------------
|
|
1227
|
+
@objc func abrirTablero() {
|
|
1228
|
+
// Si el tablero ya está levantado, esto sólo abre el navegador; si no,
|
|
1229
|
+
// qm-web lo levanta y lo abre él.
|
|
1230
|
+
let url = URL(string: "http://127.0.0.1:7391/")!
|
|
1231
|
+
let p = Process()
|
|
1232
|
+
p.executableURL = URL(fileURLWithPath: "/usr/bin/curl")
|
|
1233
|
+
p.arguments = ["-s", "-o", "/dev/null", "-m", "1", url.absoluteString]
|
|
1234
|
+
try? p.run()
|
|
1235
|
+
p.waitUntilExit()
|
|
1236
|
+
if p.terminationStatus == 0 {
|
|
1237
|
+
NSWorkspace.shared.open(url)
|
|
1238
|
+
} else {
|
|
1239
|
+
let w = Process()
|
|
1240
|
+
w.executableURL = URL(fileURLWithPath: RAIZ.appendingPathComponent("bin/qm-web").path)
|
|
1241
|
+
try? w.run()
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
@objc func salir() { NSApp.terminate(nil) }
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
let app = NSApplication.shared
|
|
1249
|
+
let barra = Barra()
|
|
1250
|
+
app.delegate = barra
|
|
1251
|
+
// .accessory: vive en la barra de menú y no aparece en el Dock ni en cmd-tab.
|
|
1252
|
+
app.setActivationPolicy(.accessory)
|
|
1253
|
+
app.run()
|