@legios/quartermaster 0.1.23 → 0.1.24

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/bin/qm-indicator CHANGED
@@ -31,7 +31,7 @@ import subprocess
31
31
  import sys
32
32
  import tempfile
33
33
  import time
34
- from datetime import datetime, timezone
34
+ from datetime import datetime, timedelta, timezone
35
35
  from pathlib import Path
36
36
 
37
37
  # El panel se abre pegado a la barra, y para eso hay que poder decir DÓNDE va la
@@ -253,7 +253,7 @@ def pct_diario(pre: dict | None) -> float | None:
253
253
  return max(0.0, min(100.0, gastado / por_dia * 100.0))
254
254
 
255
255
 
256
- def renglones_presupuesto(pre: dict) -> list[str]:
256
+ def renglones_presupuesto(pre: dict, nombre: str | None = None) -> list[str]:
257
257
  """Las mismas tres ramas que `frasePresupuesto` en el núcleo, en dos
258
258
  renglones: el del terminal entra en una línea de 100 y acá hay 308 px.
259
259
 
@@ -271,7 +271,8 @@ def renglones_presupuesto(pre: dict) -> list[str]:
271
271
  # Con el nombre de la barra pegado, como en el terminal y en el tablero: la
272
272
  # tarjeta muestra tres ventanas y el número reparte UNA, y sin decir cuál
273
273
  # queda un 24.1 que no cierra con ninguno de los tres porcentajes de arriba.
274
- barra = pre.get("barra")
274
+ # `nombre` es cómo la llama el panel («Semanal (Fable)»); la frase es la misma.
275
+ barra = nombre or pre.get("barra")
275
276
  # `porDiaHoy` y `restanteMedido`: el presupuesto fijado al arrancar la
276
277
  # medición y la resta ya hecha por el núcleo. Restar de `porDia` contaba dos
277
278
  # veces lo gastado hoy. Los de antes quedan para un qm anterior.
@@ -330,7 +331,9 @@ MARGEN = 12
330
331
  PAD_TARJETA = 14
331
332
  RADIO_TARJETA = 12
332
333
  ENTRE_TARJETAS = 8
333
- ALTO_CABECERA = 76
334
+ # La cabecera es una tarjeta más: el margen de arriba, la tarjeta y el aire de
335
+ # abajo hasta la primera cuenta.
336
+ ALTO_CABECERA = 94
334
337
  # El renglón de abajo de todo: cuándo vuelve a preguntar.
335
338
  ALTO_PIE_LECTURA = 26
336
339
  VIEJO_SEGUNDOS = 6 * 3600
@@ -438,19 +441,17 @@ def edad_de(v: dict | None, cuota: dict) -> int | None:
438
441
  return cuota.get("edadSegundos")
439
442
 
440
443
 
441
- def pie_de_barra(v: dict) -> str:
442
- """«reinicia en 3d7h · leída hace 24m». La edad sólo va cuando la barra
443
- tiene la suya: si es de cuando dice la cuenta, ya la dice el renglón de
444
- lecturas, y repetirla en cada barra es ruido."""
445
- pie = reinicio(faltan(v.get("reinicia")))
444
+ def edad_de_barra(v: dict) -> str | None:
445
+ """«leída hace 24m», sólo cuando la barra tiene su propia lectura: si es de
446
+ cuando dice la cuenta, ya lo dice la cabecera de la tarjeta, y repetirlo en
447
+ cada barra es ruido. Pasada la hora de vieja, lo dice."""
446
448
  if not v.get("medidoEn"):
447
- return pie
449
+ return None
448
450
  s = faltan(v["medidoEn"])
449
451
  if s is None:
450
- return pie
452
+ return None
451
453
  e = max(0, -s)
452
- edad = f"leída hace {duracion(e)}" + (" · vieja" if e >= VIEJO_SEGUNDOS else "")
453
- return f"{pie} · {edad}" if pie else edad
454
+ return f"leída hace {duracion(e)}" + (" · vieja" if e >= VIEJO_SEGUNDOS else "")
454
455
 
455
456
 
456
457
  def reinicio(segundos: int | None) -> str:
@@ -608,19 +609,24 @@ class Pluma:
608
609
  self.familia = familia
609
610
 
610
611
  def caja(self, texto: str, px: float, peso=Pango.Weight.NORMAL, ancho=None,
611
- tabular=False, elipsis=False):
612
+ tabular=False, elipsis=False, espaciado=0.0, marcado=False):
612
613
  lay = PangoCairo.create_layout(self.cr)
613
614
  fd = Pango.FontDescription()
614
615
  fd.set_family(self.familia)
615
616
  fd.set_weight(peso)
616
617
  fd.set_absolute_size(px * Pango.SCALE)
617
618
  lay.set_font_description(fd)
618
- if tabular:
619
- # Cifras de ancho fijo: sin esto el porcentaje, que va pegado al
620
- # borde derecho, baila un píxel cada vez que cambia un dígito.
619
+ if (tabular or espaciado) and not marcado:
621
620
  try:
622
621
  attrs = Pango.AttrList()
623
- attrs.insert(Pango.attr_font_features_new("tnum=1"))
622
+ if tabular:
623
+ # Cifras de ancho fijo: sin esto el porcentaje, que va pegado
624
+ # al borde derecho, baila un píxel cada vez que cambia un
625
+ # dígito.
626
+ attrs.insert(Pango.attr_font_features_new("tnum=1"))
627
+ if espaciado:
628
+ # Los rótulos en mayúsculas piden aire entre letras.
629
+ attrs.insert(Pango.attr_letter_spacing_new(int(espaciado * Pango.SCALE)))
624
630
  lay.set_attributes(attrs)
625
631
  except (AttributeError, TypeError):
626
632
  pass
@@ -635,7 +641,10 @@ class Pluma:
635
641
  lay.set_ellipsize(Pango.EllipsizeMode.END)
636
642
  else:
637
643
  lay.set_wrap(Pango.WrapMode.WORD_CHAR)
638
- lay.set_text(texto, -1)
644
+ if marcado:
645
+ lay.set_markup(texto, -1)
646
+ else:
647
+ lay.set_text(texto, -1)
639
648
  return lay
640
649
 
641
650
  def alto(self, *a, **k) -> float:
@@ -645,8 +654,10 @@ class Pluma:
645
654
  return self.caja(*a, **k).get_pixel_size()[0]
646
655
 
647
656
  def escribir(self, x, y, texto, px, color, peso=Pango.Weight.NORMAL,
648
- derecha=None, ancho=None, tabular=False, elipsis=False):
649
- lay = self.caja(texto, px, peso, ancho=ancho, tabular=tabular, elipsis=elipsis)
657
+ derecha=None, ancho=None, tabular=False, elipsis=False,
658
+ espaciado=0.0, marcado=False):
659
+ lay = self.caja(texto, px, peso, ancho=ancho, tabular=tabular, elipsis=elipsis,
660
+ espaciado=espaciado, marcado=marcado)
650
661
  w, h = lay.get_pixel_size()
651
662
  _color(self.cr, color)
652
663
  self.cr.move_to(derecha - w if derecha is not None else x, y)
@@ -692,26 +703,202 @@ def glifo_producto(cr, producto: str, color, x: float, y: float, lado: float) ->
692
703
 
693
704
 
694
705
  # ── lo que se dibuja de cada cuenta ──────────────────────────────────────
706
+ # La escala de letra del panel completo: 9.5 los rótulos en mayúscula, 11 la
707
+ # letra chica, 12.5 el cuerpo, 14 el nombre de la cuenta y 24 la cifra de
708
+ # arriba. Eran nueve tamaños distintos y ninguno mandaba.
709
+ DIAS = ("lun", "mar", "mié", "jue", "vie", "sáb", "dom")
710
+
711
+
712
+ def cuando_local(iso: str | None) -> str | None:
713
+ """El reinicio en hora de acá: «22:30» si es hoy, «jue 22:30» si no.
714
+
715
+ «reinicia en 3d1h» contesta cuánto falta; la hora contesta CUÁNDO, que es
716
+ lo que se usa para planear («¿llego al viernes?»). Va redondeada al minuto
717
+ y no truncada: el servidor informa 03:59:59.6, y eso son las 04:00.
718
+ """
719
+ if not iso:
720
+ return None
721
+ try:
722
+ cuando = datetime.fromisoformat(iso.replace("Z", "+00:00"))
723
+ except ValueError:
724
+ return None
725
+ cuando = (cuando + timedelta(seconds=30)).astimezone()
726
+ ahora = datetime.now().astimezone()
727
+ if cuando < ahora:
728
+ return None
729
+ hora = cuando.strftime("%H:%M")
730
+ return hora if cuando.date() == ahora.date() else f"{DIAS[cuando.weekday()]} {hora}"
731
+
732
+
733
+ def etiqueta_de(v: dict) -> str:
734
+ """El nombre de una barra para leer: «Semanal (Fable)», no «weekly_scoped (Fable)».
735
+
736
+ La clave es la de la API, y la terminal la sigue mostrando así porque es lo
737
+ que sirve para buscarla en un log. El panel se lee de un vistazo, y ahí
738
+ `weekly_all` es ruido. Se nombran las mismas dos que reconoce el núcleo
739
+ (`sesionDe` y `semanalDe` en src/core/tipos.ts); cualquier otra queda con
740
+ el nombre que trae.
741
+ """
742
+ clave, grupo, alcance = v.get("clave") or "", v.get("grupo"), v.get("alcance")
743
+ if grupo == "session" or clave in ("session", "five_hour"):
744
+ base = "Sesión"
745
+ elif grupo == "weekly" or clave.startswith("weekly") or clave == "seven_day":
746
+ base = "Semanal"
747
+ else:
748
+ return nombre_ventana(v)
749
+ return f"{base} ({alcance})" if alcance else base
750
+
751
+
752
+ def con_codigo(texto: str) -> str:
753
+ """El texto como markup de Pango, con lo que va entre acentos graves en
754
+ monoespaciada: `qm --refrescar` es un comando para copiar, y con los acentos
755
+ pegados se leía como un error de tipeo."""
756
+ partes = texto.split("`")
757
+ if len(partes) < 3 or len(partes) % 2 == 0:
758
+ return GLib.markup_escape_text(texto)
759
+ # Un comando partido en dos renglones —«qm --» y abajo «statusline»— ya no
760
+ # se puede copiar: los espacios de adentro no cortan y los guiones tampoco.
761
+ pegado = lambda t: t.replace(" ", "\u00a0").replace("-", "-\u2060")
762
+ return "".join(
763
+ f"<tt>{GLib.markup_escape_text(pegado(parte))}</tt>" if i % 2
764
+ else GLib.markup_escape_text(parte)
765
+ for i, parte in enumerate(partes)
766
+ )
767
+
768
+
769
+ def _tarjeta(cr, arriba: float, alto: float, fondo=None, borde=None) -> None:
770
+ cr.new_path()
771
+ _redondeado(cr, MARGEN + 0.5, arriba + 0.5,
772
+ ANCHO_PANEL - 2 * MARGEN - 1, alto - 1, RADIO_TARJETA)
773
+ _color(cr, fondo or TEMA.tarjeta)
774
+ cr.fill_preserve()
775
+ _color(cr, borde or TEMA.borde_tarjeta)
776
+ cr.set_line_width(1)
777
+ cr.stroke()
778
+
779
+
780
+ def _medidor(cr, x: float, y: float, ancho: float, alto: float, pct: float, color) -> None:
781
+ """Pista tenue y relleno con el color del estado. Un 0 % deja la pista sola:
782
+ un puntito de color diría que hay algo gastado."""
783
+ cr.new_path()
784
+ _redondeado(cr, x, y, ancho, alto, alto / 2)
785
+ _color(cr, TEMA.pista)
786
+ cr.fill()
787
+ if pct <= 0:
788
+ return
789
+ lleno = max(alto, ancho * min(100.0, pct) / 100.0)
790
+ cr.new_path()
791
+ _redondeado(cr, x, y, lleno, alto, alto / 2)
792
+ _color(cr, color)
793
+ cr.fill()
794
+
795
+
796
+ def _anillo(cr, cx: float, cy: float, radio: float, grosor: float, frac: float,
797
+ color, pista) -> None:
798
+ cr.save()
799
+ # Sin esto, el lápiz que dejó el último texto se une al arco con una recta.
800
+ cr.new_path()
801
+ cr.set_line_width(grosor)
802
+ cr.set_line_cap(cairo.LINE_CAP_BUTT)
803
+ cr.arc(cx, cy, radio, 0, 2 * math.pi)
804
+ _color(cr, pista)
805
+ cr.stroke()
806
+ frac = max(0.0, min(1.0, frac))
807
+ if frac > 0:
808
+ cr.set_line_cap(cairo.LINE_CAP_ROUND)
809
+ cr.arc(cx, cy, radio, -math.pi / 2, -math.pi / 2 + 2 * math.pi * frac)
810
+ _color(cr, color)
811
+ cr.stroke()
812
+ cr.restore()
813
+
814
+
815
+ def glifo_reinicio(cr, color, x: float, y: float, lado: float) -> None:
816
+ """↻, dibujada: el carácter no está en todas las tipografías, y el de
817
+ reemplazo sale de otro cuerpo y otro grosor que el texto de al lado. Es el
818
+ ícono de refrescar de siempre: un círculo abierto arriba a la derecha, con
819
+ la punta llena —a este tamaño dos trazos finos no se leen como flecha—."""
820
+ cx, cy, r = x + lado / 2, y + lado / 2 + 0.5, lado * 0.34
821
+ cr.save()
822
+ cr.new_path()
823
+ cr.set_line_width(1.25)
824
+ cr.set_line_cap(cairo.LINE_CAP_ROUND)
825
+ _color(cr, color)
826
+ cr.arc(cx, cy, r, -math.pi / 2 + 1.35, 3 * math.pi / 2 - 0.2)
827
+ cr.stroke()
828
+ h = lado * 0.36
829
+ tx, ty = cx + 0.4, cy - r
830
+ cr.move_to(tx + h, ty)
831
+ cr.line_to(tx - h * 0.25, ty - h * 0.75)
832
+ cr.line_to(tx - h * 0.25, ty + h * 0.75)
833
+ cr.close_path()
834
+ cr.fill()
835
+ cr.restore()
836
+
837
+
838
+ def glifo_tendencia(cr, color, x: float, y: float, lado: float) -> None:
839
+ """↗: sube."""
840
+ a, b = lado * 0.2, lado * 0.8
841
+ cr.save()
842
+ cr.new_path()
843
+ cr.set_line_width(1.4)
844
+ cr.set_line_cap(cairo.LINE_CAP_ROUND)
845
+ cr.set_line_join(cairo.LINE_JOIN_ROUND)
846
+ _color(cr, color)
847
+ cr.move_to(x + a, y + b)
848
+ cr.line_to(x + b, y + a)
849
+ cr.move_to(x + b - lado * 0.36, y + a)
850
+ cr.line_to(x + b, y + a)
851
+ cr.line_to(x + b, y + a + lado * 0.36)
852
+ cr.stroke()
853
+ cr.restore()
854
+
855
+
856
+ def glifo_dormida(cr, color, x: float, y: float, lado: float) -> None:
857
+ """Una luna: la cuenta está, pero nadie la usa."""
858
+ cx, cy, r = x + lado / 2, y + lado / 2, lado * 0.38
859
+ cr.save()
860
+ cr.new_path()
861
+ cr.set_fill_rule(cairo.FILL_RULE_EVEN_ODD)
862
+ cr.arc(cx, cy, r, 0, 2 * math.pi)
863
+ cr.new_sub_path()
864
+ cr.arc(cx + r * 0.55, cy - r * 0.45, r * 0.85, 0, 2 * math.pi)
865
+ cr.clip()
866
+ cr.arc(cx, cy, r, 0, 2 * math.pi)
867
+ _color(cr, color)
868
+ cr.fill()
869
+ cr.restore()
870
+
871
+
695
872
  class VistaCuenta:
696
- """Una cuenta del panel, en su tarjeta: cabecera, un renglón por barra, la
697
- curva pegada a la que frena, y el ritmo. Mide primero y dibuja después,
698
- porque el menú necesita el alto antes de que exista nada.
873
+ """Una cuenta del panel, en su tarjeta.
874
+
875
+ Arriba quién es: el nombre con su plan, el mail, y de cuándo es el número.
876
+ Después un renglón por barra —el nombre, cuánto falta para el reinicio y el
877
+ porcentaje, con el medidor abajo—, y pegada a la barra que frena, su curva.
878
+ Al pie, separado por una línea, lo que se deduce de todo eso: hacia dónde
879
+ vas y cuánto te toca hoy.
880
+
881
+ Mide y dibuja con el MISMO recorrido (`_recorrer`): el menú necesita el alto
882
+ antes de que exista nada, y un alto calculado aparte de lo que se pinta es
883
+ cómo los renglones terminan pisándose.
699
884
  """
700
885
 
701
- # Un renglón de barra = nombre (18) + medidor (11) + pie (16). Si esto no
702
- # coincide con lo que dibuja pintar(), los renglones se pisan.
703
- ALTO_BARRA = 45
704
- # 18 de curva + 16 de rótulos.
705
- ALTO_CURVA = 34
886
+ ALTO_ROTULO = 18
887
+ ALTO_MEDIDOR = 6
888
+ ENTRE_BARRAS = 11
889
+ ALTO_EDAD = 15
890
+ ALTO_CURVA = 22
891
+ ALTO_EJE = 13
892
+ ALTO_RENGLON = 16
706
893
 
707
894
  def __init__(self, p: dict, indice_color: int) -> None:
708
895
  cuota = p.get("cuota") or {}
709
896
  self.producto = p.get("producto") or "claude"
710
897
  self.indice_color = indice_color
711
898
  self.titulo = corto(p.get("perfil") or "?")
899
+ self.cuenta = p.get("cuenta")
712
900
  # planNombre es el que se dibuja; `plan` queda para un qm anterior.
713
- partes = [x for x in (p.get("cuenta"), p.get("planNombre") or p.get("plan")) if x]
714
- self.sub = " · ".join(partes)
901
+ self.plan = p.get("planNombre") or p.get("plan")
715
902
  self.hay_numero = cuota.get("estado") == "ok"
716
903
  self.frase = None if self.hay_numero else (cuota.get("frase") or "sin cuota")
717
904
  self.historia = [
@@ -726,17 +913,29 @@ class VistaCuenta:
726
913
  choca = bool(sube and proy.get("chocasAntesDelReinicio"))
727
914
  edad = cuota.get("edadSegundos")
728
915
 
916
+ def es_la_que_frena(v: dict) -> bool:
917
+ # Por clave Y alcance: dos semanales con alcance distinto comparten
918
+ # la clave `weekly_scoped`, y marcar las dos es marcar ninguna.
919
+ return bool(frena and v.get("clave") == frena.get("clave")
920
+ and v.get("alcance") == frena.get("alcance"))
921
+
729
922
  self.barras = []
730
923
  for v in (cuota.get("mostrar") or []) if self.hay_numero else []:
731
- pie = pie_de_barra(v)
732
- es_la_que_frena = bool(frena and v.get("clave") == frena.get("clave"))
924
+ seg = faltan(v.get("reinicia"))
925
+ edad_barra = edad_de_barra(v)
733
926
  self.barras.append({
734
927
  "nombre": nombre_ventana(v),
928
+ "etiqueta": etiqueta_de(v),
735
929
  "pct": v.get("porcentaje", 0),
736
930
  "nivel": nivel_de(v.get("porcentaje", 0),
737
- v.get("preocupa", False) or (choca and es_la_que_frena)),
931
+ v.get("preocupa", False) or (choca and es_la_que_frena(v))),
738
932
  "activa": bool(v.get("activa")),
739
- "pie": pie,
933
+ "frena": es_la_que_frena(v),
934
+ "reinicio": None if seg is None else ("vencido" if seg < 0 else duracion(seg)),
935
+ # Lo que se dibuja abajo del medidor: la edad propia de la
936
+ # barra, si la tiene.
937
+ "edad": edad_barra,
938
+ "vieja": bool(edad_barra and edad_barra.endswith("· vieja")),
740
939
  })
741
940
 
742
941
  self.ritmo = None
@@ -754,23 +953,29 @@ class VistaCuenta:
754
953
 
755
954
  # El presupuesto diario: cuánto por día para que la ventana larga
756
955
  # llegue entera al reinicio, y cuánto de eso queda hoy. La cuenta
757
- # —incluido CUÁL ventana se reparte— viene hecha del núcleo.
758
- self.presupuesto = []
956
+ # —incluido CUÁL ventana se reparte— viene hecha del núcleo. Al lado va
957
+ # un anillo con lo gastado de hoy: es el mismo medidor que tiene la
958
+ # cuenta en la barra de arriba, y el panel nunca lo explicaba.
959
+ self.presupuesto, self.hoy = [], None
759
960
  if self.hay_numero:
760
- self.presupuesto = renglones_presupuesto(p.get("presupuesto") or {})
761
-
762
- # Cada cuánto se lee ESTA cuenta y cuándo fue la última: la pregunta
763
- # «¿este número de cuándo es?» no se contesta con un porcentaje.
764
- self.lecturas = None
961
+ pre = p.get("presupuesto") or {}
962
+ nombre = None
963
+ if pre.get("barra"):
964
+ nombre = etiqueta_de({"clave": pre.get("clave") or "", "alcance": pre.get("alcance"),
965
+ "nombre": pre["barra"]})
966
+ self.presupuesto = renglones_presupuesto(pre, nombre)
967
+ self.hoy = pct_diario(pre)
968
+
969
+ # De cuándo es el número y cada cuánto se lee: la pregunta «¿este
970
+ # número de cuándo es?» no se contesta con un porcentaje.
971
+ self.leida, self.cada, self.vieja = None, None, False
765
972
  if self.hay_numero:
766
- partes = []
973
+ if edad is not None:
974
+ self.vieja = edad >= VIEJO_SEGUNDOS
975
+ self.leida = f"leída hace {duracion(edad)}" + (" · vieja" if self.vieja else "")
767
976
  cada = cada_cuanto(self.historia)
768
977
  if cada is not None:
769
- partes.append(f"cada ~{duracion(int(cada))}")
770
- if edad is not None:
771
- partes.append(f"última hace {duracion(edad)}"
772
- + (" · viejo" if edad >= VIEJO_SEGUNDOS else ""))
773
- self.lecturas = "lecturas: " + " · ".join(partes) if partes else None
978
+ self.cada = f"cada ~{duracion(int(cada))}"
774
979
 
775
980
  # Por qué esta cuenta quedó al fondo y no encabeza. El núcleo ya lo
776
981
  # resolvió y lo escribió en palabras; acá sólo se dibuja. Una cuenta
@@ -778,34 +983,186 @@ class VistaCuenta:
778
983
  rel = p.get("relevancia") or {}
779
984
  self.dormida = None
780
985
  if rel.get("dormida"):
781
- self.dormida = "dormida: " + " · ".join(rel.get("porque") or [])
986
+ self.dormida = "dormida: " + " · ".join(rel.get("porque") or [])
782
987
 
783
988
  @staticmethod
784
989
  def _ancho_contenido() -> float:
785
990
  return ANCHO_PANEL - 2 * MARGEN - 2 * PAD_TARJETA
786
991
 
992
+ def _con_curva(self, b: dict) -> bool:
993
+ # La curva va pegada a la barra que frena: es de ella.
994
+ return b["nombre"] == self.clave_frena and len(self.historia) >= 3
995
+
996
+ def _quieta(self) -> str | None:
997
+ """Si la serie no se movió, lo dice en palabras en vez de dibujarlo.
998
+
999
+ Una curva plana gastaba 35 px en una raya al pie de una caja vacía, y la
1000
+ caja vacía se leía como un dibujo que no terminó de cargar.
1001
+ """
1002
+ ps = [round(float(p)) for _, p in self.historia]
1003
+ if not ps or max(ps) != min(ps):
1004
+ return None
1005
+ ts = [t for t, _ in self.historia]
1006
+ horas = (max(ts) - min(ts)) / 3_600_000
1007
+ return ("sin cambios en la última hora" if horas < 1
1008
+ else f"sin cambios en las últimas {horas:.1f} h")
1009
+
787
1010
  def medir(self, pluma: Pluma) -> float:
788
- alto = PAD_TARJETA + 20 + (17 if self.sub else 0) + 6
1011
+ return self._recorrer(pluma, None, 0.0)
1012
+
1013
+ def pintar(self, cr, pluma: Pluma, arriba: float) -> float:
1014
+ alto = self.medir(pluma)
1015
+ _tarjeta(cr, arriba, alto)
1016
+ self._recorrer(pluma, cr, arriba)
1017
+ return arriba + alto
1018
+
1019
+ def _recorrer(self, pluma: Pluma, cr, arriba: float) -> float:
1020
+ """El único lugar que sabe dónde va cada cosa. Sin `cr` sólo mide."""
1021
+ ix = MARGEN + PAD_TARJETA
1022
+ ancho = self._ancho_contenido()
1023
+ der = ix + ancho
1024
+ nx = ix + 22
1025
+ y = arriba + PAD_TARJETA
1026
+
1027
+ # ── quién es ──
1028
+ derecha1 = self.leida
1029
+ w1 = pluma.ancho(derecha1, 10.5) if derecha1 else 0
1030
+ hueco = der - nx - (w1 + 12 if derecha1 else 0)
1031
+ w_titulo = min(pluma.ancho(self.titulo, 14, Pango.Weight.BOLD), hueco)
1032
+ plan_arriba = None
1033
+ if self.plan:
1034
+ w_plan = pluma.ancho(self.plan, 10, Pango.Weight.MEDIUM) + 12
1035
+ lugar = hueco - w_titulo - 8
1036
+ if lugar >= min(w_plan, 48):
1037
+ plan_arriba = min(w_plan, lugar)
1038
+ if cr is not None:
1039
+ glifo_producto(cr, self.producto, TEMA.color_cuenta(self.indice_color), ix, y + 3, 14)
1040
+ pluma.escribir(nx, y, self.titulo, 14, TEMA.etiqueta, Pango.Weight.BOLD,
1041
+ ancho=w_titulo, elipsis=True)
1042
+ if plan_arriba:
1043
+ cx = nx + w_titulo + 8
1044
+ cr.new_path()
1045
+ _redondeado(cr, cx, y + 1.5, plan_arriba, 17, 8.5)
1046
+ _color(cr, TEMA.pista[:3] + (TEMA.pista[3] * 0.6,))
1047
+ cr.fill()
1048
+ pluma.escribir(cx + 6, y + 3, self.plan, 10, TEMA.secundario,
1049
+ Pango.Weight.MEDIUM, ancho=plan_arriba - 12, elipsis=True)
1050
+ if derecha1:
1051
+ pluma.escribir(0, y + 3, derecha1, 10.5,
1052
+ TEMA.nivel("aviso") if self.vieja else TEMA.terciario,
1053
+ Pango.Weight.MEDIUM if self.vieja else Pango.Weight.NORMAL,
1054
+ derecha=der)
1055
+ y += 20
1056
+
1057
+ izquierda2 = " · ".join(x for x in (self.cuenta, None if plan_arriba else self.plan) if x)
1058
+ if izquierda2 or self.cada:
1059
+ if cr is not None:
1060
+ w2 = pluma.ancho(self.cada, 10.5) if self.cada else 0
1061
+ if izquierda2:
1062
+ pluma.escribir(nx, y, izquierda2, 11, TEMA.terciario,
1063
+ ancho=der - nx - (w2 + 12 if self.cada else 0), elipsis=True)
1064
+ if self.cada:
1065
+ pluma.escribir(0, y, self.cada, 10.5, TEMA.terciario, derecha=der)
1066
+ y += 15
1067
+ y += 11
1068
+
789
1069
  if self.frase is not None:
790
- return alto + pluma.alto(self.frase, 11.5, ancho=self._ancho_contenido()) + PAD_TARJETA
791
- alto += len(self.barras) * self.ALTO_BARRA
792
- if self.clave_frena and len(self.historia) >= 3:
793
- alto += self.ALTO_CURVA
1070
+ if cr is not None:
1071
+ pluma.escribir(ix, y, con_codigo(self.frase), 11.5, TEMA.secundario,
1072
+ ancho=ancho, marcado=True)
1073
+ y += pluma.alto(con_codigo(self.frase), 11.5, ancho=ancho, marcado=True)
1074
+ return y + PAD_TARJETA - arriba
1075
+
1076
+ # ── las barras ──
1077
+ for b in self.barras:
1078
+ if cr is not None:
1079
+ color = TEMA.nivel(b["nivel"])
1080
+ cifra = f"{b['pct']:.0f}%"
1081
+ w_cifra = pluma.ancho(cifra, 13, Pango.Weight.BOLD, tabular=True)
1082
+ pluma.escribir(0, y - 1, cifra, 13, TEMA.etiqueta, Pango.Weight.BOLD,
1083
+ derecha=der, tabular=True)
1084
+ fin_rotulo = der - w_cifra - 12
1085
+ if b["reinicio"]:
1086
+ w_r = pluma.ancho(b["reinicio"], 11, tabular=True)
1087
+ x_r = der - w_cifra - 12 - w_r
1088
+ pluma.escribir(x_r, y + 1, b["reinicio"], 11, TEMA.terciario, tabular=True)
1089
+ glifo_reinicio(cr, TEMA.terciario, x_r - 13, y + 3, 10)
1090
+ fin_rotulo = x_r - 13 - 10
1091
+ if b["frena"]:
1092
+ # La que frena se marca en el margen, como en la terminal.
1093
+ cr.new_path()
1094
+ cr.move_to(ix - 10, y + 5)
1095
+ cr.line_to(ix - 5, y + 9)
1096
+ cr.line_to(ix - 10, y + 13)
1097
+ cr.close_path()
1098
+ _color(cr, color)
1099
+ cr.fill()
1100
+ pluma.escribir(ix, y, b["etiqueta"], 12.5,
1101
+ TEMA.etiqueta if b["frena"] else TEMA.secundario,
1102
+ Pango.Weight.SEMIBOLD if b["frena"] else Pango.Weight.NORMAL,
1103
+ ancho=max(40, fin_rotulo - ix), elipsis=True)
1104
+ _medidor(cr, ix, y + self.ALTO_ROTULO, ancho, self.ALTO_MEDIDOR, b["pct"], color)
1105
+ y += self.ALTO_ROTULO + self.ALTO_MEDIDOR
1106
+ quieta = self._quieta() if self._con_curva(b) else None
1107
+ pie = " · ".join(x for x in (b["edad"], quieta) if x)
1108
+ if pie:
1109
+ if cr is not None:
1110
+ pluma.escribir(ix, y + 3, pie, 10.5,
1111
+ TEMA.nivel("aviso") if b["vieja"] else TEMA.terciario,
1112
+ ancho=ancho, elipsis=True)
1113
+ y += self.ALTO_EDAD
1114
+ if self._con_curva(b) and not quieta:
1115
+ y += 7
1116
+ if cr is not None:
1117
+ self._curva(cr, pluma, (ix, y, ancho, self.ALTO_CURVA), TEMA.nivel(b["nivel"]))
1118
+ y += self.ALTO_CURVA + self.ALTO_EJE
1119
+ y += self.ENTRE_BARRAS
1120
+
1121
+ # ── lo que se deduce ──
1122
+ renglones = (1 if self.ritmo else 0) + len(self.presupuesto) + (1 if self.dormida else 0)
1123
+ if not renglones:
1124
+ return y - self.ENTRE_BARRAS + PAD_TARJETA + 2 - arriba
1125
+ if cr is not None:
1126
+ cr.new_path()
1127
+ cr.rectangle(ix, y, ancho, 1)
1128
+ _color(cr, TEMA.borde_tarjeta)
1129
+ cr.fill()
1130
+ y += 10
1131
+ tx = ix + 20
794
1132
  if self.ritmo:
795
- alto += 20
1133
+ if cr is not None:
1134
+ color = TEMA.nivel("critico") if self.ritmo_rojo else TEMA.terciario
1135
+ glifo_tendencia(cr, color, ix + 1, y + 2, 12)
1136
+ pluma.escribir(tx, y, self.ritmo, 11.5, color,
1137
+ Pango.Weight.MEDIUM if self.ritmo_rojo else Pango.Weight.NORMAL,
1138
+ ancho=der - tx, elipsis=True)
1139
+ y += self.ALTO_RENGLON
796
1140
  if self.presupuesto:
797
- # 16 por renglón, y 4 de aire arriba del bloque.
798
- alto += 4 + 16 * len(self.presupuesto)
799
- if self.lecturas:
800
- alto += 17
1141
+ if cr is not None:
1142
+ medio = y + len(self.presupuesto) * self.ALTO_RENGLON / 2 - 1.5
1143
+ frac = (self.hoy or 0) / 100.0
1144
+ color = TEMA.nivel(nivel_de(self.hoy or 0, False))
1145
+ _anillo(cr, ix + 7, medio, 5.5, 2.4, frac, color, TEMA.pista)
1146
+ for renglon in self.presupuesto:
1147
+ pluma.escribir(tx, y, renglon, 11.5, TEMA.secundario,
1148
+ ancho=der - tx, elipsis=True)
1149
+ y += self.ALTO_RENGLON
1150
+ else:
1151
+ y += self.ALTO_RENGLON * len(self.presupuesto)
801
1152
  if self.dormida:
802
- alto += 17
803
- return alto + PAD_TARJETA - 4
1153
+ if cr is not None:
1154
+ glifo_dormida(cr, TEMA.terciario, ix + 1, y + 2, 12)
1155
+ pluma.escribir(tx, y, self.dormida, 11, TEMA.terciario,
1156
+ ancho=der - tx, elipsis=True)
1157
+ y += self.ALTO_RENGLON
1158
+ return y + PAD_TARJETA - 3 - arriba
804
1159
 
805
1160
  def _curva(self, cr, pluma, caja, color) -> None:
806
1161
  """Las muestras recientes, dibujadas. El eje Y va del mínimo al máximo
807
1162
  de la serie y no de 0 a 100: lo que interesa acá es la PENDIENTE, y a
808
- escala completa una subida de tres puntos se ve plana."""
1163
+ escala completa una subida de tres puntos se ve plana. Por eso abajo
1164
+ dice de cuánto a cuánto fue: sin eso, una subida de 10 a 12 y una de 10
1165
+ a 90 dibujan la misma rampa."""
809
1166
  x0, y0, w, h = caja
810
1167
  ts = [m[0] for m in self.historia]
811
1168
  ps = [float(m[1]) for m in self.historia]
@@ -814,15 +1171,22 @@ class VistaCuenta:
814
1171
  if t_max <= t_min:
815
1172
  return
816
1173
  rango = max(1.0, p_max - p_min)
817
- px = lambda t: x0 + w * (t - t_min) / (t_max - t_min)
818
- py = lambda p: y0 + h - h * (p - p_min) / rango
1174
+ # Un píxel de aire arriba y abajo, para que la línea y el punto del
1175
+ # final no queden cortados contra el borde.
1176
+ px = lambda t: x0 + (w - 3) * (t - t_min) / (t_max - t_min)
1177
+ py = lambda p: y0 + 2 + (h - 4) * (1 - (p - p_min) / rango)
819
1178
 
1179
+ cr.save()
1180
+ cr.new_path()
820
1181
  cr.move_to(px(ts[0]), y0 + h)
821
1182
  for t, p in zip(ts, ps):
822
1183
  cr.line_to(px(t), py(p))
823
1184
  cr.line_to(px(ts[-1]), y0 + h)
824
1185
  cr.close_path()
825
- _color(cr, color[:3] + (0.16,))
1186
+ degrade = cairo.LinearGradient(0, y0, 0, y0 + h)
1187
+ degrade.add_color_stop_rgba(0, color[0], color[1], color[2], 0.30)
1188
+ degrade.add_color_stop_rgba(1, color[0], color[1], color[2], 0.02)
1189
+ cr.set_source(degrade)
826
1190
  cr.fill()
827
1191
 
828
1192
  cr.set_line_width(1.5)
@@ -836,100 +1200,17 @@ class VistaCuenta:
836
1200
  cr.arc(px(ts[-1]), py(ps[-1]), 2.5, 0, 2 * math.pi)
837
1201
  _color(cr, color)
838
1202
  cr.fill()
1203
+ cr.restore()
839
1204
 
840
1205
  horas = (t_max - t_min) / 3_600_000
841
- pluma.escribir(x0, y0 + h + 2, f"{p_min:.0f}%", 9.5, TEMA.terciario)
1206
+ desde, hasta = ps[0], ps[-1]
1207
+ rotulo = (f"{desde:.0f} → {hasta:.0f} %" if round(desde) != round(hasta)
1208
+ else f"{hasta:.0f} %, sin cambios")
1209
+ pluma.escribir(x0, y0 + h + 2, rotulo, 9.5, TEMA.terciario, tabular=True)
842
1210
  pluma.escribir(0, y0 + h + 2,
843
1211
  f"últimas {horas:.1f} h" if horas >= 1 else "última hora",
844
1212
  9.5, TEMA.terciario, derecha=x0 + w)
845
1213
 
846
- def pintar(self, cr, pluma: Pluma, arriba: float) -> float:
847
- alto = self.medir(pluma)
848
- # La tarjeta: así agrupa GNOME, con una caja redondeada y un fondo
849
- # apenas distinto, en vez de la línea de pelo de macOS.
850
- _redondeado(cr, MARGEN + 0.5, arriba + 0.5,
851
- ANCHO_PANEL - 2 * MARGEN - 1, alto - 1, RADIO_TARJETA)
852
- _color(cr, TEMA.tarjeta)
853
- cr.fill_preserve()
854
- _color(cr, TEMA.borde_tarjeta)
855
- cr.set_line_width(1)
856
- cr.stroke()
857
-
858
- ix = MARGEN + PAD_TARJETA
859
- ancho = self._ancho_contenido()
860
- der = ix + ancho
861
- y = arriba + PAD_TARJETA
862
-
863
- glifo_producto(cr, self.producto, TEMA.color_cuenta(self.indice_color), ix, y + 2, 14)
864
- pluma.escribir(ix + 21, y, self.titulo, 13.5, TEMA.etiqueta, Pango.Weight.BOLD,
865
- ancho=ancho - 21, elipsis=True)
866
- y += 20
867
- if self.sub:
868
- pluma.escribir(ix + 21, y, self.sub, 11, TEMA.terciario,
869
- ancho=ancho - 21, elipsis=True)
870
- y += 17
871
- y += 6
872
-
873
- if self.frase is not None:
874
- pluma.escribir(ix, y, self.frase, 11.5, TEMA.secundario, ancho=ancho)
875
- return arriba + alto
876
-
877
- for b in self.barras:
878
- nombre = f"{b['nombre']} ▸" if b["activa"] else b["nombre"]
879
- cifra = f"{b['pct']:.0f}%"
880
- # El nombre cede: el número es el dato y nunca se recorta.
881
- hueco = ancho - pluma.ancho(cifra, 12, Pango.Weight.BOLD, tabular=True) - 12
882
- pluma.escribir(ix, y, nombre, 11.5,
883
- TEMA.etiqueta if b["activa"] else TEMA.secundario,
884
- Pango.Weight.MEDIUM if b["activa"] else Pango.Weight.NORMAL,
885
- ancho=hueco, elipsis=True)
886
- pluma.escribir(0, y - 0.5, cifra, 12, TEMA.etiqueta,
887
- Pango.Weight.BOLD, derecha=der, tabular=True)
888
- y += 18
889
- # El medidor: pista tenue y relleno con el color del estado.
890
- _redondeado(cr, ix, y, ancho, 5, 2.5)
891
- _color(cr, TEMA.pista)
892
- cr.fill()
893
- lleno = max(5.0, ancho * max(0.0, min(100.0, b["pct"])) / 100.0)
894
- _redondeado(cr, ix, y, lleno, 5, 2.5)
895
- _color(cr, TEMA.nivel(b["nivel"]))
896
- cr.fill()
897
- y += 11
898
- if b["pie"]:
899
- pluma.escribir(ix, y, b["pie"], 10.5, TEMA.terciario, ancho=ancho, elipsis=True)
900
- y += 16
901
- # La curva va pegada a la barra que frena: es de ella.
902
- if b["nombre"] == self.clave_frena and len(self.historia) >= 3:
903
- self._curva(cr, pluma, (ix, y - 2, ancho, 18), TEMA.nivel(b["nivel"]))
904
- y += self.ALTO_CURVA
905
-
906
- if self.ritmo:
907
- y += 4
908
- pluma.escribir(ix, y, self.ritmo, 11,
909
- TEMA.nivel("critico") if self.ritmo_rojo else TEMA.terciario,
910
- Pango.Weight.MEDIUM if self.ritmo_rojo else Pango.Weight.NORMAL,
911
- ancho=ancho, elipsis=True)
912
- y += 16
913
- # El ritmo dice hacia dónde vas; el presupuesto, a cuánto tendrías que
914
- # ir para que la cuota llegue al reinicio. Van pegados.
915
- if self.presupuesto:
916
- if not self.ritmo:
917
- y += 4
918
- for renglon in self.presupuesto:
919
- pluma.escribir(ix, y, renglon, 11, TEMA.secundario,
920
- ancho=ancho, elipsis=True)
921
- y += 16
922
- if self.lecturas:
923
- if not self.ritmo and not self.presupuesto:
924
- y += 4
925
- pluma.escribir(ix, y, self.lecturas, 10.5, TEMA.terciario, ancho=ancho, elipsis=True)
926
- y += 17
927
- if self.dormida:
928
- if not self.ritmo and not self.presupuesto and not self.lecturas:
929
- y += 4
930
- pluma.escribir(ix, y, self.dormida, 10.5, TEMA.terciario, ancho=ancho, elipsis=True)
931
- return arriba + alto
932
-
933
1214
 
934
1215
  class VistaSinCuota:
935
1216
  """Las cuentas que todavía no tienen número DE CUOTA, juntas en una tarjeta.
@@ -948,6 +1229,8 @@ class VistaSinCuota:
948
1229
  cuenta dormida sería ruido con la misma forma que un dato.
949
1230
  """
950
1231
 
1232
+ ALTO_ROTULO = 20
1233
+
951
1234
  def __init__(self, cuentas: list[tuple[str, str, int]]) -> None:
952
1235
  # Agrupadas por frase y en el orden en que aparecieron: dos cuentas
953
1236
  # pueden estar calladas por motivos distintos, y ahí la frase importa.
@@ -966,37 +1249,41 @@ class VistaSinCuota:
966
1249
  return ANCHO_PANEL - 2 * MARGEN - 2 * PAD_TARJETA
967
1250
 
968
1251
  def medir(self, pluma: Pluma) -> float:
969
- alto = PAD_TARJETA
970
- for frase, nombres in self.grupos:
971
- alto += 18 + pluma.alto(frase, 10.5, ancho=self._ancho_contenido()) + 8
972
- return alto + PAD_TARJETA - 8
1252
+ alto = PAD_TARJETA + self.ALTO_ROTULO
1253
+ for frase, _ in self.grupos:
1254
+ alto += 18 + pluma.alto(con_codigo(frase), 11, ancho=self._ancho_contenido(),
1255
+ marcado=True) + 10
1256
+ return alto + PAD_TARJETA - 10
973
1257
 
974
1258
  def pintar(self, cr, pluma: Pluma, arriba: float) -> float:
975
1259
  alto = self.medir(pluma)
976
- _redondeado(cr, MARGEN + 0.5, arriba + 0.5,
977
- ANCHO_PANEL - 2 * MARGEN - 1, alto - 1, RADIO_TARJETA)
978
- _color(cr, TEMA.tarjeta)
979
- cr.fill_preserve()
980
- _color(cr, TEMA.borde_tarjeta)
981
- cr.set_line_width(1)
982
- cr.stroke()
983
-
1260
+ _tarjeta(cr, arriba, alto)
984
1261
  ix = MARGEN + PAD_TARJETA
1262
+ ancho = self._ancho_contenido()
985
1263
  y = arriba + PAD_TARJETA
1264
+ pluma.escribir(ix, y, "SIN NÚMERO DE CUOTA", 9.5, TEMA.terciario,
1265
+ Pango.Weight.SEMIBOLD, espaciado=0.8)
1266
+ y += self.ALTO_ROTULO
986
1267
  for frase, nombres in self.grupos:
987
- pluma.escribir(ix, y, " · ".join(nombres), 11.5, TEMA.secundario,
988
- Pango.Weight.MEDIUM, ancho=self._ancho_contenido(), elipsis=True)
1268
+ pluma.escribir(ix, y, " · ".join(nombres), 12.5, TEMA.secundario,
1269
+ Pango.Weight.MEDIUM, ancho=ancho, elipsis=True)
989
1270
  y += 18
990
- y += pluma.escribir(ix, y, frase, 10.5, TEMA.terciario,
991
- ancho=self._ancho_contenido())
992
- y += 8
1271
+ y += pluma.escribir(ix, y, con_codigo(frase), 11, TEMA.terciario,
1272
+ ancho=ancho, marcado=True)
1273
+ y += 10
993
1274
  return arriba + alto
994
1275
 
995
1276
 
996
1277
  class VistaResumen:
997
1278
  """La cabecera: la respuesta de una línea. La misma pregunta que contesta el
998
1279
  héroe del tablero —qué me frena primero, en toda la máquina— y que si no
999
- está acá hay que sacarla comparando las cuentas a ojo."""
1280
+ está acá hay que sacarla comparando las cuentas a ojo.
1281
+
1282
+ Va en una tarjeta teñida con el color del estado: es lo primero que se mira,
1283
+ y el color dice si hace falta seguir leyendo antes de leer nada.
1284
+ """
1285
+
1286
+ alto = ALTO_CABECERA
1000
1287
 
1001
1288
  def __init__(self, cuenta: str, barra: str, pct: float, nivel: str, reinicia,
1002
1289
  medido_en: str | None = None) -> None:
@@ -1034,45 +1321,40 @@ class VistaResumen:
1034
1321
  proy = p.get("proyeccion")
1035
1322
  choca = bool(proy and proy.get("estado") == "sube" and proy.get("chocasAntesDelReinicio"))
1036
1323
  nombre = p.get("perfil") or lider.get("perfil") or "?"
1037
- return VistaResumen(corto(nombre), nombre_ventana(v), v["porcentaje"],
1324
+ return VistaResumen(corto(nombre), etiqueta_de(v), v["porcentaje"],
1038
1325
  nivel_de(v["porcentaje"], v.get("preocupa", False) or choca),
1039
1326
  v.get("reinicia"), v.get("medidoEn"))
1040
1327
 
1041
1328
  def pintar(self, cr, pluma: Pluma, arriba: float) -> float:
1042
1329
  color = TEMA.nivel(self.nivel)
1043
- lado = 46.0
1044
- izq = MARGEN + 6
1045
- centro = (izq + lado / 2, arriba + ALTO_CABECERA / 2 - 2)
1046
- radio = lado / 2 - 3
1330
+ y0 = arriba + MARGEN
1331
+ h = ALTO_CABECERA - MARGEN - ENTRE_TARJETAS
1332
+ _tarjeta(cr, y0, h, fondo=color[:3] + (0.09 if TEMA.oscuro else 0.07,),
1333
+ borde=color[:3] + (0.24,))
1047
1334
 
1048
- cr.set_line_width(5.5)
1049
- cr.set_line_cap(cairo.LINE_CAP_BUTT)
1050
- cr.arc(centro[0], centro[1], radio, 0, 2 * math.pi)
1051
- _color(cr, color[:3] + (0.20,))
1052
- cr.stroke()
1053
-
1054
- frac = max(0.0, min(100.0, self.pct)) / 100.0
1055
- if frac > 0:
1056
- cr.set_line_cap(cairo.LINE_CAP_ROUND)
1057
- cr.arc(centro[0], centro[1], radio, -math.pi / 2, -math.pi / 2 + 2 * math.pi * frac)
1058
- _color(cr, color)
1059
- cr.stroke()
1335
+ lado = 50.0
1336
+ izq = MARGEN + PAD_TARJETA
1337
+ _anillo(cr, izq + lado / 2, y0 + h / 2, lado / 2 - 3, 6, self.pct / 100.0,
1338
+ color, color[:3] + (0.22,))
1060
1339
 
1061
1340
  x = izq + lado + 14
1062
- pluma.escribir(x, arriba + 12, "Lo primero que te frena", 10.5, TEMA.terciario,
1063
- Pango.Weight.SEMIBOLD, ancho=ANCHO_PANEL - MARGEN - x, elipsis=True)
1341
+ der = ANCHO_PANEL - MARGEN - PAD_TARJETA
1342
+ pluma.escribir(x, y0 + 10, "LO PRIMERO QUE TE FRENA", 9.5, TEMA.terciario,
1343
+ Pango.Weight.SEMIBOLD, ancho=der - x, elipsis=True, espaciado=0.8)
1064
1344
  cifra = f"{self.pct:.0f}%"
1065
- y_cifra = arriba + 26
1066
- ancho_cifra = pluma.ancho(cifra, 22, Pango.Weight.BOLD, tabular=True)
1067
- pluma.escribir(x, y_cifra, cifra, 22, TEMA.etiqueta, Pango.Weight.BOLD, tabular=True)
1345
+ y_cifra = y0 + 21
1346
+ ancho_cifra = pluma.ancho(cifra, 24, Pango.Weight.BOLD, tabular=True)
1347
+ pluma.escribir(x, y_cifra, cifra, 24, TEMA.etiqueta, Pango.Weight.BOLD, tabular=True)
1068
1348
  # El nombre va a la derecha de la cifra, sobre su misma línea de base.
1069
- corrimiento = (pluma.linea_base(cifra, 22, Pango.Weight.BOLD)
1070
- - pluma.linea_base("x", 12))
1349
+ corrimiento = (pluma.linea_base(cifra, 24, Pango.Weight.BOLD)
1350
+ - pluma.linea_base("x", 13, Pango.Weight.MEDIUM))
1071
1351
  pluma.escribir(x + ancho_cifra + 8, y_cifra + corrimiento,
1072
- f"{self.cuenta} · {self.barra}", 12, TEMA.secundario,
1073
- ancho=ANCHO_PANEL - MARGEN - (x + ancho_cifra + 8), elipsis=True)
1352
+ f"{self.cuenta} · {self.barra}", 13, TEMA.secundario,
1353
+ Pango.Weight.MEDIUM,
1354
+ ancho=der - (x + ancho_cifra + 8), elipsis=True)
1074
1355
 
1075
1356
  seg = faltan(self.reinicia)
1357
+ hora = cuando_local(self.reinicia)
1076
1358
  if seg is None:
1077
1359
  texto, urgente = "sin reinicio informado", False
1078
1360
  elif self.pct >= 95:
@@ -1081,15 +1363,232 @@ class VistaResumen:
1081
1363
  texto, urgente = f"libre en {duracion(seg)}", True
1082
1364
  else:
1083
1365
  texto, urgente = reinicio(seg), False
1366
+ if hora and seg is not None and seg >= 0:
1367
+ texto += f" · {hora}"
1084
1368
  edad = faltan(self.medido_en)
1085
1369
  if edad is not None:
1086
- texto += f" · leída hace {duracion(max(0, -edad))}"
1087
- pluma.escribir(x, arriba + 54, texto, 11, color if urgente else TEMA.terciario,
1370
+ texto += f" · leída hace {duracion(max(0, -edad))}"
1371
+ pluma.escribir(x, y0 + h - 24, texto, 11, color if urgente else TEMA.secundario,
1088
1372
  Pango.Weight.MEDIUM if urgente else Pango.Weight.NORMAL,
1089
- ancho=ANCHO_PANEL - MARGEN - x, elipsis=True)
1373
+ ancho=der - x, elipsis=True)
1090
1374
  return arriba + ALTO_CABECERA
1091
1375
 
1092
1376
 
1377
+ # ── la apariencia minimalista ────────────────────────────────────────────
1378
+ # El panel completo explica una cuenta, y es lo que hace falta mientras uno
1379
+ # aprende a leerlo. Después, la mayoría de las veces se lo abre para UNA
1380
+ # pregunta: ¿cuánto me queda y cuándo vuelve? Esta vista contesta sólo eso, en
1381
+ # una mirada: un renglón por barra con su letra, su medidor, el porcentaje y
1382
+ # cuánto falta para el reinicio.
1383
+ #
1384
+ # El diseño es de @knighthw (issue #27). Se elige con
1385
+ # `qm --apariencia=minimalista`: la decisión la emite el CLI en `apariencia` y
1386
+ # acá sólo se dibuja, como todo lo demás. Un valor que este dibujo no conoce
1387
+ # cae en el panel de siempre.
1388
+ ANCHO_MINI = 300
1389
+ ALTO_CABECERA_MINI = 58
1390
+ ALTO_RENGLON_MINI = 21
1391
+ ENTRE_CUENTAS_MINI = 12
1392
+
1393
+
1394
+ def es_minimalista(datos) -> bool:
1395
+ return isinstance(datos, dict) and datos.get("apariencia") == "minimalista"
1396
+
1397
+
1398
+ def ancho_de(datos) -> int:
1399
+ return ANCHO_MINI if es_minimalista(datos) else ANCHO_PANEL
1400
+
1401
+
1402
+ def letra_de(v: dict) -> str:
1403
+ """La letra de una barra: `s` la sesión, `w` la semanal, `wf` la semanal de
1404
+ Fable —la segunda letra sale del alcance—. Una barra que no tiene letra
1405
+ conocida muestra su nombre, recortado: una letra inventada sería peor que
1406
+ un nombre largo."""
1407
+ clave, grupo, alcance = v.get("clave") or "", v.get("grupo"), v.get("alcance")
1408
+ if alcance:
1409
+ base = "w" if grupo == "weekly" or clave.startswith("weekly") or clave.startswith("seven") else clave[:1]
1410
+ return base + alcance[:1].lower()
1411
+ if clave in ("session", "five_hour") or grupo == "session":
1412
+ return "s"
1413
+ if clave in ("weekly_all", "seven_day", "weekly") or grupo == "weekly":
1414
+ return "w"
1415
+ nombre = nombre_ventana(v)
1416
+ return nombre if len(nombre) <= 6 else nombre[:5] + "…"
1417
+
1418
+
1419
+ def falta_corto(iso: str | None) -> str:
1420
+ """Cuánto falta para el reinicio, en la escalera de siempre; `vencido` si ya
1421
+ pasó, la palabra que usa el resto del proyecto."""
1422
+ seg = faltan(iso)
1423
+ if seg is None:
1424
+ return "—"
1425
+ return duracion(seg)
1426
+
1427
+
1428
+ class VistaResumenMini:
1429
+ """La cabecera minimalista: el anillo, el porcentaje y la letra de lo que
1430
+ frena primero; a la derecha, de qué cuenta es. Reemplaza el «Lo primero que
1431
+ te frena»: el anillo ya lo dice."""
1432
+
1433
+ alto = ALTO_CABECERA_MINI
1434
+
1435
+ def __init__(self, completa: "VistaResumen", letra: str) -> None:
1436
+ self.c = completa
1437
+ self.letra = letra
1438
+
1439
+ @staticmethod
1440
+ def desde(datos: dict) -> "VistaResumenMini | None":
1441
+ completa = VistaResumen.desde(datos)
1442
+ if completa is None:
1443
+ return None
1444
+ v = (datos.get("frenaPrimero") or {}).get("ventana") or {}
1445
+ return VistaResumenMini(completa, letra_de(v))
1446
+
1447
+ def pintar(self, cr, pluma: Pluma, arriba: float) -> float:
1448
+ color = TEMA.nivel(self.c.nivel)
1449
+ lado = 34.0
1450
+ izq = MARGEN + 4
1451
+ centro = (izq + lado / 2, arriba + self.alto / 2)
1452
+ radio = lado / 2 - 3
1453
+ cr.set_line_width(4.5)
1454
+ cr.set_line_cap(cairo.LINE_CAP_BUTT)
1455
+ cr.arc(centro[0], centro[1], radio, 0, 2 * math.pi)
1456
+ _color(cr, color[:3] + (0.20,))
1457
+ cr.stroke()
1458
+ frac = max(0.0, min(100.0, self.c.pct)) / 100.0
1459
+ if frac > 0:
1460
+ cr.set_line_cap(cairo.LINE_CAP_ROUND)
1461
+ cr.arc(centro[0], centro[1], radio, -math.pi / 2, -math.pi / 2 + 2 * math.pi * frac)
1462
+ _color(cr, color)
1463
+ cr.stroke()
1464
+
1465
+ x = izq + lado + 12
1466
+ cifra = f"{self.c.pct:.0f}%"
1467
+ y_cifra = centro[1] - pluma.alto(cifra, 20, Pango.Weight.BOLD) / 2
1468
+ pluma.escribir(x, y_cifra, cifra, 20, TEMA.etiqueta, Pango.Weight.BOLD, tabular=True)
1469
+ ancho_cifra = pluma.ancho(cifra, 20, Pango.Weight.BOLD, tabular=True)
1470
+ corrimiento = pluma.linea_base(cifra, 20, Pango.Weight.BOLD) - pluma.linea_base("x", 12.5)
1471
+ pluma.escribir(x + ancho_cifra + 6, y_cifra + corrimiento, self.letra, 12.5, TEMA.secundario)
1472
+ # La cuenta, a la derecha y sobre la misma línea de base que la letra.
1473
+ pluma.escribir(0, y_cifra + corrimiento + 1, self.c.cuenta, 11, TEMA.terciario,
1474
+ derecha=ANCHO_MINI - MARGEN - 4)
1475
+ return arriba + self.alto
1476
+
1477
+
1478
+ class VistaCuentaMini:
1479
+ """Una cuenta: su marca y su nombre, y un renglón por barra."""
1480
+
1481
+ entre = ENTRE_CUENTAS_MINI
1482
+
1483
+ def __init__(self, p: dict, indice_color: int) -> None:
1484
+ cuota = p.get("cuota") or {}
1485
+ self.producto = p.get("producto") or "claude"
1486
+ self.indice_color = indice_color
1487
+ self.titulo = corto(p.get("perfil") or "?")
1488
+ frena = cuota.get("frena") or {}
1489
+ proy = p.get("proyeccion")
1490
+ choca = bool(proy and proy.get("estado") == "sube" and proy.get("chocasAntesDelReinicio"))
1491
+ self.renglones = []
1492
+ for v in cuota.get("mostrar") or []:
1493
+ es_la_que_frena = bool(frena and v.get("clave") == frena.get("clave")
1494
+ and v.get("alcance") == frena.get("alcance"))
1495
+ pct = v.get("porcentaje", 0)
1496
+ self.renglones.append({
1497
+ "letra": letra_de(v),
1498
+ "pct": pct,
1499
+ "nivel": nivel_de(pct, v.get("preocupa", False) or (choca and es_la_que_frena)),
1500
+ "falta": falta_corto(v.get("reinicia")),
1501
+ "frena": es_la_que_frena,
1502
+ })
1503
+
1504
+ def medir(self, pluma: Pluma) -> float:
1505
+ return 20 + 4 + len(self.renglones) * ALTO_RENGLON_MINI + self.entre
1506
+
1507
+ def pintar(self, cr, pluma: Pluma, arriba: float) -> float:
1508
+ ix = MARGEN + 4
1509
+ der = ANCHO_MINI - MARGEN - 4
1510
+ y = arriba
1511
+ glifo_producto(cr, self.producto, TEMA.color_cuenta(self.indice_color), ix, y + 3, 12)
1512
+ pluma.escribir(ix + 19, y, self.titulo, 12.5, TEMA.etiqueta, Pango.Weight.BOLD,
1513
+ ancho=der - ix - 19, elipsis=True)
1514
+ y += 24
1515
+ # Columnas fijas: letra, medidor, porcentaje, reinicio. Las cifras van
1516
+ # tabulares y alineadas a la derecha para que se lean en columna.
1517
+ col_letra = 30
1518
+ col_falta = 52
1519
+ col_pct = 44
1520
+ x_barra = ix + col_letra
1521
+ fin_barra = der - col_falta - col_pct - 6
1522
+ for r in self.renglones:
1523
+ centro = y + ALTO_RENGLON_MINI / 2 - 2
1524
+ alto_letra = pluma.alto(r["letra"], 11.5)
1525
+ pluma.escribir(ix, centro - alto_letra / 2, r["letra"], 11.5,
1526
+ TEMA.etiqueta if r["frena"] else TEMA.secundario,
1527
+ Pango.Weight.SEMIBOLD if r["frena"] else Pango.Weight.NORMAL,
1528
+ ancho=col_letra - 4, elipsis=True)
1529
+ ancho_barra = fin_barra - x_barra
1530
+ _redondeado(cr, x_barra, centro - 2.5, ancho_barra, 5, 2.5)
1531
+ _color(cr, TEMA.pista)
1532
+ cr.fill()
1533
+ lleno = max(5.0, ancho_barra * max(0.0, min(100.0, r["pct"])) / 100.0)
1534
+ _redondeado(cr, x_barra, centro - 2.5, lleno, 5, 2.5)
1535
+ _color(cr, TEMA.nivel(r["nivel"]))
1536
+ cr.fill()
1537
+ cifra = f"{r['pct']:.0f}%"
1538
+ alto_cifra = pluma.alto(cifra, 11.5, Pango.Weight.SEMIBOLD)
1539
+ pluma.escribir(0, centro - alto_cifra / 2, cifra, 11.5, TEMA.etiqueta,
1540
+ Pango.Weight.SEMIBOLD, derecha=der - col_falta, tabular=True)
1541
+ alto_falta = pluma.alto(r["falta"], 10.5)
1542
+ pluma.escribir(0, centro - alto_falta / 2, r["falta"], 10.5, TEMA.terciario,
1543
+ derecha=der, tabular=True)
1544
+ y += ALTO_RENGLON_MINI
1545
+ return arriba + self.medir(pluma)
1546
+
1547
+
1548
+ class VistaRestoMini:
1549
+ """Lo que la vista minimalista no dibuja, dicho en un renglón: las cuentas
1550
+ sin número y las dormidas. Esconderlas sin decirlo sería volver al monitor
1551
+ que no avisa; dibujarlas enteras sería volver al panel completo."""
1552
+
1553
+ entre = 0
1554
+
1555
+ def __init__(self, sin_numero: list[str], dormidas: list[str]) -> None:
1556
+ partes = []
1557
+ if sin_numero:
1558
+ partes.append("sin número: " + ", ".join(sin_numero))
1559
+ if dormidas:
1560
+ partes.append("dormidas: " + ", ".join(dormidas))
1561
+ self.texto = " · ".join(partes)
1562
+
1563
+ def medir(self, pluma: Pluma) -> float:
1564
+ return pluma.alto(self.texto, 10.5, ancho=ANCHO_MINI - 2 * MARGEN - 8) + 4
1565
+
1566
+ def pintar(self, cr, pluma: Pluma, arriba: float) -> float:
1567
+ pluma.escribir(MARGEN + 4, arriba, self.texto, 10.5, TEMA.terciario,
1568
+ ancho=ANCHO_MINI - 2 * MARGEN - 8)
1569
+ return arriba + self.medir(pluma)
1570
+
1571
+
1572
+ def modelo_minimalista(datos: dict):
1573
+ vistas, sin_numero, dormidas, i = [], [], [], 0
1574
+ for p in datos.get("perfiles", []):
1575
+ nombre = corto(p.get("perfil") or "?")
1576
+ if (p.get("relevancia") or {}).get("dormida"):
1577
+ dormidas.append(nombre)
1578
+ continue
1579
+ if (p.get("cuota") or {}).get("estado") != "ok":
1580
+ sin_numero.append(nombre)
1581
+ continue
1582
+ vistas.append(VistaCuentaMini(p, i))
1583
+ i += 1
1584
+ if sin_numero or dormidas:
1585
+ vistas.append(VistaRestoMini(sin_numero, dormidas))
1586
+ elif vistas:
1587
+ # La última cuenta no necesita aire abajo: ya está el margen del panel.
1588
+ vistas[-1].entre = 0
1589
+ return VistaResumenMini.desde(datos), vistas
1590
+
1591
+
1093
1592
  # ── el item de la barra, dibujado ────────────────────────────────────────
1094
1593
  # Un medidor vertical por cuenta, en el orden del menú, lleno hasta la SESIÓN de
1095
1594
  # 5 h —o la semanal, si el plan no tiene sesión— y pintado por severidad. Es el mismo dibujo que el item de la barra de
@@ -1299,6 +1798,8 @@ def dibujar_item(piezas: list[dict], destino: str, escala: float = 1.0) -> tuple
1299
1798
  def modelo_panel(datos):
1300
1799
  if not isinstance(datos, dict):
1301
1800
  return None, []
1801
+ if es_minimalista(datos):
1802
+ return modelo_minimalista(datos)
1302
1803
  perfiles = datos.get("perfiles", [])
1303
1804
  vistas, calladas, i = [], [], 0
1304
1805
  for p in perfiles:
@@ -1326,6 +1827,11 @@ def medir_panel(datos, pie: bool = False) -> int:
1326
1827
  if isinstance(datos, str):
1327
1828
  return int(MARGEN * 2 + pluma.alto(datos, 11.5, ancho=ANCHO_PANEL - 2 * MARGEN))
1328
1829
  cabecera, vistas = modelo_panel(datos)
1830
+ if es_minimalista(datos):
1831
+ # Cada vista minimalista mide su propio aire de abajo, y no hay renglón
1832
+ # de «próxima lectura»: es justo lo que esta vista deja afuera.
1833
+ alto = cabecera.alto if cabecera else MARGEN
1834
+ return int(alto + sum(v.medir(pluma) for v in vistas) + MARGEN)
1329
1835
  alto = ALTO_CABECERA if cabecera else MARGEN
1330
1836
  for v in vistas:
1331
1837
  alto += v.medir(pluma) + ENTRE_TARJETAS
@@ -1343,6 +1849,10 @@ def dibujar_panel(cr, datos, alto: float, proxima: float | None = None) -> None:
1343
1849
  return
1344
1850
  cabecera, vistas = modelo_panel(datos)
1345
1851
  y = cabecera.pintar(cr, pluma, 0.0) if cabecera else float(MARGEN)
1852
+ if es_minimalista(datos):
1853
+ for v in vistas:
1854
+ y = v.pintar(cr, pluma, y)
1855
+ return
1346
1856
  for v in vistas:
1347
1857
  y = v.pintar(cr, pluma, y) + ENTRE_TARJETAS
1348
1858
  if proxima is not None:
@@ -1379,9 +1889,10 @@ def capturar(datos, ruta: str, proxima: float | None = None) -> int:
1379
1889
  imagen de 1034 px declarada como 1060, y la diferencia se ve como un hueco.
1380
1890
  """
1381
1891
  alto = medir_panel(datos, proxima is not None)
1382
- superficie = cairo.ImageSurface(cairo.FORMAT_ARGB32, ANCHO_PANEL, alto)
1892
+ ancho = ancho_de(datos)
1893
+ superficie = cairo.ImageSurface(cairo.FORMAT_ARGB32, ancho, alto)
1383
1894
  cr = cairo.Context(superficie)
1384
- fondo_panel(cr, ANCHO_PANEL, alto)
1895
+ fondo_panel(cr, ancho, alto)
1385
1896
  dibujar_panel(cr, datos, alto, proxima)
1386
1897
  superficie.write_to_png(ruta)
1387
1898
  return alto
@@ -1513,7 +2024,7 @@ class Panel:
1513
2024
  def _fila(self, dibujo, alto: float) -> Gtk.MenuItem:
1514
2025
  """Un renglón del menú que se dibuja solo."""
1515
2026
  lienzo = Gtk.DrawingArea()
1516
- lienzo.set_size_request(ANCHO_PANEL, int(alto))
2027
+ lienzo.set_size_request(ancho_de(self.datos), int(alto))
1517
2028
  lienzo.connect("draw", lambda _w, cr, d=dibujo: (d(cr), False)[1])
1518
2029
  fila = Gtk.MenuItem()
1519
2030
  # Insensible a propósito, y es lo único que hace que el panel se pueda
@@ -1548,15 +2059,16 @@ class Panel:
1548
2059
  ancho=ANCHO_PANEL - 2 * MARGEN), alto))
1549
2060
  else:
1550
2061
  cabecera, vistas = modelo_panel(self.datos)
2062
+ mini = es_minimalista(self.datos)
1551
2063
  if cabecera:
1552
2064
  self.filas.append(self._fila(
1553
2065
  lambda cr, v=cabecera: v.pintar(cr, Pluma(cr, FAMILIA), 0.0),
1554
- ALTO_CABECERA))
2066
+ cabecera.alto))
1555
2067
  for v in vistas:
1556
2068
  self.filas.append(self._fila(
1557
2069
  lambda cr, v=v: v.pintar(cr, Pluma(cr, FAMILIA), 0.0),
1558
- v.medir(pluma) + ENTRE_TARJETAS))
1559
- if self.cuanto_falta() is not None:
2070
+ v.medir(pluma) + (0 if mini else ENTRE_TARJETAS)))
2071
+ if self.cuanto_falta() is not None and not mini:
1560
2072
  self.filas.append(self._fila(self._pintar_lectura, ALTO_PIE_LECTURA))
1561
2073
 
1562
2074
  for fila in self.filas:
@@ -2578,7 +3090,7 @@ class Indicador:
2578
3090
  # 576 px de alto para un dibujo de 22. La extensión le cree al
2579
3091
  # archivo y arma el item de ese tamaño.
2580
3092
  alto_panel = capturar(self.datos, str(destino), self.falta_para_lectura())
2581
- panel = {"panel": str(destino), "panelAncho": ANCHO_PANEL, "panelAlto": alto_panel}
3093
+ panel = {"panel": str(destino), "panelAncho": ancho_de(self.datos), "panelAlto": alto_panel}
2582
3094
  except (OSError, MemoryError):
2583
3095
  pass # sin panel dibujado la extensión sigue mostrando el item
2584
3096
  try: