-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
2200 lines (1916 loc) · 81.9 KB
/
Copy pathextension.js
File metadata and controls
2200 lines (1916 loc) · 81.9 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
/* extension.js
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import Shell from 'gi://Shell';
import Clutter from 'gi://Clutter';
import Meta from 'gi://Meta';
import Mtk from 'gi://Mtk';
import St from 'gi://St';
import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js';
import * as Main from 'resource:///org/gnome/shell/ui/main.js';
import { _ } from './translations.js';
import { PrayaIndicator } from './indicator.js';
import { PrayaTaskbar } from './taskbar.js';
import { connectClickHandler } from './touch-helper.js';
// D-Bus constants for posture service
const POSTURE_BUS_NAME = 'com.github.blankon.praya';
const POSTURE_SERVICE_INTERFACE = 'com.github.blankon.Praya.Posture';
const POSTURE_SERVICE_PATH = '/com/github/blankon/Praya/Posture';
export default class PrayaExtension extends Extension {
enable() {
// Load services configuration
this._loadServicesConfig();
// Watch config files for live changes from preferences window
this._setupConfigMonitors();
// Save and apply gsettings
this._applySettings();
this._indicator = new PrayaIndicator();
// Add to the left side of the panel
Main.panel.addToStatusArea('praya-indicator', this._indicator, 0, 'left');
// Apply panel position (top or bottom)
this._applyPanelPosition(this._servicesConfig.panelPosition || 'top');
this._setupWorkAreaMargins();
this._setupIconGeometryTracking();
this._monitorsChangedId = Main.layoutManager.connect('monitors-changed', () => {
this._applyPanelPosition(this._panelPosition || 'top');
this._removeWorkAreaMargins();
this._setupWorkAreaMargins();
this._updateAllWindowsIconGeometry();
});
// Defer services start and panel re-apply to after GNOME Shell
// startup completes. At that point display env vars
// (WAYLAND_DISPLAY, DISPLAY, …) are guaranteed to be set, so
// the systemd environment import succeeds on the first try and
// apps launched via systemd scopes can connect to the compositor.
// Launch lowspec dialog immediately if applicable
if (this._checkLowspec() && !this._servicesConfig.lowspecDismissed) {
this._launchLowspecDialog();
}
if (!Main.layoutManager._startingUp) {
// Already started up (e.g. extension enabled from prefs)
this._startPrayaServices();
} else {
this._startupCompleteId = Main.layoutManager.connect('startup-complete', () => {
Main.layoutManager.disconnect(this._startupCompleteId);
this._startupCompleteId = null;
this._applyPanelPosition(this._panelPosition || 'top');
this._removeWorkAreaMargins();
this._setupWorkAreaMargins();
this._updateAllWindowsIconGeometry();
this._startPrayaServices();
this._scheduleLowspecCheck();
});
}
// Add percentage label to OSD windows
this._patchOsdWindows();
// Hide activities button
this._hideActivities();
// Add taskbar to the left box, after indicator (index 1)
this._taskbar = new PrayaTaskbar();
Main.panel._leftBox.insert_child_at_index(this._taskbar, 1);
// Add show desktop button to far right of panel
// Outer: black hover area, no margin, fills panel height
this._showDesktopHoverArea = new St.Bin({
style_class: 'praya-show-desktop-hover-area',
reactive: true,
track_hover: true,
});
// Inner: wallpaper thumbnail with margin
this._showDesktopButton = new St.Bin({
style_class: 'praya-show-desktop-button',
reactive: false,
});
this._showDesktopOverlay = new St.Widget({
style_class: 'praya-show-desktop-overlay',
x_expand: true,
y_expand: true,
reactive: false,
});
this._showDesktopButton.add_child(this._showDesktopOverlay);
this._showDesktopHoverArea.set_child(this._showDesktopButton);
this._showDesktopActive = false;
this._showDesktopHoverHandled = false;
this._showDesktopHoverActivate = this._servicesConfig.showDesktopHoverActivate || false;
this._showDesktopHoverArea.connect('notify::hover', (actor) => {
if (!this._showDesktopHoverActivate) return;
if (actor.hover && !this._showDesktopHoverHandled) {
this._showDesktopHoverHandled = true;
this._toggleShowDesktop();
this._showDesktopOverlay.ease({
opacity: this._showDesktopActive ? 0 : 76,
duration: 150,
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
});
} else if (!actor.hover) {
this._showDesktopHoverHandled = false;
this._showDesktopOverlay.ease({
opacity: this._showDesktopActive ? 0 : 76,
duration: 150,
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
});
}
});
// Click/touch handler for show desktop (works regardless of hover setting)
connectClickHandler(this._showDesktopHoverArea, () => {
this._toggleShowDesktop();
this._showDesktopOverlay.ease({
opacity: this._showDesktopActive ? 0 : 76,
duration: 150,
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
});
});
Main.panel._rightBox.add_child(this._showDesktopHoverArea);
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this._setShowDesktopWallpaper();
return GLib.SOURCE_REMOVE;
});
// Listen for wallpaper changes
this._bgSettings = new Gio.Settings({ schema_id: 'org.gnome.desktop.background' });
this._bgChangedId = this._bgSettings.connect('changed::picture-uri', () => {
this._setShowDesktopWallpaper();
});
this._bgDarkChangedId = this._bgSettings.connect('changed::picture-uri-dark', () => {
this._setShowDesktopWallpaper();
});
// Move date/time to the right (left of quick settings)
this._moveDateTimeToRight();
// Setup hover trigger for quick settings
this._setupQuickSettingsHover();
// Setup stage-level hover handler for calendar and quick settings
this._setupPanelHoverHandler();
// Hide the bottom dock when extension is enabled
this._dock = null;
this._hideDock();
// Override hot corner to open our panel instead of overview
this._setupHotCorner();
// Override Super key to open Praya panel instead of Activities
this._setupSuperKey();
// Setup Meta+Space keybinding to toggle panel
this._setupKeybinding();
// Initialize blur overlays array
this._blurOverlays = [];
// Auto-close tracking
this._autoCloseAnimating = false;
this._autoCloseTimeoutId = null;
this._autoCloseTolerance = 0.1; // Cancel auto-close if score exceeds this
// Only initialize posture features if enabled in config
if (this._servicesConfig.posture) {
// Setup D-Bus connection for posture status
this._initPostureDBus();
// Pause posture evaluation during initial delay
this._postureEvalPaused = true;
// Start posture polling loop (similar to Praya Preferences)
this._startPosturePolling();
}
}
_loadServicesConfig() {
let homeDir = GLib.get_home_dir();
let configDir = GLib.build_filenamev([homeDir, '.config', 'praya']);
let configPath = GLib.build_filenamev([configDir, 'services.json']);
// Default config
let defaultConfig = {
ai: false,
posture: false,
mainMenuHoverActivate: false,
taskbarHoverActivate: false,
showDesktopHoverActivate: false,
calendarHoverActivate: false,
quickAccessHoverActivate: false,
floatingPanel: true,
panelPosition: 'top',
};
try {
// Ensure config directory exists
let dir = Gio.File.new_for_path(configDir);
if (!dir.query_exists(null)) {
dir.make_directory_with_parents(null);
}
let configFile = Gio.File.new_for_path(configPath);
if (!configFile.query_exists(null)) {
// Create default config file
let content = JSON.stringify(defaultConfig, null, 2) + '\n';
configFile.replace_contents(
content,
null,
false,
Gio.FileCreateFlags.NONE,
null
);
this._servicesConfig = defaultConfig;
} else {
// Load existing config
let [success, contents] = configFile.load_contents(null);
if (success) {
let decoder = new TextDecoder('utf-8');
let jsonStr = decoder.decode(contents);
this._servicesConfig = JSON.parse(jsonStr);
} else {
this._servicesConfig = defaultConfig;
}
}
} catch (e) {
log(`Praya: Error loading services config: ${e.message}`);
this._servicesConfig = defaultConfig;
}
}
_setupConfigMonitors() {
let homeDir = GLib.get_home_dir();
let preferencesPath = GLib.build_filenamev([homeDir, '.config', 'praya', 'services.json']);
let chatbotPath = GLib.build_filenamev([homeDir, '.config', 'praya', 'chatbot.json']);
this._preferencesMonitorDebounceId = null;
this._chatbotMonitorDebounceId = null;
// Monitor services.json for preferences changes
try {
let preferencesFile = Gio.File.new_for_path(preferencesPath);
this._preferencesMonitor = preferencesFile.monitor_file(Gio.FileMonitorFlags.NONE, null);
this._preferencesMonitor.connect('changed', (_monitor, _file, _otherFile, eventType) => {
if (eventType === Gio.FileMonitorEvent.CHANGED ||
eventType === Gio.FileMonitorEvent.CHANGES_DONE_HINT ||
eventType === Gio.FileMonitorEvent.CREATED) {
if (this._preferencesMonitorDebounceId) {
GLib.source_remove(this._preferencesMonitorDebounceId);
}
this._preferencesMonitorDebounceId = GLib.timeout_add(
GLib.PRIORITY_DEFAULT, 300, () => {
this._preferencesMonitorDebounceId = null;
this._onPreferencesChanged();
return GLib.SOURCE_REMOVE;
});
}
});
log('Praya: Preferences file monitor set up');
} catch (e) {
log(`Praya: Error setting up preferences monitor: ${e.message}`);
}
// Monitor chatbot.json for chatbot config changes
try {
let chatbotFile = Gio.File.new_for_path(chatbotPath);
this._chatbotMonitor = chatbotFile.monitor_file(Gio.FileMonitorFlags.NONE, null);
this._chatbotMonitor.connect('changed', (_monitor, _file, _otherFile, eventType) => {
if (eventType === Gio.FileMonitorEvent.CHANGED ||
eventType === Gio.FileMonitorEvent.CHANGES_DONE_HINT ||
eventType === Gio.FileMonitorEvent.CREATED) {
if (this._chatbotMonitorDebounceId) {
GLib.source_remove(this._chatbotMonitorDebounceId);
}
this._chatbotMonitorDebounceId = GLib.timeout_add(
GLib.PRIORITY_DEFAULT, 300, () => {
this._chatbotMonitorDebounceId = null;
this._onChatbotConfigChanged();
return GLib.SOURCE_REMOVE;
});
}
});
log('Praya: Chatbot file monitor set up');
} catch (e) {
log(`Praya: Error setting up chatbot monitor: ${e.message}`);
}
}
_onPreferencesChanged() {
let oldConfig = this._servicesConfig;
this._loadServicesConfig();
let newConfig = this._servicesConfig;
// Apply panel position change
if (oldConfig.panelPosition !== newConfig.panelPosition) {
this.setPanelPosition(newConfig.panelPosition || 'top');
}
// Apply floating panel change
if (oldConfig.floatingPanel !== newConfig.floatingPanel) {
this._applyPanelPosition(newConfig.panelPosition || 'top');
this._removeWorkAreaMargins();
this._setupWorkAreaMargins();
}
// Apply hover activation settings to indicator
if (this._indicator) {
this._indicator.setMainMenuHoverActivate(newConfig.mainMenuHoverActivate || false);
}
// Apply hover activation to taskbar
if (this._taskbar && oldConfig.taskbarHoverActivate !== newConfig.taskbarHoverActivate) {
this._taskbar.setHoverActivate(newConfig.taskbarHoverActivate || false);
}
// Apply hover activation to show desktop
if (oldConfig.showDesktopHoverActivate !== newConfig.showDesktopHoverActivate) {
this._showDesktopHoverActivate = newConfig.showDesktopHoverActivate || false;
}
// Apply calendar and quick access hover activation
if (oldConfig.calendarHoverActivate !== newConfig.calendarHoverActivate) {
this._calendarHoverActivate = newConfig.calendarHoverActivate || false;
}
if (oldConfig.quickAccessHoverActivate !== newConfig.quickAccessHoverActivate) {
this._quickAccessHoverActivate = newConfig.quickAccessHoverActivate || false;
}
// Apply posture service toggle
if (oldConfig.posture !== newConfig.posture) {
if (newConfig.posture) {
this._initPostureDBus();
this._postureEvalPaused = true;
this._startPosturePolling();
} else {
this._cleanupPostureDBus();
}
}
log('Praya: Preferences reloaded');
}
_onChatbotConfigChanged() {
if (this._indicator && this._indicator._chatbotSettings) {
this._indicator._chatbotSettings.reload();
}
log('Praya: Chatbot config reloaded');
}
_cleanupConfigMonitors() {
if (this._preferencesMonitorDebounceId) {
GLib.source_remove(this._preferencesMonitorDebounceId);
this._preferencesMonitorDebounceId = null;
}
if (this._chatbotMonitorDebounceId) {
GLib.source_remove(this._chatbotMonitorDebounceId);
this._chatbotMonitorDebounceId = null;
}
if (this._preferencesMonitor) {
this._preferencesMonitor.cancel();
this._preferencesMonitor = null;
}
if (this._chatbotMonitor) {
this._chatbotMonitor.cancel();
this._chatbotMonitor = null;
}
}
_checkLowspec() {
try {
let cpuFile = Gio.File.new_for_path('/proc/cpuinfo');
let [cpuSuccess, cpuContents] = cpuFile.load_contents(null);
let cpuCores = 0;
if (cpuSuccess) {
let decoder = new TextDecoder('utf-8');
let cpuText = decoder.decode(cpuContents);
for (let line of cpuText.split('\n')) {
if (line.startsWith('processor'))
cpuCores++;
}
}
let memFile = Gio.File.new_for_path('/proc/meminfo');
let [memSuccess, memContents] = memFile.load_contents(null);
let ramMB = 0;
if (memSuccess) {
let decoder = new TextDecoder('utf-8');
let memText = decoder.decode(memContents);
for (let line of memText.split('\n')) {
if (line.startsWith('MemTotal')) {
let kB = parseInt(line.split(/\s+/)[1], 10);
ramMB = kB / 1024;
break;
}
}
}
let isLowspec = cpuCores < 3 || ramMB < 5000;
log(`Praya: Lowspec check: isLowspec=${isLowspec}, cpuCores=${cpuCores} vs 3, ramMB=${ramMB} vs 5000`);
return isLowspec;
} catch (e) {
log(`Praya: Error checking lowspec: ${e.message}`);
return false;
}
}
_scheduleLowspecCheck() {
log('Praya: Scheduling lowspec check in 10 seconds');
this._lowspecTimeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 10000, () => {
this._lowspecTimeoutId = null;
let isLowspec = this._checkLowspec();
let dismissed = this._servicesConfig.lowspecDismissed;
log(`Praya: Lowspec check: isLowspec=${isLowspec}, dismissed=${dismissed}`);
if (isLowspec && !dismissed) {
log('Praya: Launching lowspec dialog');
this._launchLowspecDialog();
}
return GLib.SOURCE_REMOVE;
});
}
_launchLowspecDialog() {
if (this._lowspecProc) return;
let scriptPath = GLib.build_filenamev([this.path, 'lowspec-dialog.py']);
try {
let launcher = new Gio.SubprocessLauncher({
flags: Gio.SubprocessFlags.STDERR_PIPE,
});
// Ensure display env vars are set for the subprocess
let waylandDisplay = GLib.getenv('WAYLAND_DISPLAY');
let display = GLib.getenv('DISPLAY');
let xdgRuntime = GLib.getenv('XDG_RUNTIME_DIR');
if (waylandDisplay) launcher.setenv('WAYLAND_DISPLAY', waylandDisplay, true);
if (display) launcher.setenv('DISPLAY', display, true);
if (xdgRuntime) launcher.setenv('XDG_RUNTIME_DIR', xdgRuntime, true);
launcher.setenv('GDK_BACKEND', waylandDisplay ? 'wayland' : 'x11', true);
// Ensure locale env vars are forwarded so gettext works
for (let v of ['LANG', 'LANGUAGE', 'LC_ALL', 'LC_MESSAGES']) {
let val = GLib.getenv(v);
if (val) launcher.setenv(v, val, true);
}
log(`Praya: Launching lowspec dialog: WAYLAND_DISPLAY=${waylandDisplay}, DISPLAY=${display}`);
this._lowspecProc = launcher.spawnv(['python3', scriptPath]);
this._lowspecProc.wait_async(null, (proc, result) => {
try {
proc.wait_finish(result);
let exitCode = proc.get_exit_status();
log(`Praya: Lowspec dialog exited with code ${exitCode}`);
// Write stderr to file for debugging
try {
let stderrStream = proc.get_stderr_pipe();
let stderrData = stderrStream.read_bytes(8192, null);
if (stderrData && stderrData.get_size() > 0) {
let decoder = new TextDecoder('utf-8');
let errText = decoder.decode(stderrData.get_data());
log(`Praya: Lowspec stderr: ${errText}`);
let errFile = Gio.File.new_for_path('/tmp/praya-lowspec-error.log');
errFile.replace_contents(errText, null, false, Gio.FileCreateFlags.NONE, null);
}
} catch (e) {
log(`Praya: Error reading lowspec stderr: ${e.message}`);
}
if (exitCode === 1) {
// Disable GNOME animations
try {
let ifaceSettings = new Gio.Settings({schema_id: 'org.gnome.desktop.interface'});
ifaceSettings.set_boolean('enable-animations', false);
} catch (e) {
log(`Praya: Error disabling animations: ${e.message}`);
}
// Disable tilingshell extension
try {
let shellSettings = new Gio.Settings({schema_id: 'org.gnome.shell'});
let tilingId = 'tilingshell@ferrarodomenico.com';
let enabled = shellSettings.get_strv('enabled-extensions');
enabled = enabled.filter(id => id !== tilingId);
shellSettings.set_strv('enabled-extensions', enabled);
let disabled = shellSettings.get_strv('disabled-extensions');
if (!disabled.includes(tilingId)) {
disabled.push(tilingId);
shellSettings.set_strv('disabled-extensions', disabled);
}
} catch (e) {
log(`Praya: Error disabling tilingshell: ${e.message}`);
}
// Update menu layout to list
this._servicesConfig.appMenuLayout = 'list';
this._servicesConfig.lowspecEnabled = true;
}
// Only mark as dismissed if user actually chose (0=Ignore, 1=Apply)
// Exit code 2 means crash/error — don't dismiss, try again next time
if (exitCode === 0 || exitCode === 1) {
this._servicesConfig.lowspecDismissed = true;
this._saveLowspecConfig();
}
} catch (e) {
log(`Praya: Error in lowspec dialog: ${e.message}`);
}
this._lowspecProc = null;
});
} catch (e) {
log(`Praya: Error launching lowspec dialog: ${e.message}`);
this._lowspecProc = null;
}
}
_saveLowspecConfig() {
let homeDir = GLib.get_home_dir();
let configDir = GLib.build_filenamev([homeDir, '.config', 'praya']);
let configPath = GLib.build_filenamev([configDir, 'services.json']);
try {
let dir = Gio.File.new_for_path(configDir);
if (!dir.query_exists(null)) {
dir.make_directory_with_parents(null);
}
let configFile = Gio.File.new_for_path(configPath);
let content = JSON.stringify(this._servicesConfig, null, 2) + '\n';
configFile.replace_contents(
content,
null,
false,
Gio.FileCreateFlags.NONE,
null
);
} catch (e) {
log(`Praya: Error saving services config: ${e.message}`);
}
}
_applyPanelPosition(position) {
this._panelPosition = position;
let monitor = Main.layoutManager.primaryMonitor;
if (!monitor) return;
let panelBox = Main.layoutManager.panelBox;
// Apply floating style via CSS (keeps panelBox struts correct)
if (this._servicesConfig.floatingPanel) {
Main.panel.add_style_class_name('praya-floating-panel');
} else {
Main.panel.remove_style_class_name('praya-floating-panel');
}
if (position === 'bottom') {
// Defer so panelBox.height reflects CSS margins after layout settles
if (this._panelPositionIdleId) {
GLib.source_remove(this._panelPositionIdleId);
}
this._panelPositionIdleId = GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this._panelPositionIdleId = null;
let m = Main.layoutManager.primaryMonitor;
if (m) {
panelBox.set_position(m.x, m.y + m.height - panelBox.height);
}
return GLib.SOURCE_REMOVE;
});
} else {
panelBox.set_position(monitor.x, monitor.y);
}
}
setPanelPosition(position) {
this._applyPanelPosition(position);
this._removeWorkAreaMargins();
this._setupWorkAreaMargins();
this._updateAllWindowsIconGeometry();
}
_setupWorkAreaMargins() {
if (!this._servicesConfig.floatingPanel) return;
let monitor = Main.layoutManager.primaryMonitor;
if (!monitor) return;
let margin = 5;
let isBottom = this._panelPosition === 'bottom';
this._marginStruts = [];
// Left edge strut
let leftStrut = new St.Widget({
x: monitor.x, y: monitor.y,
width: margin, height: monitor.height,
reactive: false,
});
Main.layoutManager.addTopChrome(leftStrut, { affectsStruts: true, affectsInputRegion: false });
this._marginStruts.push(leftStrut);
// Right edge strut
let rightStrut = new St.Widget({
x: monitor.x + monitor.width - margin, y: monitor.y,
width: margin, height: monitor.height,
reactive: false,
});
Main.layoutManager.addTopChrome(rightStrut, { affectsStruts: true, affectsInputRegion: false });
this._marginStruts.push(rightStrut);
// Opposite side of panel
if (isBottom) {
let topStrut = new St.Widget({
x: monitor.x, y: monitor.y,
width: monitor.width, height: margin,
reactive: false,
});
Main.layoutManager.addTopChrome(topStrut, { affectsStruts: true, affectsInputRegion: false });
this._marginStruts.push(topStrut);
} else {
let bottomStrut = new St.Widget({
x: monitor.x, y: monitor.y + monitor.height - margin,
width: monitor.width, height: margin,
reactive: false,
});
Main.layoutManager.addTopChrome(bottomStrut, { affectsStruts: true, affectsInputRegion: false });
this._marginStruts.push(bottomStrut);
}
}
_removeWorkAreaMargins() {
if (this._marginStruts) {
for (let strut of this._marginStruts) {
Main.layoutManager.removeChrome(strut);
strut.destroy();
}
this._marginStruts = null;
}
}
_setWindowIconGeometry(window) {
if (!window || window.get_window_type() !== Meta.WindowType.NORMAL)
return;
let monitor = Main.layoutManager.primaryMonitor;
if (!monitor) return;
let rect = new Mtk.Rectangle();
rect.x = monitor.x;
rect.width = Main.panel.width;
rect.height = Main.layoutManager.panelBox.height;
if (this._panelPosition === 'bottom') {
rect.y = monitor.y + monitor.height - rect.height;
} else {
rect.y = monitor.y;
}
window.set_icon_geometry(rect);
}
_updateAllWindowsIconGeometry() {
let windows = global.get_window_actors()
.map(a => a.meta_window);
for (let w of windows) {
this._setWindowIconGeometry(w);
}
}
_setupIconGeometryTracking() {
this._windowCreatedId = global.display.connect('window-created', (_display, window) => {
this._setWindowIconGeometry(window);
});
this._updateAllWindowsIconGeometry();
}
_removeIconGeometryTracking() {
if (this._windowCreatedId) {
global.display.disconnect(this._windowCreatedId);
this._windowCreatedId = null;
}
let windows = global.get_window_actors()
.map(a => a.meta_window);
for (let w of windows) {
if (w.get_window_type() === Meta.WindowType.NORMAL)
w.set_icon_geometry(null);
}
}
_startPrayaServices() {
// Import display environment variables into systemd user session
// immediately. Without this, apps launched via systemd scopes
// (which is how GNOME Shell launches apps) won't have
// WAYLAND_DISPLAY/DISPLAY and will fail to connect to the
// display server.
this._importEnvironment();
// Start praya systemd user service after a short delay
// to let import-environment complete first
this._startPrayaServiceTimeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 500, () => {
this._startPrayaServiceTimeoutId = null;
try {
Gio.Subprocess.new(
['systemctl', '--user', 'start', 'praya'],
Gio.SubprocessFlags.STDOUT_SILENCE | Gio.SubprocessFlags.STDERR_SILENCE
);
} catch (e) {
// Silent failure
}
return GLib.SOURCE_REMOVE;
});
// Enable feature services based on config
try {
let connection = Gio.bus_get_sync(Gio.BusType.SESSION, null);
// Enable posture service if configured
if (this._servicesConfig.posture) {
connection.call(
'com.github.blankon.praya',
'/com/github/blankon/Praya',
'com.github.blankon.Praya',
'EnableService',
new GLib.Variant('(s)', ['posture']),
null,
Gio.DBusCallFlags.NONE,
-1,
null,
(conn, result) => {
try {
conn.call_finish(result);
} catch (e) {
// Silent failure
}
}
);
}
// Enable AI service if configured
if (this._servicesConfig.ai) {
connection.call(
'com.github.blankon.praya',
'/com/github/blankon/Praya',
'com.github.blankon.Praya',
'EnableService',
new GLib.Variant('(s)', ['ai']),
null,
Gio.DBusCallFlags.NONE,
-1,
null,
(conn, result) => {
try {
conn.call_finish(result);
} catch (e) {
// Silent failure
}
}
);
}
} catch (e) {
// Silent failure
}
}
_importEnvironment() {
// Build the list of env vars to import
let envVars = ['WAYLAND_DISPLAY', 'DISPLAY', 'XDG_RUNTIME_DIR',
'XDG_SESSION_TYPE', 'XDG_CURRENT_DESKTOP'];
// Filter to only vars that are actually set in our process
let availableVars = envVars.filter(v => GLib.getenv(v) !== null);
if (availableVars.length === 0) {
// No display vars available yet - schedule a retry
this._importEnvRetries = 0;
this._importEnvTimeoutId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 1, () => {
this._importEnvRetries++;
if (this._importEnvRetries >= 30) {
this._importEnvTimeoutId = null;
return GLib.SOURCE_REMOVE;
}
let ready = envVars.some(v => GLib.getenv(v) !== null);
if (ready) {
this._doImportEnvironment(envVars.filter(v => GLib.getenv(v) !== null));
this._importEnvTimeoutId = null;
return GLib.SOURCE_REMOVE;
}
return GLib.SOURCE_CONTINUE;
});
return;
}
this._doImportEnvironment(availableVars);
}
_doImportEnvironment(vars) {
// Use systemctl import-environment
try {
let args = ['systemctl', '--user', 'import-environment', ...vars];
let proc = Gio.Subprocess.new(
args,
Gio.SubprocessFlags.STDOUT_SILENCE | Gio.SubprocessFlags.STDERR_SILENCE
);
// Wait async to ensure it completes
proc.wait_async(null, (proc, result) => {
try {
proc.wait_finish(result);
} catch (e) {
// Silent failure
}
});
} catch (e) {
// Silent failure
}
// Also update D-Bus activation environment for portal-launched apps
try {
let args = ['dbus-update-activation-environment', '--systemd', ...vars];
let proc = Gio.Subprocess.new(
args,
Gio.SubprocessFlags.STDOUT_SILENCE | Gio.SubprocessFlags.STDERR_SILENCE
);
proc.wait_async(null, (proc, result) => {
try {
proc.wait_finish(result);
} catch (e) {
// Silent failure
}
});
} catch (e) {
// Silent failure
}
}
_setupSuperKey() {
// Ensure the overlay-key is set to Super_L so that
// Super (not Alt) triggers the overview toggle.
this._mutterSettings = new Gio.Settings({schema_id: 'org.gnome.mutter'});
this._originalOverlayKey = this._mutterSettings.get_string('overlay-key');
this._mutterSettings.set_string('overlay-key', 'Super_L');
// Override the overview toggle so pressing the Super key
// opens the Praya panel instead of GNOME Activities Overview.
this._originalOverviewToggle = Main.overview.toggle.bind(Main.overview);
Main.overview.toggle = () => {
if (this._indicator) {
this._indicator._togglePanel();
}
};
// Setup Alt key tap to open GNOME workspace view (Activities Overview)
this._setupAltOverview();
}
_setupAltOverview() {
this._altTapState = null;
this._altCapturedEventId = global.stage.connect('captured-event', (actor, event) => {
let type = event.type();
if (type === Clutter.EventType.KEY_PRESS) {
let symbol = event.get_key_symbol();
if (symbol === Clutter.KEY_Alt_L || symbol === Clutter.KEY_Alt_R) {
if (!this._altTapState) {
this._altTapState = 'pressed';
}
} else {
// Another key was pressed, cancel Alt tap
this._altTapState = null;
}
} else if (type === Clutter.EventType.KEY_RELEASE) {
let symbol = event.get_key_symbol();
if ((symbol === Clutter.KEY_Alt_L || symbol === Clutter.KEY_Alt_R) &&
this._altTapState === 'pressed') {
this._altTapState = null;
// Open GNOME Activities Overview (workspace view)
if (this._originalOverviewToggle) {
this._originalOverviewToggle();
}
} else {
this._altTapState = null;
}
}
return Clutter.EVENT_PROPAGATE;
});
}
_removeAltOverview() {
if (this._altCapturedEventId) {
global.stage.disconnect(this._altCapturedEventId);
this._altCapturedEventId = null;
}
this._altTapState = null;
}
_restoreSuperKey() {
// Remove Alt overview handler
this._removeAltOverview();
// Restore original overlay-key
if (this._mutterSettings && this._originalOverlayKey !== undefined) {
this._mutterSettings.set_string('overlay-key', this._originalOverlayKey);
this._mutterSettings = null;
this._originalOverlayKey = undefined;
}
if (this._originalOverviewToggle) {
Main.overview.toggle = this._originalOverviewToggle;
this._originalOverviewToggle = null;
}
}
_setupKeybinding() {
// Grab the Super+Space accelerator
this._acceleratorAction = global.display.grab_accelerator('<Super>space', Meta.KeyBindingFlags.NONE);
// Disable GNOME's built-in switch-to-application-N bindings so we can grab Super+N
this._savedSwitchToApp = [];
let shellKeybindings = new Gio.Settings({ schema_id: 'org.gnome.shell.keybindings' });
for (let i = 1; i <= 9; i++) {
let key = `switch-to-application-${i}`;
this._savedSwitchToApp.push(shellKeybindings.get_strv(key));
shellKeybindings.set_strv(key, []);
}
// Grab Super+1 through Super+9 for taskbar window switching
this._numberAcceleratorActions = [];
for (let i = 1; i <= 9; i++) {
let action = global.display.grab_accelerator(`<Super>${i}`, Meta.KeyBindingFlags.NONE);
if (action !== Meta.KeyBindingAction.NONE) {
let name = Meta.external_binding_name_for_action(action);
Main.wm.allowKeybinding(name, Shell.ActionMode.ALL);
this._numberAcceleratorActions.push({ action, index: i - 1 });
}
}
if (this._acceleratorAction !== Meta.KeyBindingAction.NONE) {
let name = Meta.external_binding_name_for_action(this._acceleratorAction);
Main.wm.allowKeybinding(name, Shell.ActionMode.ALL);
}
this._acceleratorActivatedId = global.display.connect('accelerator-activated', (display, action) => {
if (action === this._acceleratorAction) {
if (this._indicator) {
this._indicator._togglePanel();
}
return;
}
// Check Super+number actions
for (let entry of this._numberAcceleratorActions) {
if (action === entry.action) {
this._activateTaskbarWindow(entry.index);
return;
}
}
});
}
_activateTaskbarWindow(index) {
if (!this._taskbar) return;
let windows = this._taskbar.getWindows();
if (index < windows.length) {
let window = windows[index];
if (window.minimized)
window.unminimize();
window.activate(global.get_current_time());
}
}
_removeKeybinding() {
if (this._acceleratorActivatedId) {
global.display.disconnect(this._acceleratorActivatedId);