forked from nick-redwill/LiveLockScreen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
5011 lines (4513 loc) · 217 KB
/
extension.js
File metadata and controls
5011 lines (4513 loc) · 217 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
import * as Main from 'resource:///org/gnome/shell/ui/main.js';
import * as LoginManager from 'resource:///org/gnome/shell/misc/loginManager.js';
import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js';
import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js';
import {Extension, InjectionManager} from 'resource:///org/gnome/shell/extensions/extension.js';
import St from 'gi://St';
import Gst from 'gi://Gst';
import Shell from 'gi://Shell';
import Clutter from 'gi://Clutter';
import Cogl from 'gi://Cogl';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import GstPbutils from 'gi://GstPbutils';
import Meta from 'gi://Meta';
import Pipeline from './core/pipeline.js';
import { PlayerProcess } from './core/player_process.js';
import { Keys, PauseWhenHiddenMode, VideoRenderer, ScalingMode } from "./enums.js";
import { setImageData } from './utils/set_image_data.js';
import { isGtk4PaintableSinkAvailable } from './utils/check_dependencies.js';
import { sendErrorNotification } from './utils/notifications.js';
import { createActor } from './core/scalers.js';
export default class LockscreenExtension extends Extension {
enable() {
const mode = Main.sessionMode.currentMode;
console.log(`[LiveLockPaper] enable() called, sessionMode=${mode}`);
// Cancel any pending teardown from a previous disable()
if (this._deferredTeardownId) {
GLib.Source.remove(this._deferredTeardownId);
this._deferredTeardownId = null;
}
// Cancel any pending init from a previous enable() (debounce)
if (this._deferredInitId) {
GLib.Source.remove(this._deferredInitId);
this._deferredInitId = null;
}
// Cancel any pending idle activation from a previous init
if (this._deferredActivateId) {
GLib.Source.remove(this._deferredActivateId);
this._deferredActivateId = null;
}
// Cancel any pending startup-complete listener
if (this._startupCompleteId) {
Main.layoutManager.disconnect(this._startupCompleteId);
this._startupCompleteId = null;
}
this._active = true;
const gstReady = Gst.is_initialized();
if (!gstReady && Main.layoutManager._startingUp) {
// On fresh boot, wait for startup-complete before heavy init.
console.log('[LiveLockPaper] Session starting up, waiting for startup-complete signal…');
this._startupCompleteId = Main.layoutManager.connect('startup-complete', () => {
Main.layoutManager.disconnect(this._startupCompleteId);
this._startupCompleteId = null;
if (!this._active) return;
console.log('[LiveLockPaper] startup-complete received, scheduling init in 500ms');
// Small buffer after startup-complete for VA-API/PipeWire to settle
this._deferredInitId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 500, () => {
this._deferredInitId = null;
if (!this._active) return GLib.SOURCE_REMOVE;
this._deferredInit();
return GLib.SOURCE_REMOVE;
});
});
} else {
// Normal path for lock/unlock or mid-session toggles.
const delay = gstReady ? 250 : 500;
this._deferredInitId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, delay, () => {
this._deferredInitId = null;
if (!this._active) return GLib.SOURCE_REMOVE;
this._deferredInit();
return GLib.SOURCE_REMOVE;
});
console.log(`[LiveLockPaper] Init scheduled in ${delay}ms (gstReady=${gstReady})`);
}
}
disable() {
const mode = Main.sessionMode.currentMode;
console.log(`[LiveLockPaper] disable() called, sessionMode=${mode}`);
this._active = false;
// Cancel pending deferred init (the main debounce mechanism)
if (this._deferredInitId) {
GLib.Source.remove(this._deferredInitId);
this._deferredInitId = null;
}
// Cancel pending idle activation
if (this._deferredActivateId) {
GLib.Source.remove(this._deferredActivateId);
this._deferredActivateId = null;
}
// Cancel pending startup-complete listener
if (this._startupCompleteId) {
Main.layoutManager.disconnect(this._startupCompleteId);
this._startupCompleteId = null;
}
// Cancel pending deferred teardown from a PREVIOUS disable
if (this._deferredTeardownId) {
GLib.Source.remove(this._deferredTeardownId);
this._deferredTeardownId = null;
}
// Defer teardown — if enable() is called within 350ms, cancel teardown
this._deferredTeardownId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 350, () => {
this._deferredTeardownId = null;
if (this._active) return GLib.SOURCE_REMOVE; // re-enabled, skip
console.log('[LiveLockPaper] Deferred teardown running (extension truly disabled)');
this._fullTeardown();
return GLib.SOURCE_REMOVE;
});
}
// One-time init + mode activation.
_deferredInit() {
try {
// Cancel any pending activation from a previous init
if (this._deferredActivateId) {
GLib.Source.remove(this._deferredActivateId);
this._deferredActivateId = null;
}
console.log('[LiveLockPaper] diagnostics build active: snapshot-v1');
if (!Gst.is_initialized()) {
console.log('[LiveLockPaper] Initializing GStreamer…');
if (!Gst.init_check([])[0]) {
console.error('[LiveLockPaper] Failed to initialize GStreamer');
return;
}
console.log('[LiveLockPaper] GStreamer initialized ✓');
}
if (!this._settings) {
this._settings = this.getSettings();
}
this._maybeMigrateVideoRendererSetting();
this._syncKeepAwakeHooks();
if (!this._panelVisibilityChangedId) {
this._panelVisibilityChangedId = this._settings.connect(
`changed::${Keys.DEBUG_SHOW_PANEL_BUTTON}`,
() => {
this._ensureStatusIndicator();
this._syncStatusIndicator();
}
);
}
if (!this._lockRuntimeSettingIds) {
this._lockRuntimeSettingIds = [];
this._lockRuntimeSettingIds.push(
this._settings.connect(`changed::${Keys.LOCKSCREEN_ENABLED}`, () => {
this._onLockRuntimeSettingChanged();
})
);
this._lockRuntimeSettingIds.push(
this._settings.connect(`changed::${Keys.VIDEO_RENDERER}`, () => {
this._onLockRuntimeSettingChanged();
})
);
}
if (!this._lockTextSettingIds) {
this._lockTextSettingIds = [];
const textKeys = [
Keys.LOCKSCREEN_TEXT_CUSTOMIZE_ENABLED,
Keys.LOCKSCREEN_TEXT_HIDE_CMD,
Keys.LOCKSCREEN_TEXT_HIDE_TIME,
Keys.LOCKSCREEN_TEXT_HIDE_DATE,
Keys.LOCKSCREEN_TEXT_HIDE_HINT,
Keys.LOCKSCREEN_TEXT_CMD_SIZE,
Keys.LOCKSCREEN_TEXT_TIME_SIZE,
Keys.LOCKSCREEN_TEXT_DATE_SIZE,
Keys.LOCKSCREEN_TEXT_HINT_SIZE,
Keys.LOCKSCREEN_TEXT_CMD_COLOR,
Keys.LOCKSCREEN_TEXT_TIME_COLOR,
Keys.LOCKSCREEN_TEXT_DATE_COLOR,
Keys.LOCKSCREEN_TEXT_HINT_COLOR,
Keys.LOCKSCREEN_TEXT_CMD_FONT,
Keys.LOCKSCREEN_TEXT_TIME_FONT,
Keys.LOCKSCREEN_TEXT_DATE_FONT,
Keys.LOCKSCREEN_TEXT_HINT_FONT,
Keys.LOCKSCREEN_TEXT_CMD_WEIGHT,
Keys.LOCKSCREEN_TEXT_TIME_WEIGHT,
Keys.LOCKSCREEN_TEXT_DATE_WEIGHT,
Keys.LOCKSCREEN_TEXT_HINT_WEIGHT,
Keys.LOCKSCREEN_TEXT_CMD_STYLE,
Keys.LOCKSCREEN_TEXT_TIME_STYLE,
Keys.LOCKSCREEN_TEXT_DATE_STYLE,
Keys.LOCKSCREEN_TEXT_HINT_STYLE,
Keys.LOCKSCREEN_TEXT_CMD_COMMAND,
Keys.LOCKSCREEN_TEXT_TIME_FORMAT,
Keys.LOCKSCREEN_TEXT_DATE_FORMAT,
Keys.LOCKSCREEN_KEEP_AWAKE_ENABLED,
Keys.LOCKSCREEN_KEEP_AWAKE_TIMEOUT_SECONDS,
Keys.LOCKSCREEN_KEEP_AWAKE_ONLY_ON_AC,
];
for (const key of textKeys) {
this._lockTextSettingIds.push(
this._settings.connect(`changed::${key}`, () => this._onLockTextSettingsChanged())
);
}
}
this._ensureStatusIndicator();
// Check gtk4paintablesink availability (one-time)
if (this._gtk4SinkAvailable === undefined) {
this._gtk4SinkAvailable = isGtk4PaintableSinkAvailable();
console.log(`[LiveLockPaper] gtk4paintablesink available: ${this._gtk4SinkAvailable}`);
}
this._mpvProgram = GLib.find_program_in_path('mpv') || '';
console.log(`[LiveLockPaper] mpv in PATH: ${!!this._mpvProgram}`);
if (!this._mpvPathRefreshId) {
this._mpvPathRefreshId = this._settings.connect(`changed::${Keys.VIDEO_RENDERER}`, () => {
this._mpvProgram = GLib.find_program_in_path('mpv') || '';
});
}
// Connect session-mode handler ONCE (idempotent)
if (!this._sessionModeChangedId) {
this._sessionModeChangedId = Main.sessionMode.connect('updated', () => {
this._onSessionModeChanged();
});
}
// Defer activation to idle so compositor work settles first.
const mode = Main.sessionMode.currentMode;
console.log(`[LiveLockPaper] Deferred init complete, scheduling activation for: ${mode}`);
this._deferredActivateId = GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this._deferredActivateId = null;
if (!this._active) return GLib.SOURCE_REMOVE;
const currentMode = Main.sessionMode.currentMode;
console.log(`[LiveLockPaper] Idle activation firing for: ${currentMode}`);
try {
this._activateForMode(currentMode);
} catch (e) {
console.error(`[LiveLockPaper] Activation failed: ${e.message}\n${e.stack}`);
}
return GLib.SOURCE_REMOVE;
});
} catch (e) {
console.error(`[LiveLockPaper] _deferredInit failed: ${e.message}\n${e.stack}`);
}
}
// Full teardown when extension is truly disabled.
_fullTeardown() {
try {
if (this._sessionModeChangedId) {
Main.sessionMode.disconnect(this._sessionModeChangedId);
this._sessionModeChangedId = null;
}
if (this._startupCompleteId) {
Main.layoutManager.disconnect(this._startupCompleteId);
this._startupCompleteId = null;
}
if (this._deferredInitId) {
GLib.Source.remove(this._deferredInitId);
this._deferredInitId = null;
}
if (this._deferredActivateId) {
GLib.Source.remove(this._deferredActivateId);
this._deferredActivateId = null;
}
if (this._deferredTeardownId) {
GLib.Source.remove(this._deferredTeardownId);
this._deferredTeardownId = null;
}
this._disableLockScreen();
this._disableWallpaper();
this._cleanupPauseWhenHidden();
this._destroyStatusIndicator();
if (this._panelVisibilityChangedId && this._settings) {
try { this._settings.disconnect(this._panelVisibilityChangedId); } catch (_) {}
this._panelVisibilityChangedId = null;
}
if (this._mpvPathRefreshId && this._settings) {
try { this._settings.disconnect(this._mpvPathRefreshId); } catch (_) {}
this._mpvPathRefreshId = null;
}
if (this._lockRuntimeSettingIds && this._settings) {
for (const id of this._lockRuntimeSettingIds) {
try { this._settings.disconnect(id); } catch (_) {}
}
this._lockRuntimeSettingIds = [];
}
if (this._lockTextSettingIds && this._settings) {
for (const id of this._lockTextSettingIds) {
try { this._settings.disconnect(id); } catch (_) {}
}
this._lockTextSettingIds = [];
}
this._removeKeepAwakeHooks();
this._clearLockTextCommandState();
this._stopAllPlayCountTracking();
this._currentActivatedMode = null;
this._settings = null;
} catch (e) {
console.error(`[LiveLockPaper] _fullTeardown failed: ${e.message}\n${e.stack}`);
}
}
// Handle session-mode transitions (user <-> unlock-dialog).
_onSessionModeChanged() {
const mode = Main.sessionMode.currentMode;
if (mode === this._currentActivatedMode) return; // no real change
// If deferred init is pending, let it handle activation.
if (this._deferredInitId) {
console.log(`[LiveLockPaper] Session mode → ${mode} (deferred init pending, will handle)`);
return;
}
// Cancel pending deferred activation and handle the new mode now.
if (this._deferredActivateId) {
GLib.Source.remove(this._deferredActivateId);
this._deferredActivateId = null;
}
console.log(`[LiveLockPaper] Session mode changed → ${mode}`);
try {
this._activateForMode(mode);
} catch (e) {
console.error(`[LiveLockPaper] _onSessionModeChanged crashed: ${e.message}\n${e.stack}`);
}
}
// Activate features for the current session mode.
_activateForMode(mode) {
if (mode === this._currentActivatedMode) {
console.log(`[LiveLockPaper] Already active for ${mode}, skipping`);
return;
}
if (mode === 'unlock-dialog') {
// Lock screen: pause wallpaper and set up lock video.
const lockscreenEnabled = this._settings?.get_boolean(Keys.LOCKSCREEN_ENABLED) ?? true;
console.log(`[LiveLockPaper] → pausing wallpaper, lock screen video ${lockscreenEnabled ? 'enabled' : 'disabled'}`);
this._currentActivatedMode = mode;
this._pauseWallpaper();
if (lockscreenEnabled)
this._enableLockScreen();
else {
this._disableLockScreen();
// Keep lockscreen text customization independent from lockscreen video enablement.
this._applyLockscreenTextCustomization();
this._restartKeepAwakeTimerIfNeeded();
}
} else if (mode === 'user') {
// Desktop — tear down lock screen, resume wallpaper
console.log('[LiveLockPaper] → tearing down lock screen, resuming wallpaper');
this._currentActivatedMode = mode;
this._disableLockScreen();
this._clearKeepAwakeTimer();
this._resumeWallpaper();
}
this._syncStatusIndicator();
}
_maybeMigrateVideoRendererSetting() {
if (!this._settings)
return;
try {
const ur = this._settings.get_user_value(Keys.VIDEO_RENDERER);
if (ur != null)
return;
const ug = this._settings.get_user_value(Keys.DEBUG_USE_GTK4_SINK);
if (ug == null)
return;
const legacy = ug.unpack();
this._settings.set_int(Keys.VIDEO_RENDERER, legacy ? VideoRenderer.APPSINK : VideoRenderer.GTK4);
} catch (e) {
console.warn(`[LiveLockPaper] video-renderer migration skipped: ${e.message}`);
}
}
/** Resolved renderer after availability checks (may differ from Settings when mpv/GTK4 missing). */
_effectiveVideoRenderer() {
if (!this._settings)
return VideoRenderer.APPSINK;
let m = VideoRenderer.GTK4;
try {
m = this._settings.get_int(Keys.VIDEO_RENDERER);
} catch (e) {}
if (!Number.isFinite(m) || m < 0 || m > 2)
m = VideoRenderer.GTK4;
if (m === VideoRenderer.MPV) {
if (!this._mpvProgram) {
console.warn('[LiveLockPaper] mpv not found in PATH; falling back');
if (!this._mpvMissingNotified) {
this._mpvMissingNotified = true;
sendErrorNotification(
'mpv was not found in PATH.\nInstall mpv or choose another renderer in Settings → Diagnostics.',
);
}
m = VideoRenderer.GTK4;
}
}
if (m === VideoRenderer.GTK4) {
if (!this._gtk4SinkAvailable) {
console.warn('[LiveLockPaper] gtk4paintablesink not available, falling back to appsink');
if (!this._gtk4MissingNotified) {
this._gtk4MissingNotified = true;
sendErrorNotification(
'gtk4paintablesink is not installed.\n' +
'Install gstreamer-plugin-gtk4 (or gstreamer1.0-gtk4 on Debian/Ubuntu), ' +
'or use the mpv / legacy appsink renderer in Settings.',
);
}
m = VideoRenderer.APPSINK;
}
}
return m;
}
_subprocessPlayerPath() {
return this._effectiveVideoRenderer() === VideoRenderer.MPV
? `${this.path}/external/mpv_run.js`
: `${this.path}/external/run.js`;
}
/** True when wallpaper/lock should use an external helper (GTK4 or mpv), not in-process appsink. */
_shouldUseGtk4Sink() {
if (!this._settings) return false;
const m = this._effectiveVideoRenderer();
return m === VideoRenderer.GTK4 || m === VideoRenderer.MPV;
}
_onLockRuntimeSettingChanged() {
this._syncStatusIndicator();
if (Main.sessionMode.currentMode !== 'unlock-dialog')
return;
this._disableLockScreen();
if (this._settings?.get_boolean(Keys.LOCKSCREEN_ENABLED))
this._enableLockScreen();
else {
// Runtime lockscreen video disable should not disable text customization.
this._applyLockscreenTextCustomization();
this._restartKeepAwakeTimerIfNeeded();
}
}
_onLockTextSettingsChanged() {
this._syncKeepAwakeHooks();
if (Main.sessionMode.currentMode !== 'unlock-dialog')
return;
this._applyLockscreenTextCustomization();
this._restartKeepAwakeTimerIfNeeded();
}
_getLockscreenTextSettings() {
return {
enabled: this._settings.get_boolean(Keys.LOCKSCREEN_TEXT_CUSTOMIZE_ENABLED),
hideCmd: this._settings.get_boolean(Keys.LOCKSCREEN_TEXT_HIDE_CMD),
hideTime: this._settings.get_boolean(Keys.LOCKSCREEN_TEXT_HIDE_TIME),
hideDate: this._settings.get_boolean(Keys.LOCKSCREEN_TEXT_HIDE_DATE),
hideHint: this._settings.get_boolean(Keys.LOCKSCREEN_TEXT_HIDE_HINT),
cmdSize: this._settings.get_int(Keys.LOCKSCREEN_TEXT_CMD_SIZE),
timeSize: this._settings.get_int(Keys.LOCKSCREEN_TEXT_TIME_SIZE),
dateSize: this._settings.get_int(Keys.LOCKSCREEN_TEXT_DATE_SIZE),
hintSize: this._settings.get_int(Keys.LOCKSCREEN_TEXT_HINT_SIZE),
cmdColor: this._settings.get_string(Keys.LOCKSCREEN_TEXT_CMD_COLOR),
timeColor: this._settings.get_string(Keys.LOCKSCREEN_TEXT_TIME_COLOR),
dateColor: this._settings.get_string(Keys.LOCKSCREEN_TEXT_DATE_COLOR),
hintColor: this._settings.get_string(Keys.LOCKSCREEN_TEXT_HINT_COLOR),
cmdFont: this._settings.get_string(Keys.LOCKSCREEN_TEXT_CMD_FONT).trim(),
timeFont: this._settings.get_string(Keys.LOCKSCREEN_TEXT_TIME_FONT).trim(),
dateFont: this._settings.get_string(Keys.LOCKSCREEN_TEXT_DATE_FONT).trim(),
hintFont: this._settings.get_string(Keys.LOCKSCREEN_TEXT_HINT_FONT).trim(),
cmdWeight: this._settings.get_string(Keys.LOCKSCREEN_TEXT_CMD_WEIGHT).trim(),
timeWeight: this._settings.get_string(Keys.LOCKSCREEN_TEXT_TIME_WEIGHT).trim(),
dateWeight: this._settings.get_string(Keys.LOCKSCREEN_TEXT_DATE_WEIGHT).trim(),
hintWeight: this._settings.get_string(Keys.LOCKSCREEN_TEXT_HINT_WEIGHT).trim(),
cmdStyle: this._settings.get_string(Keys.LOCKSCREEN_TEXT_CMD_STYLE).trim(),
timeStyle: this._settings.get_string(Keys.LOCKSCREEN_TEXT_TIME_STYLE).trim(),
dateStyle: this._settings.get_string(Keys.LOCKSCREEN_TEXT_DATE_STYLE).trim(),
hintStyle: this._settings.get_string(Keys.LOCKSCREEN_TEXT_HINT_STYLE).trim(),
cmdCommand: this._settings.get_string(Keys.LOCKSCREEN_TEXT_CMD_COMMAND).trim(),
timeFormat: this._settings.get_string(Keys.LOCKSCREEN_TEXT_TIME_FORMAT).trim(),
dateFormat: this._settings.get_string(Keys.LOCKSCREEN_TEXT_DATE_FORMAT).trim(),
};
}
_findActorByStyleClass(root, className) {
if (!root)
return null;
if (typeof root.has_style_class_name === 'function' && root.has_style_class_name(className))
return root;
if (typeof root.get_children !== 'function')
return null;
for (const child of root.get_children()) {
const found = this._findActorByStyleClass(child, className);
if (found)
return found;
}
return null;
}
_ensureCmdOutputLabel(clock) {
if (!clock)
return null;
if (this._lockTextCmdLabel && this._lockTextCmdLabel.get_parent()) {
this._lockTextCmdLabel.remove_style_class_name?.('screen-shield-hint-label');
this._lockTextCmdLabel.add_style_class_name?.('live-lockpaper-cmd-label');
return this._lockTextCmdLabel;
}
const container = clock._box ?? clock;
if (!container || typeof container.insert_child_at_index !== 'function')
return null;
const label = new St.Label({
style_class: 'live-lockpaper-cmd-label',
x_align: Clutter.ActorAlign.CENTER,
});
container.insert_child_at_index(label, 0);
this._lockTextCmdLabel = label;
return label;
}
_clearLockTextTimer() {
if (this._lockTextRefreshId) {
GLib.Source.remove(this._lockTextRefreshId);
this._lockTextRefreshId = null;
}
this._clearLockTextLabelHooks();
}
_clearLockTextLabelHooks() {
if (!this._lockTextLabelHookIds)
return;
for (const [label, id] of this._lockTextLabelHookIds) {
try {
if (label && id)
label.disconnect(id);
} catch (_) {}
}
this._lockTextLabelHookIds = null;
}
_clearLockTextCommandState() {
if (this._lockTextCommandTimeoutIds) {
for (const id of this._lockTextCommandTimeoutIds.values())
GLib.Source.remove(id);
this._lockTextCommandTimeoutIds.clear();
}
this._lockTextPendingCommands?.clear();
this._lockTextCommandState = {};
}
_formatNow(formatString, fallbackText) {
if (!formatString)
return fallbackText;
try {
return GLib.DateTime.new_now_local().format(formatString) ?? fallbackText;
} catch (_) {
return fallbackText;
}
}
_buildLockTextStyle(sizePx, color, fontFamily, fontWeight, fontStyle) {
const parts = [`font-size: ${sizePx}px`, `color: ${color}`];
if (fontFamily)
parts.push(`font-family: "${fontFamily.replace(/"/g, '\\"')}"`);
if (fontWeight)
parts.push(`font-weight: ${fontWeight}`);
if (fontStyle)
parts.push(`font-style: ${fontStyle}`);
return `${parts.join('; ')};`;
}
_runLockTextCommand(kind, command, label, options = {}) {
if (!command || !label)
return;
if (!this._lockTextPendingCommands)
this._lockTextPendingCommands = new Set();
if (!this._lockTextCommandTimeoutIds)
this._lockTextCommandTimeoutIds = new Map();
if (!this._lockTextCommandState)
this._lockTextCommandState = {};
if (!this._lockTextCommandState[kind])
this._lockTextCommandState[kind] = {lastOutput: '', pauseUntilMs: 0, lastHour: -1};
const state = this._lockTextCommandState[kind];
// Check if hour changed - force refresh for time-sensitive commands
const now = GLib.DateTime.new_now_local();
const currentHour = now.get_hour();
const hourChanged = state.lastHour !== -1 && state.lastHour !== currentHour;
if (hourChanged)
state.pauseUntilMs = 0; // Force refresh on hour change
if (this._lockTextPendingCommands.has(kind)) {
// If hour changed and command is running, cancel it to restart with new hour
if (hourChanged && this._lockTextCommandTimeoutIds.has(kind)) {
const timeoutId = this._lockTextCommandTimeoutIds.get(kind);
GLib.Source.remove(timeoutId);
this._lockTextCommandTimeoutIds.delete(kind);
this._lockTextPendingCommands.delete(kind);
} else {
return;
}
}
if ((options.pauseWhenUnchanged ?? false) && Date.now() < state.pauseUntilMs)
return;
this._lockTextPendingCommands.add(kind);
try {
const proc = Gio.Subprocess.new(
['/bin/sh', '-c', command],
Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_PIPE
);
const timeoutMs = Math.max(100, options.timeoutMs ?? 1500);
const timeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, timeoutMs, () => {
try { proc.force_exit(); } catch (_) {}
this._lockTextCommandTimeoutIds?.delete(kind);
return GLib.SOURCE_REMOVE;
});
this._lockTextCommandTimeoutIds.set(kind, timeoutId);
proc.communicate_utf8_async(null, null, (p, res) => {
this._lockTextPendingCommands?.delete(kind);
if (this._lockTextCommandTimeoutIds?.has(kind)) {
GLib.Source.remove(this._lockTextCommandTimeoutIds.get(kind));
this._lockTextCommandTimeoutIds.delete(kind);
}
try {
const [, stdout] = p.communicate_utf8_finish(res);
let output = stdout ?? '';
if (options.trimOutput ?? true)
output = output.trim();
if ((options.maxLength ?? 256) > 0 && output.length > options.maxLength)
output = output.slice(0, options.maxLength);
if ((options.pauseWhenUnchanged ?? false) && output === state.lastOutput) {
state.pauseUntilMs = Date.now() + Math.max(1, options.unchangedBackoffSeconds ?? 15) * 1000;
} else {
state.pauseUntilMs = 0;
}
state.lastOutput = output;
// Track current hour for detecting hour changes
const now = GLib.DateTime.new_now_local();
state.lastHour = now.get_hour();
if (Main.sessionMode.currentMode === 'unlock-dialog' && label.visible)
label.text = output;
} catch (_) {}
});
} catch (_) {
this._lockTextPendingCommands.delete(kind);
if (this._lockTextCommandTimeoutIds?.has(kind)) {
GLib.Source.remove(this._lockTextCommandTimeoutIds.get(kind));
this._lockTextCommandTimeoutIds.delete(kind);
}
}
}
_applyLockscreenTextCustomization() {
const dialog = Main.screenShield?._dialog;
if (!dialog)
return;
const clock = dialog._clock ?? null;
const timeLabel = clock?._time ?? this._findActorByStyleClass(dialog, 'screen-shield-clock-time');
const dateLabel = clock?._date ?? this._findActorByStyleClass(dialog, 'screen-shield-clock-date');
const cmdLabel = this._ensureCmdOutputLabel(clock);
const hintLabel =
this._findActorByStyleClass(dialog, 'screen-shield-hint-label')
|| this._findActorByStyleClass(dialog, 'screen-shield-hint-text')
|| this._findActorByStyleClass(dialog, 'screen-shield-hint')
|| (clock?._hint ?? null);
if (!cmdLabel && !timeLabel && !dateLabel && !hintLabel)
return;
const cfg = this._getLockscreenTextSettings();
if (!cfg.enabled) {
if (cmdLabel) {
cmdLabel.set_style('');
cmdLabel.visible = false;
cmdLabel.text = '';
}
if (timeLabel) timeLabel.set_style('');
if (dateLabel) dateLabel.set_style('');
if (hintLabel) {
hintLabel.set_style('');
hintLabel.visible = true;
}
this._clearLockTextTimer();
this._clearLockTextCommandState();
return;
}
if (cmdLabel) {
cmdLabel.set_style(this._buildLockTextStyle(cfg.cmdSize, cfg.cmdColor, cfg.cmdFont, cfg.cmdWeight, cfg.cmdStyle));
cmdLabel.visible = !cfg.hideCmd && cfg.cmdCommand.length > 0;
if (!cfg.cmdCommand.length)
cmdLabel.text = '';
}
if (timeLabel)
timeLabel.set_style(this._buildLockTextStyle(cfg.timeSize, cfg.timeColor, cfg.timeFont, cfg.timeWeight, cfg.timeStyle));
if (dateLabel)
dateLabel.set_style(this._buildLockTextStyle(cfg.dateSize, cfg.dateColor, cfg.dateFont, cfg.dateWeight, cfg.dateStyle));
if (timeLabel)
timeLabel.visible = !cfg.hideTime;
if (dateLabel)
dateLabel.visible = !cfg.hideDate;
if (hintLabel) {
hintLabel.set_style(this._buildLockTextStyle(cfg.hintSize, cfg.hintColor, cfg.hintFont, cfg.hintWeight, cfg.hintStyle));
hintLabel.visible = !cfg.hideHint;
}
const needsCustomFormat = cfg.timeFormat.length > 0 || cfg.dateFormat.length > 0;
const needsCommandOutput = cfg.cmdCommand.length > 0;
this._clearLockTextTimer();
if (!needsCustomFormat && !needsCommandOutput)
return;
this._lockTextLabelHookIds = [];
const attachFormatHook = (label, format) => {
if (!label || !format)
return;
let applying = false;
const id = label.connect('notify::text', () => {
if (applying || Main.sessionMode.currentMode !== 'unlock-dialog')
return;
const expected = this._formatNow(format, '');
if (!expected || label.text === expected)
return;
applying = true;
label.text = expected;
applying = false;
});
this._lockTextLabelHookIds.push([label, id]);
};
attachFormatHook(timeLabel, cfg.timeFormat);
attachFormatHook(dateLabel, cfg.dateFormat);
const refresh = () => {
if (Main.sessionMode.currentMode !== 'unlock-dialog')
return GLib.SOURCE_CONTINUE;
// Always format with current time - never use fallback that might be missing seconds
if (timeLabel && cfg.timeFormat) {
const formatted = this._formatNow(cfg.timeFormat, '');
if (formatted) timeLabel.text = formatted;
}
if (dateLabel && cfg.dateFormat) {
const formatted = this._formatNow(cfg.dateFormat, '');
if (formatted) dateLabel.text = formatted;
}
const cmdOptions = {
timeoutMs: 1500,
trimOutput: true,
maxLength: 256,
pauseWhenUnchanged: true,
unchangedBackoffSeconds: 15,
};
if (cmdLabel && cfg.cmdCommand && cmdLabel.visible) {
// Force refresh on minute 0 to catch hour changes immediately
const now = GLib.DateTime.new_now_local();
const currentMinute = now.get_minute();
if (currentMinute === 0) {
// At top of hour, reduce pause to ensure we catch hour changes
cmdOptions.unchangedBackoffSeconds = 1;
}
this._runLockTextCommand('cmd', cfg.cmdCommand, cmdLabel, cmdOptions);
}
return GLib.SOURCE_CONTINUE;
};
// Keep a low-frequency refresh for command output/date rollover; label hooks handle immediate rewrites.
refresh(); // Initial update
this._lockTextRefreshId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 1, refresh);
}
_pokeLockscreen() {
const shield = Main.screenShield;
try {
if (typeof shield?._wakeUpScreen === 'function')
shield._wakeUpScreen();
else if (typeof shield?.wakeUpScreen === 'function')
shield.wakeUpScreen();
} catch (_) {}
}
_isKeepAwakeEnabledNow() {
if (!this._settings)
return false;
if (!this._settings.get_boolean(Keys.LOCKSCREEN_KEEP_AWAKE_ENABLED))
return false;
if (this._settings.get_boolean(Keys.LOCKSCREEN_KEEP_AWAKE_ONLY_ON_AC) && this._isOnBattery())
return false;
return true;
}
_syncKeepAwakeHooks() {
if (this._isKeepAwakeEnabledNow())
this._installKeepAwakeHooks();
else
this._removeKeepAwakeHooks();
}
_installKeepAwakeHooks() {
if (this._keepAwakeHooksInstalled)
return;
const shield = Main.screenShield;
if (!shield || typeof shield._setActive !== 'function')
return;
this._keepAwakeHooksInstalled = true;
this._keepAwakeActiveOnce = false;
this._screenShieldSetActiveOriginal = shield._setActive;
shield._setActive = active => this._keepAwakeSetActive(shield, active);
}
_removeKeepAwakeHooks() {
if (!this._keepAwakeHooksInstalled)
return;
const shield = Main.screenShield;
if (shield && this._screenShieldSetActiveOriginal)
shield._setActive = this._screenShieldSetActiveOriginal;
this._screenShieldSetActiveOriginal = null;
this._keepAwakeHooksInstalled = false;
this._keepAwakeActiveOnce = false;
}
_keepAwakeSetActive(shield, active) {
const wasActive = shield._isActive;
shield._isActive = active;
if (wasActive !== shield._isActive) {
if (!this._isKeepAwakeEnabledNow() || this._keepAwakeActiveOnce) {
shield.emit('active-changed');
this._keepAwakeActiveOnce = false;
}
}
if (active) {
this._startKeepAwakeTimerIfNeeded();
} else {
this._clearKeepAwakeTimer();
}
if (shield._loginSession)
shield._loginSession.SetLockedHintRemote(active);
shield._syncInhibitor();
}
_clearKeepAwakeTimer() {
if (this._lockKeepAwakePulseId) {
GLib.Source.remove(this._lockKeepAwakePulseId);
this._lockKeepAwakePulseId = null;
}
if (this._lockKeepAwakeTimeoutId) {
GLib.Source.remove(this._lockKeepAwakeTimeoutId);
this._lockKeepAwakeTimeoutId = null;
}
}
_startKeepAwakeTimerIfNeeded() {
this._clearKeepAwakeTimer();
if (!this._settings)
return;
if (Main.sessionMode.currentMode !== 'unlock-dialog')
return;
if (!this._isKeepAwakeEnabledNow())
return;
// Keep lock screen visible while timer is active.
this._pokeLockscreen();
this._lockKeepAwakePulseId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 15, () => {
if (Main.sessionMode.currentMode !== 'unlock-dialog')
return GLib.SOURCE_REMOVE;
this._pokeLockscreen();
return GLib.SOURCE_CONTINUE;
});
GLib.Source.set_name_by_id(this._lockKeepAwakePulseId, '[livelockpaper] lock-keep-awake-pulse');
const timeout = Math.max(0, this._settings.get_int(Keys.LOCKSCREEN_KEEP_AWAKE_TIMEOUT_SECONDS));
if (timeout > 0) {
this._lockKeepAwakeTimeoutId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, timeout, () => {
this._lockKeepAwakeTimeoutId = null;
this._clearKeepAwakeTimer();
// Stop wake-ups and let GNOME's native blank timeout handle blackout.
this._keepAwakeActiveOnce = true;
try { Main.screenShield?.emit?.('active-changed'); } catch (_) {}
return GLib.SOURCE_REMOVE;
});
GLib.Source.set_name_by_id(this._lockKeepAwakeTimeoutId, '[livelockpaper] lock-keep-awake-timeout');
}
}
_restartKeepAwakeTimerIfNeeded() {
if (Main.sessionMode.currentMode !== 'unlock-dialog')
return;
this._startKeepAwakeTimerIfNeeded();
}
_hasBatteryDevice() {
if (this._batteryPresent !== undefined)
return this._batteryPresent;
try {
const displayDevice = Gio.DBusProxy.new_for_bus_sync(
Gio.BusType.SYSTEM,
Gio.DBusProxyFlags.NONE,
null,
'org.freedesktop.UPower',
'/org/freedesktop/UPower/devices/DisplayDevice',
'org.freedesktop.UPower.Device',
null
);
const isPresent = displayDevice.get_cached_property('IsPresent')?.unpack() ?? false;
const type = displayDevice.get_cached_property('Type')?.unpack() ?? 0;
this._batteryPresent = isPresent && type === 2; // 2 = Battery
} catch (e) {
this._batteryPresent = false;
}
return this._batteryPresent;
}
_ensureStatusIndicator() {
if (!this._settings)
return;
const shouldShow = this._settings.get_boolean(Keys.DEBUG_SHOW_PANEL_BUTTON);
if (!shouldShow) {
this._destroyStatusIndicator();
return;
}
if (this._panelButton)
return;
this._panelSignals = [];
this._manualWallpaperPaused = false;
this._panelButton = new PanelMenu.Button(0.0, 'LiveLockPaper');
// Use standard icon that should work with most icon packs
this._panelIcon = new St.Icon({
icon_name: 'preferences-desktop-wallpaper-symbolic',
fallback_icon_name: 'image-x-generic-symbolic',
style_class: 'system-status-icon',
});
this._panelButton.add_child(this._panelIcon);
this._menuPlayPauseItem = new PopupMenu.PopupMenuItem('Pause Wallpaper');
this._menuPlayPauseId = this._menuPlayPauseItem.connect('activate', () => {
this._toggleWallpaperPlaybackFromMenu();
return false; // Prevent menu from closing
});
this._panelButton.menu.addMenuItem(this._menuPlayPauseItem);
this._menuNextItem = new PopupMenu.PopupMenuItem('Next Video');
this._menuNextId = this._menuNextItem.connect('activate', () => {
this._advanceWallpaperFromMenu();
return false; // Prevent menu from closing
});
this._panelButton.menu.addMenuItem(this._menuNextItem);
// Wallpaper group (submenu)
this._menuWallpaperGroup = new PopupMenu.PopupSubMenuMenuItem('Wallpaper', true);
const wallpaperSubmenu = this._menuWallpaperGroup.menu;
this._menuWallpaperEnabledSwitch = new PopupMenu.PopupSwitchMenuItem(
'Wallpaper enabled',
this._settings.get_boolean(Keys.WALLPAPER_ENABLED)
);
this._menuWallpaperEnabledId = this._menuWallpaperEnabledSwitch.connect('toggled', (_item, state) => {
this._settings.set_boolean(Keys.WALLPAPER_ENABLED, state);
});
wallpaperSubmenu.addMenuItem(this._menuWallpaperEnabledSwitch);
this._menuRandomOrderSwitch = new PopupMenu.PopupSwitchMenuItem(
'Random order',
this._settings.get_boolean(Keys.WALLPAPER_RANDOM_ORDER)
);
this._menuRandomOrderId = this._menuRandomOrderSwitch.connect('toggled', (_item, state) => {
this._settings.set_boolean(Keys.WALLPAPER_RANDOM_ORDER, state);
});
wallpaperSubmenu.addMenuItem(this._menuRandomOrderSwitch);