Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGPUMode.py
More file actions
Latest commit
553 lines (462 loc) · 20.7 KB
/
Copy pathGPUMode.py
File metadata and controls
553 lines (462 loc) · 20.7 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
#!/usr/bin/env python3
importgi
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
gi.require_version('Notify', '0.7')
gi.require_version('UPowerGlib', '1.0')
fromgi.repositoryimportGtk, AppIndicator3, Notify, GLib, UPowerGlib
importsubprocess
importthreading
importos
importsys
importfcntl
importlogging
frompathlibimportPath
VERSION="1.01"
LOCK_FILE="/tmp/gpumode.lock"
LOG_DIR=Path.home() /".local/share/gpumode"
LOG_FILE=LOG_DIR/"gpumode.log"
SETTINGS_FILE=LOG_DIR/"settings.conf"
classGPUIndicator:
def__init__(self):
LOG_DIR.mkdir(parents=True, exist_ok=True)
logging.basicConfig(
filename=LOG_FILE,
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.info("GPUMode started")
ifnotself.check_envycontrol():
self.show_error_and_exit("envycontrol not found",
"Please install envycontrol:\ninstall envycontrol\nfrom https://github.com/bayasdev/envycontrol, releases/assets")
return
Notify.init("GPUMode")
self.indicator=AppIndicator3.Indicator.new(
"gpumode",
"video-display",
AppIndicator3.IndicatorCategory.HARDWARE
)
self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
self.switching=False
self.current_mode=self.get_current_mode()
self.update_icon()
self.power_prompts_enabled=self.load_power_prompts_setting()
self.indicator.set_menu(self.build_menu())
self.upower_client=UPowerGlib.Client.new()
self.upower_client.connect('notify::on-battery', self.on_power_changed)
self.last_power_state=self.upower_client.get_on_battery()
logging.info(f"Initial GPU mode: {self.current_mode}")
logging.info(f"Initial power state: {'battery'ifself.last_power_stateelse'AC'}")
logging.info(f"Power prompts enabled: {self.power_prompts_enabled}")
GLib.timeout_add(2000, self.check_startup_mismatch)
defcheck_startup_mismatch(self):
"""Check if GPU mode mismatches power state at startup"""
ifnotself.power_prompts_enabled:
logging.info("Power prompts disabled, skipping startup check")
returnFalse
on_battery=self.upower_client.get_on_battery()
ifon_batteryandself.current_modein ['nvidia', 'hybrid']:
logging.info("Startup mismatch: On battery but using NVIDIA/Hybrid")
self.prompt_switch_on_battery()
elifnoton_batteryandself.current_mode=='integrated':
logging.info("Startup mismatch: On AC but using Integrated")
self.prompt_switch_on_ac()
else:
logging.info("No startup mismatch detected")
returnFalse
defload_power_prompts_setting(self):
"""Load power prompts enabled setting from file"""
ifnotSETTINGS_FILE.exists():
returnTrue
try:
content=SETTINGS_FILE.read_text().strip()
returncontent=="enabled"
except:
returnTrue
defsave_power_prompts_setting(self, enabled):
"""Save power prompts enabled setting to file"""
try:
SETTINGS_FILE.write_text("enabled"ifenabledelse"disabled")
logging.info(f"Power prompts {'enabled'ifenabledelse'disabled'}")
exceptExceptionase:
logging.error(f"Failed to save power prompts setting: {e}")
deftoggle_power_prompts(self, widget):
"""Toggle power change prompts on/off"""
self.power_prompts_enabled=widget.get_active()
self.save_power_prompts_setting(self.power_prompts_enabled)
notification=Notify.Notification.new(
"Power Prompts "+ ("Enabled"ifself.power_prompts_enabledelse"Disabled"),
"You will "+ ("now"ifself.power_prompts_enabledelse"no longer") +" be prompted to switch GPU when AC power changes.",
"dialog-information"
)
notification.show()
defon_power_changed(self, client, pspec):
"""Handle AC/battery power changes"""
on_battery=client.get_on_battery()
ifon_battery==self.last_power_state:
return
logging.info(f"Power state changed: {'AC->Battery'ifon_batteryelse'Battery->AC'}")
self.last_power_state=on_battery
ifnotself.power_prompts_enabled:
logging.info("Power prompts disabled, skipping")
return
ifon_battery:
self.prompt_switch_on_battery()
else:
self.prompt_switch_on_ac()
defprompt_switch_on_battery(self):
"""Prompt to switch to integrated when on battery"""
ifself.current_mode=="integrated":
logging.info("Already on integrated, skipping battery prompt")
return
logging.info("Prompting switch to integrated on battery")
dialog=Gtk.MessageDialog(
message_type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.YES_NO,
text="Switch to Integrated GPU?"
)
dialog.format_secondary_text(
"You're now on battery power.\n\n"
"Would you like to switch to Integrated GPU mode for better battery life?\n\n"
"This will require a reboot."
)
response=dialog.run()
dialog.destroy()
ifresponse==Gtk.ResponseType.YES:
logging.info("User accepted battery switch prompt")
self.switch_and_reboot('integrated')
else:
logging.info("User declined battery switch prompt")
defprompt_switch_on_ac(self):
"""Prompt to switch to Hybrid when on AC"""
ifself.current_mode=="hybrid":
logging.info("Already on Hybrid, skipping AC prompt")
return
logging.info("Prompting switch to Hybrid on AC")
dialog=Gtk.MessageDialog(
message_type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.YES_NO,
text="Switch to Hybrid Mode?"
)
dialog.format_secondary_text(
"You're now on AC power.\n\n"
"Would you like to switch to Hybrid mode for balanced performance?\n\n"
"This will require a reboot."
)
response=dialog.run()
dialog.destroy()
ifresponse==Gtk.ResponseType.YES:
logging.info("User accepted AC switch prompt")
self.switch_and_reboot('hybrid')
else:
logging.info("User declined AC switch prompt")
defswitch_and_reboot(self, mode):
"""Switch GPU mode and reboot"""
self.switching=True
self.update_icon()
self.indicator.set_menu(self.build_menu())
notification=Notify.Notification.new(
"GPUMode",
f"Switching to {mode} mode and rebooting...",
"emblem-synchronizing"
)
notification.show()
defswitch_reboot_thread():
try:
cmd= ['pkexec', 'envycontrol', '-s', mode]
ifmode=='hybrid':
cmd.extend(['--rtd3', '2'])
result=subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=60
)
ifresult.returncode==0:
logging.info(f"Switched to {mode}, initiating reboot")
subprocess.run(['systemctl', 'reboot'], timeout=5)
else:
logging.error(f"Failed to switch: {result.stderr}")
GLib.idle_add(self.switch_complete, mode, False, result.stderr)
exceptExceptionase:
logging.error(f"Switch and reboot error: {e}")
GLib.idle_add(self.switch_complete, mode, False, str(e))
thread=threading.Thread(target=switch_reboot_thread)
thread.daemon=True
thread.start()
defcheck_envycontrol(self):
"""Check if envycontrol is installed"""
try:
result=subprocess.run(['which', 'envycontrol'],
capture_output=True, timeout=2)
returnresult.returncode==0
except:
returnFalse
defshow_error_and_exit(self, title, message):
"""Show error dialog and exit"""
logging.error(f"{title}: {message}")
dialog=Gtk.MessageDialog(
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.OK,
text=title
)
dialog.format_secondary_text(message)
dialog.run()
dialog.destroy()
sys.exit(1)
defget_current_mode(self):
"""Query current GPU mode - checks glxinfo first to detect BIOS-set NVIDIA mode"""
try:
# Check glxinfo OpenGL renderer line specifically
glx_result=subprocess.run(['sh', '-c', 'glxinfo | grep "OpenGL renderer"'],
capture_output=True, text=True, timeout=2)
ifglx_result.returncode==0:
renderer=glx_result.stdout.strip()
logging.info(f"glxinfo renderer string: {renderer}")
# Check the actual OpenGL renderer string
if'NVIDIA'inrendererand'AMD'notinrenderer:
logging.info("Detected NVIDIA-only mode via glxinfo (BIOS-set)")
return"nvidia"
elif'AMD'inrendererand'NVIDIA'notinrenderer:
# AMD only - check envycontrol to confirm integrated mode
try:
result=subprocess.run(['envycontrol', '--query'],
capture_output=True, text=True, timeout=2)
ifresult.returncode==0:
mode=result.stdout.strip().lower()
logging.info(f"Queried GPU mode from envycontrol: {mode}")
returnmode
except:
pass
logging.info("Detected integrated mode via glxinfo")
return"integrated"
elif'AMD'inrendererand'NVIDIA'inrenderer:
# Both GPUs in renderer string - likely hybrid
logging.info("Detected hybrid mode via glxinfo")
return"hybrid"
exceptExceptionase:
logging.error(f"Failed to query GPU mode with glxinfo: {e}")
# Final fallback to envycontrol only
try:
result=subprocess.run(['envycontrol', '--query'],
capture_output=True, text=True, timeout=2)
ifresult.returncode==0:
mode=result.stdout.strip().lower()
logging.info(f"Queried GPU mode from envycontrol (fallback): {mode}")
returnmode
except:
pass
return"unknown"
defupdate_icon(self):
"""Update tray icon based on current state"""
ifself.switching:
self.indicator.set_icon("emblem-synchronizing-symbolic")
elifself.current_mode=="integrated":
self.indicator.set_icon("drive-harddisk-solidstate-symbolic")
elifself.current_mode=="nvidia":
self.indicator.set_icon("video-display-symbolic")
elifself.current_mode=="hybrid":
self.indicator.set_icon("video-single-display-symbolic")
else:
self.indicator.set_icon("dialog-question-symbolic")
defrefresh_mode(self):
"""Refresh current GPU mode"""
ifnotself.switching:
old_mode=self.current_mode
self.current_mode=self.get_current_mode()
ifold_mode!=self.current_mode:
logging.info(f"GPU mode changed: {old_mode} -> {self.current_mode}")
self.update_icon()
self.indicator.set_menu(self.build_menu())
defbuild_menu(self):
"""Build the indicator menu"""
menu=Gtk.Menu()
menu.connect('show', lambda_: self.refresh_mode())
ifself.switching:
status=Gtk.MenuItem(label='━━━ SWITCHING... ━━━')
else:
status=Gtk.MenuItem(label=f'━━━ Current: {self.current_mode.upper()} ━━━')
status.set_sensitive(False)
menu.append(status)
menu.append(Gtk.SeparatorMenuItem())
# If in NVIDIA mode, show blocking message
ifself.current_mode=='nvidia':
blocked_warning=Gtk.MenuItem(label='⚠ NVIDIA Mode Active')
blocked_warning.set_sensitive(False)
menu.append(blocked_warning)
blocked_msg=Gtk.MenuItem(label='Set BIOS to Hybrid (F2) to enable switching')
blocked_msg.set_sensitive(False)
menu.append(blocked_msg)
menu.append(Gtk.SeparatorMenuItem())
# Show all modes as disabled
integrated=Gtk.MenuItem(label='⚪ Integrated GPU')
integrated.set_sensitive(False)
menu.append(integrated)
hybrid=Gtk.MenuItem(label='⚪ Hybrid Mode')
hybrid.set_sensitive(False)
menu.append(hybrid)
nvidia=Gtk.MenuItem(label='● NVIDIA GPU (ACTIVE)')
nvidia.set_sensitive(False)
menu.append(nvidia)
else:
# Normal mode - Warning about NVIDIA mode
warning=Gtk.MenuItem(label='⚠ NVIDIA mode: Use BIOS (F2)')
warning.set_sensitive(False)
menu.append(warning)
menu.append(Gtk.SeparatorMenuItem())
# Integrated - switchable
integrated=Gtk.MenuItem(
label='⚪ Integrated GPU'ifself.current_mode!='integrated'
else'● Integrated GPU (ACTIVE)'
)
integrated.connect('activate', self.switch_integrated)
ifself.current_mode=='integrated'orself.switching:
integrated.set_sensitive(False)
menu.append(integrated)
# Hybrid - switchable
hybrid=Gtk.MenuItem(
label='⚪ Hybrid Mode'ifself.current_mode!='hybrid'
else'● Hybrid Mode (ACTIVE)'
)
hybrid.connect('activate', self.switch_hybrid)
ifself.current_mode=='hybrid'orself.switching:
hybrid.set_sensitive(False)
menu.append(hybrid)
# NVIDIA - show status only, not switchable
nvidia=Gtk.MenuItem(label='⚪ NVIDIA GPU')
nvidia.set_sensitive(False)
menu.append(nvidia)
menu.append(Gtk.SeparatorMenuItem())
power_prompts_item=Gtk.CheckMenuItem(label='Prompt on Power Change')
power_prompts_item.set_active(self.power_prompts_enabled)
power_prompts_item.connect('activate', self.toggle_power_prompts)
ifself.switchingorself.current_mode=='nvidia':
power_prompts_item.set_sensitive(False)
menu.append(power_prompts_item)
about_item=Gtk.MenuItem(label='About')
about_item.connect('activate', self.show_about)
menu.append(about_item)
menu.append(Gtk.SeparatorMenuItem())
quit_item=Gtk.MenuItem(label='Quit')
quit_item.connect('activate', Gtk.main_quit)
ifself.switching:
quit_item.set_sensitive(False)
menu.append(quit_item)
menu.show_all()
returnmenu
defswitch_integrated(self, _):
self.switch_gpu('integrated')
defswitch_hybrid(self, _):
self.switch_gpu('hybrid')
defswitch_gpu(self, mode):
"""Switch GPU mode"""
ifself.switching:
return
logging.info(f"Switching to {mode} mode")
self.switching=True
self.update_icon()
self.indicator.set_menu(self.build_menu())
notification=Notify.Notification.new(
"GPUMode",
f"Switching to {mode} mode...",
"emblem-synchronizing"
)
notification.show()
defswitch_thread():
try:
cmd= ['pkexec', 'envycontrol', '-s', mode]
ifmode=='hybrid':
cmd.extend(['--rtd3', '2'])
result=subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=60
)
ifresult.returncode==126orresult.returncode==127:
GLib.idle_add(self.switch_cancelled)
elifresult.returncode==0:
GLib.idle_add(self.switch_complete, mode, True, None)
else:
GLib.idle_add(self.switch_complete, mode, False, result.stderr)
exceptsubprocess.TimeoutExpired:
logging.error("Switch command timed out")
GLib.idle_add(self.switch_complete, mode, False, "Command timed out")
exceptExceptionase:
logging.error(f"Switch error: {e}")
GLib.idle_add(self.switch_complete, mode, False, str(e))
thread=threading.Thread(target=switch_thread)
thread.daemon=True
thread.start()
defswitch_cancelled(self):
"""Handle user cancelling pkexec password prompt"""
logging.info("User cancelled authentication")
self.switching=False
self.update_icon()
self.indicator.set_menu(self.build_menu())
notification=Notify.Notification.new(
"Switch Cancelled",
"Authentication was cancelled. GPU mode unchanged.",
"dialog-information"
)
notification.show()
returnFalse
defswitch_complete(self, mode, success, error_msg):
"""Handle switch completion"""
self.switching=False
ifsuccess:
logging.info(f"Successfully switched to {mode}")
self.current_mode=mode
self.update_icon()
self.indicator.set_menu(self.build_menu())
notification=Notify.Notification.new(
"✓ GPU Switched Successfully!",
f"Switched to {mode.upper()} mode.\n\n⚠️ REBOOT NOW for changes to take effect!",
"dialog-warning"
)
notification.set_urgency(Notify.Urgency.CRITICAL)
notification.set_timeout(10000)
notification.show()
else:
logging.error(f"Failed to switch to {mode}: {error_msg}")
self.update_icon()
self.indicator.set_menu(self.build_menu())
notification=Notify.Notification.new(
"✗ GPU Switch Failed",
f"Error: {error_msgiferror_msgelse'Command failed'}",
"dialog-error"
)
notification.show()
returnFalse
defshow_about(self, _):
"""Show about dialog"""
dialog=Gtk.AboutDialog()
dialog.set_program_name("GPUMode")
dialog.set_version(VERSION)
dialog.set_comments("Automatic GPU mode switching for laptops with NVIDIA graphics.\n\nNOTE: NVIDIA-only mode must be set in BIOS (F2).")
dialog.set_website("https://github.com/FrameworkComputer/GPUMode")
dialog.set_website_label("GPUMode on GitHub")
dialog.set_logo_icon_name("video-display")
dialog.run()
dialog.destroy()
defsingle_instance():
"""Ensure only one instance is running"""
try:
lock_file=open(LOCK_FILE, 'w')
fcntl.lockf(lock_file, fcntl.LOCK_EX|fcntl.LOCK_NB)
returnTrue
exceptIOError:
returnFalse
if__name__=="__main__":
ifnotsingle_instance():
dialog=Gtk.MessageDialog(
message_type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.OK,
text="GPUMode is already running"
)
dialog.format_secondary_text("Check your system tray for the GPUMode icon.")
dialog.run()
dialog.destroy()
sys.exit(0)
GPUIndicator()
Gtk.main()