-
Notifications
You must be signed in to change notification settings - Fork 3
/
settings.py
executable file
·1159 lines (975 loc) · 42.9 KB
/
settings.py
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
import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import Gtk, Adw, Gdk, GLib, Gio
import json
import os
import subprocess
import sounddevice as sd
import numpy as np
import threading
import requests
import time
import sys
from collections import deque
from ThemeManager import ThemeManager
class MAGISettings(Adw.Application):
def __init__(self):
super().__init__(application_id='com.system.magi.settings')
self.connect('activate', self.on_activate)
self.connect('shutdown', self.on_shutdown)
# Load config and theme data
self.config_dir = os.path.expanduser("~/.config/magi")
self.config_file = os.path.join(self.config_dir, "config.json")
self.config = self.load_config()
# Initialize theme system
self.theme_manager = ThemeManager()
self.current_magi_theme = self.config.get('magi_theme', 'Plain')
def on_shutdown(self, app):
"""Clean up when the application closes"""
self.stop_audio_monitor()
def on_activate(self, app):
"""Initialize the main window with proper layout"""
# Create window with proper titlebar
self.win = Adw.ApplicationWindow(application=app)
self.win.set_default_size(1024, 768)
self.win.maximize()
# Register window with theme manager
self.theme_manager.register_window(self.win)
# Create main layout box
main_layout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
main_layout.set_hexpand(True)
main_layout.set_vexpand(True)
# Add header bar
header = Adw.HeaderBar()
header.set_title_widget(Gtk.Label(label="MAGI Settings"))
main_layout.append(header)
# Main content box
main_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
main_box.set_hexpand(True)
main_box.set_vexpand(True)
main_layout.append(main_box)
# Create split view for adaptive layout
self.split_view = Adw.Leaflet()
self.split_view.set_can_unfold(True)
self.split_view.set_hexpand(True)
self.split_view.set_vexpand(True)
main_box.append(self.split_view)
# Sidebar
sidebar_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
sidebar_box.set_size_request(200, -1)
# Sidebar list
self.sidebar = Gtk.ListBox(css_classes=['navigation-sidebar'])
self.sidebar.set_selection_mode(Gtk.SelectionMode.SINGLE)
self.sidebar.connect('row-selected', self.on_sidebar_select)
sidebar_box.append(self.sidebar)
# Content area with full width
content_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
content_box.set_hexpand(True)
content_box.set_vexpand(True)
# Stack for content pages
self.stack = Gtk.Stack()
self.stack.set_hexpand(True)
self.stack.set_vexpand(True)
self.stack.set_transition_type(Gtk.StackTransitionType.CROSSFADE)
content_box.append(self.stack)
# Add content pages
self.add_page("General", self.create_general_page(), "preferences-desktop-symbolic")
self.add_page("Audio", self.create_audio_page(), "audio-card-symbolic")
self.add_page("AI", self.create_ai_page(), "preferences-system-symbolic")
self.add_page("Appearance", self.create_appearance_page(), "preferences-desktop-theme-symbolic")
# Add boxes to split view
self.split_view.append(sidebar_box)
self.split_view.append(content_box)
# Select first item
self.sidebar.select_row(self.sidebar.get_row_at_index(0))
# Set the main layout as window content
self.win.set_content(main_layout)
self.win.present()
def on_sidebar_select(self, listbox, row):
"""Handle sidebar selection"""
if row:
page_name = row.get_child().get_last_child().get_text().lower()
self.stack.set_visible_child_name(page_name)
def add_page(self, title, content, icon_name):
"""Add a page to the stack and sidebar with proper layout"""
# Create sidebar item
row = Gtk.ListBoxRow()
box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
box.set_margin_start(12)
box.set_margin_end(12)
box.set_margin_top(8)
box.set_margin_bottom(8)
row.set_child(box)
icon = Gtk.Image()
icon.set_from_icon_name(icon_name)
label = Gtk.Label(label=title)
label.set_xalign(0)
box.append(icon)
box.append(label)
self.sidebar.append(row)
# Create full-width container for the content
content_container = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
content_container.set_hexpand(True)
content_container.set_vexpand(True)
# Center the content with appropriate margins
margin_start = Gtk.Box()
margin_start.set_hexpand(True)
margin_end = Gtk.Box()
margin_end.set_hexpand(True)
content.set_margin_start(24)
content.set_margin_end(24)
content.set_margin_top(24)
content.set_margin_bottom(24)
content.set_hexpand(True) # Make content expand horizontally
# Pack content with flexible margins
content_container.append(margin_start)
content_container.append(content)
content_container.append(margin_end)
# Add to stack
self.stack.add_named(content_container, title.lower())
def create_general_page(self):
"""Create general settings page with full width layout"""
clamp = Adw.Clamp()
page = Adw.PreferencesPage()
page.set_hexpand(True)
page.set_vexpand(True)
# Panel settings group
panel_group = Adw.PreferencesGroup(
title="Panel Settings",
description="Configure the appearance and behavior of the panels"
)
page.add(panel_group)
# Panel height
height_row = Adw.ActionRow(
title="Panel Height",
subtitle="Height of the top and bottom panels in pixels"
)
height_spin = Gtk.SpinButton.new_with_range(24, 48, 2)
height_spin.set_value(self.config.get('panel_height', 28))
height_spin.set_valign(Gtk.Align.CENTER)
height_spin.connect('value-changed', self.on_panel_height_changed)
height_row.add_suffix(height_spin)
panel_group.add(height_row)
# Workspace settings group
workspace_group = Adw.PreferencesGroup(
title="Workspace Settings",
description="Configure virtual workspace behavior"
)
page.add(workspace_group)
# Workspace count
workspace_row = Adw.ActionRow(
title="Workspace Count",
subtitle="Number of virtual desktops available"
)
workspace_spin = Gtk.SpinButton.new_with_range(1, 10, 1)
workspace_spin.set_value(self.config.get('workspace_count', 4))
workspace_spin.set_valign(Gtk.Align.CENTER)
workspace_spin.connect('value-changed', self.on_workspace_count_changed)
workspace_row.add_suffix(workspace_spin)
workspace_group.add(workspace_row)
# Application settings group
app_group = Adw.PreferencesGroup(
title="Application Settings",
description="Configure default applications and launchers"
)
page.add(app_group)
# Terminal command
terminal_row = Adw.ActionRow(
title="Terminal Command",
subtitle="Command used to launch the terminal application"
)
terminal_entry = Gtk.Entry()
terminal_entry.set_text(self.config.get('terminal', 'mate-terminal'))
terminal_entry.set_valign(Gtk.Align.CENTER)
terminal_entry.set_hexpand(True)
terminal_entry.connect('changed', self.on_terminal_changed)
terminal_row.add_suffix(terminal_entry)
app_group.add(terminal_row)
# Launcher command
launcher_row = Adw.ActionRow(
title="Launcher Command",
subtitle="Command used to show the application launcher"
)
launcher_entry = Gtk.Entry()
launcher_entry.set_text(self.config.get('launcher', 'mate-panel --run-dialog'))
launcher_entry.set_valign(Gtk.Align.CENTER)
launcher_entry.set_hexpand(True)
launcher_entry.connect('changed', self.on_launcher_changed)
launcher_row.add_suffix(launcher_entry)
app_group.add(launcher_row)
# System settings group
system_group = Adw.PreferencesGroup(
title="System Settings",
description="Configure system-wide behavior"
)
page.add(system_group)
# Startup delay
startup_row = Adw.ActionRow(
title="Startup Delay",
subtitle="Delay in seconds before starting background services"
)
startup_spin = Gtk.SpinButton.new_with_range(0, 10, 1)
startup_spin.set_value(self.config.get('startup_delay', 2))
startup_spin.set_valign(Gtk.Align.CENTER)
startup_spin.connect('value-changed', self.on_startup_delay_changed)
startup_row.add_suffix(startup_spin)
system_group.add(startup_row)
clamp.set_child(page)
return clamp
def on_terminal_changed(self, entry):
self.config['terminal'] = entry.get_text()
self.save_config()
def on_launcher_changed(self, entry):
self.config['launcher'] = entry.get_text()
self.save_config()
def on_startup_delay_changed(self, spin):
self.config['startup_delay'] = spin.get_value_as_int()
self.save_config()
def on_panel_height_changed(self, spin):
self.config['panel_height'] = spin.get_value_as_int()
self.save_config()
def on_workspace_count_changed(self, spin):
self.config['workspace_count'] = spin.get_value_as_int()
self.save_config()
def create_audio_page(self):
"""Create simplified audio settings page that redirects to system settings"""
page = Adw.PreferencesPage()
page.set_hexpand(True)
# Audio settings group
audio_group = Adw.PreferencesGroup(
title="Audio Settings",
description="Configure system-wide audio settings including microphone selection"
)
page.add(audio_group)
# Button to open system sound settings
settings_row = Adw.ActionRow(
title="System Sound Settings",
subtitle="Open the system sound control panel to configure audio devices"
)
open_button = Gtk.Button(label="Open Settings")
open_button.connect('clicked', self.open_sound_settings)
open_button.add_css_class("flat")
settings_row.add_suffix(open_button)
audio_group.add(settings_row)
# Sample rate setting (keep this as it's needed for voice recognition)
rate_group = Adw.PreferencesGroup(
title="Voice Recognition Settings",
description="Configure audio sampling rate for voice recognition"
)
page.add(rate_group)
rate_row = Adw.ComboRow(
title="Sample Rate",
subtitle="Audio recording sample rate in Hz"
)
rate_store = Gtk.StringList()
self.sample_rates = [16000, 22050, 44100, 48000]
current_rate = self.config.get('sample_rate', 16000)
selected_idx = self.sample_rates.index(current_rate) if current_rate in self.sample_rates else 0
for rate in self.sample_rates:
rate_store.append(f"{rate} Hz")
rate_row.set_model(rate_store)
rate_row.set_selected(selected_idx)
rate_row.connect('notify::selected', self.on_sample_rate_changed)
rate_group.add(rate_row)
return page
def open_sound_settings(self, button):
"""Try to open system sound settings using available tools"""
try:
# Try MATE volume control first
subprocess.run(['mate-volume-control'], check=True)
except FileNotFoundError:
try:
# Try pavucontrol as fallback
subprocess.run(['pavucontrol'], check=True)
except FileNotFoundError:
# If neither is available, show error dialog
dialog = Adw.MessageDialog.new(
self.win,
"Error Opening Sound Settings",
"Could not find mate-volume-control or pavucontrol. Please install one of these packages to configure audio settings."
)
dialog.add_response("ok", "OK")
dialog.present()
except Exception as e:
# Show error if launch fails
dialog = Adw.MessageDialog.new(
self.win,
"Error Opening Sound Settings",
str(e)
)
dialog.add_response("ok", "OK")
dialog.present()
def create_ai_page(self):
"""Create AI settings page with dynamic model selection"""
page = Adw.PreferencesPage()
page.set_hexpand(True)
# AI Features group
ai_group = Adw.PreferencesGroup(title="AI Features")
page.add(ai_group)
# Enable AI toggle
enable_row = Adw.ActionRow(
title="Enable AI Features",
subtitle="Enable or disable AI-powered features"
)
enable_switch = Gtk.Switch()
enable_switch.set_active(self.config.get('enable_ai', True))
enable_switch.connect('notify::active', self.on_ai_enabled_changed)
enable_row.add_suffix(enable_switch)
ai_group.add(enable_row)
# Model settings group
model_group = Adw.PreferencesGroup(title="Model Settings")
page.add(model_group)
# Ollama model selection
model_row = Adw.ComboRow(
title="Ollama Model",
subtitle="Select the AI model to use for text generation"
)
# Create model store
model_store = Gtk.StringList()
models = self.get_ollama_models()
current_model = self.config.get('ollama_model', 'mistral')
selected_idx = 0
for i, model in enumerate(models):
model_store.append(model)
if model == current_model:
selected_idx = i
model_row.set_model(model_store)
model_row.set_selected(selected_idx)
model_row.connect('notify::selected',
lambda r,p: self.on_model_changed(r, models))
model_group.add(model_row)
# Refresh models button
refresh_row = Adw.ActionRow(
title="Available Models",
subtitle="Refresh the list of available Ollama models"
)
refresh_button = Gtk.Button(label="Refresh")
refresh_button.connect('clicked', self.on_refresh_models_clicked)
refresh_button.add_css_class("flat")
refresh_row.add_suffix(refresh_button)
model_group.add(refresh_row)
return page
def create_appearance_page(self):
"""Replace the existing appearance page with new theme system"""
return self.create_theme_section()
def create_theme_section(self):
"""Create theme selection UI with three sections"""
page = Adw.PreferencesPage()
# GTK3 themes
gtk3_group = Adw.PreferencesGroup(
title="GTK3 Theme",
description="Theme for legacy applications"
)
gtk3_row = Adw.ComboRow(
title="GTK3 Theme",
model=Gtk.StringList.new(self.get_gtk3_themes())
)
# Set current GTK3 theme
current_gtk3 = self.config.get('gtk3_theme', 'Default')
gtk3_themes = self.get_gtk3_themes()
if current_gtk3 in gtk3_themes:
gtk3_row.set_selected(gtk3_themes.index(current_gtk3))
gtk3_row.connect('notify::selected', self.on_gtk3_theme_changed)
gtk3_group.add(gtk3_row)
# GTK4 color scheme
gtk4_group = Adw.PreferencesGroup(
title="GTK4 Style",
description="Color scheme for modern applications"
)
gtk4_row = Adw.ComboRow(
title="Color Scheme",
model=Gtk.StringList.new(["System Default", "Prefer Dark", "Prefer Light", "Force Dark"])
)
gtk4_row.set_selected(self.config.get('gtk4_scheme', 0))
gtk4_row.connect('notify::selected', self.on_gtk4_theme_changed)
gtk4_group.add(gtk4_row)
# MAGI theme
magi_group = Adw.PreferencesGroup(
title="MAGI Theme",
description="Theme for MAGI panels and menus"
)
magi_row = Adw.ComboRow(
title="MAGI Theme",
model=Gtk.StringList.new(list(self.theme_manager.themes.keys()))
)
current_theme_idx = list(self.theme_manager.themes.keys()).index(self.current_magi_theme)
magi_row.set_selected(current_theme_idx)
magi_row.connect('notify::selected', self.on_magi_theme_changed)
magi_group.add(magi_row)
page.add(gtk3_group)
page.add(gtk4_group)
page.add(magi_group)
return page
def get_gtk3_themes(self):
"""Get list of installed GTK3 themes"""
themes = set(["Default"])
theme_paths = [
os.path.expanduser('~/.themes'),
os.path.expanduser('~/.local/share/themes'),
'/usr/share/themes'
]
for path in theme_paths:
if os.path.exists(path):
for theme in os.listdir(path):
theme_dir = os.path.join(path, theme)
if os.path.isdir(theme_dir):
# Check for GTK3 theme files
if (os.path.exists(os.path.join(theme_dir, 'gtk-3.0', 'gtk.css')) or
os.path.exists(os.path.join(theme_dir, 'gtk-3.0', 'gtk-main.css'))):
themes.add(theme)
return sorted(list(themes))
def on_gtk3_theme_changed(self, row, _):
"""Handle GTK3 theme changes safely"""
selected = row.get_selected()
themes = self.get_gtk3_themes()
if 0 <= selected < len(themes):
theme_name = themes[selected]
# Update GTK settings
settings = Gtk.Settings.get_default()
settings.set_property('gtk-theme-name', theme_name)
# Update system settings safely
try:
# Update MATE interface theme
subprocess.run(['gsettings', 'set', 'org.mate.interface', 'gtk-theme', theme_name],
check=False)
# Update window manager theme
subprocess.run(['gsettings', 'set', 'org.mate.Marco.general', 'theme', theme_name],
check=False)
# Update through dconf for persistence
subprocess.run(['dconf', 'write', '/org/mate/desktop/interface/gtk-theme',
f"'{theme_name}'"], check=False)
except Exception as e:
print(f"Error updating GTK3 theme: {e}")
self.config['gtk3_theme'] = theme_name
self.save_config()
# Show notification
if hasattr(self, 'toast_overlay'):
toast = Adw.Toast.new(f"GTK3 theme changed to {theme_name}")
toast.set_timeout(2)
self.toast_overlay.add_toast(toast)
# Suggest logout for complete theme application
dialog = Adw.MessageDialog.new(
self,
"Theme Changed",
"Some applications may need to be restarted or require a logout to fully apply the theme."
)
dialog.add_response("ok", "OK")
dialog.present()
def on_gtk4_theme_changed(self, row, _):
"""Handle GTK4 color scheme changes"""
schemes = [
Adw.ColorScheme.DEFAULT,
Adw.ColorScheme.PREFER_DARK,
Adw.ColorScheme.PREFER_LIGHT,
Adw.ColorScheme.FORCE_DARK
]
selected = row.get_selected()
if 0 <= selected < len(schemes):
style_manager = Adw.StyleManager.get_default()
style_manager.set_color_scheme(schemes[selected])
self.config['gtk4_scheme'] = selected
self.save_config()
def on_magi_theme_changed(self, row, _):
"""Handle MAGI theme changes"""
selected = row.get_selected()
themes = list(self.theme_manager.themes.keys())
if 0 <= selected < len(themes):
theme_name = themes[selected]
self.current_magi_theme = theme_name
self.config['magi_theme'] = theme_name
self.save_config()
def _show_window_after_theme_change(self):
"""Helper to show window after brief delay to allow theme to apply"""
self.win.show()
return False
def get_available_themes(self):
"""Get list of installed GTK themes with validation"""
themes = set()
theme_paths = [
os.path.expanduser('~/.themes'),
os.path.expanduser('~/.local/share/themes'),
'/usr/share/themes'
]
for path in theme_paths:
if os.path.exists(path):
for theme in os.listdir(path):
theme_dir = os.path.join(path, theme)
if os.path.isdir(theme_dir):
# Check for theme files in order of preference
if (os.path.exists(os.path.join(theme_dir, 'gtk-4.0', 'gtk.css')) or
os.path.exists(os.path.join(theme_dir, 'gtk-3.0', 'gtk.css')) or
os.path.exists(os.path.join(theme_dir, 'gtk-3.0', 'gtk-main.css')) or
os.path.exists(os.path.join(theme_dir, 'gtk-2.0', 'gtkrc'))):
themes.add(theme)
return sorted(list(themes))
def start_audio_monitor(self):
"""Start monitoring audio input level"""
self.stop_audio_monitor() # Ensure any existing monitor is stopped
device_id = self.config.get('default_microphone')
sample_rate = self.config.get('sample_rate', 16000)
if device_id is None:
self.level_label.set_text("No microphone selected")
return
self.monitor_running = True
def audio_callback(indata, frames, time, status):
if status:
print(status)
if self.monitor_running:
# Calculate RMS level with proper scaling
rms = np.sqrt(np.mean(indata**2))
# Convert to dB with proper range
db = max(-60, 20 * np.log10(rms + 1e-10))
# Normalize to 0-1 range for level bar
normalized = (db + 60) / 60
GLib.idle_add(self.update_level_indicator, normalized, db)
try:
self.monitor_stream = sd.InputStream(
device=device_id,
channels=1,
callback=audio_callback,
blocksize=1024,
samplerate=sample_rate,
dtype=np.float32
)
self.monitor_stream.start()
except Exception as e:
print(f"Error starting audio monitor: {e}")
self.level_label.set_text(f"Error: {str(e)}")
def stop_audio_monitor(self):
"""Stop the audio monitor"""
self.monitor_running = False
if hasattr(self, 'monitor_stream'):
try:
self.monitor_stream.stop()
self.monitor_stream.close()
self.monitor_stream = None
except Exception as e:
print(f"Error stopping audio monitor: {e}")
def apply_theme(self, theme_name):
"""Apply theme and save to config"""
settings = Gtk.Settings.get_default()
if theme_name == 'Default':
# Reset to system theme
settings.set_property('gtk-theme-name', None)
else:
settings.set_property('gtk-theme-name', theme_name)
self.config['gtk_theme'] = theme_name
self.save_config()
def update_level_indicator(self, level, db):
"""Update the level bar and label with proper formatting"""
if hasattr(self, 'level_bar'):
self.level_bar.set_value(level)
if db < -60:
self.level_label.set_text("Level: -60 dB")
else:
self.level_label.set_text(f"Level: {db:.1f} dB")
return False
def stop_audio_monitor(self):
"""Stop the audio monitor"""
self.monitor_running = False
if hasattr(self, 'monitor_stream'):
try:
self.monitor_stream.stop()
self.monitor_stream.close()
except Exception as e:
print(f"Error stopping audio monitor: {e}")
def get_ollama_models(self):
"""Get list of installed Ollama models"""
try:
result = subprocess.run(['ollama', 'list'],
capture_output=True,
text=True,
check=True)
models = []
lines = result.stdout.strip().split('\n')
if len(lines) > 1: # Skip header row
for line in lines[1:]:
# Split on whitespace and get first column (name)
parts = line.split()
if parts:
model_name = parts[0]
# Remove :latest if present
if model_name.endswith(':latest'):
model_name = model_name[:-7]
models.append(model_name)
return sorted(models)
except subprocess.CalledProcessError as e:
print(f"Error getting Ollama models: {e}")
return []
except Exception as e:
print(f"Unexpected error getting Ollama models: {e}")
return []
def on_choose_background(self, button):
"""Handle background image selection"""
dialog = Gtk.FileChooserDialog(
title="Choose Background Image",
action=Gtk.FileChooserAction.OPEN,
)
dialog.add_buttons(
"_Cancel",
Gtk.ResponseType.CANCEL,
"_Open",
Gtk.ResponseType.ACCEPT,
)
dialog.set_transient_for(self.win)
dialog.set_modal(True)
filter_images = Gtk.FileFilter()
filter_images.set_name("Image files")
filter_images.add_mime_type("image/jpeg")
filter_images.add_mime_type("image/png")
dialog.add_filter(filter_images)
dialog.connect('response', self.on_background_dialog_response)
dialog.show()
def on_background_dialog_response(self, dialog, response):
if response == Gtk.ResponseType.ACCEPT:
file = dialog.get_file()
if file:
path = file.get_path()
self.config['background'] = path
self.save_config()
# Update background
try:
subprocess.run(['feh', '--bg-fill', path])
except Exception as e:
print(f"Error setting background: {e}")
dialog.destroy()
def on_panel_height_changed(self, spin):
self.config['panel_height'] = spin.get_value_as_int()
self.save_config()
def on_workspace_count_changed(self, spin):
self.config['workspace_count'] = spin.get_value_as_int()
self.save_config()
def on_terminal_changed(self, entry):
self.config['terminal'] = entry.get_text()
self.save_config()
def on_microphone_changed(self, row, _):
"""Handle microphone selection change"""
selected = row.get_selected()
if 0 <= selected < len(self.mic_devices):
device_id = self.mic_devices[selected]
self.config['default_microphone'] = device_id
self.save_config()
# Restart audio monitoring with new device
self.stop_audio_monitor()
self.start_audio_monitor()
def on_test_microphone(self, button):
"""Test selected microphone with improved error handling and feedback"""
device_id = self.config.get('default_microphone')
if device_id is None:
dialog = Adw.MessageDialog.new(
self.win,
"No microphone selected",
"Please select a microphone first."
)
dialog.add_response("ok", "OK")
dialog.present()
return
# Get device info first to check capabilities
try:
device_info = sd.query_devices(device_id)
if device_info['max_input_channels'] < 1:
raise ValueError("Selected device has no input channels")
# Get supported sample rates
supported_rates = []
test_rates = [8000, 16000, 22050, 44100, 48000]
for rate in test_rates:
try:
sd.check_input_settings(
device=device_id,
channels=1,
dtype=np.float32,
samplerate=rate
)
supported_rates.append(rate)
except Exception:
continue
if not supported_rates:
raise ValueError("No supported sample rates found for this device")
# Use the closest supported rate to our configured rate
configured_rate = self.config.get('sample_rate', 16000)
sample_rate = min(supported_rates, key=lambda x: abs(x - configured_rate))
# Create recording progress dialog
progress_dialog = Adw.MessageDialog.new(
self.win,
"Testing Microphone",
"Recording in progress..."
)
progress_dialog.add_response("cancel", "Cancel")
# Add progress bar
content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
content.set_margin_top(12)
content.set_margin_bottom(12)
content.set_margin_start(12)
content.set_margin_end(12)
progress_bar = Gtk.ProgressBar()
progress_bar.set_fraction(0.0)
content.append(progress_bar)
level_label = Gtk.Label(label="Level: 0 dB")
content.append(level_label)
progress_dialog.set_extra_child(content)
# Variables for recording
duration = 3 # seconds
recording_data = []
start_time = None
is_recording = True
def audio_callback(indata, frames, time, status):
if status:
print(status)
if is_recording:
recording_data.append(indata.copy())
# Update level meter
level = 20 * np.log10(np.max(np.abs(indata)) + 1e-10)
GLib.idle_add(level_label.set_text, f"Level: {level:.1f} dB")
def update_progress():
if not is_recording:
return False
nonlocal start_time
if start_time is None:
start_time = time.time()
elapsed = time.time() - start_time
if elapsed >= duration:
stream.stop()
progress_dialog.close()
return False
progress_bar.set_fraction(elapsed / duration)
return True
# Start recording
try:
stream = sd.InputStream(
device=device_id,
channels=1,
samplerate=sample_rate,
callback=audio_callback,
dtype=np.float32
)
stream.start()
GLib.timeout_add(100, update_progress)
progress_dialog.present()
def on_dialog_response(dialog, response):
nonlocal is_recording
is_recording = False
stream.stop()
stream.close()
progress_dialog.connect('response', on_dialog_response)
# When recording is done, play it back
def on_recording_complete():
if not recording_data:
return
# Combine all recorded chunks
recorded_audio = np.concatenate(recording_data)
# Play the recording back
playback_dialog = Adw.MessageDialog.new(
self.win,
"Playback",
"Playing back recorded audio..."
)
playback_dialog.present()
try:
sd.play(recorded_audio, sample_rate)
sd.wait()
except Exception as e:
print(f"Playback error: {e}")
finally:
playback_dialog.close()
GLib.timeout_add_seconds(duration, on_recording_complete)
except Exception as e:
error_msg = str(e)
if "Invalid sample rate" in error_msg:
error_msg = f"Sample rate {sample_rate}Hz not supported by device. Supported rates: {supported_rates}"
elif "Invalid number of channels" in error_msg:
error_msg = "Device does not support mono recording"
error_dialog = Adw.MessageDialog.new(
self.win,
"Recording Failed",
error_msg
)
error_dialog.add_response("ok", "OK")
error_dialog.present()
return
except Exception as e:
error_msg = str(e)
if "Invalid device" in error_msg:
error_msg = "Selected device is no longer available"
error_dialog = Adw.MessageDialog.new(
self.win,
"Device Error",
error_msg
)
error_dialog.add_response("ok", "OK")
error_dialog.present()
def on_sample_rate_changed(self, row, _):
"""Handle sample rate selection change"""
selected = row.get_selected()
if 0 <= selected < len(self.sample_rates):
rate = self.sample_rates[selected]
self.config['sample_rate'] = rate
self.save_config()
# Restart audio monitoring with new sample rate
self.stop_audio_monitor()
self.start_audio_monitor()
def on_refresh_models_clicked(self, button):
"""Refresh the Ollama models list"""
models = self.get_ollama_models()
model_row = self.find_model_row()
if model_row:
# Update model store
model_store = Gtk.StringList()
current_model = self.config.get('ollama_model', 'mistral')
selected_idx = 0
for i, model in enumerate(models):
model_store.append(model)
if model == current_model:
selected_idx = i
model_row.set_model(model_store)
model_row.set_selected(selected_idx)
def find_model_row(self):
"""Find the Ollama model ComboRow in the UI"""
stack = self.stack
ai_page = stack.get_child_by_name('ai')
if ai_page:
for group in ai_page:
if isinstance(group, Adw.PreferencesGroup):
for row in group:
if isinstance(row, Adw.ComboRow) and row.get_title() == "Ollama Model":
return row
return None
def on_model_changed(self, row, models):
"""Handle Ollama model selection"""