Debian Codegraph @

extensions/apps-menu/extension.js

raw
1 // SPDX-FileCopyrightText: 2011 Vamsi Krishna Brahmajosyula <[email protected]>
2 // SPDX-FileCopyrightText: 2011 Giovanni Campagna <[email protected]>
3 // SPDX-FileCopyrightText: 2013 Debarshi Ray <[email protected]>
4 // SPDX-FileCopyrightText: 2013 Florian Müllner <[email protected]>
5 //
6 // SPDX-License-Identifier: GPL-2.0-or-later
7
8 import Atk from 'gi://Atk';
9 import Clutter from 'gi://Clutter';
10 import Gio from 'gi://Gio';
11 import GLib from 'gi://GLib';
12 import GMenu from 'gi://GMenu';
13 import GObject from 'gi://GObject';
14 import Meta from 'gi://Meta';
15 import Shell from 'gi://Shell';
16 import St from 'gi://St';
17 import {EventEmitter} from 'resource:///org/gnome/shell/misc/signals.js';
18
19 import {Extension, gettext as _} from 'resource:///org/gnome/shell/extensions/extension.js';
20
21 import * as DND from 'resource:///org/gnome/shell/ui/dnd.js';
22 import * as Main from 'resource:///org/gnome/shell/ui/main.js';
23 import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js';
24 import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js';
25
26 const APPLICATION_ICON_SIZE = 32;
27 const HORIZ_FACTOR = 5;
28 const MENU_HEIGHT_OFFSET = 132;
29 const NAVIGATION_REGION_OVERSHOOT = 50;
30
31 Gio._promisify(Gio._LocalFilePrototype, 'query_info_async', 'query_info_finish');
32 Gio._promisify(Gio._LocalFilePrototype, 'set_attributes_async', 'set_attributes_finish');
33
34 class ApplicationMenuItem extends PopupMenu.PopupBaseMenuItem {
35 static {
36 GObject.registerClass(this);
37 }
38
39 constructor(button, app) {
40 super();
41 this._app = app;
42 this._button = button;
43
44 this._icon = this.getDragActor();
45 this._icon.style_class = 'icon-dropshadow';
46 this.add_child(this._icon);
47
48 const appLabel = new St.Label({
49 text: app.get_name(),
50 y_expand: true,
51 y_align: Clutter.ActorAlign.CENTER,
52 });
53 this.add_child(appLabel);
54 this.label_actor = appLabel;
55
56 this._delegate = this;
57 const draggable = DND.makeDraggable(this);
58
59 const maybeStartDrag = draggable._maybeStartDrag;
60 draggable._maybeStartDrag = event => {
61 if (this._dragEnabled)
62 return maybeStartDrag.call(draggable, event);
63 return false;
64 };
65
66 this.connect('notify::active', this._onActiveChanged.bind(this));
67 }
68
69 activate(event) {
70 this._app.open_new_window(-1);
71 this._button.selectCategory(null);
72 this._button.menu.toggle();
73 super.activate(event);
74
75 Main.overview.hide();
76 }
77
78 _onActiveChanged() {
79 if (!this.active)
80 return;
81
82 this._button.scrollToButton(this);
83 }
84
85 setDragEnabled(enabled) {
86 this._dragEnabled = enabled;
87 }
88
89 getDragActor() {
90 return this._app.create_icon_texture(APPLICATION_ICON_SIZE);
91 }
92
93 getDragActorSource() {
94 return this._icon;
95 }
96 }
97
98 class CategoryMenuItem extends PopupMenu.PopupBaseMenuItem {
99 static {
100 GObject.registerClass(this);
101 }
102
103 constructor(button, category) {
104 super();
105 this._category = category;
106 this._button = button;
107
108 this._oldX = -1;
109 this._oldY = -1;
110
111 let name;
112 if (this._category)
113 name = this._category.get_name();
114 else
115 name = _('Favorites');
116
117 const label = new St.Label({text: name});
118 this.add_child(label);
119 this.actor.label_actor = label;
120
121 this.connect('motion-event', this._onMotionEvent.bind(this));
122 this.connect('notify::active', this._onActiveChanged.bind(this));
123 }
124
125 activate(event) {
126 this._button.selectCategory(this._category);
127 this._button.scrollToCatButton(this);
128 super.activate(event);
129 }
130
131 _isNavigatingSubmenu([x, y]) {
132 const [posX, posY] = this.get_transformed_position();
133
134 if (this._oldX === -1) {
135 this._oldX = x;
136 this._oldY = y;
137 return true;
138 }
139
140 const deltaX = Math.abs(x - this._oldX);
141 const deltaY = Math.abs(y - this._oldY);
142
143 this._oldX = x;
144 this._oldY = y;
145
146 // If it lies outside the x-coordinates then it is definitely outside.
147 if (posX > x || posX + this.width < x)
148 return false;
149
150 // If it lies inside the menu item then it is definitely inside.
151 if (posY <= y && posY + this.height >= y)
152 return true;
153
154 // We want the keep-up triangle only if the movement is more
155 // horizontal than vertical.
156 if (deltaX * HORIZ_FACTOR < deltaY)
157 return false;
158
159 // Check whether the point lies inside triangle ABC, and a similar
160 // triangle on the other side of the menu item.
161 //
162 // +---------------------+
163 // | menu item |
164 // A +---------------------+ C
165 // P |
166 // B
167
168 // Ensure that the point P always lies below line AC so that we can
169 // only check for triangle ABC.
170 if (posY > y) {
171 const offset = posY - y;
172 y = posY + this.height + offset;
173 }
174
175 // Ensure that A is (0, 0).
176 x -= posX;
177 y -= posY + this.height;
178
179 // Check which side of line AB the point P lies on by taking the
180 // cross-product of AB and AP. See:
181 // http://stackoverflow.com/questions/3461453/determine-which-side-of-a-line-a-point-lies
182 if (this.width * y - NAVIGATION_REGION_OVERSHOOT * x <= 0)
183 return true;
184
185 return false;
186 }
187
188 _onMotionEvent(actor, event) {
189 if (!this._grab) {
190 this._oldX = -1;
191 this._oldY = -1;
192 this._grab = global.stage.grab(this);
193 }
194 this.hover = true;
195
196 if (this._isNavigatingSubmenu(event.get_coords()))
197 return Clutter.EVENT_STOP;
198
199 this._oldX = -1;
200 this._oldY = -1;
201 this.hover = false;
202 this._grab?.dismiss();
203 delete this._grab;
204
205 const targetActor = global.stage.get_event_actor(event);
206 if (targetActor instanceof St.Widget)
207 targetActor.sync_hover();
208
209 return Clutter.EVENT_PROPAGATE;
210 }
211
212 _onActiveChanged() {
213 if (!this.active)
214 return;
215
216 this._button.selectCategory(this._category);
217 this._button.scrollToCatButton(this);
218 }
219 }
220
221 class ApplicationsMenu extends PopupMenu.PopupMenu {
222 constructor(sourceActor, arrowAlignment, arrowSide, button) {
223 super(sourceActor, arrowAlignment, arrowSide);
224 this._button = button;
225 }
226
227 isEmpty() {
228 return false;
229 }
230
231 toggle() {
232 if (this.isOpen)
233 this._button.selectCategory(null);
234 super.toggle();
235 }
236 }
237
238 class DesktopTarget extends EventEmitter {
239 constructor() {
240 super();
241
242 this._desktop = null;
243 this._desktopDestroyedId = 0;
244
245 global.window_group.connectObject('child-added',
246 this._onWindowAdded.bind(this), this);
247
248 global.get_window_actors().forEach(a => {
249 this._onWindowAdded(a.get_parent(), a);
250 });
251 }
252
253 get hasDesktop() {
254 return this._desktop !== null;
255 }
256
257 _onWindowAdded(group, actor) {
258 if (!(actor instanceof Meta.WindowActor))
259 return;
260
261 if (actor.meta_window.get_window_type() === Meta.WindowType.DESKTOP)
262 this._setDesktop(actor);
263 }
264
265 _setDesktop(desktop) {
266 if (this._desktop) {
267 this._desktop.disconnectObject(this);
268 delete this._desktop._delegate;
269 }
270
271 this._desktop = desktop;
272 this.emit('desktop-changed');
273
274 if (this._desktop) {
275 this._desktop.connectObject('destroy', () => {
276 this._setDesktop(null);
277 }, this);
278 this._desktop._delegate = this;
279 }
280 }
281
282 _getSourceAppInfo(source) {
283 if (!(source instanceof ApplicationMenuItem))
284 return null;
285 return source._app.app_info;
286 }
287
288 async _markTrusted(file) {
289 const modeAttr = Gio.FILE_ATTRIBUTE_UNIX_MODE;
290 const trustedAttr = 'metadata::trusted';
291 const queryFlags = Gio.FileQueryInfoFlags.NONE;
292 const ioPriority = GLib.PRIORITY_DEFAULT;
293
294 try {
295 let info = await file.query_info_async(modeAttr, queryFlags, ioPriority, null);
296
297 const mode = info.get_attribute_uint32(modeAttr) | 0o100;
298 info.set_attribute_uint32(modeAttr, mode);
299 info.set_attribute_string(trustedAttr, 'yes');
300 await file.set_attributes_async(info, queryFlags, ioPriority, null);
301
302 // Hack: force nautilus to reload file info
303 info = new Gio.FileInfo();
304 info.set_attribute_uint64(
305 Gio.FILE_ATTRIBUTE_TIME_ACCESS, GLib.get_real_time());
306 try {
307 await file.set_attributes_async(info, queryFlags, ioPriority, null);
308 } catch (e) {
309 log(`Failed to update access time: ${e.message}`);
310 }
311 } catch (e) {
312 log(`Failed to mark file as trusted: ${e.message}`);
313 }
314 }
315
316 destroy() {
317 global.window_group.disconnectObject(this);
318 this._setDesktop(null);
319 }
320
321 handleDragOver(source, _actor, _x, _y, _time) {
322 const appInfo = this._getSourceAppInfo(source);
323 if (!appInfo)
324 return DND.DragMotionResult.CONTINUE;
325
326 return DND.DragMotionResult.COPY_DROP;
327 }
328
329 acceptDrop(source, _actor, _x, _y, _time) {
330 const appInfo = this._getSourceAppInfo(source);
331 if (!appInfo)
332 return false;
333
334 this.emit('app-dropped');
335
336 const desktop = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DESKTOP);
337
338 const src = Gio.File.new_for_path(appInfo.get_filename());
339 const dst = Gio.File.new_for_path(GLib.build_filenamev([desktop, src.get_basename()]));
340
341 try {
342 // copy_async() isn't introspectable :-(
343 src.copy(dst, Gio.FileCopyFlags.OVERWRITE, null, null);
344 this._markTrusted(dst);
345 } catch (e) {
346 log(`Failed to copy to desktop: ${e.message}`);
347 }
348
349 return true;
350 }
351 }
352
353 class MainLayout extends Clutter.BoxLayout {
354 static {
355 GObject.registerClass(this);
356 }
357
358 vfunc_get_preferred_height(container, forWidth) {
359 const [mainChild] = container;
360 const [minHeight, natHeight] =
361 mainChild.get_preferred_height(forWidth);
362
363 return [minHeight, natHeight + MENU_HEIGHT_OFFSET];
364 }
365 }
366
367 class ApplicationsButton extends PanelMenu.Button {
368 static {
369 GObject.registerClass(this);
370 }
371
372 constructor(settings) {
373 super(1.0, null, false);
374
375 this.setMenu(new ApplicationsMenu(this, 1.0, St.Side.TOP, this));
376 Main.panel.menuManager.addMenu(this.menu);
377
378 // At this moment applications menu is not keyboard navigable at
379 // all (so not accessible), so it doesn't make sense to set as
380 // role ATK_ROLE_MENU like other elements of the panel.
381 this.accessible_role = Atk.Role.LABEL;
382
383 this._appSys = Shell.AppSystem.get_default();
384
385 this._label = new St.Label({
386 text: _('Apps'),
387 y_expand: true,
388 y_align: Clutter.ActorAlign.CENTER,
389 });
390
391 this.add_child(this._label);
392 this.name = 'panelApplications';
393 this.label_actor = this._label;
394
395 Main.overview.connectObject(
396 'showing', () => this.add_accessible_state(Atk.StateType.CHECKED),
397 'hiding', () => this.remove_accessible_state(Atk.StateType.CHECKED),
398 this);
399
400 Main.wm.addKeybinding(
401 'apps-menu-toggle-menu',
402 settings,
403 Meta.KeyBindingFlags.IGNORE_AUTOREPEAT,
404 Shell.ActionMode.NORMAL | Shell.ActionMode.OVERVIEW,
405 () => this.menu.toggle());
406
407 this._desktopTarget = new DesktopTarget();
408 this._desktopTarget.connectObject(
409 'app-dropped', () => this.menu.close(),
410 'desktop-changed', () => {
411 this._applicationsButtons.forEach(item => {
412 item.setDragEnabled(this._desktopTarget.hasDesktop);
413 });
414 }, this);
415
416 this._tree = new GMenu.Tree({menu_basename: 'applications.menu'});
417 this._tree.connectObject('changed',
418 () => this._onTreeChanged(), this);
419
420 this._applicationsButtons = new Map();
421 this.reloadFlag = false;
422 this._createLayout();
423 this._display();
424 this._appSys.connectObject('installed-changed',
425 () => this._onTreeChanged(), this);
426 }
427
428 _onTreeChanged() {
429 if (this.menu.isOpen) {
430 this._redisplay();
431 this.mainBox.show();
432 } else {
433 this.reloadFlag = true;
434 }
435 }
436
437 _onDestroy() {
438 super._onDestroy();
439
440 delete this._tree;
441
442 Main.wm.removeKeybinding('apps-menu-toggle-menu');
443
444 this._desktopTarget.disconnectObject(this);
445 this._desktopTarget.destroy();
446 }
447
448 _onMenuKeyPress(actor, event) {
449 const symbol = event.get_key_symbol();
450 if (symbol === Clutter.KEY_Left || symbol === Clutter.KEY_Right) {
451 const direction = symbol === Clutter.KEY_Left
452 ? St.DirectionType.LEFT : St.DirectionType.RIGHT;
453 if (this.menu.actor.navigate_focus(global.stage.key_focus, direction, false))
454 return Clutter.EVENT_STOP;
455 }
456 return super._onMenuKeyPress(actor, event);
457 }
458
459 _onOpenStateChanged(menu, open) {
460 if (open) {
461 if (this.reloadFlag) {
462 this._redisplay();
463 this.reloadFlag = false;
464 }
465 this.mainBox.show();
466 }
467 super._onOpenStateChanged(menu, open);
468 }
469
470 _redisplay() {
471 this.applicationsBox.destroy_all_children();
472 this.categoriesBox.destroy_all_children();
473 this._display();
474 }
475
476 _loadCategory(categoryId, dir) {
477 const iter = dir.iter();
478 let nextType;
479 while ((nextType = iter.next()) !== GMenu.TreeItemType.INVALID) {
480 if (nextType === GMenu.TreeItemType.ENTRY) {
481 const entry = iter.get_entry();
482 let id;
483 try {
484 id = entry.get_desktop_file_id(); // catch non-UTF8 filenames
485 } catch {
486 continue;
487 }
488 let app = this._appSys.lookup_app(id);
489 if (!app)
490 app = new Shell.App({app_info: entry.get_app_info()});
491 if (app.get_app_info().should_show())
492 this.applicationsByCategory[categoryId].push(app);
493 } else if (nextType === GMenu.TreeItemType.SEPARATOR) {
494 this.applicationsByCategory[categoryId].push('separator');
495 } else if (nextType === GMenu.TreeItemType.DIRECTORY) {
496 const subdir = iter.get_directory();
497 if (!subdir.get_is_nodisplay())
498 this._loadCategory(categoryId, subdir);
499 }
500 }
501 }
502
503 scrollToButton(button) {
504 const appsScrollBoxAdj = this.applicationsScrollBox.get_vadjustment();
505 const appsScrollBoxAlloc = this.applicationsScrollBox.get_allocation_box();
506 const currentScrollValue = appsScrollBoxAdj.get_value();
507 const boxHeight = appsScrollBoxAlloc.y2 - appsScrollBoxAlloc.y1;
508 const buttonAlloc = button.get_allocation_box();
509 let newScrollValue = currentScrollValue;
510 if (currentScrollValue > buttonAlloc.y1 - 10)
511 newScrollValue = buttonAlloc.y1 - 10;
512 if (boxHeight + currentScrollValue < buttonAlloc.y2 + 10)
513 newScrollValue = buttonAlloc.y2 - boxHeight + 10;
514 if (newScrollValue !== currentScrollValue)
515 appsScrollBoxAdj.set_value(newScrollValue);
516 }
517
518 scrollToCatButton(button) {
519 const catsScrollBoxAdj = this.categoriesScrollBox.get_vadjustment();
520 const catsScrollBoxAlloc = this.categoriesScrollBox.get_allocation_box();
521 const currentScrollValue = catsScrollBoxAdj.get_value();
522 const boxHeight = catsScrollBoxAlloc.y2 - catsScrollBoxAlloc.y1;
523 const buttonAlloc = button.get_allocation_box();
524 let newScrollValue = currentScrollValue;
525 if (currentScrollValue > buttonAlloc.y1 - 10)
526 newScrollValue = buttonAlloc.y1 - 10;
527 if (boxHeight + currentScrollValue < buttonAlloc.y2 + 10)
528 newScrollValue = buttonAlloc.y2 - boxHeight + 10;
529 if (newScrollValue !== currentScrollValue)
530 catsScrollBoxAdj.set_value(newScrollValue);
531 }
532
533 _createLayout() {
534 const section = new PopupMenu.PopupMenuSection();
535 this.menu.addMenuItem(section);
536 this.mainBox = new St.BoxLayout({layoutManager: new MainLayout()});
537 this.leftBox = new St.BoxLayout({
538 orientation: Clutter.Orientation.VERTICAL,
539 });
540 this.applicationsScrollBox = new St.ScrollView({
541 style_class: 'apps-menu vfade',
542 x_expand: true,
543 });
544 this.categoriesScrollBox = new St.ScrollView({
545 style_class: 'vfade',
546 });
547 this.leftBox.add_child(this.categoriesScrollBox);
548
549 this.applicationsBox = new St.BoxLayout({
550 orientation: Clutter.Orientation.VERTICAL,
551 });
552 this.applicationsScrollBox.set_child(this.applicationsBox);
553 this.categoriesBox = new St.BoxLayout({
554 orientation: Clutter.Orientation.VERTICAL,
555 });
556 this.categoriesScrollBox.set_child(this.categoriesBox);
557
558 this.mainBox.add_child(this.leftBox);
559 this.mainBox.add_child(this.applicationsScrollBox);
560 section.actor.add_child(this.mainBox);
561 }
562
563 _display() {
564 this._applicationsButtons.clear();
565 this.mainBox.hide();
566
567 // Load categories
568 this.applicationsByCategory = {};
569 this._tree.load_sync();
570 const root = this._tree.get_root_directory();
571 let categoryMenuItem = new CategoryMenuItem(this, null);
572 this.categoriesBox.add_child(categoryMenuItem);
573 const iter = root.iter();
574 let nextType;
575 while ((nextType = iter.next()) !== GMenu.TreeItemType.INVALID) {
576 if (nextType !== GMenu.TreeItemType.DIRECTORY)
577 continue;
578
579 const dir = iter.get_directory();
580 if (dir.get_is_nodisplay())
581 continue;
582
583 const categoryId = dir.get_menu_id();
584 this.applicationsByCategory[categoryId] = [];
585 this._loadCategory(categoryId, dir);
586 if (this.applicationsByCategory[categoryId].length > 0) {
587 categoryMenuItem = new CategoryMenuItem(this, dir);
588 this.categoriesBox.add_child(categoryMenuItem);
589 }
590 }
591
592 // Load applications
593 this._displayButtons(this._listApplications(null));
594 }
595
596 selectCategory(dir) {
597 this.applicationsBox.get_children().forEach(c => {
598 if (c._delegate instanceof PopupMenu.PopupSeparatorMenuItem)
599 c._delegate.destroy();
600 else
601 this.applicationsBox.remove_child(c);
602 });
603
604 if (dir)
605 this._displayButtons(this._listApplications(dir.get_menu_id()));
606 else
607 this._displayButtons(this._listApplications(null));
608 }
609
610 _displayButtons(apps) {
611 for (let i = 0; i < apps.length; i++) {
612 const app = apps[i];
613 let item;
614 if (app instanceof Shell.App)
615 item = this._applicationsButtons.get(app);
616 else
617 item = new PopupMenu.PopupSeparatorMenuItem();
618 if (!item) {
619 item = new ApplicationMenuItem(this, app);
620 item.setDragEnabled(this._desktopTarget.hasDesktop);
621 this._applicationsButtons.set(app, item);
622 }
623 if (!item.get_parent())
624 this.applicationsBox.add_child(item);
625 }
626 }
627
628 _listApplications(categoryMenuId) {
629 let applist;
630
631 if (categoryMenuId) {
632 applist = this.applicationsByCategory[categoryMenuId];
633 } else {
634 applist = global.settings.get_strv('favorite-apps')
635 .map(id => this._appSys.lookup_app(id))
636 .filter(app => app);
637 }
638
639 return applist;
640 }
641 }
642
643 export default class AppsMenuExtension extends Extension {
644 enable() {
645 this._appsMenuButton = new ApplicationsButton(this.getSettings());
646 const index = Main.sessionMode.panel.left.indexOf('activities') + 1;
647 Main.panel.addToStatusArea(
648 'apps-menu', this._appsMenuButton, index, 'left');
649 }
650
651 disable() {
652 Main.panel.menuManager.removeMenu(this._appsMenuButton.menu);
653 this._appsMenuButton.destroy();
654 this._appsMenuButton = null;
655 }
656 }