-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprefs.js
More file actions
1440 lines (1277 loc) · 51.8 KB
/
Copy pathprefs.js
File metadata and controls
1440 lines (1277 loc) · 51.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: GPL-2.0-or-later
// The preferences window, which is also the place snapper itself gets set up.
//
// snapper's own settings live in root's files and its daemon refuses to change
// them for anybody else, so the usual way to reach them is a text editor and
// sudo. Everything they say, though, is readable without a password:
// ListConfigs hands out every config file to any caller that asks, systemd
// answers is-enabled for anybody, and btrfs writes its allocation into sysfs.
// So this window shows the whole picture for free and only asks for a password
// at the moment something is actually being changed - once per change, not
// once per keystroke, which is why the retention rows collect what they were
// told and wait for Apply.
import Adw from 'gi://Adw';
import Gdk from 'gi://Gdk';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import GObject from 'gi://GObject';
import Gtk from 'gi://Gtk';
import {ExtensionPreferences, gettext as _, ngettext} from 'resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js';
import * as Btrfs from './lib/btrfs.js';
import * as Configs from './lib/configs.js';
import * as Units from './lib/units.js';
import {commandLine, failure, have} from './lib/exec.js';
import {available as canLock} from './lib/authorization.js';
import {installCommand} from './lib/packages.js';
const PANEL_BOXES = ['left', 'center', 'right'];
const VISIBILITY = ['always', 'when-usable'];
const MIDDLE_CLICK = ['none', 'take-snapshot', 'settings'];
const DATE_STYLES = ['relative', 'absolute'];
const MESSAGE_STYLES = ['pill', 'notification'];
const LOCKS = ['never', 'after-idle', 'always'];
const PROJECT_URL = 'https://github.com/epogonii/wisp';
const ISSUES_URL = 'https://github.com/epogonii/wisp/issues';
const FEATURE_URL = 'https://github.com/epogonii/wisp/issues/new?labels=enhancement';
const SPONSORS_URL = 'https://github.com/sponsors/epogonii';
const PAYPAL_URL = 'https://www.paypal.com/paypalme/pogonii';
const WALLETS = [
['Bitcoin', 'bc1qe6fjj3uv23e2yx2ry3wwhyrl7s2pqshau7mga3'],
['Ethereum', '0xDC9e1EfA0F8FAE71377F4018d4ff7D123369438e'],
['Solana', '3sYQyR27CVz1VcwCfoDLUioaAHk8jspQaSDHXEvBALxg'],
];
// Where tools/gen-qr.sh keeps the codes it draws for those addresses, and how
// wide one of them is shown. They are drawn larger than that, so the picture is
// scaled down rather than up and the modules stay square.
const QR_DIR = 'icons/qr';
const QR_SIZE = 168;
/**
* @param {string} key - one of Configs.TIMELINE_LIMITS
* @returns {string} how often that many are kept
*/
function timelineLabel(key) {
switch (key) {
case 'TIMELINE_LIMIT_HOURLY':
return _('Hourly');
case 'TIMELINE_LIMIT_DAILY':
return _('Daily');
case 'TIMELINE_LIMIT_WEEKLY':
return _('Weekly');
case 'TIMELINE_LIMIT_MONTHLY':
return _('Monthly');
case 'TIMELINE_LIMIT_QUARTERLY':
return _('Quarterly');
default:
return _('Yearly');
}
}
/**
* @param {string} unit - one of Units.SNAPPER_TIMERS
* @returns {{title: string, subtitle: string}} what it does, in a sentence
*/
function timerLabel(unit) {
switch (unit) {
case Units.TIMELINE:
return {
title: _('Take timeline snapshots'),
subtitle: _('One an hour, for every config with the timeline switched on'),
};
case Units.CLEANUP:
return {
title: _('Clear out old snapshots'),
subtitle: _('Applies the limits below. Without this they are only ever counted, never enforced'),
};
default:
return {
title: _('Snapshot at boot'),
subtitle: _('One taken the first time the machine comes up each day'),
};
}
}
/**
* @param {string} key - one of the BTRFS_*_PERIOD keys
* @returns {{title: string, subtitle: string}} what the job is for
*/
function jobLabel(key) {
switch (key) {
case 'BTRFS_BALANCE_PERIOD':
return {
title: _('Balance'),
subtitle: _('Packs half-empty chunks together and hands the room back'),
};
case 'BTRFS_SCRUB_PERIOD':
return {
title: _('Scrub'),
subtitle: _('Reads everything back and checks it against its checksums'),
};
case 'BTRFS_DEFRAG_PERIOD':
return {
title: _('Defragment'),
subtitle: _('Rewrites scattered files. Costs space where snapshots share their blocks'),
};
default:
return {
title: _('Trim'),
subtitle: _('Tells an SSD which blocks are no longer in use'),
};
}
}
/**
* @param {string} period - a value of one of the BTRFS_*_PERIOD keys
* @returns {number} which of Btrfs.PERIODS it is, or the length of that list
* when it is something systemd understands and this window does not
*/
function periodIndex(period) {
const known = Btrfs.PERIODS.indexOf(period);
return known === -1 ? Btrfs.PERIODS.length : known;
}
// What snapper is willing to call a config, and what stays a file name and
// not a path once it is written under /etc/snapper/configs.
const CONFIG_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
/**
* A row of buttons at the foot of a group: what has been changed but not yet
* written, with the two ways of writing it.
*
* Nothing here writes as it is typed. snapper refuses every change to a
* config for anyone but root, so each write is a password, and a spin button
* held down would be a password a second. What the rows do instead is
* remember, and this is where the remembering is spent.
*/
const ApplyRow = GObject.registerClass(
class ApplyRow extends Adw.ActionRow {
_init({onApply, onRevert, onCopy}) {
super._init({title: _('Not saved yet')});
this._copy = new Gtk.Button({
icon_name: 'edit-copy-symbolic',
tooltip_text: _('Copy the command that would do this'),
valign: Gtk.Align.CENTER,
});
this._copy.connect('clicked', () => onCopy());
this.add_suffix(this._copy);
this._revert = new Gtk.Button({
label: _('Revert'),
valign: Gtk.Align.CENTER,
});
this._revert.connect('clicked', () => onRevert());
this.add_suffix(this._revert);
this._apply = new Gtk.Button({
label: _('Apply'),
valign: Gtk.Align.CENTER,
css_classes: ['suggested-action'],
});
this._apply.connect('clicked', () => onApply());
this.add_suffix(this._apply);
this.visible = false;
}
/**
* @param {string[]} keys - what has been changed and not written
*/
update(keys) {
this.visible = keys.length > 0;
this.subtitle = keys.length > 0
// Translators: the list is snapper's own setting names.
? _('Needs administrator rights: %s').format(keys.join(', '))
: '';
}
set busy(busy) {
this._apply.sensitive = !busy;
this._revert.sensitive = !busy;
this._copy.sensitive = !busy;
}
});
/**
* One snapper config: what it takes snapshots of, who may use it, how many of
* them it keeps, and the way to be rid of it.
*/
const ConfigRow = GObject.registerClass(
class ConfigRow extends Adw.ExpanderRow {
_init({config, settings, window, onChanged, closed}) {
super._init({
title: config.name,
subtitle: config.subvolume,
});
this._config = config;
this._settings = settings;
this._window = window;
this._onChanged = onChanged;
this._closed = closed;
this._dirty = new Map();
this._widgets = [];
this._loading = true;
this._addVisibility();
this._addAccess();
this._addTimeline();
this._addNumber();
this._apply = new ApplyRow({
onApply: () => this._write(),
onRevert: () => this._revert(),
onCopy: () => this._copy(),
});
this.add_row(this._apply);
this._addDelete();
this._loading = false;
}
/** Whether the config shows up in the menu at all. This one is ours to
* set, not snapper's, so it is written the moment it is switched. */
_addVisibility() {
const row = new Adw.SwitchRow({
title: _('Show in the menu'),
active: !this._settings.get_strv('hidden-configs').includes(this._config.name),
});
row.connect('notify::active', () => {
const hidden = this._settings.get_strv('hidden-configs')
.filter(name => name !== this._config.name);
if (!row.active)
hidden.push(this._config.name);
this._settings.set_strv('hidden-configs', hidden);
});
this.add_row(row);
}
/**
* Who snapper lets near this config. Being on the list is what buys the
* right to list, take and delete snapshots without a password every time,
* so an account that is not on it is the one thing worth offering to fix
* from here.
*/
_addAccess() {
const {values} = this._config;
const users = Configs.allowedUsers(values['ALLOW_USERS']);
const groups = Configs.allowedUsers(values['ALLOW_GROUPS']);
const me = GLib.get_user_name();
const mine = users.includes(me);
const parts = [];
if (users.length > 0)
parts.push(_('Accounts: %s').format(users.join(', ')));
if (groups.length > 0)
parts.push(_('Groups: %s').format(groups.join(', ')));
const row = new Adw.ActionRow({
title: mine ? _('This account may use it') : _('Root only'),
subtitle: parts.length > 0
? parts.join(' · ')
: _('Nobody but root is named in ALLOW_USERS, so nothing here is readable without a password'),
});
row.add_prefix(new Gtk.Image({
icon_name: mine ? 'changes-allow-symbolic' : 'changes-prevent-symbolic',
}));
if (!mine) {
const button = new Gtk.Button({
label: _('Add This Account'),
valign: Gtk.Align.CENTER,
});
button.connect('clicked', () => {
this._set('ALLOW_USERS', Configs.withUser(values['ALLOW_USERS']));
this._set('SYNC_ACL', 'yes');
button.sensitive = false;
});
row.add_suffix(button);
}
this.add_row(row);
}
/** The hourly snapshots, and how many of each age survive. */
_addTimeline() {
const {values} = this._config;
const timeline = new Adw.SwitchRow({
title: _('Timeline snapshots'),
subtitle: _('One an hour, thinned out as they age'),
active: values['TIMELINE_CREATE'] === 'yes',
});
timeline.connect('notify::active', () =>
this._set('TIMELINE_CREATE', timeline.active ? 'yes' : 'no'));
this.add_row(timeline);
this._widgets.push(['TIMELINE_CREATE', timeline, 'active',
v => v === 'yes']);
for (const key of Configs.TIMELINE_LIMITS) {
const row = this._numberRow(timelineLabel(key), null, key, 0, 9999);
if (row)
timeline.bind_property('active', row, 'sensitive',
GObject.BindingFlags.SYNC_CREATE);
}
}
/** The set kept by count rather than by age, which is what the snapshots
* taken around a package transaction belong to. */
_addNumber() {
const {values} = this._config;
const cleanup = new Adw.SwitchRow({
title: _('Keep a fixed number'),
subtitle: _('For the pairs taken around installs and upgrades'),
active: values['NUMBER_CLEANUP'] === 'yes',
});
cleanup.connect('notify::active', () =>
this._set('NUMBER_CLEANUP', cleanup.active ? 'yes' : 'no'));
this.add_row(cleanup);
this._widgets.push(['NUMBER_CLEANUP', cleanup, 'active', v => v === 'yes']);
for (const [key, title, subtitle] of [
['NUMBER_LIMIT', _('Keep'), _('How many of them survive the cleanup')],
['NUMBER_LIMIT_IMPORTANT', _('Keep marked important'),
_('Counted separately, so a starred snapshot is not pushed out by ordinary ones')],
]) {
const row = this._numberRow(title, subtitle, key, 0, 9999);
if (row)
cleanup.bind_property('active', row, 'sensitive',
GObject.BindingFlags.SYNC_CREATE);
}
}
/**
* A spin row for a key that holds a number - and a plain line for one
* that does not.
*
* NUMBER_LIMIT is allowed to say "2-10", meaning a range snapper narrows
* as the filesystem fills up. A spin button cannot hold that, and rounding
* it to one of the two ends would quietly throw away a setting somebody
* chose on purpose, so a value this window cannot represent is shown and
* left alone.
*
* @param {string} title - what the row is called
* @param {string|null} subtitle - the sentence under it, if any
* @param {string} key - snapper's own name for it
* @param {number} lower - smallest allowed
* @param {number} upper - largest allowed
* @returns {Adw.SpinRow|null} the row, when it turned out to be editable
*/
_numberRow(title, subtitle, key, lower, upper) {
const raw = this._config.values[key] ?? '';
const asNumber = /^\d+$/.test(raw.trim())
? Number.parseInt(raw, 10)
: null;
if (asNumber === null) {
const row = new Adw.ActionRow({
title,
subtitle: _('Set to %s, which this window leaves as it is').format(raw || '-'),
});
row.add_suffix(new Gtk.Label({
label: raw || '-',
css_classes: ['dim-label', 'numeric'],
}));
this.add_row(row);
return null;
}
const row = new Adw.SpinRow({
title,
subtitle: subtitle ?? '',
adjustment: new Gtk.Adjustment({
lower,
upper,
step_increment: 1,
page_increment: 10,
value: asNumber,
}),
});
row.connect('notify::value', () => this._set(key, String(row.value)));
this.add_row(row);
this._widgets.push([key, row, 'value', v => Number.parseInt(v, 10) || 0]);
return row;
}
/** The one thing here that cannot be taken back. */
_addDelete() {
// Adw.ButtonRow is what Settings uses for this: a label across the
// whole row, and destructive-action turns it red without filling
// anything in. It arrived in libadwaita 1.6, so the oldest GNOME this
// extension supports gets the button it always had instead. The row
// does not carry the button class the theme's rule wants, so it is
// passed in.
if (Adw.ButtonRow) {
const row = new Adw.ButtonRow({
title: _('Delete this config…'),
css_classes: ['button', 'destructive-action'],
});
row.connect('activated', () => this._confirmDelete());
this.add_row(row);
return;
}
const button = new Gtk.Button({
label: _('Delete this config…'),
css_classes: ['destructive-action', 'pill'],
halign: Gtk.Align.CENTER,
margin_top: 6,
margin_bottom: 6,
});
button.connect('clicked', () => this._confirmDelete());
this.add_row(new Adw.PreferencesRow({
activatable: false,
selectable: false,
focusable: false,
child: button,
}));
}
_confirmDelete() {
const dialog = new Adw.AlertDialog({
heading: _('Delete the %s config?').format(this._config.name),
body: _('This removes the config and the .snapshots subvolume it keeps, and every snapshot in it. %s itself is left alone. None of it can be undone.').format(this._config.subvolume),
});
dialog.add_response('cancel', _('Cancel'));
dialog.add_response('delete', _('Delete'));
dialog.set_response_appearance('delete', Adw.ResponseAppearance.DESTRUCTIVE);
dialog.set_default_response('cancel');
dialog.set_close_response('cancel');
dialog.connect('response', (_dialog, response) => {
if (response === 'delete')
this._delete();
});
dialog.present(this._window);
}
async _delete() {
const result = await Configs.deleteConfig(this._config.name);
const said = failure(result);
if (said) {
this._toast(said);
return;
}
if (result.status === 0)
this._onChanged();
}
/**
* Remembers a change without writing it.
*
* @param {string} key - snapper's own name for it
* @param {string} value - what it should become
*/
_set(key, value) {
if (this._loading)
return;
if ((this._config.values[key] ?? '') === value)
this._dirty.delete(key);
else
this._dirty.set(key, value);
this._apply.update([...this._dirty.keys()]);
}
/** Puts every row back to what the config file still says. */
_revert() {
this._loading = true;
for (const [key, widget, property, parse] of this._widgets)
widget[property] = parse(this._config.values[key] ?? '');
this._loading = false;
this._dirty.clear();
this._apply.update([]);
}
_copy() {
const argv = Configs.setConfigArgv(this._config.name,
Object.fromEntries(this._dirty));
this._window.get_clipboard().set(commandLine(argv));
this._toast(_('Command copied. It does the same thing as Apply.'));
}
async _write() {
const values = Object.fromEntries(this._dirty);
this._apply.busy = true;
const result = await Configs.setConfig(this._config.name, values);
if (this._closed())
return;
this._apply.busy = false;
const said = failure(result);
if (said) {
this._toast(said);
return;
}
if (result.status !== 0)
return;
// What was asked for is now what the file says, so the rows are
// already right and only the record of what is unsaved has to catch up.
Object.assign(this._config.values, values);
this._dirty.clear();
this._apply.update([]);
this._toast(_('Saved to %s.').format(`/etc/snapper/configs/${this._config.name}`));
}
_toast(message) {
if (this._closed())
return;
this._window.add_toast?.(new Adw.Toast({title: message, timeout: 6}));
}
});
export default class WispPreferences extends ExtensionPreferences {
fillPreferencesWindow(window) {
this._settings = this.getSettings();
this._window = window;
// Filling this window means asking snapper and btrfs for things they
// take their time over, and a row written to after the window is gone
// is a row that no longer exists.
this._closed = false;
// Which is heard at close-request, not at destroy. Closing a window -
// the button in its own header, Escape, gtk_window_close - hides and
// unrealizes it; destroy comes from being disposed, and a window the
// process is about to exit with is never disposed at all. Measured on
// an Adw.PreferencesWindow here: close-request and unrealize, no
// destroy. Both are connected because a window that really is
// destroyed sends only the second.
const going = () => {
this._closed = true;
};
window.connect('close-request', () => {
going();
return false;
});
window.connect('destroy', going);
window.add(this._appearancePage());
this._configsPage = new Adw.PreferencesPage({
title: _('Snapshots'),
icon_name: 'document-open-recent-symbolic',
});
window.add(this._configsPage);
this._schedulePage = new Adw.PreferencesPage({
title: _('Schedule'),
icon_name: 'alarm-symbolic',
});
window.add(this._schedulePage);
this._storagePage = new Adw.PreferencesPage({
title: _('Storage'),
icon_name: 'drive-harddisk-symbolic',
});
window.add(this._storagePage);
window.add(this._aboutPage());
this._reload();
}
/** Everything that is the extension's own business rather than snapper's. */
_appearancePage() {
const settings = this._settings;
const page = new Adw.PreferencesPage({
title: _('Appearance'),
icon_name: 'preferences-desktop-appearance-symbolic',
});
const panel = new Adw.PreferencesGroup({title: _('Panel')});
page.add(panel);
panel.add(this._combo({
title: _('Position'),
subtitle: _('Which end of the top bar the indicator sits at'),
labels: [_('Left'), _('Centre'), _('Right')],
key: 'panel-box',
values: PANEL_BOXES,
}));
const index = new Adw.SpinRow({
title: _('Place'),
subtitle: _('Counted from that end. Zero is outermost'),
adjustment: new Gtk.Adjustment({
lower: 0,
upper: 20,
step_increment: 1,
value: settings.get_int('panel-index'),
}),
});
index.connect('notify::value', () =>
settings.set_int('panel-index', index.value));
panel.add(index);
panel.add(this._combo({
title: _('Show the indicator'),
subtitle: _('Hidden when unusable, it comes back as soon as snapper does'),
labels: [_('Always'), _('Only when snapper is set up')],
key: 'indicator-visibility',
values: VISIBILITY,
}));
panel.add(this._combo({
title: _('Middle click'),
subtitle: _('Uses the first config shown in the menu'),
labels: [_('Nothing'), _('Take a snapshot'), _('Open these settings')],
key: 'middle-click',
values: MIDDLE_CLICK,
}));
const menu = new Adw.PreferencesGroup({title: _('Menu')});
page.add(menu);
const count = new Adw.SpinRow({
title: _('Snapshots listed'),
subtitle: _('How many of the newest each config shows'),
adjustment: new Gtk.Adjustment({
lower: 1,
upper: 50,
step_increment: 1,
value: settings.get_int('snapshot-count'),
}),
});
count.connect('notify::value', () =>
settings.set_int('snapshot-count', count.value));
menu.add(count);
menu.add(this._combo({
title: _('Dates'),
subtitle: _('An age reads faster; a date and time is what matches a snapshot against something else'),
labels: [_('How long ago'), _('Date and time')],
key: 'date-style',
values: DATE_STYLES,
}));
const cleanup = new Adw.SwitchRow({
title: _('Show the cleanup rule'),
subtitle: _('What decides when snapper removes each snapshot on its own'),
active: settings.get_boolean('show-cleanup'),
});
cleanup.connect('notify::active', () =>
settings.set_boolean('show-cleanup', cleanup.active));
menu.add(cleanup);
const messages = new Adw.PreferencesGroup({
title: _('Messages'),
description: _('What a snapshot taken and a command copied are answered with. Anything that changed the disk - a rollback, files put back - is a notification either way, since that is worth finding again later.'),
});
page.add(messages);
messages.add(this._combo({
title: _('Say it with'),
subtitle: _('The pill appears under the panel and is gone in a couple of seconds'),
labels: [_('A pill under the panel'), _('A notification')],
key: 'message-style',
values: MESSAGE_STYLES,
}));
const protection = new Adw.PreferencesGroup({
title: _('Lock'),
description: _('Being allowed to read a config is granted once and belongs to the account from then on, so nothing here can take that back. What it can do is put a lock in front of the menu, asked for by polkit - the same password, or the same finger, that authorising anything else on this machine takes.'),
});
page.add(protection);
const lock = this._combo({
title: _('Ask before showing the list'),
subtitle: _('Locked, nothing is read at all until it is unlocked'),
labels: [_('Never'), _('When it has been a while'), _('Every time')],
key: 'lock',
values: LOCKS,
});
protection.add(lock);
const timeout = new Adw.SpinRow({
title: _('Ask again after'),
subtitle: _('Minutes since it was last unlocked'),
adjustment: new Gtk.Adjustment({
lower: 1,
upper: 240,
step_increment: 1,
page_increment: 15,
value: settings.get_int('lock-timeout'),
}),
});
timeout.connect('notify::value', () =>
settings.set_int('lock-timeout', timeout.value));
protection.add(timeout);
const followLock = () => {
timeout.sensitive = settings.get_string('lock') === 'after-idle';
};
followLock();
settings.connect('changed::lock', followLock);
// The lock is a polkit check and nothing else. Without polkit's
// command line tools there is nothing to ask with, so rather than
// offer a setting that would do nothing, the group says why.
if (!canLock()) {
protection.description = _('Not available here: this needs pkcheck, from polkit. Install polkit and the lock can be switched on.');
lock.sensitive = false;
timeout.sensitive = false;
}
return page;
}
/**
* @param {object} options - what the row is for
* @param {string} options.title - the row's name
* @param {string} options.subtitle - the sentence under it
* @param {string[]} options.labels - what to show, in order
* @param {string} options.key - the setting behind it
* @param {string[]} options.values - the setting's own words, same order
* @returns {Adw.ComboRow} the row, already wired up
*/
_combo({title, subtitle, labels, key, values}) {
const row = new Adw.ComboRow({
title,
subtitle,
model: new Gtk.StringList({strings: labels}),
selected: Math.max(0, values.indexOf(this._settings.get_string(key))),
});
row.connect('notify::selected', () =>
this._settings.set_string(key, values[row.selected]));
return row;
}
/**
* Where the extension came from, and a place to say thanks from. Nothing on
* this page has anything to do with the extension working, and nothing on
* it asks for anything.
*/
_aboutPage() {
const page = new Adw.PreferencesPage({
title: _('About'),
icon_name: 'help-about-symbolic',
});
const about = new Adw.PreferencesGroup({
title: _('Wisp'),
description: _('Snapper snapshots, from the top bar'),
});
page.add(about);
about.add(this._linkRow(_('Project page'), PROJECT_URL, PROJECT_URL));
// Both halves of an issue as two buttons rather than two more rows,
// because they are the two things somebody on this page came to do.
const buttons = new Gtk.Box({
orientation: Gtk.Orientation.HORIZONTAL,
homogeneous: true,
halign: Gtk.Align.CENTER,
spacing: 12,
margin_top: 18,
});
buttons.append(this._pill(_('Report a problem'), ISSUES_URL));
buttons.append(this._pill(_('Request a feature'), FEATURE_URL));
about.add(buttons);
// Adw.PreferencesGroup takes any widget, so the line that says where
// to write goes under the buttons instead of into a row of its own.
const wrote = new Gtk.Label({
label: _('Something it does wrong, or something it does not do yet - either one belongs in an issue.'),
justify: Gtk.Justification.CENTER,
wrap: true,
max_width_chars: 44,
margin_top: 12,
css_classes: ['dim-label', 'caption'],
});
about.add(wrote);
const support = new Adw.PreferencesGroup({
title: _('Support'),
description: _('The extension is free and stays free. If it earned a coffee ☕'),
});
page.add(support);
support.add(this._linkRow(_('GitHub Sponsors'),
_('Monthly or one time'), SPONSORS_URL));
support.add(this._linkRow(_('PayPal'), PAYPAL_URL, PAYPAL_URL));
this._wallets(support);
const footer = new Adw.PreferencesGroup();
page.add(footer);
footer.add(new Gtk.Label({
label: `· ${_('Wisp %s').format(this.metadata['version-name'] ?? '')} ·`,
justify: Gtk.Justification.CENTER,
margin_top: 6,
css_classes: ['dim-label', 'caption'],
}));
return page;
}
/**
* The wallets, one at a time: the network to send on, the address it
* belongs to, and the code to point a phone at instead of typing it out.
* The codes are drawn by tools/gen-qr.sh and ship as files - an encoder
* written in here would be a few hundred lines of arithmetic for anybody
* reviewing the extension to read, and a wrong module in a QR code is money
* sent nowhere.
*
* @param {Adw.PreferencesGroup} group - the Support group they belong to
*/
_wallets(group) {
const networks = new Gtk.StringList();
for (const [name] of WALLETS)
networks.append(name);
const network = new Adw.ComboRow({
title: _('Cryptocurrency'),
model: networks,
});
group.add(network);
const address = new Adw.ActionRow({
title: _('Address'),
subtitle_selectable: true,
subtitle_lines: 0,
});
const copy = new Gtk.Button({
icon_name: 'edit-copy-symbolic',
tooltip_text: _('Copy the address'),
valign: Gtk.Align.CENTER,
css_classes: ['flat'],
});
address.add_suffix(copy);
group.add(address);
const code = new Gtk.Picture({
halign: Gtk.Align.CENTER,
margin_top: 12,
width_request: QR_SIZE,
height_request: QR_SIZE,
});
group.add(code);
const chosen = () => WALLETS[network.selected] ?? WALLETS[0];
const show = () => {
const [name, wallet] = chosen();
const file = `${name.toLowerCase().replaceAll(' ', '-')}.svg`;
address.subtitle = wallet;
code.file = Gio.File.new_for_path(`${this.path}/${QR_DIR}/${file}`);
code.alternative_text =
_('The %s address as a QR code').format(name);
};
network.connect('notify::selected', show);
show();
copy.connect('clicked', () => {
const [name, wallet] = chosen();
this._clipboard(wallet);
this._toast(_('%s address copied').format(name));
});
}
/**
* A rounded button that opens something in a browser.
*
* @param {string} label - what it says
* @param {string} url - where it goes
* @returns {Gtk.Button} the button
*/
_pill(label, url) {
const button = new Gtk.Button({label, css_classes: ['pill']});
button.connect('clicked', () =>
Gio.AppInfo.launch_default_for_uri(url, null));
return button;
}
/**
* A row that opens something in a browser.
*
* @param {string} title - what it is
* @param {string} subtitle - the line under it, often the address itself
* @param {string} url - where it goes
* @returns {Adw.ActionRow} the row
*/
_linkRow(title, subtitle, url) {
const row = new Adw.ActionRow({title, subtitle, activatable: true});
row.add_suffix(new Gtk.Image({icon_name: 'adw-external-link-symbolic'}));
row.connect('activated', () =>
Gio.AppInfo.launch_default_for_uri(url, null));
return row;
}
/**
* Puts text on the clipboard. Gdk wants a GValue for that rather than a
* string.
*
* @param {string} text - what to copy
*/
_clipboard(text) {
const value = new GObject.Value();
value.init(GObject.TYPE_STRING);
value.set_string(text);
Gdk.Display.get_default()?.get_clipboard().set_value(value);
}
_reload() {
if (this._closed)
return;
this._fillConfigs().catch(error => this._failed(this._configsPage, error));
this._fillSchedule().catch(error => this._failed(this._schedulePage, error));
this._fillStorage().catch(error => this._failed(this._storagePage, error));
}
/**
* @param {Adw.PreferencesPage} page - the page that has nothing to show
* @param {Error} error - why
*/
_failed(page, error) {
if (this._closed)
return;
const group = new Adw.PreferencesGroup();
group.add(new Adw.ActionRow({
title: _('Could not read this'),
subtitle: error.message,
}));
page.add(group);
}
/**
* @param {Adw.PreferencesPage} page - the page to empty
*/
_clear(page) {
let child = page.get_first_child();
const groups = [];
// The page keeps its groups inside a scrolled box rather than as
// children of its own, so they are collected by walking what Adw made
// rather than by asking the page.
const walk = widget => {
for (let w = widget.get_first_child(); w; w = w.get_next_sibling()) {
if (w instanceof Adw.PreferencesGroup)
groups.push(w);
else
walk(w);
}
};
while (child) {
walk(child);
child = child.get_next_sibling();
}
for (const group of groups)
page.remove(group);
}
async _fillConfigs() {
this._clear(this._configsPage);
// Without snapper there is nothing on this page to read or to change,
// and a page that said no configs were set up would be blaming the
// wrong thing.
if (!GLib.find_program_in_path('snapper')) {
this._configsPage.add(this._absent(_('snapper is not installed'),
_('Wisp manages the snapshots snapper takes, and there is no snapper on this system taking any. Everything in this window waits on it.'),
'snapper'));
return;
}
const configs = await Configs.listConfigs();
if (this._closed)
return;
const group = new Adw.PreferencesGroup({
title: _('Configs'),
description: _('One config per subvolume, kept in /etc/snapper/configs. Everything here is readable without a password; changing it is root’s, so changes wait for Apply and go out together.'),
});
const add = new Gtk.Button({
icon_name: 'list-add-symbolic',
tooltip_text: _('Set up a new config'),