-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgui.py
More file actions
1258 lines (1098 loc) · 48.8 KB
/
Copy pathgui.py
File metadata and controls
1258 lines (1098 loc) · 48.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
ChromeOS_PowerControl GUI
"""
import math
import os
from pathlib import Path
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GLib
try:
import cairo
CAIRO_AVAILABLE = True
except ImportError:
CAIRO_AVAILABLE = False
def find_available_theme(*candidates):
theme_dirs = [
Path("/usr/share/themes"),
Path.home() / ".local/share/themes",
Path.home() / ".themes",
]
for name in candidates:
for d in theme_dirs:
if (d / name).exists():
return name
return candidates[-1]
def gpu_config_to_mhz(gpu_type: str, value: int) -> int:
if gpu_type in ("mali", "adreno"):
if value >= 10000:
return value // 1_000_000
return value
def gpu_mhz_to_config(gpu_type: str, mhz: int) -> int:
if gpu_type in ("mali", "adreno"):
return mhz * 1_000_000
return mhz
_BG = (0.10, 0.10, 0.10)
_PLOT_BG = (0.07, 0.07, 0.07)
_GRID = (0.22, 0.22, 0.22)
_AXIS = (0.55, 0.55, 0.55)
_TEXT = (0.85, 0.85, 0.85)
_DIM_TEXT = (0.55, 0.55, 0.55)
_CPU_C = (0.20, 0.72, 1.00)
_FAN_C = (1.00, 0.60, 0.18)
_BAT_C = (0.30, 0.88, 0.45)
_GPU_C = (0.78, 0.40, 1.00)
class BaseGraph(Gtk.DrawingArea):
PAD = dict(left=50, right=18, top=28, bottom=38)
def __init__(self, title, w=380, h=210):
super().__init__()
self.title = title
self.set_size_request(w, h)
self.connect("draw", self._on_draw)
def _plot_rect(self, W, H):
p = self.PAD
return (p['left'], p['top'],
W - p['left'] - p['right'],
H - p['top'] - p['bottom'])
def _to_screen(self, vx, vy, px, py, pw, ph, xr, yr):
sx = px + (vx - xr[0]) / (xr[1] - xr[0]) * pw
sy = py + ph - (vy - yr[0]) / (yr[1] - yr[0]) * ph
return sx, sy
def _draw_frame(self, cr, W, H, xr, yr, xlabel, ylabel, xticks=5, yticks=5):
px, py, pw, ph = self._plot_rect(W, H)
cr.set_source_rgb(*_BG)
cr.paint()
cr.set_source_rgb(*_TEXT)
cr.set_font_size(12)
ext = cr.text_extents(self.title)
cr.move_to(W / 2 - ext[2] / 2, py - 8)
cr.show_text(self.title)
cr.set_source_rgb(*_PLOT_BG)
cr.rectangle(px, py, pw, ph)
cr.fill()
cr.set_source_rgba(*_GRID, 1.0)
cr.set_line_width(0.5)
for i in range(xticks + 1):
xi = px + pw * i / xticks
cr.move_to(xi, py); cr.line_to(xi, py + ph); cr.stroke()
for i in range(yticks + 1):
yi = py + ph * i / yticks
cr.move_to(px, yi); cr.line_to(px + pw, yi); cr.stroke()
cr.set_source_rgb(*_AXIS)
cr.set_line_width(1.2)
cr.rectangle(px, py, pw, ph)
cr.stroke()
cr.set_source_rgb(*_TEXT)
cr.set_font_size(9)
for i in range(xticks + 1):
xi = px + pw * i / xticks
val = xr[0] + (xr[1] - xr[0]) * i / xticks
lbl = str(int(val))
ext = cr.text_extents(lbl)
cr.move_to(xi - ext[2] / 2, py + ph + 14)
cr.show_text(lbl)
for i in range(yticks + 1):
yi = py + ph - ph * i / yticks
val = yr[0] + (yr[1] - yr[0]) * i / yticks
lbl = str(int(val))
ext = cr.text_extents(lbl)
cr.move_to(px - ext[2] - 5, yi + 4)
cr.show_text(lbl)
cr.set_font_size(10)
cr.set_source_rgb(*_DIM_TEXT)
if xlabel:
ext = cr.text_extents(xlabel)
cr.move_to(px + pw / 2 - ext[2] / 2, py + ph + 30)
cr.show_text(xlabel)
if ylabel:
cr.save()
cr.translate(12, py + ph / 2)
cr.rotate(-math.pi / 2)
ext = cr.text_extents(ylabel)
cr.move_to(-ext[2] / 2, 0)
cr.show_text(ylabel)
cr.restore()
return px, py, pw, ph
def _vmarker(self, cr, xi, py, ph, color, label=None):
cr.set_source_rgba(*color, 0.75)
cr.set_line_width(1.0)
cr.set_dash([4, 3])
cr.move_to(xi, py); cr.line_to(xi, py + ph); cr.stroke()
cr.set_dash([])
if label:
cr.set_source_rgb(*color)
cr.set_font_size(9)
cr.move_to(xi + 3, py + 12)
cr.show_text(label)
def _filled_curve(self, cr, points, px, py, pw, ph, xr, yr, color):
s = lambda vx, vy: self._to_screen(vx, vy, px, py, pw, ph, xr, yr)
cr.set_source_rgba(*color, 0.18)
sx0, sy0 = s(*points[0])
cr.move_to(sx0, py + ph)
cr.line_to(sx0, sy0)
for pt in points[1:]:
cr.line_to(*s(*pt))
sxL, _ = s(*points[-1])
cr.line_to(sxL, py + ph)
cr.close_path()
cr.fill()
cr.set_source_rgb(*color)
cr.set_line_width(2.2)
cr.move_to(*s(*points[0]))
for pt in points[1:]:
cr.line_to(*s(*pt))
cr.stroke()
def _on_draw(self, widget, cr):
pass
def refresh(self):
self.queue_draw()
class CPUCurveGraph(BaseGraph):
"""PowerControl Curve"""
def __init__(self, get_val):
super().__init__("PowerControl Curve")
self.get_val = get_val
def _on_draw(self, widget, cr):
W, H = widget.get_allocated_width(), widget.get_allocated_height()
gv = self.get_val
min_t = gv("MIN_TEMP", 50)
hot_t = gv("HOTZONE", 70)
max_t = gv("MAX_TEMP", 85)
min_p = gv("MIN_PERF_PCT", 10)
max_p = gv("MAX_PERF_PCT", 100)
xr = (30, 100); yr = (0, 100)
px, py, pw, ph = self._draw_frame(cr, W, H, xr, yr,
"Temperature (°C)", "Performance (%)")
s = lambda vx, vy: self._to_screen(vx, vy, px, py, pw, ph, xr, yr)
d1 = hot_t - min_t
d2 = max_t - hot_t
hot_perf = (2 * d2 * max_p + d1 * min_p) / (2 * d2 + d1) if (2*d2 + d1) != 0 else (max_p + min_p) / 2
x1, _ = s(hot_t, 0); x2, _ = s(max_t, 0)
cr.set_source_rgba(1.0, 0.70, 0.20, 0.10)
cr.rectangle(x1, py, x2 - x1, ph); cr.fill()
x3 = px + pw
cr.set_source_rgba(1.0, 0.30, 0.30, 0.12)
cr.rectangle(x2, py, x3 - x2, ph); cr.fill()
points = [
(xr[0], max_p),
(min_t, max_p),
(hot_t, hot_perf),
(max_t, min_p),
(xr[1], min_p),
]
self._filled_curve(cr, points, px, py, pw, ph, xr, yr, _CPU_C)
for temp, col, lbl in [
(min_t, (0.40, 0.90, 0.40), f" {int(min_t)}°"),
(hot_t, (1.00, 0.70, 0.20), f" {int(hot_t)}°"),
(max_t, (1.00, 0.40, 0.30), f" {int(max_t)}°"),
]:
xi, _ = s(temp, 0)
self._vmarker(cr, xi, py, ph, col, lbl)
for perf, col in [(max_p, _CPU_C), (min_p, (0.7, 0.7, 0.7))]:
_, yi = s(0, perf)
cr.set_source_rgba(*col, 0.5)
cr.set_line_width(0.8)
cr.set_dash([2, 4])
cr.move_to(px, yi); cr.line_to(px + pw, yi); cr.stroke()
cr.set_dash([])
class FanCurveGraph(BaseGraph):
"""FanControl Curve"""
def __init__(self, get_val):
super().__init__("FanControl Curve")
self.get_val = get_val
def _on_draw(self, widget, cr):
W, H = widget.get_allocated_width(), widget.get_allocated_height()
gv = self.get_val
fmin_t = gv("FAN_MIN_TEMP", 40)
fmax_t = gv("FAN_MAX_TEMP", 80)
min_fan = gv("MIN_FAN", 0)
max_fan = gv("MAX_FAN", 100)
xr = (30, 100); yr = (0, 100)
px, py, pw, ph = self._draw_frame(cr, W, H, xr, yr,
"Temperature (°C)", "Fan Speed (%)")
s = lambda vx, vy: self._to_screen(vx, vy, px, py, pw, ph, xr, yr)
points = [
(xr[0], min_fan),
(fmin_t, min_fan),
(fmax_t, max_fan),
(xr[1], max_fan),
]
self._filled_curve(cr, points, px, py, pw, ph, xr, yr, _FAN_C)
for temp, col, lbl in [
(fmin_t, (0.40, 0.90, 0.40), f"{int(fmin_t)}°"),
(fmax_t, (1.00, 0.40, 0.30), f"{int(fmax_t)}°"),
]:
xi, _ = s(temp, 0)
self._vmarker(cr, xi, py, ph, col, lbl)
for speed, col in [(min_fan, (0.6, 0.6, 0.6)), (max_fan, _FAN_C)]:
_, yi = s(0, speed)
cr.set_source_rgba(*col, 0.45)
cr.set_line_width(0.8)
cr.set_dash([2, 4])
cr.move_to(px, yi); cr.line_to(px + pw, yi); cr.stroke()
cr.set_dash([])
class SleepTimelineGraph(Gtk.DrawingArea):
"""SleepControl Bars"""
PAD = dict(left=90, right=18, top=36, bottom=12)
ROW_H = 32
ROW_GAP = 14
_SEG_COLORS = [
(0.25, 0.55, 0.85),
(0.12, 0.30, 0.65),
(0.06, 0.12, 0.35),
]
_SEG_LABELS = ["Dim ->", "Off ->", "Sleep ->"]
def __init__(self, get_val):
super().__init__()
self.get_val = get_val
self.set_size_request(360, 148)
self.connect("draw", self._on_draw)
def _draw_row(self, cr, W, label, dim, backlight, delay, y0):
p = self.PAD
pw = W - p['left'] - p['right']
px = p['left']
ph = self.ROW_H
total = max(delay, 1)
cr.set_source_rgb(*_TEXT)
cr.set_font_size(10)
ext = cr.text_extents(label)
cr.move_to(px - ext[2] - 10, y0 + ph / 2 + 4)
cr.show_text(label)
cr.set_source_rgb(*_PLOT_BG)
cr.rectangle(px, y0, pw, ph)
cr.fill()
cr.set_source_rgb(*_AXIS)
cr.set_line_width(0.8)
cr.rectangle(px, y0, pw, ph)
cr.stroke()
boundaries = [0, dim, backlight, delay]
for i, (col, seg_label) in enumerate(zip(self._SEG_COLORS, self._SEG_LABELS)):
t0, t1 = boundaries[i], boundaries[i + 1]
x0 = px + (t0 / total) * pw
x1 = px + (t1 / total) * pw
sw = x1 - x0
if sw < 1:
continue
cr.set_source_rgb(*col)
cr.rectangle(x0, y0, sw, ph)
cr.fill()
cr.set_source_rgba(1, 1, 1, 0.06)
cr.rectangle(x0, y0, sw, ph / 2)
cr.fill()
cr.set_source_rgba(0, 0, 0, 0.4)
cr.set_line_width(0.5)
cr.rectangle(x0, y0, sw, ph)
cr.stroke()
if sw > 36:
cr.set_source_rgb(0.85, 0.85, 0.85)
cr.set_font_size(9)
ext = cr.text_extents(seg_label)
if ext[2] < sw - 6:
cr.move_to(x0 + sw / 2 - ext[2] / 2, y0 + ph / 2 + 4)
cr.show_text(seg_label)
cr.set_source_rgb(*_DIM_TEXT)
cr.set_font_size(8)
for t in [dim, backlight, delay]:
xi = px + (t / total) * pw
mins = int(t)
if mins >= 60:
lbl = f"{mins // 60}h{mins % 60:02d}m" if mins % 60 else f"{mins // 60}h"
else:
lbl = f"{mins}m"
ext = cr.text_extents(lbl)
cr.move_to(xi - ext[2] / 2, y0 + ph + 12)
cr.show_text(lbl)
cr.set_source_rgba(*_AXIS, 0.6)
cr.set_line_width(0.8)
cr.move_to(xi, y0 + ph)
cr.line_to(xi, y0 + ph + 4)
cr.stroke()
cr.set_source_rgb(*_DIM_TEXT)
def _on_draw(self, widget, cr):
W, H = widget.get_allocated_width(), widget.get_allocated_height()
gv = self.get_val
cr.set_source_rgb(*_BG)
cr.paint()
cr.set_source_rgb(*_TEXT)
cr.set_font_size(12)
title = "SleepControl"
ext = cr.text_extents(title)
cr.move_to(W / 2 - ext[2] / 2, 20)
cr.show_text(title)
bat_dim = gv("BATTERY_DIM_DELAY", 5)
bat_bl = gv("BATTERY_BACKLIGHT", 10)
bat_delay = gv("BATTERY_DELAY", 15)
ac_dim = gv("POWER_DIM_DELAY", 10)
ac_bl = gv("POWER_BACKLIGHT", 20)
ac_delay = gv("POWER_DELAY", 30)
y0 = self.PAD['top']
self._draw_row(cr, W, " Battery",
bat_dim, bat_bl, bat_delay, y0)
self._draw_row(cr, W, " AC Power",
ac_dim, ac_bl, ac_delay, y0 + self.ROW_H + self.ROW_GAP)
lx = W - self.PAD['right'] - 180
ly = H - 14
for i, (col, lbl) in enumerate(zip(self._SEG_COLORS, self._SEG_LABELS)):
x = lx + i * 62
cr.set_source_rgb(*col)
cr.rectangle(x, ly - 8, 10, 8)
cr.fill()
cr.set_source_rgb(*_DIM_TEXT)
cr.set_font_size(8)
cr.move_to(x + 13, ly)
cr.show_text(lbl)
def refresh(self):
self.queue_draw()
class GaugeGraph(Gtk.DrawingArea):
PAD = dict(left=18, right=18, top=30, bottom=10)
BAR_H = 34
def __init__(self, title, get_val, key, color, fmt_fn=None, w=370, h=90):
super().__init__()
self.title = title
self.get_val = get_val
self.key = key
self.color = color
self.fmt_fn = fmt_fn or (lambda v, mx: f"{int(v)}")
self.set_size_request(w, h)
self.connect("draw", self._on_draw)
def _fraction(self):
return 0.5, 1.0
def _on_draw(self, widget, cr):
W, H = widget.get_allocated_width(), widget.get_allocated_height()
p = self.PAD
px = p['left']; py = p['top']
pw = W - p['left'] - p['right']
ph = self.BAR_H
cr.set_source_rgb(*_BG)
cr.paint()
cr.set_source_rgb(*_TEXT)
cr.set_font_size(12)
ext = cr.text_extents(self.title)
cr.move_to(W / 2 - ext[2] / 2, py - 8)
cr.show_text(self.title)
cur, mx = self._fraction()
frac = max(0.0, min(1.0, cur / mx if mx else 0))
cr.set_source_rgb(*_PLOT_BG)
cr.rectangle(px, py, pw, ph)
cr.fill()
cr.set_source_rgb(*_AXIS)
cr.set_line_width(1.0)
cr.rectangle(px, py, pw, ph)
cr.stroke()
fill_w = pw * frac
if fill_w > 1 and CAIRO_AVAILABLE:
pat = cairo.LinearGradient(px, 0, px + fill_w, 0)
if self.key == "CHARGE_MAX":
pat.add_color_stop_rgb(0.0, 0.00, 0.22, 0.00)
pat.add_color_stop_rgb(0.5, 0.08, 0.50, 0.08)
pat.add_color_stop_rgb(1.0, 0.15, 0.75, 0.15)
else:
r, g, b = self.color
pat.add_color_stop_rgb(0.0, r * 0.15, g * 0.45, b * 0.45)
pat.add_color_stop_rgb(0.8, r, g, b)
pat.add_color_stop_rgb(1.0, min(r + 0.1, 1), min(g + 0.1, 1), min(b + 0.1, 1))
cr.set_source(pat)
else:
cr.set_source_rgb(*self.color)
cr.rectangle(px, py, fill_w, ph)
cr.fill()
cr.set_source_rgba(1, 1, 1, 0.07)
cr.rectangle(px, py, fill_w, ph / 2)
cr.fill()
label = self.fmt_fn(cur, mx)
cr.set_source_rgb(1, 1, 1)
cr.set_font_size(13)
ext = cr.text_extents(label)
cr.move_to(px + pw / 2 - ext[2] / 2, py + ph / 2 + 5)
cr.show_text(label)
cr.set_source_rgba(*_AXIS, 0.4)
cr.set_line_width(0.7)
for frac_tick in [0.25, 0.50, 0.75]:
xt = px + pw * frac_tick
cr.move_to(xt, py + ph - 6)
cr.line_to(xt, py + ph)
cr.stroke()
def refresh(self):
self.queue_draw()
class BatteryGauge(GaugeGraph):
def __init__(self, get_val):
super().__init__("BatteryControl", get_val, "CHARGE_MAX", _BAT_C,
fmt_fn=lambda v, mx: f"Limited to: {int(v)}%")
def _fraction(self):
v = self.get_val("CHARGE_MAX", 80)
return v, 100
class GPUGauge(GaugeGraph):
def __init__(self, get_val, get_gpu_max_fn):
super().__init__("GPUControl", get_val, "GPU_MAX_FREQ", _GPU_C,
fmt_fn=lambda v, mx: f"{int(v)} MHz / {int(mx)} MHz max")
self.get_gpu_max = get_gpu_max_fn
def _fraction(self):
cur = self.get_val("GPU_MAX_FREQ", 500)
mx = self.get_gpu_max()
return cur, max(mx, 1)
class GraphPanel:
"""Not a widget - just holds graph widget references so refresh_all() works."""
def __init__(self):
self._graphs = []
def register(self, graph):
self._graphs.append(graph)
def refresh_all(self):
for g in self._graphs:
g.refresh()
_TOOLTIPS = {
"MAX_TEMP": "Maximum temperature ceiling. CPU performance is throttled to its minimum above this point.",
"HOTZONE": "Temperature at which throttling begins. Acts as the curve's inflection point.",
"MIN_TEMP": "Below this temperature, CPU runs at maximum performance.",
"MAX_PERF_PCT": "Highest CPU performance - applied when CPU is below minimum temp.",
"MIN_PERF_PCT": "Lowest CPU performance - applied when temperature exceeds maximum temp.",
"RAMP_UP": "How quickly performance increases when the CPU cools down (% per poll).",
"RAMP_DOWN": "How quickly performance decreases when the CPU heats up (% per poll).",
"CPU_POLL": "How often PowerControl polls CPU temperature and adjusts performance (seconds).",
"GPU_MAX_FREQ": "Maximum GPU clock frequency allowed. Lowering this reduces GPU heat and power draw.",
"MIN_FAN": "Minimum fan speed when temperature is below the fan threshold. 0 = Zero RPM.",
"MAX_FAN": "Maximum fan speed the controller will target at peak temperatures.",
"FAN_MIN_TEMP": "Temperature below which the fan stays at its minimum speed.",
"FAN_MAX_TEMP": "Temperature at which the fan reaches its maximum speed.",
"STEP_UP": "How many % points the fan speed increases each poll when heating up.",
"STEP_DOWN": "How many % points the fan speed decreases each poll when cooling down.",
"FAN_POLL": "How often FanControl polls temperature and adjusts fan speed (seconds).",
"CHARGE_MAX": "Maximum battery charge level. Keeping this below 100% reduces long-term battery wear.",
"BATTERY_DIM_DELAY": "Minutes of inactivity on battery before the display dims.",
"BATTERY_BACKLIGHT": "Minutes of inactivity on battery before the display turns off entirely.",
"BATTERY_DELAY": "Minutes of inactivity on battery before the system suspends.",
"AUDIO_DETECTION_BATTERY": "When enabled, detected active audio playback prevents sleep on battery.",
"LIDSLEEP_BATTERY": "When enabled, closing the lid immediately suspends the system on battery.",
"POWER_DIM_DELAY": "Minutes of inactivity on AC power before the display dims.",
"POWER_BACKLIGHT": "Minutes of inactivity on AC power before the display turns off entirely.",
"POWER_DELAY": "Minutes of inactivity on AC power before the system suspends.",
"AUDIO_DETECTION_POWER": "When enabled, detected active audio playback prevents sleep on AC power.",
"LIDSLEEP_POWER": "When enabled, closing the lid immediately suspends the system on AC power.",
"STARTUP_BATTERYCONTROL": "Start BatteryControl automatically on boot.",
"STARTUP_POWERCONTROL": "Start PowerControl automatically on boot.",
"STARTUP_FANCONTROL": "Start FanControl automatically on boot.",
"STARTUP_GPUCONTROL": "Start GPUControl automatically on boot.",
"STARTUP_SLEEPCONTROL": "Start SleepControl automatically on boot.",
}
class ConfigEditor(Gtk.Window):
def __init__(self):
settings = Gtk.Settings.get_default()
settings.set_property("gtk-application-prefer-dark-theme", True)
settings.set_property("gtk-tooltip-timeout", 667)
settings.set_property("gtk-tooltip-browse-timeout", 300)
super().__init__(title="ChromeOS_PowerControl GUI")
self.set_default_size(1000, 600)
headerbar = Gtk.HeaderBar()
headerbar.set_show_close_button(True)
headerbar.props.title = "ChromeOS_PowerControl GUI"
headerbar.set_decoration_layout("menu:minimize,maximize,close")
self.set_titlebar(headerbar)
self.reload_btn = Gtk.Button()
reload_icon = Gtk.Image.new_from_icon_name("view-refresh-symbolic",
Gtk.IconSize.BUTTON)
self.reload_btn.set_image(reload_icon)
self.reload_btn.set_tooltip_text("Reload config from disk")
self.reload_btn.connect("clicked", self.on_reload_clicked)
headerbar.pack_end(self.reload_btn)
self.config_path = self.find_config_file()
self.spinbuttons = {}
self.config_data = {}
self.widgets = {}
self.original_gpu_max = None
self.gpu_type = None
self.updating_constraints = False
self.initial_load = True
self.focusable_widgets = []
if not self.config_path:
self.show_error_dialog(
"Config File Not Found",
"Could not find config file at:\n"
"/mnt/chromeos/MyFiles/Downloads/ChromeOS_PowerControl_Config/config\n"
"/mnt/shared/MyFiles/Downloads/ChromeOS_PowerControl_Config/config\n"
"/usr/local/bin/ChromeOS_PowerControl_Config/config\n"
"/home/chronos/user/MyFiles/Downloads/ChromeOS_PowerControl_Config/config\n\n"
"Please ensure the folder is shared to Crostini/Chard."
)
self.destroy()
return
self.preload_gpu_range()
self.create_ui()
self.load_config()
self.setup_constraints()
self.connect_graph_signals()
self.setup_keyboard_navigation()
self.initial_load = False
def find_config_file(self):
possible_paths = [
"/mnt/chromeos/MyFiles/Downloads/ChromeOS_PowerControl_Config/config",
"/usr/local/bin/ChromeOS_PowerControl_Config/config",
os.path.expanduser(
"/home/chronos/user/MyFiles/Downloads/ChromeOS_PowerControl_Config/config"),
"/mnt/shared/MyFiles/Downloads/ChromeOS_PowerControl_Config/config",
]
for path in possible_paths:
if os.path.exists(path):
return path
return None
def preload_gpu_range(self):
"""Read ORIGINAL_GPU_MAX_FREQ/GPU_TYPE before building the UI so the
GPU slider is created with the correct range immediately."""
if not self.config_path or not os.path.exists(self.config_path):
return
try:
data = {}
with open(self.config_path, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
k, v = line.split('=', 1)
data[k.strip()] = v.strip()
raw = data.get("ORIGINAL_GPU_MAX_FREQ")
if raw:
self.original_gpu_max = int(raw)
self.gpu_type = data.get("GPU_TYPE", "intel").lower()
except Exception:
pass
def get_widget_value(self, key, default=0.0):
if key in self.widgets:
w = self.widgets[key]
if isinstance(w, Gtk.Scale):
return w.get_value()
if isinstance(w, Gtk.Switch):
return 1.0 if w.get_active() else 0.0
return float(default)
def get_gpu_max(self):
if self.original_gpu_max and self.gpu_type:
return float(gpu_config_to_mhz(self.gpu_type, self.original_gpu_max))
if "GPU_MAX_FREQ" in self.widgets:
adj = self.widgets["GPU_MAX_FREQ"].get_adjustment()
return adj.get_upper()
return 2000.0
def connect_graph_signals(self):
graph_keys = [
"MIN_TEMP", "HOTZONE", "MAX_TEMP", "MIN_PERF_PCT", "MAX_PERF_PCT",
"MIN_FAN", "MAX_FAN", "FAN_MIN_TEMP", "FAN_MAX_TEMP",
"CHARGE_MAX", "GPU_MAX_FREQ",
"BATTERY_DIM_DELAY", "BATTERY_BACKLIGHT", "BATTERY_DELAY",
"POWER_DIM_DELAY", "POWER_BACKLIGHT", "POWER_DELAY",
]
for key in graph_keys:
if key in self.widgets:
w = self.widgets[key]
if isinstance(w, Gtk.Scale):
w.connect("value-changed", lambda *_: self.graph_panel.refresh_all())
elif isinstance(w, Gtk.Switch):
w.connect("notify::active", lambda *_: self.graph_panel.refresh_all())
def setup_keyboard_navigation(self):
self.connect("key-press-event", self.on_key_press)
def on_key_press(self, widget, event):
keyval = event.keyval
if keyval in (Gdk.KEY_Up, Gdk.KEY_Down):
focus = self.get_focus()
if focus is None:
if self.focusable_widgets:
self.focusable_widgets[0].grab_focus()
return True
try:
idx = self.focusable_widgets.index(focus)
except ValueError:
return False
if keyval == Gdk.KEY_Up:
idx = (idx - 1) % len(self.focusable_widgets)
else:
idx = (idx + 1) % len(self.focusable_widgets)
self.focusable_widgets[idx].grab_focus()
return True
return False
def create_ui(self):
outer_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
self.add(outer_vbox)
main_scroll = Gtk.ScrolledWindow()
main_scroll.set_vexpand(True)
main_scroll.set_hexpand(True)
main_scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
outer_vbox.pack_start(main_scroll, True, True, 0)
self.graph_panel = GraphPanel()
self.grid = Gtk.Grid()
self.grid.set_column_spacing(12)
self.grid.set_row_spacing(5)
self.grid.set_margin_start(10)
self.grid.set_margin_end(10)
self.grid.set_margin_top(10)
self.grid.set_margin_bottom(10)
main_scroll.add(self.grid)
self.create_config_sections()
button_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
button_box.set_halign(Gtk.Align.CENTER)
button_box.set_border_width(8)
outer_vbox.pack_start(button_box, False, False, 0)
self.save_btn = Gtk.Button(label="Apply")
self.save_btn.connect("clicked", self.on_save_clicked)
button_box.pack_start(self.save_btn, False, False, 0)
self.focusable_widgets.append(self.save_btn)
exit_btn = Gtk.Button(label="Exit")
exit_btn.connect("clicked", lambda x: self.destroy())
button_box.pack_start(exit_btn, False, False, 0)
self.focusable_widgets.append(exit_btn)
def create_slider(self, min_val, max_val, step=1):
scale = Gtk.Scale.new_with_range(
Gtk.Orientation.HORIZONTAL, min_val, max_val, step)
scale.set_digits(0 if step >= 1 else 1)
scale.set_value_pos(Gtk.PositionType.RIGHT)
scale.set_hexpand(True)
scale.set_size_request(300, -1)
return scale
def create_slider_with_spinbutton(self, min_val, max_val, step=1):
box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
scale = Gtk.Scale.new_with_range(
Gtk.Orientation.HORIZONTAL, min_val, max_val, step)
scale.set_digits(0 if step >= 1 else 1)
scale.set_value_pos(Gtk.PositionType.RIGHT)
scale.set_hexpand(True)
scale.set_size_request(100, -1)
scale.set_draw_value(False)
adjustment = Gtk.Adjustment(
value=min_val, lower=min_val, upper=max_val,
step_increment=step, page_increment=step * 10)
spinbutton = Gtk.SpinButton(
adjustment=adjustment, climb_rate=step, digits=0)
spinbutton.set_width_chars(6)
def on_scale_changed(s):
if spinbutton.get_value() != s.get_value():
spinbutton.set_value(s.get_value())
def on_spin_changed(s):
if scale.get_value() != s.get_value():
scale.set_value(s.get_value())
scale.connect("value-changed", on_scale_changed)
spinbutton.connect("value-changed", on_spin_changed)
box.pack_start(scale, True, True, 0)
box.pack_start(spinbutton, False, False, 0)
return box, scale, spinbutton
def create_switch(self):
switch = Gtk.Switch()
switch.set_halign(Gtk.Align.START)
return switch
def create_combo(self, options):
combo = Gtk.ComboBoxText()
for option in options:
combo.append_text(option)
return combo
def _apply_tooltip(self, widget, key, container=None):
"""Apply tooltip text from _TOOLTIPS to a widget (and optionally its container)."""
tip = _TOOLTIPS.get(key)
if not tip:
return
widget.set_tooltip_text(tip)
if container is not None:
container.set_tooltip_text(tip)
def create_config_sections(self):
sections = [
("PowerControl", [
("MAX_TEMP", "Maximum Temperature (°C)", "slider", 30, 95, 1, True),
("HOTZONE", "Hotzone Temperature (°C)", "slider", 30, 90, 1, True),
("MIN_TEMP", "Minimum Temperature (°C)", "slider", 30, 90, 1, True),
("MAX_PERF_PCT", "Maximum Performance (%)", "slider", 10, 100, 1, True),
("MIN_PERF_PCT", "Minimum Performance (%)", "slider", 10, 100, 1, True),
("RAMP_UP", "Ramp Up Speed (%)", "slider", 1, 50, 1, True),
("RAMP_DOWN", "Ramp Down Speed (%)", "slider", 1, 50, 1, True),
("CPU_POLL", "CPU Poll Interval (s)", "slider", 0.1, 5.0, 0.1, True),
], "cpu"),
("GPUControl", [
("GPU_MAX_FREQ", "GPU Max Frequency (MHz)", "slider", 100, 2000, 10, True),
], "gpu"),
("FanControl", [
("MIN_FAN", "Minimum Fan Speed (%)", "slider", 0, 100, 1, True),
("MAX_FAN", "Maximum Fan Speed (%)", "slider", 0, 100, 1, True),
("FAN_MIN_TEMP", "Fan Minimum Temp (°C)", "slider", 30, 70, 1, True),
("FAN_MAX_TEMP", "Fan Maximum Temp (°C)", "slider", 30, 94, 1, True),
("STEP_UP", "Fan Step Up (%)", "slider", 1, 20, 1, True),
("STEP_DOWN", "Fan Step Down (%)", "slider", 1, 20, 1, True),
("FAN_POLL", "Fan Poll Interval (s)", "slider", 1, 10, 1, True),
], "fan"),
("BatteryControl", [
("CHARGE_MAX", "Maximum Charge (%)", "slider", 20, 100, 1, True),
], "bat"),
("SleepControl - Battery", [
("BATTERY_DIM_DELAY", "Dim Delay (minutes)", "slider", 1, 1440, 1, True),
("BATTERY_BACKLIGHT", "Display Off (minutes)", "slider", 1, 1440, 1, True),
("BATTERY_DELAY", "Sleep Delay (minutes)", "slider", 1, 1440, 1, True),
("AUDIO_DETECTION_BATTERY", "Audio Detection", "switch", None, None, None, True),
("LIDSLEEP_BATTERY", "Lid Sleep", "switch", None, None, None, True),
], "sleep"),
("SleepControl - AC Power", [
("POWER_DIM_DELAY", "Dim Delay (minutes)", "slider", 1, 4320, 1, True),
("POWER_BACKLIGHT", "Display Off (minutes)", "slider", 1, 4320, 1, True),
("POWER_DELAY", "Sleep Delay (minutes)", "slider", 1, 4320, 1, True),
("AUDIO_DETECTION_POWER", "Audio Detection", "switch", None, None, None, True),
("LIDSLEEP_POWER", "Lid Sleep", "switch", None, None, None, True),
], "sleep"),
("Start on Boot", [
("STARTUP_BATTERYCONTROL", "BatteryControl", "switch", None, None, None, False),
("STARTUP_POWERCONTROL", "PowerControl", "switch", None, None, None, False),
("STARTUP_FANCONTROL", "FanControl", "switch", None, None, None, False),
("STARTUP_GPUCONTROL", "GPUControl", "switch", None, None, None, False),
("STARTUP_SLEEPCONTROL", "SleepControl", "switch", None, None, None, False),
], None),
]
def _make_graph(graph_id):
if graph_id == "cpu":
g = CPUCurveGraph(self.get_widget_value)
g.set_vexpand(False)
g.set_valign(Gtk.Align.CENTER)
return g
if graph_id == "gpu":
g = GPUGauge(self.get_widget_value, self.get_gpu_max)
g.set_vexpand(False)
g.set_valign(Gtk.Align.CENTER)
return g
if graph_id == "fan":
g = FanCurveGraph(self.get_widget_value)
g.set_vexpand(False)
g.set_valign(Gtk.Align.CENTER)
return g
if graph_id == "bat":
g = BatteryGauge(self.get_widget_value)
g.set_vexpand(False)
g.set_valign(Gtk.Align.CENTER)
return g
if graph_id == "sleep":
g = SleepTimelineGraph(self.get_widget_value)
g.set_vexpand(False)
g.set_valign(Gtk.Align.CENTER)
return g
return None
graph_cache = {}
row = 0
for section_name, fields, graph_id in sections:
section_start = row
header = Gtk.Label()
header.set_markup(f"<b><big>{section_name}</big></b>")
header.set_halign(Gtk.Align.START)
header.set_margin_start(20)
header.set_margin_top(15)
header.set_margin_bottom(5)
self.grid.attach(header, 0, row, 2, 1)
row += 1
separator = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
separator.set_margin_bottom(5)
separator.set_margin_start(10)
self.grid.attach(separator, 0, row, 2, 1)
row += 1
for field in fields:
key = field[0]
label = field[1]
widget_type = field[2]
if key == "MAX_PERF_PCT":
lbl = Gtk.Label()
lbl.set_markup(f"<b>{label}</b>")
else:
lbl = Gtk.Label(label=label)
lbl.set_halign(Gtk.Align.END)
lbl.set_margin_start(10)
lbl.set_size_request(100, -1)
if key in _TOOLTIPS:
lbl.set_tooltip_text(_TOOLTIPS[key])
self.grid.attach(lbl, 0, row, 1, 1)
if widget_type == "slider":
min_val, max_val, step, with_spinbutton = (
field[3], field[4], field[5], field[6])
if key == "GPU_MAX_FREQ" and self.original_gpu_max:
display_max = gpu_config_to_mhz(self.gpu_type, self.original_gpu_max)
display_min = max(100, int(display_max * 0.1))
max_val = display_max
min_val = display_min
if with_spinbutton:
box, scale, spinbutton = self.create_slider_with_spinbutton(
min_val, max_val, step)
self._apply_tooltip(scale, key, container=box)
spinbutton.set_tooltip_text(_TOOLTIPS.get(key, ""))
self.grid.attach(box, 1, row, 1, 1)
self.widgets[key] = scale
self.spinbuttons[key] = spinbutton
self.focusable_widgets.append(scale)
else:
widget = self.create_slider(min_val, max_val, step)
self._apply_tooltip(widget, key)
self.grid.attach(widget, 1, row, 1, 1)
self.widgets[key] = widget
self.focusable_widgets.append(widget)
elif widget_type == "switch":
widget = self.create_switch()
self._apply_tooltip(widget, key)
self.grid.attach(widget, 1, row, 1, 1)
self.widgets[key] = widget
self.focusable_widgets.append(widget)
elif widget_type == "combo":
options = field[3]
widget = self.create_combo(options)
self._apply_tooltip(widget, key)
self.grid.attach(widget, 1, row, 1, 1)
self.widgets[key] = widget
self.focusable_widgets.append(widget)
row += 1
section_end = row
if graph_id and CAIRO_AVAILABLE:
if graph_id not in graph_cache:
g = _make_graph(graph_id)
if g is not None:
span = section_end - section_start
self.grid.attach(g, 2, section_start, 1, span)
self.graph_panel.register(g)
graph_cache[graph_id] = (g, section_start, section_end)
else:
g, orig_start, _ = graph_cache[graph_id]
self.grid.remove(g)
combined_span = section_end - orig_start
self.grid.attach(g, 2, orig_start, 1, combined_span)
graph_cache[graph_id] = (g, orig_start, section_end)
def setup_constraints(self):
pairs = [
(["MIN_TEMP", "HOTZONE", "MAX_TEMP"],
self.on_temp_constraint),
(["MIN_PERF_PCT", "MAX_PERF_PCT"],
self.on_perf_constraint),
(["MIN_FAN", "MAX_FAN"],
self.on_fan_speed_constraint),
(["FAN_MIN_TEMP", "FAN_MAX_TEMP"],
self.on_fan_temp_constraint),
(["BATTERY_DIM_DELAY", "BATTERY_BACKLIGHT", "BATTERY_DELAY"],
self.on_battery_sleep_constraint),
(["POWER_DIM_DELAY", "POWER_BACKLIGHT", "POWER_DELAY"],
self.on_power_sleep_constraint),
]
for keys, handler in pairs:
if all(k in self.widgets for k in keys):
for k in keys:
self.widgets[k].connect("value-changed", handler)
def on_temp_constraint(self, scale):
if self.updating_constraints:
return
self.updating_constraints = True
min_t = self.widgets["MIN_TEMP"].get_value()
hot = self.widgets["HOTZONE"].get_value()
max_t = self.widgets["MAX_TEMP"].get_value()