-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcommandsUI.js
More file actions
657 lines (524 loc) · 23.5 KB
/
commandsUI.js
File metadata and controls
657 lines (524 loc) · 23.5 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
/* commandsUI.js
*
* This file is part of the Custom Command Menu GNOME Shell extension
* https://github.com/StorageB/custom-command-menu
*
* 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 { gettext as _ } from 'resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js';
import Gio from 'gi://Gio';
import Adw from 'gi://Adw';
import Gtk from 'gi://Gtk';
import Gdk from 'gi://Gdk';
import GLib from 'gi://GLib';
import GObject from 'gi://GObject';
let numberOfCommands = 99;
let draggedRow = null;
export default class commandsUI extends Adw.PreferencesPage {
static {
GObject.registerClass({
GTypeName: 'commandsUI',
}, this);
}
_init(params = {}) {
this._settings = params?.Settings;
this._expanderRows = [];
let { Settings, ...args } = params;
super._init(args);
const style = new Gtk.CssProvider();
const cssData = `button > label { font-weight: normal; }`;
style.load_from_data(cssData, cssData.length);
Gtk.StyleContext.add_provider_for_display(
Gdk.Display.get_default(),
style,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
);
this._commandBoxList = new Gtk.ListBox();
this._commandBoxList.add_css_class('boxed-list');
this._scroller = new Gtk.ScrolledWindow();
this._scroller.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC);
this._scroller.set_propagate_natural_height(true);
this._scroller.set_child(this._commandBoxList);
const clamp = new Adw.Clamp({ child: this._scroller });
this._overlay = new Adw.ToastOverlay();
this._overlay.set_child(clamp);
const box = new Gtk.Box({ orientation: Gtk.Orientation.VERTICAL });
box.append(this._overlay);
const group = new Adw.PreferencesGroup();
group.add(box);
this.add(group);
this._initDragMenu();
}
//#region addRow
_addRow(dragBox, rowNumber, index) {
const row = new Adw.ExpanderRow({
title: '',
selectable: false,
expanded: false,
});
row._rowNumber = rowNumber;
this._expanderRows.push(row);
const entryRowName = new Adw.EntryRow({ title: _('Name:') });
const entryRowCommand = new Adw.EntryRow({ title: _('Command:') });
const entryRowIcon = new Adw.EntryRow({ title: _('Icon:') });
row.add_row(entryRowName);
row.add_row(entryRowCommand);
row.add_row(entryRowIcon);
row._entryRowName = entryRowName;
row._entryRowCommand = entryRowCommand;
row._entryRowIcon = entryRowIcon;
const [name, command, icon] = this._settings.get_value(`command${rowNumber}`).deep_unpack();
entryRowName.text = name;
entryRowCommand.text = command;
entryRowIcon.text = icon;
row.title = entryRowName.text.replace(/&/g, '&');
//#region (menuButton)
const gMenu = new Gio.Menu();
gMenu.append(_('Insert new'), 'row.insert');
gMenu.append(_('Duplicate'), 'row.duplicate');
gMenu.append(_('Delete'), 'row.delete');
const menuButton = new Gtk.MenuButton({
icon_name: 'view-more-symbolic',
valign: Gtk.Align.CENTER,
has_frame: false,
menu_model: gMenu,
});
const actionGroup = new Gio.SimpleActionGroup();
//#region (insert)
const insertAction = new Gio.SimpleAction({ name: 'insert' });
insertAction.connect('activate', () => {
let inserted = false;
for (const child of this._commandBoxList) {
if (child instanceof Adw.ExpanderRow && !child.visible) {
this._settings.set_value(`command${child._rowNumber}`, new GLib.Variant('(sssb)', ["", "", "", true]));
child._entryRowName.text = '';
child._entryRowCommand.text = '';
child._entryRowIcon.text = '';
child.title = '';
child._checkButton.get_child().set_from_icon_name("checkbox-checked-symbolic");
child.remove_css_class('dim-label');
this._commandBoxList.remove(child);
const updatedRows = this._getListBoxRows(this._commandBoxList);
const insertIndex = updatedRows.indexOf(row) + 1;
this._commandBoxList.insert(child, insertIndex);
child.visible = true;
child.expanded = true;
this._emitReorder();
inserted = true;
break;
}
}
if (!inserted) this._overlay.add_toast(new Adw.Toast({ title: _('Maximum row limit reached') }));
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this._refreshMenuTitles();
return GLib.SOURCE_REMOVE;
});
});
actionGroup.add_action(insertAction);
//#region (duplicate)
const duplicateAction = new Gio.SimpleAction({ name: 'duplicate' });
duplicateAction.connect('activate', () => {
let inserted = false;
for (const child of this._commandBoxList) {
if (child instanceof Adw.ExpanderRow && !child.visible) {
const [name, command, icon] = this._settings.get_value(`command${row._rowNumber}`).deep_unpack();
const newName = `${name} (copy)`;
this._settings.set_value(`command${child._rowNumber}`, new GLib.Variant('(sssb)', [newName, command, icon, true]));
child._entryRowName.text = newName;
child._entryRowCommand.text = command;
child._entryRowIcon.text = icon;
child.title = newName.replace(/&/g, '&');
child._checkButton.get_child().set_from_icon_name("checkbox-checked-symbolic");
child.remove_css_class('dim-label');
this._commandBoxList.remove(child);
const updatedRows = this._getListBoxRows(this._commandBoxList);
const insertIndex = updatedRows.indexOf(row) + 1;
this._commandBoxList.insert(child, insertIndex);
child.visible = true;
child.expanded = true;
this._emitReorder();
inserted = true;
break;
}
}
if (!inserted) this._overlay.add_toast(new Adw.Toast({ title: _('Maximum row limit reached') }));
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this._refreshMenuTitles();
return GLib.SOURCE_REMOVE;
});
});
actionGroup.add_action(duplicateAction);
//#region (delete)
const deleteAction = new Gio.SimpleAction({ name: 'delete' });
deleteAction.connect('activate', () => {
const adjustment = this._scroller.get_vadjustment();
const scrollValue = adjustment.get_value();
draggedRow = null;
row._entryRowName.text = '';
row._entryRowCommand.text = '';
row._entryRowIcon.text = '';
row.title = '';
row.visible = false;
this._settings.set_value(`command${rowNumber}`, new GLib.Variant('(sssb)', ["", "", "", true]));
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
adjustment.set_value(scrollValue);
return GLib.SOURCE_REMOVE;
});
const clock = this._scroller.get_frame_clock?.();
if (clock) {
const handlerId = clock.connect('after-paint', () => {
adjustment.set_value(scrollValue);
clock.disconnect(handlerId);
});
}
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this._refreshMenuTitles();
return GLib.SOURCE_REMOVE;
});
});
actionGroup.add_action(deleteAction);
row.add_suffix(menuButton);
row.insert_action_group('row', actionGroup);
//#region (checkbox)
let checkButtonIcon = this._settings.get_value(`command${rowNumber}`).deep_unpack()[3] ? 'checkbox-checked-symbolic' : 'checkbox-symbolic';
const checkButton = new Gtk.Button({
child: new Gtk.Image({ icon_name: checkButtonIcon, pixel_size: 14 }),
has_frame: false,
valign: Gtk.Align.CENTER,
});
row._checkButton = checkButton;
if (checkButtonIcon === 'checkbox-checked-symbolic')
row.remove_css_class('dim-label');
else
row.add_css_class('dim-label');
checkButton.connect('clicked', () => {
const image = checkButton.get_child();
const newIcon = image.icon_name === 'checkbox-checked-symbolic' ? 'checkbox-symbolic' : 'checkbox-checked-symbolic';
image.set_from_icon_name(newIcon);
const [name, command, icon] = this._settings.get_value(`command${rowNumber}`).deep_unpack();
this._settings.set_value(
`command${rowNumber}`,
new GLib.Variant('(sssb)', [
name,
command,
icon,
newIcon === 'checkbox-checked-symbolic',
])
);
if (newIcon === 'checkbox-checked-symbolic')
row.remove_css_class('dim-label');
else
row.add_css_class('dim-label');
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this._refreshMenuTitles();
return GLib.SOURCE_REMOVE;
});
});
row.add_suffix(checkButton);
entryRowName.connect('notify::text', () => {
row.title = entryRowName.text.replace(/&/g, '&');
const [, , , visible] = this._settings.get_value(`command${rowNumber}`).deep_unpack();
this._settings.set_value(
`command${rowNumber}`,
new GLib.Variant('(sssb)', [
entryRowName.text,
entryRowCommand.text,
entryRowIcon.text,
visible,
])
);
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this._refreshMenuTitles();
return GLib.SOURCE_REMOVE;
});
});
entryRowCommand.connect('notify::text', () => {
const [name, , icon, visible] = this._settings.get_value(`command${rowNumber}`).deep_unpack();
this._settings.set_value(
`command${rowNumber}`,
new GLib.Variant('(sssb)', [
name,
entryRowCommand.text,
icon,
visible,
])
);
});
entryRowIcon.connect('notify::text', () => {
const [name, command, , visible] = this._settings.get_value(`command${rowNumber}`).deep_unpack();
this._settings.set_value(
`command${rowNumber}`,
new GLib.Variant('(sssb)', [
name,
command,
entryRowIcon.text,
visible,
])
);
});
row.add_prefix(new Gtk.Image({
icon_name: 'list-drag-handle-symbolic',
css_classes: ['dim-label'],
}));
//#region (drag)
let dragX, dragY;
const dropController = new Gtk.DropControllerMotion();
const dragSource = new Gtk.DragSource({ actions: Gdk.DragAction.MOVE });
row.add_controller(dragSource);
row.add_controller(dropController);
dragSource.connect('prepare', (_source, x, y) => {
dragX = x;
dragY = y;
const value = new GObject.Value();
value.init(Gtk.ListBoxRow);
value.set_object(row);
return Gdk.ContentProvider.new_for_value(value);
});
dragSource.connect('drag-begin', (_source, drag) => {
draggedRow = row;
const dragWidget = new Gtk.ListBox();
dragWidget.set_size_request(row.get_width(), row.get_height());
dragWidget.add_css_class('boxed-list');
const dragRow = new Adw.ExpanderRow({
title: row.title,
selectable: false,
});
dragRow.add_prefix(new Gtk.Image({
icon_name: 'list-drag-handle-symbolic',
css_classes: ['dim-label'],
}));
dragWidget.append(dragRow);
dragWidget.drag_highlight_row(dragRow);
const icon = Gtk.DragIcon.get_for_drag(drag);
icon.child = dragWidget;
drag.set_hotspot(dragX, dragY);
});
dropController.connect('enter', () => dragBox.drag_highlight_row(row));
dropController.connect('leave', () => dragBox.drag_unhighlight_row());
dragBox.insert(row, index);
if (entryRowName.text === '' && entryRowCommand.text === '' && entryRowIcon.text === '') {
row.visible = false;
}
}
//#endregion addRow
//#region initDragMenu
_initDragMenu() {
this._expanderRows.length = 0;
const commandBoxTarget = Gtk.DropTarget.new(Gtk.ListBoxRow, Gdk.DragAction.MOVE);
this._commandBoxList.add_controller(commandBoxTarget);
this._commandBoxList.set_vexpand(false);
let savedOrder = [];
try {
savedOrder = this._settings.get_value('command-order').deep_unpack();
} catch (e) {
console.log('[Custom Command Menu] Failed to read command-order from settings:', e);
}
if (!Array.isArray(savedOrder) || savedOrder.length !== numberOfCommands) {
console.log('[Custom Command Menu] Invalid savedOrder array');
savedOrder = Array.from({ length: numberOfCommands }, (_, i) => i + 1);
}
for (let i = 0; i < savedOrder.length; i++) {
const rowNumber = savedOrder[i];
this._addRow(this._commandBoxList, rowNumber, -1);
}
//#region (add command)
this._addCommandButton = new Gtk.ListBoxRow({
selectable: false,
activatable: true,
});
const buttonBox = new Gtk.Box({
orientation: Gtk.Orientation.HORIZONTAL,
spacing: 6,
halign: Gtk.Align.CENTER,
valign: Gtk.Align.CENTER,
margin_top: 8,
margin_bottom: 8,
});
const icon = new Gtk.Image({
icon_name: 'list-add-symbolic',
pixel_size: 16,
});
buttonBox.append(icon);
this._addCommandButton.set_child(buttonBox);
const clickGesture = new Gtk.GestureClick();
clickGesture.connect('released', () => {
let inserted = false;
for (const child of this._commandBoxList) {
if (child instanceof Adw.ExpanderRow && !child.visible) {
this._settings.set_value(`command${child._rowNumber}`, new GLib.Variant('(sssb)', ["", "", "", true]));
child._checkButton.get_child().set_from_icon_name("checkbox-checked-symbolic");
child.remove_css_class('dim-label');
this._commandBoxList.remove(child);
const index = Array.from(this._commandBoxList).indexOf(this._addCommandButton);
this._commandBoxList.insert(child, index);
let order = this._settings.get_value('command-order').deep_unpack();
order = order.filter(n => n !== child._rowNumber);
order.push(child._rowNumber);
this._settings.set_value('command-order', new GLib.Variant('ai', order));
child.visible = true;
child.expanded = true;
inserted = true;
break;
}
}
if (!inserted) this._overlay.add_toast(new Adw.Toast({ title: _('Maximum row limit reached') }));
});
this._addCommandButton.add_controller(clickGesture);
const ignoreDrop = new Gtk.DropControllerMotion();
ignoreDrop.connect('enter', () => this._commandBoxList.drag_unhighlight_row());
ignoreDrop.connect('leave', () => this._commandBoxList.drag_unhighlight_row());
this._addCommandButton.add_controller(ignoreDrop);
this._commandBoxList.append(this._addCommandButton);
commandBoxTarget.connect('drop', (target, value, x, y) =>
this._onTargetDropped(target, value, x, y, this._commandBoxList)
);
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this._refreshMenuTitles();
return GLib.SOURCE_REMOVE;
});
}
//#endregion initDragMenu
//#region functions
_onTargetDropped(_drop, value, _x, y, listbox) {
const targetRow = listbox.get_row_at_y(y);
if (!value || !targetRow || !draggedRow) return false;
this._commandBoxList.drag_unhighlight_row();
if (targetRow === draggedRow || targetRow === this._addCommandButton) return false;
const children = Array.from(this._commandBoxList);
const fromIndex = children.indexOf(draggedRow);
const toIndex = children.indexOf(targetRow);
if (fromIndex === -1 || toIndex === -1 || fromIndex === toIndex) return false;
const adjustment = this._scroller.get_vadjustment();
const scrollValue = adjustment.get_value();
this._commandBoxList.remove(draggedRow);
const adjustedIndex = fromIndex < toIndex ? toIndex - 1 : toIndex;
this._commandBoxList.insert(draggedRow, adjustedIndex);
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
adjustment.set_value(scrollValue);
return GLib.SOURCE_REMOVE;
});
const clock = this._scroller.get_frame_clock?.();
if (clock) {
const handlerId = clock.connect('after-paint', () => {
adjustment.set_value(scrollValue);
clock.disconnect(handlerId);
});
}
this._emitReorder();
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this._refreshMenuTitles();
return GLib.SOURCE_REMOVE;
});
draggedRow = null;
return true;
}
_emitReorder() {
let order = [];
for (const row of this._commandBoxList) {
if (row !== this._addCommandButton && row._rowNumber)
order.push(row._rowNumber);
}
this._settings.set_value('command-order', new GLib.Variant('ai', order));
}
_getListBoxRows(listBox) {
let rows = [];
let row = listBox.get_first_child();
while (row) {
rows.push(row);
row = row.get_next_sibling();
}
return rows;
}
refreshCommandList() {
this._expanderRows.length = 0;
// Remove all current rows except the "Add Command" button
const rowsToRemove = Array.from(this._commandBoxList).filter(child => child instanceof Adw.ExpanderRow);
for (const row of rowsToRemove) {
this._commandBoxList.remove(row);
}
// Rebuild rows based on current settings
let savedOrder;
try {
savedOrder = this._settings.get_value('command-order').deep_unpack();
} catch (e) {
console.log('Failed to read command-order from settings:', e);
savedOrder = Array.from({ length: numberOfCommands }, (_, i) => i + 1);
}
for (let i = 0; i < savedOrder.length; i++) {
const rowNumber = savedOrder[i];
this._addRow(this._commandBoxList, rowNumber, -1);
}
// Make sure "Add Command" button stays at the end
this._commandBoxList.remove(this._addCommandButton);
this._commandBoxList.append(this._addCommandButton);
}
_showToast(message) {
const toast = new Adw.Toast({ title: message });
this._overlay.add_toast(toast);
}
_refreshMenuTitles() {
const order = this._settings.get_value('command-order').deep_unpack();
const separators = ['~~~', '---', '───'];
function isSeparator(text) {
if (!text) return false;
text = text.trim();
return separators.some(prefix =>
text === prefix || (text.startsWith(prefix) && text.length > prefix.length)
);
}
for (let i = 0; i < order.length; i++) {
const n = order[i];
if (n < 1 || n > numberOfCommands) continue;
const row = Array.from(this._commandBoxList).find(r => r._rowNumber === n);
if (!row) continue;
if (row._entryRowName) row._entryRowName.title = _('Name:');
if (row._entryRowName) row._entryRowName.show();
if (row._entryRowCommand) row._entryRowCommand.show();
if (row._entryRowIcon) row._entryRowIcon.show();
const text = row._entryRowName.text;
row.title = text.replace(/&/g, '&');
if (isSeparator(text)) {
row._entryRowCommand.hide();
row._entryRowIcon.hide();
row._entryRowName.title = _('Separator Row');
}
if (!this._settings.get_value(`command${n}`).deep_unpack()[3]) continue;
const [entryA, entryB, entryC] = this._settings.get_value(`command${n}`).deep_unpack().slice(0, 3).map(s => s.trim());
if (entryA === '' && entryB === '' && entryC === '') continue;
if (!entryA.startsWith('*')) {
let nextValid = null;
for (let j = i + 1; j < order.length; j++) {
const nextRowNum = order[j];
if (nextRowNum < 1 || nextRowNum > numberOfCommands) continue;
if (!this._settings.get_value(`command${nextRowNum}`).deep_unpack()[3]) continue;
const [nextA, nextB, nextC] = this._settings.get_value(`command${nextRowNum}`).deep_unpack().slice(0, 3).map(s => s.trim());
if (nextA === '' && nextB === '' && nextC === '') continue;
nextValid = nextA;
break;
}
if (nextValid?.startsWith('*')) {
row._entryRowName.title = _('Submenu Title:');
row._entryRowCommand.hide();
row._entryRowIcon.hide();
}
}
}
}
collapseAll() {
for (const row of this._expanderRows) row.expanded = false;
}
//#endregion functions
}