Debian Codegraph @

extensions/workspace-indicator/workspaceIndicator.js

raw
1 // SPDX-FileCopyrightText: 2011 Erick Pérez Castellanos <[email protected]>
2 // SPDX-FileCopyrightText: 2011 Giovanni Campagna <[email protected]>
3 // SPDX-FileCopyrightText: 2017 Florian Müllner <[email protected]>
4 //
5 // SPDX-License-Identifier: GPL-2.0-or-later
6
7 import Clutter from 'gi://Clutter';
8 import Gio from 'gi://Gio';
9 import GObject from 'gi://GObject';
10 import Meta from 'gi://Meta';
11 import Shell from 'gi://Shell';
12 import St from 'gi://St';
13
14 import {gettext as _} from 'resource:///org/gnome/shell/extensions/extension.js';
15
16 import * as DND from 'resource:///org/gnome/shell/ui/dnd.js';
17 import * as Main from 'resource:///org/gnome/shell/ui/main.js';
18 import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js';
19 import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js';
20 import {ensureActorVisibleInScrollView} from 'resource:///org/gnome/shell/misc/animationUtils.js';
21
22 const TOOLTIP_OFFSET = 6;
23 const TOOLTIP_ANIMATION_TIME = 150;
24
25 const SCROLL_TIME = 100;
26
27 let baseStyleClassName = '';
28
29 class WindowPreview extends St.Button {
30 static {
31 GObject.registerClass(this);
32 }
33
34 constructor(window) {
35 super({
36 style_class: `${baseStyleClassName}-window-preview`,
37 });
38
39 this._delegate = this;
40 DND.makeDraggable(this, {restoreOnSuccess: true});
41
42 this._window = window;
43
44 this._window.connectObject(
45 'size-changed', () => this._checkRelayout(),
46 'position-changed', () => this._checkRelayout(),
47 'notify::minimized', this._updateVisible.bind(this),
48 'notify::skip-taskbar', this._updateVisible.bind(this),
49 this);
50 this._updateVisible();
51
52 global.display.connectObject('notify::focus-window',
53 this._onFocusChanged.bind(this), this);
54 this._onFocusChanged();
55 }
56
57 // needed for DND
58 get metaWindow() {
59 return this._window;
60 }
61
62 _onFocusChanged() {
63 if (global.display.focus_window === this._window)
64 this.add_style_class_name('active');
65 else
66 this.remove_style_class_name('active');
67 }
68
69 _checkRelayout() {
70 const monitor = Main.layoutManager.findIndexForActor(this);
71 const workArea = Main.layoutManager.getWorkAreaForMonitor(monitor);
72 if (this._window.get_frame_rect().overlap(workArea))
73 this.queue_relayout();
74 }
75
76 _updateVisible() {
77 this.visible = !this._window.skip_taskbar &&
78 this._window.showing_on_its_workspace();
79 }
80 }
81
82 class WorkspaceLayout extends Clutter.LayoutManager {
83 static {
84 GObject.registerClass(this);
85 }
86
87 vfunc_get_preferred_width() {
88 return [0, 0];
89 }
90
91 vfunc_get_preferred_height() {
92 return [0, 0];
93 }
94
95 vfunc_allocate(container, box) {
96 const monitor = Main.layoutManager.findIndexForActor(container);
97 const workArea = Main.layoutManager.getWorkAreaForMonitor(monitor);
98 const hscale = box.get_width() / workArea.width;
99 const vscale = box.get_height() / workArea.height;
100
101 for (const child of container) {
102 const childBox = new Clutter.ActorBox();
103 const frameRect = child.metaWindow.get_frame_rect();
104 childBox.set_size(
105 Math.round(Math.min(frameRect.width, workArea.width) * hscale),
106 Math.round(Math.min(frameRect.height, workArea.height) * vscale));
107 childBox.set_origin(
108 Math.round((frameRect.x - workArea.x) * hscale),
109 Math.round((frameRect.y - workArea.y) * vscale));
110 child.allocate(childBox);
111 }
112 }
113 }
114
115 class WorkspaceThumbnail extends St.Button {
116 static [GObject.properties] = {
117 'active': GObject.ParamSpec.boolean(
118 'active', null, null,
119 GObject.ParamFlags.READWRITE,
120 false),
121 };
122
123 static {
124 GObject.registerClass(this);
125 }
126
127 constructor(index) {
128 super();
129
130 const box = new St.BoxLayout({
131 style_class: 'workspace-box',
132 y_expand: true,
133 orientation: Clutter.Orientation.VERTICAL,
134 });
135 this.set_child(box);
136
137 this._preview = new St.Bin({
138 style_class: 'workspace',
139 child: new Clutter.Actor({
140 layout_manager: new WorkspaceLayout(),
141 clip_to_allocation: true,
142 x_expand: true,
143 y_expand: true,
144 }),
145 y_expand: true,
146 });
147 box.add_child(this._preview);
148
149 this._tooltip = new St.Label({
150 style_class: 'dash-label',
151 visible: false,
152 });
153 Main.uiGroup.add_child(this._tooltip);
154
155 this.connect('destroy', this._onDestroy.bind(this));
156 this.connect('notify::hover', this._syncTooltip.bind(this));
157
158 this._index = index;
159 this._delegate = this; // needed for DND
160
161 this._windowPreviews = new Map();
162
163 const workspaceManager = global.workspace_manager;
164 this._workspace = workspaceManager.get_workspace_by_index(index);
165
166 this._workspace.bind_property('active',
167 this, 'active',
168 GObject.BindingFlags.SYNC_CREATE);
169
170 this._workspace.connectObject(
171 'window-added', (ws, window) => this._addWindow(window),
172 'window-removed', (ws, window) => this._removeWindow(window),
173 this);
174
175 global.display.connectObject('restacked',
176 this._onRestacked.bind(this), this);
177
178 this._workspace.list_windows().forEach(w => this._addWindow(w));
179 this._onRestacked();
180 }
181
182 get active() {
183 return this._preview.has_style_class_name('active');
184 }
185
186 set active(active) {
187 if (active)
188 this._preview.add_style_class_name('active');
189 else
190 this._preview.remove_style_class_name('active');
191 this.notify('active');
192 }
193
194 acceptDrop(source) {
195 if (!source.metaWindow)
196 return false;
197
198 this._moveWindow(source.metaWindow);
199 return true;
200 }
201
202 handleDragOver(source) {
203 if (source.metaWindow)
204 return DND.DragMotionResult.MOVE_DROP;
205 else
206 return DND.DragMotionResult.CONTINUE;
207 }
208
209 _addWindow(window) {
210 if (this._windowPreviews.has(window))
211 return;
212
213 const preview = new WindowPreview(window);
214 preview.connect('clicked', (a, btn) => this.emit('clicked', btn));
215 this._windowPreviews.set(window, preview);
216 this._preview.child.add_child(preview);
217 }
218
219 _removeWindow(window) {
220 const preview = this._windowPreviews.get(window);
221 if (!preview)
222 return;
223
224 this._windowPreviews.delete(window);
225 preview.destroy();
226 }
227
228 _onRestacked() {
229 let lastPreview = null;
230 const windows = global.get_window_actors().map(a => a.meta_window);
231 for (let i = 0; i < windows.length; i++) {
232 const preview = this._windowPreviews.get(windows[i]);
233 if (!preview)
234 continue;
235
236 this._preview.child.set_child_above_sibling(preview, lastPreview);
237 lastPreview = preview;
238 }
239 }
240
241 _moveWindow(window) {
242 const monitorIndex = Main.layoutManager.findIndexForActor(this);
243 if (monitorIndex !== window.get_monitor())
244 window.move_to_monitor(monitorIndex);
245 window.change_workspace_by_index(this._index, false);
246 }
247
248 on_clicked() {
249 const ws = global.workspace_manager.get_workspace_by_index(this._index);
250 if (ws)
251 ws.activate(global.get_current_time());
252 }
253
254 _syncTooltip() {
255 if (this.hover) {
256 this._tooltip.set({
257 text: Meta.prefs_get_workspace_name(this._index),
258 visible: true,
259 opacity: 0,
260 });
261
262 const [stageX, stageY] = this.get_transformed_position();
263 const [thumbWidth, thumbHeight] = this.allocation.get_size();
264 const [tipWidth, tipHeight] = this._tooltip.get_size();
265 const xOffset = Math.floor((thumbWidth - tipWidth) / 2);
266 const monitor = Main.layoutManager.findMonitorForActor(this);
267 const x = Math.clamp(
268 stageX + xOffset,
269 monitor.x,
270 monitor.x + monitor.width - tipWidth);
271 const y = stageY - monitor.y > thumbHeight + TOOLTIP_OFFSET
272 ? stageY - tipHeight - TOOLTIP_OFFSET // show above
273 : stageY + thumbHeight + TOOLTIP_OFFSET; // show below
274 this._tooltip.set_position(x, y);
275 }
276
277 this._tooltip.ease({
278 opacity: this.hover ? 255 : 0,
279 duration: TOOLTIP_ANIMATION_TIME,
280 mode: Clutter.AnimationMode.EASE_OUT_QUAD,
281 onComplete: () => (this._tooltip.visible = this.hover),
282 });
283 }
284
285 _onDestroy() {
286 this._tooltip.destroy();
287 }
288 }
289
290 class WorkspacePreviews extends Clutter.Actor {
291 static {
292 GObject.registerClass(this);
293 }
294
295 constructor(params) {
296 super({
297 ...params,
298 layout_manager: new Clutter.BinLayout(),
299 reactive: true,
300 y_expand: true,
301 });
302
303 this.connect('scroll-event',
304 (a, event) => Main.wm.handleWorkspaceScroll(event));
305
306 const {workspaceManager} = global;
307
308 workspaceManager.connectObject(
309 'notify::n-workspaces', () => this._updateThumbnails(), GObject.ConnectFlags.AFTER,
310 'workspace-switched', () => this._updateScrollPosition(),
311 this);
312
313 this.connect('notify::mapped', () => {
314 if (this.mapped)
315 this._updateScrollPosition();
316 });
317
318 this._thumbnailsBox = new St.BoxLayout({
319 style_class: 'workspaces-box',
320 y_expand: true,
321 });
322
323 this._scrollView = new St.ScrollView({
324 style_class: 'workspaces-view hfade',
325 enable_mouse_scrolling: false,
326 hscrollbar_policy: St.PolicyType.EXTERNAL,
327 vscrollbar_policy: St.PolicyType.NEVER,
328 y_expand: true,
329 child: this._thumbnailsBox,
330 });
331
332 this.add_child(this._scrollView);
333
334 this._updateThumbnails();
335 }
336
337 _updateThumbnails() {
338 const {nWorkspaces} = global.workspace_manager;
339
340 this._thumbnailsBox.destroy_all_children();
341
342 for (let i = 0; i < nWorkspaces; i++)
343 this._thumbnailsBox.add_child(new WorkspaceThumbnail(i));
344
345 if (this.mapped)
346 this._updateScrollPosition();
347 }
348
349 _updateScrollPosition() {
350 const adjustment = this._scrollView.hadjustment;
351 const {upper, pageSize} = adjustment;
352 let {value} = adjustment;
353
354 const activeWorkspace =
355 [...this._thumbnailsBox].find(a => a.active);
356
357 if (!activeWorkspace)
358 return;
359
360 let offset = 0;
361 const hfade = this._scrollView.get_effect('fade');
362 if (hfade)
363 offset = hfade.fade_margins.left;
364
365 let {x1, x2} = activeWorkspace.get_allocation_box();
366 let parent = activeWorkspace.get_parent();
367 while (parent !== this._scrollView) {
368 if (!parent)
369 throw new Error('actor not in scroll view');
370
371 const box = parent.get_allocation_box();
372 x1 += box.x1;
373 x2 += box.x1;
374 parent = parent.get_parent();
375 }
376
377 if (x1 < value + offset)
378 value = Math.max(0, x1 - offset);
379 else if (x2 > value + pageSize - offset)
380 value = Math.min(upper, x2 + offset - pageSize);
381 else
382 return;
383
384 adjustment.ease(value, {
385 mode: Clutter.AnimationMode.EASE_OUT_QUAD,
386 duration: SCROLL_TIME,
387 });
388 }
389 }
390
391 class EditableMenuItem extends PopupMenu.PopupBaseMenuItem {
392 static [GObject.signals] = {
393 'edited': {},
394 };
395
396 static {
397 GObject.registerClass(this);
398 }
399
400 constructor() {
401 super({
402 style_class: 'editable-menu-item',
403 });
404 this.get_accessible()?.set_description(
405 _('Press %s to edit').format('e'));
406
407 const stack = new Shell.Stack({
408 x_expand: true,
409 x_align: Clutter.ActorAlign.START,
410 });
411 this.add_child(stack);
412
413 this.label = new St.Label({
414 y_align: Clutter.ActorAlign.CENTER,
415 });
416 stack.add_child(this.label);
417 this.label_actor = this.label;
418
419 this._entry = new St.Entry({
420 opacity: 0,
421 visible: false,
422 });
423 stack.add_child(this._entry);
424
425 this.label.bind_property('text',
426 this._entry, 'text',
427 GObject.BindingFlags.DEFAULT);
428
429 this._entry.clutter_text.connect('activate',
430 () => this._stopEditing());
431
432 this._editButton = new St.Button({
433 style_class: 'icon-button flat',
434 icon_name: 'document-edit-symbolic',
435 button_mask: St.ButtonMask.ONE,
436 toggle_mode: true,
437 x_align: Clutter.ActorAlign.END,
438 y_align: Clutter.ActorAlign.CENTER,
439 });
440 this.add_child(this._editButton);
441
442 this._editButton.connect('notify::checked', () => {
443 if (this._editButton.checked) {
444 this._editButton.icon_name = 'ornament-check-symbolic';
445 this._startEditing();
446 } else {
447 this._editButton.icon_name = 'document-edit-symbolic';
448 this._stopEditing();
449 }
450 });
451 this.connect('key-release-event', (o, event) => {
452 if (event.get_key_symbol() !== Clutter.KEY_e)
453 return Clutter.EVENT_PROPAGATE;
454
455 if (this._editButton.checked)
456 return Clutter.EVENT_PROPAGATE;
457
458 this._editButton.checked = true;
459 return Clutter.EVENT_STOP;
460 });
461
462 global.stage.connectObject('notify::key-focus', () => {
463 const {keyFocus} = global.stage;
464 if (!keyFocus || !this.contains(keyFocus))
465 this._stopEditing();
466 }, this);
467 }
468
469 _switchActor(from, to) {
470 to.visible = from.visible = true;
471 to.ease({
472 opacity: 255,
473 duration: 300,
474 mode: Clutter.AnimationMode.EASE_OUT_QUAD,
475 });
476
477 from.ease({
478 opacity: 0,
479 duration: 300,
480 mode: Clutter.AnimationMode.EASE_OUT_QUAD,
481 onComplete: () => {
482 from.visible = false;
483 },
484 });
485 }
486
487 _startEditing() {
488 this._switchActor(this.label, this._entry);
489
490 this._entry.clutter_text.set_selection(0, -1);
491 this._entry.clutter_text.grab_key_focus();
492 }
493
494 _stopEditing() {
495 if (this.label.text !== this._entry.text) {
496 this.label.text = this._entry.text;
497 this.emit('edited');
498 }
499
500 if (this._editButton.checked)
501 this._editButton.checked = false;
502
503 this._switchActor(this._entry, this.label);
504 this.navigate_focus(this, St.DirectionType.TAB_FORWARD, false);
505 }
506 }
507
508 class WorkspacesMenu extends PopupMenu.PopupMenu {
509 constructor(sourceActor, extension) {
510 super(sourceActor, 0.5, St.Side.TOP);
511
512 this.actor.add_style_class_name(`${baseStyleClassName}-menu`);
513
514 this._workspacesSection = new PopupMenu.PopupMenuSection();
515
516 // make the section scrollable to avoid growing indefinitely
517 const scrollView = new St.ScrollView({
518 style_class: 'vfade',
519 child: this._workspacesSection.box,
520 });
521 scrollView._delegate = this._workspacesSection;
522 this._workspacesSection.actor = scrollView;
523
524 this.addMenuItem(this._workspacesSection);
525
526 this.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
527
528 this.addAction(_('Settings'), () => {
529 extension.openPreferences();
530 });
531
532 this._desktopSettings =
533 new Gio.Settings({schema_id: 'org.gnome.desktop.wm.preferences'});
534 this._desktopSettings.connectObject('changed::workspace-names', () => {
535 this._updateWorkspaceLabels();
536 this.emit('active-name-changed');
537 }, this);
538
539 const {workspaceManager} = global;
540 workspaceManager.connectObject(
541 'notify::n-workspaces', () => this._updateWorkspaceItems(),
542 'workspace-switched', () => this._updateActiveIndicator(),
543 this.actor);
544 this._updateWorkspaceItems();
545 }
546
547 get activeName() {
548 const {workspaceManager} = global;
549 const active = workspaceManager.get_active_workspace_index();
550 return Meta.prefs_get_workspace_name(active);
551 }
552
553 _updateWorkspaceItems() {
554 const {workspaceManager} = global;
555 const {nWorkspaces} = workspaceManager;
556
557 const section = this._workspacesSection.box;
558 while (section.get_n_children() < nWorkspaces) {
559 const item = new EditableMenuItem();
560 item.connect('activate', (o, event) => {
561 const index = [...section].indexOf(item);
562 const workspace = workspaceManager.get_workspace_by_index(index);
563 workspace?.activate(event.get_time());
564 });
565 item.connect('edited', () => {
566 const nLabels = section.get_n_children();
567 const oldNames = this._desktopSettings.get_strv('workspace-names');
568 const newNames = [...section].map(c => c.label.text);
569 this._desktopSettings.set_strv('workspace-names',
570 [...newNames, ...oldNames.slice(nLabels)]);
571 });
572 item.connect('notify::active', () => {
573 const view = this._workspacesSection.actor;
574 if (item.active)
575 ensureActorVisibleInScrollView(view, item);
576 });
577 this._workspacesSection.addMenuItem(item);
578 }
579
580 [...section].splice(nWorkspaces).forEach(item => item.destroy());
581
582 this._updateWorkspaceLabels();
583 this._updateActiveIndicator();
584 }
585
586 _updateWorkspaceLabels() {
587 const items = [...this._workspacesSection.box];
588 items.forEach(
589 (item, i) => (item.label.text = Meta.prefs_get_workspace_name(i)));
590 }
591
592 _updateActiveIndicator() {
593 const {workspaceManager} = global;
594 const active = workspaceManager.get_active_workspace_index();
595
596 const items = [...this._workspacesSection.box];
597 items.forEach((item, i) => {
598 item.setOrnament(i === active
599 ? PopupMenu.Ornament.CHECK
600 : PopupMenu.Ornament.NONE);
601 });
602 this.emit('active-name-changed');
603 }
604 }
605
606 export class WorkspaceIndicator extends PanelMenu.Button {
607 static {
608 GObject.registerClass(this);
609 }
610
611 constructor(params = {}) {
612 super(0.5, _('Workspace Indicator'), true);
613
614 const {
615 baseStyleClass = 'workspace-indicator',
616 extension,
617 } = params;
618
619 this._settings = extension.getSettings();
620
621 baseStyleClassName = baseStyleClass;
622 this.add_style_class_name(baseStyleClassName);
623
624 this.setMenu(new WorkspacesMenu(this, extension));
625
626 const container = new St.Widget({
627 layout_manager: new Clutter.BinLayout(),
628 x_expand: true,
629 y_expand: true,
630 });
631 this.add_child(container);
632
633 this._statusBox = new St.BoxLayout();
634 container.add_child(this._statusBox);
635
636 this._statusLabel = new St.Label({
637 style_class: 'status-label',
638 x_expand: true,
639 y_align: Clutter.ActorAlign.CENTER,
640 text: this.menu.activeName,
641 });
642 this._statusBox.add_child(this._statusLabel);
643 this._statusBox.add_child(new St.Icon({
644 icon_name: 'pan-down-symbolic',
645 style_class: 'system-status-icon',
646 }));
647
648 this.menu.connect('active-name-changed',
649 () => this._statusLabel.set_text(this.menu.activeName));
650
651 this._thumbnails = new WorkspacePreviews();
652 container.add_child(this._thumbnails);
653
654 this._thumbnails.connect('button-press-event', (a, event) => {
655 if (event.get_button() !== Clutter.BUTTON_SECONDARY)
656 return Clutter.EVENT_PROPAGATE;
657
658 this.menu.toggle();
659 return Clutter.EVENT_STOP;
660 });
661
662 this.connect('scroll-event',
663 (a, event) => Main.wm.handleWorkspaceScroll(event));
664
665 this._inTopBar = false;
666 this.connect('notify::realized', () => {
667 if (!this.realized)
668 return;
669
670 this._inTopBar = Main.panel.contains(this);
671 this._updateTopBarRedirect();
672 });
673
674 this._settings.connect('changed::embed-previews',
675 () => this._updateThumbnailVisibility());
676 this._updateThumbnailVisibility();
677 }
678
679 _onDestroy() {
680 if (this._inTopBar)
681 Main.panel.set_offscreen_redirect(Clutter.OffscreenRedirect.ALWAYS);
682 this._inTopBar = false;
683
684 super._onDestroy();
685 }
686
687 _updateThumbnailVisibility() {
688 const usePreviews = this._settings.get_boolean('embed-previews');
689 this.reactive = !usePreviews;
690
691 this._thumbnails.visible = usePreviews;
692 this._statusBox.visible = !usePreviews;
693
694 if (usePreviews) {
695 this.add_style_class_name('previews');
696 this.remove_style_class_name('name-label');
697 } else {
698 this.remove_style_class_name('previews');
699 this.add_style_class_name('name-label');
700 }
701
702 this._updateTopBarRedirect();
703 }
704
705 _updateTopBarRedirect() {
706 if (!this._inTopBar)
707 return;
708
709 // Disable offscreen-redirect when showing the workspace switcher
710 // so that clip-to-allocation works
711 Main.panel.set_offscreen_redirect(this._thumbnails.visible
712 ? Clutter.OffscreenRedirect.ALWAYS
713 : Clutter.OffscreenRedirect.AUTOMATIC_FOR_OPACITY);
714 }
715 }