-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathextension.js
More file actions
361 lines (305 loc) · 14 KB
/
extension.js
File metadata and controls
361 lines (305 loc) · 14 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
/* extension.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 Clutter from 'gi://Clutter';
import GObject from 'gi://GObject';
import {Extension, gettext as _} from 'resource:///org/gnome/shell/extensions/extension.js';
import * as Main from 'resource:///org/gnome/shell/ui/main.js';
import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js';
import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import St from 'gi://St';
let numberOfCommands = 99;
class CommandMenu extends PanelMenu.Button {
static {
GObject.registerClass(this);
}
constructor(mySettings) {
super(0.5, _('Commands'));
this._pendingCancellables = [];
let labelText;
if (mySettings.get_int('menuoptions-setting') === 2) {
labelText = mySettings.get_string('menuicon-setting');
this._label = new St.Icon({
icon_name: labelText.trim(),
style_class: 'system-status-icon',
});
this.add_child(this._label);
} else if (mySettings.get_int('menuoptions-setting') === 1) {
labelText = mySettings.get_string('menutitle-setting');
this._label = new St.Label({
text: labelText,
y_expand: true,
y_align: Clutter.ActorAlign.CENTER,
});
this.add_child(this._label);
} else {
labelText = _('Commands');
this._label = new St.Label({
text: labelText,
y_expand: true,
y_align: Clutter.ActorAlign.CENTER,
});
this.add_child(this._label);
}
const commandOrder = mySettings.get_value('command-order').deep_unpack();
let menuTitle = '';
let currentSubMenu = null;
let subMenuStatus = 0; // 0 - no sub menu; 1 - sub menu detected on next line; 2 - submenu creation in progress
for (let j of commandOrder) {
if (j < 1 || j > numberOfCommands) continue;
if (!mySettings.get_value(`command${j}`).deep_unpack()[3]) continue;
const [entryRowA, entryRowB, entryRowC] = mySettings.get_value(`command${j}`).deep_unpack();
if (entryRowA === '' && entryRowB === '' && entryRowC === '') continue;
let currentIndex = commandOrder.indexOf(j);
let foundNext = false;
for (let m = currentIndex + 1; m < commandOrder.length; m++) {
let nextId = commandOrder[m];
if (nextId < 1 || nextId > numberOfCommands) continue;
if (!mySettings.get_value(`command${nextId}`).deep_unpack()[3]) continue;
const [nextEntryRowA, nextEntryRowB, nextEntryRowC, nextVisible] = mySettings.get_value(`command${nextId}`).deep_unpack();
if (nextEntryRowA === '' && nextEntryRowB === '' && nextEntryRowC === '') continue;
const nextRow = mySettings.get_value(`command${nextId}`).deep_unpack()[0].trim();
if (nextRow.startsWith('*')) {
if (subMenuStatus === 0) subMenuStatus = 1;
else if ( subMenuStatus === 1) subMenuStatus = 2;
} else {
subMenuStatus = 0;
}
foundNext = true;
break;
}
if (!foundNext) subMenuStatus = 0;
if (subMenuStatus === 1) {
if (entryRowA.trim().startsWith('*')) {
menuTitle = '';
} else {
menuTitle = entryRowA.trim();
currentSubMenu = null;
continue;
}
}
const separators = ['~~~', '---', '───'];
// menu entry for separator
if (separators.some(prefix => entryRowA.trim() === prefix)) {
this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
continue;
}
// menu entry for labeled separator
if (separators.some(prefix => entryRowA.trimStart().startsWith(prefix) && entryRowA.trimStart().length > prefix.length)) {
const matchingSeparator = separators.find(prefix => entryRowA.trimStart().startsWith(prefix));
const sectionLabel = new PopupMenu.PopupBaseMenuItem({
reactive: false,
style_class: 'section-label-menu-item',
});
const labelText = entryRowA.trimStart().slice(matchingSeparator.length).trim();
const label = new St.Label({
text: labelText,
style_class: 'popup-subtitle-menu-item',
x_expand: true,
x_align: Clutter.ActorAlign.START,
y_align: Clutter.ActorAlign.CENTER,
});
label.set_style('font-size: 0.8em; padding: 0em; margin: 0em; line-height: 1em;');
this._resolveLabelAsync(label, labelText);
sectionLabel.actor.set_style('padding-top: 0px; padding-bottom: 0px; min-height: 0;');
sectionLabel.actor.add_child(label);
this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
if (matchingSeparator !== '───') this.menu.addMenuItem(sectionLabel);
continue;
}
const subMenuName = entryRowA.trim();
// submenu entry
if (subMenuName.startsWith('*')) {
if (!currentSubMenu) {
const sub = new PopupMenu.PopupSubMenuMenuItem(menuTitle);
this.menu.addMenuItem(sub);
currentSubMenu = sub.menu;
}
const itemLabel = subMenuName.replace(/^\*\s*/, '');
this._addMenuItem(itemLabel, entryRowB, entryRowC.trim(), currentSubMenu);
continue;
} else {
currentSubMenu = null;
}
// menu entry for command
if (entryRowA.trim() !== '') {
this._addMenuItem(entryRowA, entryRowB, entryRowC.trim());
}
}
}
destroy() {
for (const c of this._pendingCancellables)
c.cancel();
this._pendingCancellables = [];
super.destroy();
}
_resolveLabelAsync(labelWidget, text) {
const pattern = /\$\(([^)]+)\)/g;
let match;
while ((match = pattern.exec(text)) !== null) {
const fullMatch = match[0];
const cmd = match[1];
const cancellable = new Gio.Cancellable();
this._pendingCancellables.push(cancellable);
let timeoutId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 2, () => {
if (timeoutId > 0) {
cancellable.cancel();
timeoutId = 0;
}
return GLib.SOURCE_REMOVE;
});
try {
const proc = Gio.Subprocess.new(
['bash', '-c', cmd],
Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_SILENCE
);
proc.communicate_utf8_async(null, cancellable, (proc, res) => {
if (timeoutId > 0) {
GLib.Source.remove(timeoutId);
timeoutId = 0;
}
try {
const [, stdout] = proc.communicate_utf8_finish(res);
if (stdout) {
const current = labelWidget.get_text();
labelWidget.set_text(current.replace(fullMatch, stdout.trim()));
}
} catch (e) {
console.log(`[Custom Command Menu] Error resolving dynamic label: ${cmd}: ${e}`);
}
});
} catch (e) {
if (timeoutId > 0) {
GLib.Source.remove(timeoutId);
timeoutId = 0;
}
console.log(`[Custom Command Menu] Error spawning command: ${cmd}: ${e}`);
}
}
}
_addMenuItem(label, command, icon, targetMenu = this.menu) {
let newItem = new PopupMenu.PopupMenuItem('');
if (icon) {
let commandIcon = new St.Icon({
icon_name: icon,
style_class: 'popup-menu-icon',
});
newItem.add_child(commandIcon);
}
let commandLabel = new St.Label({ text: label });
newItem.add_child(commandLabel);
this._resolveLabelAsync(commandLabel, label);
newItem.connect('activate', () => {
// Run associated command when a menu item is clicked
console.log(_('[Custom Command Menu] Attempting to execute command:\n%s').replace('%s', command));
let [success, pid] = GLib.spawn_async(null, ["/usr/bin/env", "bash", "-c", command], null, GLib.SpawnFlags.SEARCH_PATH, null);
if (!success) {
console.log(_('[Custom Command Menu] Error running command:\n%s').replace('%s', command));
}
});
targetMenu.addMenuItem(newItem);
}
updateLabel(text) {
if (this._label instanceof St.Label) {
this._label.text = text;
} else if (this._label instanceof St.Icon) {
this._label.icon_name = text.trim();
}
}
}
export default class CommandMenuExtension extends Extension {
enable() {
this._settings = this.getSettings();
this._settingsSignals = [];
this._indicator = new CommandMenu(this._settings);
let location = this._settings.get_int('menulocation-setting') === 2 ? 'right' : 'left';
let pos = this._settings.get_int('menuposition-setting');
if (this._settings.get_int('menulocation-setting') === 0) {Main.panel.addToStatusArea('command-menu', this._indicator, Main.sessionMode.panel.left.length, 'left');}
else {Main.panel.addToStatusArea('command-menu', this._indicator, pos, location);}
this._commandRefreshTimeout = null;
for (let k = 1; k <= numberOfCommands; k++) {
this._settingsSignals.push(this._settings.connect(`changed::command${k}`, () => {
if (this._commandRefreshTimeout !== null) return;
this._commandRefreshTimeout = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 300, () => {
this._commandRefreshTimeout = null;
refreshIndicator.call(this);
return GLib.SOURCE_REMOVE;
}
);
}));
}
// Watch for changes to menu display settings
this._settingsSignals.push(this._settings.connect('changed::menuoptions-setting', () => {
refreshIndicator.call(this);
}));
this._settingsSignals.push(this._settings.connect('changed::menutitle-setting', () => {
let newLabelText = this._settings.get_string('menutitle-setting');
this._indicator.updateLabel(newLabelText);
}));
this._settingsSignals.push(this._settings.connect('changed::menuicon-setting', () => {
let newLabelText = this._settings.get_string('menuicon-setting');
this._indicator.updateLabel(newLabelText);
}));
this._settingsSignals.push(this._settings.connect('changed::command-order', () => {
refreshIndicator.call(this);
const newCommandOrder = this._settings.get_value('command-order').deep_unpack();
}));
this._settingsSignals.push(this._settings.connect('changed::menulocation-setting', () => {
refreshIndicator.call(this);
}));
this._settingsSignals.push(this._settings.connect('changed::menuposition-setting', () => {
refreshIndicator.call(this);
}));
function refreshIndicator() {
if (this._commandRefreshTimeout !== null) {
GLib.Source.remove(this._commandRefreshTimeout);
this._commandRefreshTimeout = null;
}
if (this._indicator) {
this._indicator.destroy();
this._indicator = null;
}
this._indicator = new CommandMenu(this._settings);
let location = this._settings.get_int('menulocation-setting') === 2 ? 'right' : 'left';
let pos = this._settings.get_int('menuposition-setting');
if (this._settings.get_int('menulocation-setting') === 0) {Main.panel.addToStatusArea('command-menu', this._indicator, Main.sessionMode.panel.left.length, 'left');}
else {Main.panel.addToStatusArea('command-menu', this._indicator, pos, location);}
}
}
disable() {
if (this._settingsSignals) {
for (const id of this._settingsSignals) {
this._settings.disconnect(id);
}
this._settingsSignals = null;
}
if (this._indicator) {
this._indicator.destroy();
this._indicator = null;
}
this._settings = null;
if (this._commandRefreshTimeout !== null) {
GLib.Source.remove(this._commandRefreshTimeout);
this._commandRefreshTimeout = null;
}
}
}