├── .gitignore
├── tiling-assistant@leleat-on-github
├── src
│ ├── dependencies
│ │ ├── unexported
│ │ │ └── windowManager.js
│ │ ├── prefs.js
│ │ ├── prefs
│ │ │ └── gi.js
│ │ ├── gi.js
│ │ └── shell.js
│ ├── ui
│ │ ├── shortcutListener.ui
│ │ ├── layoutRowEntry.ui
│ │ └── layoutRow.ui
│ ├── layouts_example.json
│ ├── prefs
│ │ ├── layoutRowEntry.js
│ │ ├── shortcutListener.js
│ │ ├── layoutRow.js
│ │ └── layoutsPrefs.js
│ ├── common.js
│ └── extension
│ │ ├── tilingPopup.js
│ │ ├── altTab.js
│ │ └── layoutsManager.js
├── stylesheet.css
├── metadata.json
├── media
│ ├── preferences-desktop-apps-symbolic.svg
│ └── insert-link-symbolic.svg
├── schemas
│ └── org.gnome.shell.extensions.tiling-assistant.gschema.xml
├── prefs.js
└── extension.js
├── jsconfig.json
├── .github
├── ignore-words.txt
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ ├── create-release.yml
│ └── run-ci.yml
├── package.json
├── scripts
├── aur-build
│ ├── .SRCINFO
│ ├── INSTALL
│ └── PKGBUILD
├── update-tl.sh
├── build.sh
└── release.sh
├── ambient.d.ts
├── README.md
├── eslint.config.js
├── CHANGELOG.md
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | *.zip
2 | *~
3 | gschemas.compiled
4 | locale/
5 | node_modules/
6 | TODO.txt
7 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/dependencies/unexported/windowManager.js:
--------------------------------------------------------------------------------
1 | export const WINDOW_ANIMATION_TIME = 250;
2 |
--------------------------------------------------------------------------------
/jsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "NodeNext",
4 | "target": "ESNext",
5 | "baseUrl": "."
6 | },
7 | "exclude": ["node_modules"]
8 | }
9 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/dependencies/prefs.js:
--------------------------------------------------------------------------------
1 | export {
2 | ExtensionPreferences,
3 | gettext as _
4 | } from 'resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js';
5 |
--------------------------------------------------------------------------------
/.github/ignore-words.txt:
--------------------------------------------------------------------------------
1 | allws
2 | Distro
3 | finalX
4 | finalY
5 | fullscreen
6 | gettext
7 | Journalctl
8 | journalctl
9 | leleat
10 | Msgid
11 | msgid
12 | msgstr
13 | prefs
14 | Rects
15 | Untiling
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/stylesheet.css:
--------------------------------------------------------------------------------
1 | .tiling-layout-search-highlight {
2 | background-color: rgba(255, 255, 255, 0.1);
3 | border-radius: 20px;
4 | }
5 |
6 | .layout-shortcut .boxed-list {
7 | box-shadow: none;
8 | }
9 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/dependencies/prefs/gi.js:
--------------------------------------------------------------------------------
1 | export { default as Adw } from 'gi://Adw';
2 | export { default as Gdk } from 'gi://Gdk';
3 | export { default as Gio } from 'gi://Gio';
4 | export { default as GLib } from 'gi://GLib';
5 | export { default as GObject } from 'gi://GObject';
6 | export { default as Gtk } from 'gi://Gtk';
7 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/dependencies/gi.js:
--------------------------------------------------------------------------------
1 | export { default as Atk } from 'gi://Atk';
2 | export { default as Clutter } from 'gi://Clutter';
3 | export { default as Gio } from 'gi://Gio';
4 | export { default as GLib } from 'gi://GLib';
5 | export { default as GObject } from 'gi://GObject';
6 | export { default as Meta } from 'gi://Meta';
7 | export { default as Mtk } from 'gi://Mtk';
8 | export { default as Shell } from 'gi://Shell';
9 | export { default as St } from 'gi://St';
10 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/metadata.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Expand GNOME's 2 column tiling and add a Windows-snap-assist-inspired popup...",
3 | "name": "Tiling Assistant",
4 | "shell-version": [
5 | "48",
6 | "49",
7 | "50"
8 | ],
9 | "url": "https://github.com/Leleat/Tiling-Assistant",
10 | "uuid": "tiling-assistant@leleat-on-github",
11 | "gettext-domain": "tiling-assistant@leleat-on-github",
12 | "settings-schema": "org.gnome.shell.extensions.tiling-assistant",
13 | "version": 53
14 | }
15 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/media/preferences-desktop-apps-symbolic.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: bug
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 |
12 | **Steps To Reproduce**
13 |
14 | **System Info:**
15 | - Distro (incl. version):
16 | - GNOME Shell version:
17 | - Extension version and from where (e. g. EGO, `main` branch...):
18 | - XOrg/Wayland:
19 |
20 | **Journalctl logs**
21 |
22 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "tiling-assistant",
3 | "version": "46.0",
4 | "description": "Expand GNOME's 2 column tiling and add a Windows-snap-assist-inspired popup...",
5 | "private": true,
6 | "homepage": "https://github.com/Leleat/Tiling-Assistant",
7 | "main": "tiling-assistant@leleat-on-github/extension.js",
8 | "scripts": {},
9 | "author": "Leleat",
10 | "license": "GPL-2.0-or-later",
11 | "type": "module",
12 | "devDependencies": {
13 | "@eslint/js": "^9.0.0",
14 | "@girs/gjs": "^4.0.0-beta.19",
15 | "@girs/gnome-shell": "^47.0.1",
16 | "eslint": "^9.0.0"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/scripts/aur-build/.SRCINFO:
--------------------------------------------------------------------------------
1 | pkgbase = gnome-shell-extension-tiling-assistant
2 | pkgdesc = A GNOME Shell extension to expand GNOME's native 2 column design.
3 | pkgver = 53
4 | pkgrel = 1
5 | url = https://github.com/Leleat/Tiling-Assistant
6 | install = INSTALL
7 | arch = x86_64
8 | license = GPL2
9 | makedepends = gettext
10 | depends = gnome-shell
11 | provides = gnome-shell-extension-tiling-assistant
12 | conflicts = gnome-shell-extension-tiling-assistant
13 | source = gnome-shell-extension-tiling-assistant::git+https://github.com/Leleat/Tiling-Assistant.git#tag=v53
14 | sha256sums = SKIP
15 |
16 | pkgname = gnome-shell-extension-tiling-assistant
17 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest a new feature
4 | title: ''
5 | labels: enhancement
6 | assignees: ''
7 |
8 | ---
9 |
10 |
14 |
15 | **Briefly describe how the feature should work**
16 |
17 |
18 |
19 | **Explain why this feature should be added**
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.github/workflows/create-release.yml:
--------------------------------------------------------------------------------
1 | name: Release
2 | run-name: Create Release
3 | on:
4 | push:
5 | tags:
6 | - "v*"
7 | jobs:
8 | release:
9 | name: Create release
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v3
13 | - run: sudo apt-get update -q && sudo apt-get install gettext
14 | - run: bash scripts/build.sh
15 | - uses: svenstaro/upload-release-action@2.5.0
16 | with:
17 | file: tiling-assistant@leleat-on-github.shell-extension.zip
18 | overwrite: true
19 | release_name: Tiling Assistant ${{ github.ref_name }}
20 | body: "Read about all the changes [here](https://github.com/Leleat/Tiling-Assistant/blob/main/CHANGELOG.md#${{ github.ref_name }})."
21 |
--------------------------------------------------------------------------------
/scripts/update-tl.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # exit, if a command fails
4 | set -e
5 |
6 | # cd to repo dir
7 | SCRIPT_DIR="$( cd "$( dirname "$0" )" && pwd )"
8 | cd "$SCRIPT_DIR"/../
9 |
10 | # update main.pot
11 | echo -n Updating \'translations/main.pot\'
12 | xgettext \
13 | --from-code=UTF-8 \
14 | --output=translations/main.pot \
15 | --add-comments='Translators:' \
16 | ./tiling-assistant@leleat-on-github/*/*/*.ui \
17 | ./tiling-assistant@leleat-on-github/*.js \
18 | ./tiling-assistant@leleat-on-github/*/*.js \
19 | ./tiling-assistant@leleat-on-github/*/*/*.js
20 | echo \ ......... done.
21 |
22 | # update .po files
23 | for FILE in translations/*.po; do
24 | echo -n "Updating '$FILE' "
25 | msgmerge -NU "$FILE" translations/main.pot
26 | done
27 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/dependencies/shell.js:
--------------------------------------------------------------------------------
1 | export {
2 | Extension,
3 | gettext as _
4 | } from 'resource:///org/gnome/shell/extensions/extension.js';
5 |
6 | export * as AppFavorites from 'resource:///org/gnome/shell/ui/appFavorites.js';
7 | export * as AltTab from 'resource:///org/gnome/shell/ui/altTab.js';
8 | export * as Main from 'resource:///org/gnome/shell/ui/main.js';
9 | export * as OsdWindow from 'resource:///org/gnome/shell/ui/osdWindow.js';
10 | export * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js';
11 | export * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js';
12 | export * as SwitcherPopup from 'resource:///org/gnome/shell/ui/switcherPopup.js';
13 | export * as WindowManager from 'resource:///org/gnome/shell/ui/windowManager.js';
14 |
--------------------------------------------------------------------------------
/ambient.d.ts:
--------------------------------------------------------------------------------
1 | import "@girs/gjs";
2 | import "@girs/gjs/dom";
3 | import "@girs/gnome-shell/ambient";
4 | import "@girs/gnome-shell/extensions/global";
5 |
6 | /***********************
7 | * Module Augmentation *
8 | ***********************/
9 |
10 | import "tiling-assistant@leleat-on-github/src/dependencies/gi.js";
11 | import { Rect } from "tiling-assistant@leleat-on-github/src/extension/utility.js";
12 |
13 | declare module "tiling-assistant@leleat-on-github/src/dependencies/gi.js" {
14 | namespace Clutter {
15 | interface Actor {
16 | ease: (params: object) => void;
17 | }
18 | }
19 |
20 | namespace GObject {
21 | interface Object {
22 | connectObject: (...args: unknown[]) => void;
23 | disconnectObject: (object: object) => void;
24 | }
25 | }
26 |
27 | namespace Meta {
28 | interface Window {
29 | assertExistence: () => void;
30 | isTiled: boolean
31 | tiledRect?: Rect
32 | untiledRect?: Rect
33 | }
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/scripts/aur-build/INSTALL:
--------------------------------------------------------------------------------
1 | ## arg 1: the new package version
2 | post_install() {
3 | echo ""
4 | echo -------------------------------------------------------------------------------
5 | echo Reload GNOME Shell and enable the extension to finish the installation process.
6 | echo -------------------------------------------------------------------------------
7 | echo
8 | }
9 |
10 | ## arg 1: the new package version
11 | ## arg 2: the old package version
12 | post_upgrade() {
13 | echo ""
14 | echo -------------------------------------------------
15 | echo Reload GNOME Shell to finish the upgrade process.
16 | echo -------------------------------------------------
17 | echo
18 | }
19 |
20 | ## arg 1: the old package version
21 | post_remove() {
22 | echo ""
23 | echo ---------------------------------------------------------
24 | echo Reload GNOME Shell to finish the uninstallation process.
25 | echo ""
26 | echo If you didn\'t disable the extension before removal, run
27 | echo "'gsettings set org.gnome.mutter edge-tiling true ; \\"
28 | echo gsettings set org.gnome.shell.overrides edge-tiling true\'
29 | echo to re-enable GNOME\'s native edge tiling.
30 | echo ---------------------------------------------------------
31 | echo
32 | }
33 |
--------------------------------------------------------------------------------
/scripts/aur-build/PKGBUILD:
--------------------------------------------------------------------------------
1 | # Maintainer: Leleat
2 | # Contributor: VeldoraTheDragon <127216238+VeldoraTheDragon@users.noreply.github.com>
3 |
4 | pkgname=gnome-shell-extension-tiling-assistant
5 | pkgver=53
6 | pkgrel=1
7 | pkgdesc="A GNOME Shell extension to expand GNOME's native 2 column design."
8 | arch=('x86_64')
9 | url="https://github.com/Leleat/Tiling-Assistant"
10 | license=('GPL2')
11 | depends=('gnome-shell')
12 | install='INSTALL'
13 | makedepends=('gettext')
14 | provides=("${pkgname}")
15 | conflicts=("${pkgname}")
16 | source=("${pkgname}::git+https://github.com/Leleat/Tiling-Assistant.git#tag=v${pkgver}")
17 | sha256sums=('SKIP')
18 |
19 | _uuid="tiling-assistant@leleat-on-github"
20 |
21 | prepare() {
22 | install -dm755 "${srcdir}/${pkgname}/${_uuid}/locale"
23 | }
24 |
25 | build() {
26 | cd "${srcdir}/${pkgname}/${_uuid}"
27 |
28 | # compile gschema
29 | glib-compile-schemas ./schemas/
30 |
31 | # compile tl
32 | for FILE in ${srcdir}/${pkgname}/translations/*.po; do
33 | LANG=$(basename "$FILE" .po)
34 | mkdir -p "${srcdir}/${pkgname}/${_uuid}/locale/$LANG/LC_MESSAGES"
35 | msgfmt -c "$FILE" -o "${srcdir}/${pkgname}/${_uuid}/locale/$LANG/LC_MESSAGES/${_uuid}.mo"
36 | done
37 | }
38 |
39 | package() {
40 | install -dm755 "${pkgdir}/usr/share/gnome-shell/extensions"
41 | cp -r "${srcdir}/${pkgname}/${_uuid}" "${pkgdir}/usr/share/gnome-shell/extensions/${_uuid}"
42 | }
43 |
--------------------------------------------------------------------------------
/scripts/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # exit, if a command fails
4 | set -e
5 |
6 | # cd to repo dir
7 | SCRIPT_DIR="$( cd "$( dirname "$0" )" && pwd )"
8 | cd "$SCRIPT_DIR"/../
9 |
10 | # compile settings
11 | glib-compile-schemas tiling-assistant@leleat-on-github/schemas
12 |
13 | # compile tl: requires gettext
14 | for FILE in translations/*.po; do
15 | LANG=$(basename "$FILE" .po)
16 | mkdir -p "tiling-assistant@leleat-on-github/locale/$LANG/LC_MESSAGES"
17 | msgfmt -c "$FILE" -o "tiling-assistant@leleat-on-github/locale/$LANG/LC_MESSAGES/tiling-assistant@leleat-on-github.mo"
18 | done
19 |
20 | # create zip package and delete locale directory
21 | rm -f tiling-assistant@leleat-on-github.shell-extension.zip
22 | cd tiling-assistant@leleat-on-github
23 | zip -qr tiling-assistant@leleat-on-github.shell-extension.zip ./*
24 | cd ..
25 | mv tiling-assistant@leleat-on-github/tiling-assistant@leleat-on-github.shell-extension.zip ./
26 |
27 | while getopts i FLAG; do
28 | case $FLAG in
29 |
30 | i) echo Installing extension...
31 | gnome-extensions install --force tiling-assistant@leleat-on-github.shell-extension.zip && \
32 | rm -f tiling-assistant@leleat-on-github.shell-extension.zip && \
33 | echo Installation complete. Restart GNOME Shell and enable the extension to use it. || \
34 | exit 1;;
35 |
36 | *) echo Don\'t use any flags to just create an extension package. Use \'-i\' to additionally install the extension.
37 | exit 1;;
38 | esac
39 | done
40 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/ui/shortcutListener.ui:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
10 | True
11 | Replace the keyboard shortcuts. Press 'space' or 'return' when listening for a shortcut to append a new one to the existing shortcuts instead.
12 |
13 |
16 |
17 |
18 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/scripts/release.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # exit, if a command fails
4 | set -e
5 |
6 | # cd to repo dir
7 | SCRIPT_DIR="$( cd "$( dirname "$0" )" && pwd )"
8 | cd "$SCRIPT_DIR"/../
9 |
10 | METADATA=tiling-assistant@leleat-on-github/metadata.json
11 |
12 | # get new version nr
13 | VERSION_LINE=$(cat $METADATA | grep \"version\":)
14 | # split after ":" and trim the spaces
15 | VERSION_NR=$(echo "$VERSION_LINE" | cut -d ':' -f 2 | xargs)
16 | NEW_VERSION_NR=$((VERSION_NR + 1))
17 |
18 | # switch to new release branch
19 | git checkout -b "release-$NEW_VERSION_NR"
20 |
21 | # bump up version nr in metadata.json
22 | echo Updating metadata.json...
23 | sed -i "s/\"version\": $VERSION_NR/\"version\": $NEW_VERSION_NR/" $METADATA
24 | echo Metadata updated.
25 | echo
26 |
27 | # bump up version nr in AUR files
28 | PKGBUILD=scripts/aur-build/PKGBUILD
29 | echo Updating Arch\'s PKGBUILD...
30 | sed -i "s/pkgver=$VERSION_NR/pkgver=$NEW_VERSION_NR/" $PKGBUILD
31 | cd scripts/aur-build/
32 | makepkg --printsrcinfo > .SRCINFO
33 | cd ../../
34 | echo PKGBUILD updated.
35 | echo
36 |
37 | # update translations
38 | bash scripts/update-tl.sh
39 | echo
40 |
41 | # package zip for EGO
42 | bash scripts/build.sh
43 |
44 | # commit changes
45 | echo Committing version bump...
46 | git add $METADATA $PKGBUILD CHANGELOG.md scripts/aur-build/.SRCINFO translations/*.po translations/*.pot
47 | git commit -m "Release: Bump version to $NEW_VERSION_NR"
48 | echo
49 |
50 | echo Release done.
51 | echo
52 |
53 | echo TODO:
54 | echo
55 | echo [] Push release branch and and create pull request
56 | echo [] Create and push tag
57 | echo [] Upload the extension to EGO
58 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/ui/layoutRowEntry.ui:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 8
6 |
7 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/.github/workflows/run-ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | run-name: Check ${{ github.ref_name }} by @${{ github.actor }}
3 | on: pull_request
4 | jobs:
5 | linters:
6 | name: Run linters
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/checkout@v3
10 | with:
11 | fetch-depth: 0
12 | - uses: actions/setup-node@v3
13 | with:
14 | node-version: "*"
15 | - name: Prepare Linters
16 | run: npm i
17 | - name: Run ESLint (*.js)
18 | run: >
19 | git diff --name-only --diff-filter=ACMTUXB origin/${{ github.base_ref }} HEAD |
20 | grep -E "\.js$" |
21 | xargs -r npx eslint
22 | - name: Run ShellCheck (*.sh)
23 | if: success() || failure()
24 | run: >
25 | git diff --name-only --diff-filter=ACMTUXB origin/${{ github.base_ref }} HEAD |
26 | grep -E "\.sh$" |
27 | xargs -r shellcheck
28 |
29 | spellcheck:
30 | name: Run spell check
31 | runs-on: ubuntu-latest
32 | steps:
33 | - uses: actions/checkout@v3
34 | with:
35 | fetch-depth: 0
36 | - uses: actions/setup-node@v3
37 | with:
38 | node-version: "*"
39 | - run: pip install codespell
40 | # The case sensitivity of codespeller for ignore-words seems to be buggy. See
41 | # issue tracker. According to the help page it should be case sensitive but
42 | # only 'allws' makes codespeller ignore 'allWs' in code files.
43 | - name: Run codespell
44 | run: >
45 | git diff --name-only --diff-filter=ACMTUXB origin/${{ github.base_ref }} HEAD |
46 | xargs -r codespell -q 3 --skip="*.po*,*.git/*" --ignore-words .github/ignore-words.txt
47 |
48 | build:
49 | name: Run build
50 | runs-on: ubuntu-latest
51 | steps:
52 | - uses: actions/checkout@v3
53 | - run: sudo apt-get update -q && sudo apt-get install gettext
54 | - run: bash scripts/build.sh
55 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/media/insert-link-symbolic.svg:
--------------------------------------------------------------------------------
1 |
2 |
47 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Tiling Assistant
2 |
3 | Tiling Assistant is a GNOME Shell extension which adds a Windows-like snap assist to the GNOME desktop. It expands GNOME's 2 column tiling layout and adds many more features.
4 |
5 | ## Features
6 |
7 | Please visit the [wiki](https://github.com/Leleat/Tiling-Assistant/wiki) for a list of all features. You'll also find videos and explanations for each of them there.
8 |
9 | ## Supported GNOME Versions
10 |
11 | The [metadata](https://github.com/Leleat/Tiling-Assistant/blob/main/tiling-assistant%40leleat-on-github/metadata.json#L4) file lists all currently supported GNOME Shell versions. Generally, only the most recent GNOME Shell is supported. That means older releases may not include all features and bug fixes. You can look at the revisions of the wiki articles to find out when a feature was added, changed, or improved. The [changelog](https://github.com/Leleat/Tiling-Assistant/blob/main/CHANGELOG.md) will show all changes in chronological order.
12 |
13 | Here is a table showing the GNOME Shell releases and the latest extension version supporting them.
14 |
15 | | GNOME Shell | Tiling Assistant |
16 | |:-------------:|:-----------:|
17 | | 45 | 44 |
18 | | 44 | 43 |
19 | | 43 | 43 |
20 | | 42 | 36 |
21 | | 41 | 32 |
22 | | 40 | 32 |
23 | | 3.38 | 23 |
24 | | 3.36 | 23 |
25 |
26 | ## Installation
27 |
28 | You can install it via https://extensions.gnome.org/extension/3733/tiling-assistant/. Alternatively, or if you want an up-to-date version, download / clone the repository and run the `scripts/build.sh` script with the `-i` flag. Make sure to have `gettext` installed. If you've manually installed the extension, you need to reload GNOME Shell afterwards (e.g. by logging out). It's also on the AUR but that repository is maintained by a 3rd party.
29 |
30 | ## Translation
31 |
32 | Translations are welcome! If you are already familiar with how it works, feel free to directly open a pull request with a `YOUR_LANG.po` file at `translations/`. Don't worry, in case you don't know how to create a `.po` file. Just open an issue and I'll set everything up. You'll only need a text editor and your language skills 🙂.
33 |
34 | ## License
35 |
36 | This extension is distributed under the terms of the GNU General Public License, version 2 or later. See the license file for details.
37 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/layouts_example.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "_name": "Master and Stack [V]",
4 | "_items": [
5 | {
6 | "rect": {
7 | "x": 0,
8 | "y": 0,
9 | "width": 0.5,
10 | "height": 1
11 | },
12 | "appId": null,
13 | "loopType": null
14 | },
15 | {
16 | "rect": {
17 | "x": 0.5,
18 | "y": 0,
19 | "width": 0.5,
20 | "height": 1
21 | },
22 | "appId": null,
23 | "loopType": "h"
24 | }
25 | ]
26 | },
27 | {
28 | "_name": "N-Columns",
29 | "_items": [
30 | {
31 | "rect": {
32 | "x": 0,
33 | "y": 0,
34 | "width": 1,
35 | "height": 1
36 | },
37 | "appId": null,
38 | "loopType": "v"
39 | }
40 | ]
41 | },
42 | {
43 | "_name": "2 : 1 [V]",
44 | "_items": [
45 | {
46 | "rect": {
47 | "x": 0,
48 | "y": 0,
49 | "width": 0.66,
50 | "height": 1
51 | },
52 | "appId": null,
53 | "loopType": null
54 | },
55 | {
56 | "rect": {
57 | "x": 0.66,
58 | "y": 0,
59 | "width": 0.34,
60 | "height": 1
61 | },
62 | "appId": null,
63 | "loopType": null
64 | }
65 | ]
66 | },
67 | {
68 | "_name": "4 Quarters",
69 | "_items": [
70 | {
71 | "rect": {
72 | "x": 0,
73 | "y": 0,
74 | "width": 0.5,
75 | "height": 0.5
76 | },
77 | "appId": null,
78 | "loopType": null
79 | },
80 | {
81 | "rect": {
82 | "x": 0.5,
83 | "y": 0,
84 | "width": 0.5,
85 | "height": 0.5
86 | },
87 | "appId": null,
88 | "loopType": null
89 | },
90 | {
91 | "rect": {
92 | "x": 0,
93 | "y": 0.5,
94 | "width": 0.5,
95 | "height": 0.5
96 | },
97 | "appId": null,
98 | "loopType": null
99 | },
100 | {
101 | "rect": {
102 | "x": 0.5,
103 | "y": 0.5,
104 | "width": 0.5,
105 | "height": 0.5
106 | },
107 | "appId": null,
108 | "loopType": null
109 | }
110 | ]
111 | }
112 | ]
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/prefs/layoutRowEntry.js:
--------------------------------------------------------------------------------
1 | import { Gio, Gtk, GObject } from '../dependencies/prefs/gi.js';
2 | import { _ } from '../dependencies/prefs.js';
3 |
4 | /**
5 | * Multiple LayoutRowEntries make up a LayoutRow.js. See that file for more info.
6 | */
7 |
8 | export const LayoutRowEntry = GObject.registerClass({
9 | GTypeName: 'TilingLayoutRowEntry',
10 | Template: import.meta.url.replace(/prefs\/(.*)\.js$/, 'ui/$1.ui'),
11 | InternalChildren: [
12 | 'rectEntry',
13 | 'rectLabel',
14 | 'rectAppButton'
15 | ],
16 | Signals: { 'changed': { param_types: [GObject.TYPE_BOOLEAN] } }
17 | }, class TilingLayoutRowEntry extends Gtk.Box {
18 | _init(idx, item) {
19 | super._init({
20 | orientation: Gtk.Orientation.HORIZONTAL,
21 | spacing: 8
22 | });
23 |
24 | this._item = item;
25 |
26 | this._rectLabel.set_label(`Rect ${idx}`);
27 | const loop = item.loopType ? `--${item.loopType}` : '';
28 | const rect = item.rect;
29 | const text = Object.keys(rect).length !== 0
30 | ? `${rect.x}--${rect.y}--${rect.width}--${rect.height}${loop}`
31 | : '';
32 | this._rectEntry.get_buffer().set_text(text, -1);
33 |
34 | // Show a placeholder on the first entry, if it's empty
35 | if (!text) {
36 | if (idx === 0) {
37 | // Translators: This is a placeholder text of an entry in the prefs when defining a tiling layout.
38 | const placeholder = _("'User Guide' for help...");
39 | this._rectEntry.set_placeholder_text(placeholder);
40 | } else {
41 | this._rectEntry.set_placeholder_text('x--y--width--height[--h|v]');
42 | }
43 | }
44 |
45 | const appInfo = item.appId && Gio.DesktopAppInfo.new(item.appId);
46 | const iconName = appInfo?.get_icon().to_string() ?? 'list-add-symbolic';
47 | this._rectAppButton.set_icon_name(iconName);
48 | }
49 |
50 | _onAppButtonClicked() {
51 | // Reset app button, if it already has an app attached
52 | if (this._item.appId) {
53 | this._rectAppButton.set_icon_name('list-add-symbolic');
54 | this._item.appId = null;
55 | this.emit('changed', true);
56 |
57 | // Attach app to the button
58 | } else {
59 | const chooserDialog = new Gtk.AppChooserDialog({ modal: true });
60 | chooserDialog.get_widget().set({ show_all: true, show_other: true });
61 | chooserDialog.connect('response', (dlg, id) => {
62 | if (id === Gtk.ResponseType.OK) {
63 | const appInfo = chooserDialog.get_widget().get_app_info();
64 | const iconName = appInfo.get_icon().to_string();
65 | this._rectAppButton.set_icon_name(iconName);
66 | this._item.appId = appInfo.get_id();
67 | this.emit('changed', true);
68 | }
69 |
70 | chooserDialog.destroy();
71 | });
72 |
73 | chooserDialog.show();
74 | }
75 | }
76 |
77 | /**
78 | * @param {Gtk.Entry} entry src of the event.
79 | */
80 | _onRectEntryChanged(entry) {
81 | const text = entry.get_buffer().get_text();
82 | const [ok] = this._validateFormat(text);
83 | if (ok) {
84 | const values = text.split('--');
85 | this._item.rect = {
86 | x: parseFloat(values[0].trim()),
87 | y: parseFloat(values[1].trim()),
88 | width: parseFloat(values[2].trim()),
89 | height: parseFloat(values[3].trim())
90 | };
91 | this._item.loopType = values[4] || null;
92 | } else {
93 | this._item.rect = {};
94 | this._item.loopType = null;
95 | }
96 |
97 | this.emit('changed', ok);
98 | }
99 |
100 | /**
101 | * Validates whether `text` follows the format \
102 | * 'Float--Float--Float--Float[--String]'
103 | *
104 | * @param {string} text
105 | * @returns {[boolean, string]} whether the `text` is valid and a
106 | * potential error message.
107 | */
108 | _validateFormat(text) {
109 | const values = text.split('--');
110 | // 4 -> x, y, width, height; 5 -> additionally, a loopType
111 | if (values.length < 4 || values.length > 5)
112 | return [false, 'Wrong format: invalid count.'];
113 |
114 | const notJustNrs = ['x', 'y', 'width', 'height'].some((p, idx) => {
115 | return Number.isNaN(parseFloat(values[idx].trim()));
116 | });
117 |
118 | return notJustNrs
119 | ? [false, 'Wrong format: only numbers are allowed.']
120 | : [true, ''];
121 | }
122 | });
123 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/ui/layoutRow.ui:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | vertical
8 |
9 |
10 | 12
11 | 12
12 | 12
13 | 12
14 | 12
15 |
16 |
17 | center
18 | 0
19 | 0
20 | edit-delete-symbolic
21 |
22 |
23 |
24 |
25 |
26 | center
27 | True
28 | 36
29 |
30 |
31 |
32 |
33 |
34 | 0
35 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
48 |
49 |
50 |
51 |
52 | center
53 | 0
54 | pan-down-symbolic
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 | 1
63 | 1
64 |
65 |
66 | 12
67 | 12
68 | 12
69 | 12
70 | 12
71 |
72 |
73 | 1
74 | 175
75 |
76 |
77 | 1
78 |
79 |
80 | 6
81 | vertical
82 | 6
83 |
84 |
85 | vertical
86 | 6
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 | 1
95 | 6
96 | list-add-symbolic
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 | 6
109 | 1
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 | 1
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/prefs/shortcutListener.js:
--------------------------------------------------------------------------------
1 | import { Adw, Gdk, GObject, Gtk } from '../dependencies/prefs/gi.js';
2 | import { _ } from '../dependencies/prefs.js';
3 |
4 | /**
5 | * A Widget to implement the shortcuts in the preference window.
6 | * It's an AdwActionRow, which contains a label showing the keybinding(s)
7 | * and a shortcut-clear-button.
8 | *
9 | * Some parts are from https://extensions.gnome.org/extension/2236/night-theme-switcher/.
10 | * _isBindingValid & _isKeyvalForbidden are straight up copied from its util.js
11 | * https://gitlab.com/rmnvgr/nightthemeswitcher-gnome-shell-extension/-/blob/main/src/utils.js
12 | */
13 |
14 | export const ShortcutListener = GObject.registerClass({
15 | GTypeName: 'ShortcutListener',
16 | Template: import.meta.url.replace(/prefs\/(.*)\.js$/, 'ui/$1.ui'),
17 | InternalChildren: ['keybindingLabel', 'clearButton', 'eventKeyController'],
18 | Properties: {
19 | keybinding: GObject.ParamSpec.string(
20 | 'keybinding',
21 | 'Keybinding',
22 | 'Key sequence',
23 | GObject.ParamFlags.READWRITE,
24 | null
25 | )
26 | }
27 | }, class ShortcutListener extends Adw.ActionRow {
28 | /**
29 | * Only allow 1 active ShortcutListener at a time
30 | */
31 | static isListening = false;
32 | static isAppendingShortcut = false;
33 | static listener = null;
34 | static listeningText = 'Press a shortcut...';
35 | static appendingText = 'Append a new shortcut...';
36 |
37 | /**
38 | * Starts listening for a keyboard shortcut.
39 | *
40 | * @param {ShortcutListener} shortcutListener the new active ShortcutListener
41 | */
42 | static listen(shortcutListener) {
43 | if (shortcutListener === ShortcutListener.listener)
44 | return;
45 |
46 | ShortcutListener.stopListening();
47 |
48 | shortcutListener.isActive = true;
49 | shortcutListener.setKeybindingLabel(ShortcutListener.listeningText);
50 | ShortcutListener.listener = shortcutListener;
51 | ShortcutListener.isListening = true;
52 | }
53 |
54 | /**
55 | * Stops listening for a keyboard shortcut.
56 | */
57 | static stopListening() {
58 | if (!ShortcutListener.isListening)
59 | return;
60 |
61 | ShortcutListener.isListening = false;
62 | ShortcutListener.isAppendingShortcut = false;
63 | ShortcutListener.listener.isActive = false;
64 | ShortcutListener.listener.setKeybindingLabel(ShortcutListener.listener.getKeybindingLabel());
65 | ShortcutListener.listener = null;
66 | }
67 |
68 | initialize(key, setting) {
69 | this._key = key;
70 | this._setting = setting;
71 | this.isActive = false;
72 |
73 | this.connect('realize', () => this.get_root().add_controller(this._eventKeyController));
74 |
75 | this.keybinding = this._setting.get_strv(key) ?? [];
76 | }
77 |
78 | /*
79 | * Sets the label of the keybinding.
80 | */
81 | setKeybindingLabel(label) {
82 | this._keybindingLabel.set_label(label);
83 | }
84 |
85 | /**
86 | * Gets the keybinding in a more pleasant to read format.
87 | * For example: [e,a] will become
88 | * 'Ctrl+Super+E / Super+A' or 'Disabled'
89 | *
90 | * @returns {string}
91 | */
92 | getKeybindingLabel() {
93 | const kbLabel = this.keybinding.reduce((label, kb) => {
94 | const [, keyval, mask] = Gtk.accelerator_parse(kb);
95 | const l = Gtk.accelerator_get_label(keyval, mask);
96 | if (!label)
97 | return l;
98 |
99 | return l ? `${label} / ${l}` : label;
100 | }, '');
101 |
102 | return kbLabel || _('Disabled');
103 | }
104 |
105 | _onActivated() {
106 | this.isActive ? ShortcutListener.stopListening() : ShortcutListener.listen(this);
107 | }
108 |
109 | _onKeybindingChanged() {
110 | this._setting.set_strv(this._key, this.keybinding);
111 | this._clearButton.set_sensitive(this.keybinding.length);
112 | this.setKeybindingLabel(this.getKeybindingLabel());
113 | }
114 |
115 | _onClearButtonClicked() {
116 | this.keybinding = [];
117 | ShortcutListener.stopListening();
118 | }
119 |
120 | _onKeyPressed(eventControllerKey, keyval, keycode, state) {
121 | if (this !== ShortcutListener.listener)
122 | return Gdk.EVENT_PROPAGATE;
123 |
124 | let mask = state & Gtk.accelerator_get_default_mod_mask();
125 | mask &= ~Gdk.ModifierType.LOCK_MASK;
126 |
127 | if (mask === 0) {
128 | switch (keyval) {
129 | case Gdk.KEY_BackSpace:
130 | this.keybinding = [];
131 | // falls through
132 | case Gdk.KEY_Escape:
133 | ShortcutListener.stopListening();
134 | return Gdk.EVENT_STOP;
135 | case Gdk.KEY_KP_Enter:
136 | case Gdk.KEY_Return:
137 | case Gdk.KEY_space:
138 | ShortcutListener.isAppendingShortcut = !ShortcutListener.isAppendingShortcut;
139 | this.setKeybindingLabel(ShortcutListener.isAppendingShortcut
140 | ? ShortcutListener.appendingText
141 | : ShortcutListener.listeningText
142 | );
143 | return Gdk.EVENT_STOP;
144 | }
145 | }
146 |
147 | if (!this._isBindingValid({ mask, keycode, keyval }) ||
148 | !Gtk.accelerator_valid(keyval, mask))
149 | return Gdk.EVENT_STOP;
150 |
151 | const sc = Gtk.accelerator_name_with_keycode(null, keyval, keycode, mask);
152 | this.keybinding = ShortcutListener.isAppendingShortcut ? [...this.keybinding, sc] : [sc];
153 |
154 | ShortcutListener.stopListening();
155 | return Gdk.EVENT_STOP;
156 | }
157 |
158 | /**
159 | * Checks, if the given key combo is a valid binding.
160 | *
161 | * @param {{mask: number, keycode: number, keyval:number}} combo An object
162 | * representing the key combo.
163 | * @returns {boolean} `true` if the key combo is a valid binding.
164 | */
165 | _isBindingValid({ mask, keycode, keyval }) {
166 | if ((mask === 0 || mask === Gdk.ModifierType.SHIFT_MASK) && keycode !== 0) {
167 | if (
168 | (keyval >= Gdk.KEY_a && keyval <= Gdk.KEY_z) ||
169 | (keyval >= Gdk.KEY_A && keyval <= Gdk.KEY_Z) ||
170 | (keyval >= Gdk.KEY_0 && keyval <= Gdk.KEY_9) ||
171 | (keyval >= Gdk.KEY_kana_fullstop && keyval <= Gdk.KEY_semivoicedsound) ||
172 | (keyval >= Gdk.KEY_Arabic_comma && keyval <= Gdk.KEY_Arabic_sukun) ||
173 | (keyval >= Gdk.KEY_Serbian_dje && keyval <= Gdk.KEY_Cyrillic_HARDSIGN) ||
174 | (keyval >= Gdk.KEY_Greek_ALPHAaccent && keyval <= Gdk.KEY_Greek_omega) ||
175 | (keyval >= Gdk.KEY_hebrew_doublelowline && keyval <= Gdk.KEY_hebrew_taf) ||
176 | (keyval >= Gdk.KEY_Thai_kokai && keyval <= Gdk.KEY_Thai_lekkao) ||
177 | (keyval >= Gdk.KEY_Hangul_Kiyeog && keyval <= Gdk.KEY_Hangul_J_YeorinHieuh) ||
178 | (keyval === Gdk.KEY_space && mask === 0) ||
179 | this._isKeyvalForbidden(keyval)
180 | )
181 | return false;
182 | }
183 | return true;
184 | }
185 |
186 | /**
187 | * Checks, if the given keyval is forbidden.
188 | *
189 | * @param {number} keyval The keyval number.
190 | * @returns {boolean} `true` if the keyval is forbidden.
191 | */
192 | _isKeyvalForbidden(keyval) {
193 | const forbiddenKeyvals = [
194 | Gdk.KEY_Home,
195 | Gdk.KEY_Left,
196 | Gdk.KEY_Up,
197 | Gdk.KEY_Right,
198 | Gdk.KEY_Down,
199 | Gdk.KEY_Page_Up,
200 | Gdk.KEY_Page_Down,
201 | Gdk.KEY_End,
202 | Gdk.KEY_Tab,
203 | Gdk.KEY_KP_Enter,
204 | Gdk.KEY_Return,
205 | Gdk.KEY_Mode_switch
206 | ];
207 | return forbiddenKeyvals.includes(keyval);
208 | }
209 | });
210 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/prefs/layoutRow.js:
--------------------------------------------------------------------------------
1 | import { Gdk, Gtk, GObject } from '../dependencies/prefs/gi.js';
2 | import { _ } from '../dependencies/prefs.js';
3 |
4 | import { Layout } from '../common.js';
5 | import { LayoutRowEntry } from './layoutRowEntry.js';
6 |
7 | /**
8 | * 1 LayoutRow represents 1 Layout in the preference window. It's just instanced
9 | * by layoutsPrefs.js (see that file for more details and general information
10 | * about layouts). 1 LayoutRow has a bunch of LayoutRowEntries, which each
11 | * represent a LayoutItem. A LayoutItem is a simple JS Object and has a
12 | * { rect, appId, loopType }. The rect is mandatory, the rest not.
13 | */
14 |
15 | export const LayoutRow = GObject.registerClass({
16 | GTypeName: 'TilingLayoutRow',
17 | Template: import.meta.url.replace(/prefs\/(.*)\.js$/, 'ui/$1.ui'),
18 | InternalChildren: [
19 | 'addRowEntryButton',
20 | 'deleteButton',
21 | 'drawingArea',
22 | 'entryBox',
23 | 'errorLabel',
24 | 'expanderButton',
25 | 'nameEntry',
26 | 'rectCountLabel',
27 | 'shortcut',
28 | 'revealer'
29 | ],
30 | Signals: { 'changed': { param_types: [GObject.TYPE_BOOLEAN] } }
31 | }, class TilingLayoutRow extends Gtk.ListBoxRow {
32 | // Use a static variable to make sure the indices are unique since just using
33 | // something like the child index isn't enough because the user may add *and*
34 | // delete rows at random... so 1 child index may appear multiple times
35 | static instanceCount = 0;
36 |
37 | /**
38 | * @returns {number} the number of created LayoutRows since the last time
39 | * the layouts were loaded into the preference window.
40 | */
41 | static getInstanceCount() {
42 | return TilingLayoutRow.instanceCount;
43 | }
44 |
45 | static resetInstanceCount() {
46 | TilingLayoutRow.instanceCount = 0;
47 | }
48 |
49 | /**
50 | * @param {{_name: string, _items: {rect: object, appId: ?string, loopType: ?string}[]
51 | * }|null} layout a parsed JS object representing a layout from the
52 | * layouts.json file.
53 | */
54 | _init(layout, settings) {
55 | super._init();
56 |
57 | this._settings = settings;
58 | this._layout = new Layout(layout);
59 | this._idx = TilingLayoutRow.instanceCount++;
60 | this._shortcutKey = `activate-layout${this._idx}`;
61 |
62 | // Initialize shortcut and its clear-button
63 | this._shortcut.initialize(this._shortcutKey, this._settings);
64 |
65 | // Set name. Don't use a placeholder, if there is one because of a bug
66 | // when reloading the layouts
67 | const name = this._layout.getName();
68 | this._nameEntry.get_buffer().set_text(name, -1);
69 | this._nameEntry.set_placeholder_text(name ? '' : 'Nameless Layout...');
70 |
71 | // Load the entries with values from the layout
72 | const items = this._layout.getItems();
73 | items.forEach((item, idx) => {
74 | const rowEntry = new LayoutRowEntry(idx, item);
75 | rowEntry.connect('changed', this._onRowEntryChanged.bind(this));
76 | this._entryBox.append(rowEntry);
77 | });
78 |
79 | // Show the nr of rects for a quicker overview.
80 | this._rectCountLabel.set_label(items.length ? `(${items.length})` : '');
81 |
82 | // Add one empty entry row
83 | this._onAddRowEntryButtonClicked();
84 |
85 | // Update the preview / show the errorLabel
86 | this._updatePreview();
87 | }
88 |
89 | destroy() {
90 | this.get_parent().remove(this);
91 | }
92 |
93 | activate() {
94 | this._nameEntry.grab_focus();
95 | }
96 |
97 | /**
98 | * toggles whether the layout's rects are visible.
99 | */
100 | toggleReveal() {
101 | this._revealer.reveal_child = !this._revealer.reveal_child;
102 | }
103 |
104 | /**
105 | * @returns {number} the index of this layout.
106 | */
107 | getIdx() {
108 | return this._idx;
109 | }
110 |
111 | /**
112 | * @returns {{_name: string, _items: {rect: object, appId: ?string, loopType: ?string}[]
113 | * }|null} the layout object represented by this row.
114 | */
115 | getLayout() {
116 | // First, filter out empty rows (i. e. rows without valid rects)
117 | this._layout.setItems(this._layout.getItems());
118 |
119 | // Then, remove problematic items, if the rects have problems. E. g.,
120 | // they may overlap each other, extend outside of the screen etc...
121 | // This is irreversible but fine since this function is only called
122 | // when the user presses the save button. Before that there will be
123 | // error messages shown in the preview area.
124 | let [ok, , idx] = this._layout.validate();
125 | while (this._layout.getItemCount() && !ok) {
126 | this._layout.removeItem(idx);
127 | [ok, , idx] = this._layout.validate();
128 | }
129 |
130 | return this._layout.getItemCount() ? this._layout : null;
131 | }
132 |
133 | /**
134 | * @returns {[boolean, string]} whether the preview was successful and a
135 | * potential error message.
136 | */
137 | _updatePreview() {
138 | const [ok, errMsg] = this._layout.validate();
139 | if (!ok) {
140 | // Print error in the preview area
141 | this._errorLabel.set_label(errMsg);
142 | this._drawingArea.set_draw_func(() => {});
143 | } else {
144 | // Draw the actual preview for the rects
145 | this._errorLabel.set_label('');
146 | this._drawingArea.set_draw_func((drawingArea, cr) => {
147 | const color = new Gdk.RGBA();
148 | const width = drawingArea.get_allocated_width();
149 | const height = drawingArea.get_allocated_height();
150 |
151 | cr.setLineWidth(1.0);
152 |
153 | this._layout.getItems().forEach(item => {
154 | // Rects are in a slightly transparent white with a 1px outline
155 | // and a 5px gap between the different rects
156 | const rect = item.rect;
157 | color.parse('rgba(255, 255, 255, .2)');
158 | Gdk.cairo_set_source_rgba(cr, color);
159 | cr.moveTo(rect.x * width + 5, rect.y * height + 5);
160 | cr.lineTo((rect.x + rect.width) * width - 5, rect.y * height + 5);
161 | cr.lineTo((rect.x + rect.width) * width - 5, (rect.y + rect.height) * height - 5);
162 | cr.lineTo(rect.x * width + 5, (rect.y + rect.height) * height - 5);
163 | cr.lineTo(rect.x * width + 5, rect.y * height + 5);
164 | cr.strokePreserve();
165 |
166 | // Fill the rects in transparent black.
167 | // If the rect is a 'loop', lower the transparency.
168 | color.parse(`rgba(0, 0, 0, ${item.loopType ? .1 : .3})`);
169 | Gdk.cairo_set_source_rgba(cr, color);
170 | cr.fill();
171 | });
172 |
173 | cr.$dispose();
174 | });
175 | }
176 |
177 | this._drawingArea.queue_draw();
178 | return [ok, errMsg];
179 | }
180 |
181 | _onNameEntryChanged() {
182 | const name = this._nameEntry.get_buffer().get_text();
183 | this._nameEntry.set_tooltip_text(name);
184 | this._layout.setName(name);
185 | const [ok] = this._layout.validate();
186 | this.emit('changed', ok);
187 | }
188 |
189 | _onDeleteButtonClicked() {
190 | this._settings.set_strv(this._shortcutKey, []);
191 | this.emit('changed', true);
192 | this.destroy();
193 | }
194 |
195 | _onExpanderButtonClicked() {
196 | this.toggleReveal();
197 | }
198 |
199 | _onClearShortcutButtonClicked() {
200 | this._settings.set_strv(`activate-layout${this._idx}`, []);
201 | }
202 |
203 | _onAddRowEntryButtonClicked() {
204 | const rowEntry = new LayoutRowEntry(this._layout.getItemCount(), this._layout.addItem());
205 | rowEntry.connect('changed', this._onRowEntryChanged.bind(this));
206 | this._entryBox.append(rowEntry);
207 | }
208 |
209 | _onRowEntryChanged(entry, ok) {
210 | // ok only is about the change being ok for the *individual* entry
211 | // i. e. whether their format is correct
212 | if (!ok) {
213 | this.emit('changed', ok);
214 | return;
215 | }
216 |
217 | // allOk is about whether the guiEntries are also valid as a whole
218 | const [allOk] = this._updatePreview();
219 | this.emit('changed', allOk);
220 | }
221 | });
222 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/common.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Helper classes / enums for the settings.xml used in the extension files
3 | * *and* prefs files
4 | */
5 |
6 | import { Meta } from './dependencies/gi.js';
7 |
8 | /**
9 | * A Singleton providing access to the settings.
10 | */
11 | export class Settings {
12 | static _settings;
13 |
14 | static initialize(gioSettings) {
15 | this._settings = gioSettings;
16 | }
17 |
18 | static destroy() {
19 | this._settings = null;
20 | }
21 |
22 | /**
23 | * @returns {import("./dependencies/gi.js").Gio.Settings} the Gio.Settings object.
24 | */
25 | static getGioObject() {
26 | return this._settings;
27 | }
28 |
29 | /**
30 | * Listens for the change of a setting.
31 | *
32 | * @param {string} key a settings key.
33 | * @param {*} func function to call when the setting changed.
34 | */
35 | static changed(key, func) {
36 | return this._settings.connect(`changed::${key}`, func);
37 | }
38 |
39 | static disconnect(id) {
40 | this._settings.disconnect(id);
41 | }
42 |
43 | /**
44 | * Getters
45 | */
46 |
47 | static getEnum(key) {
48 | return this._settings.get_enum(key);
49 | }
50 |
51 | static getString(key) {
52 | return this._settings.get_string(key);
53 | }
54 |
55 | static getStrv(key) {
56 | return this._settings.get_strv(key);
57 | }
58 |
59 | static getInt(key) {
60 | return this._settings.get_int(key);
61 | }
62 |
63 | static getBoolean(key) {
64 | return this._settings.get_boolean(key);
65 | }
66 |
67 | static getValue(key) {
68 | return this._settings.get_value(key);
69 | }
70 |
71 | static getUserValue(key) {
72 | return this._settings.get_user_value(key);
73 | }
74 |
75 | /**
76 | * Setters
77 | */
78 |
79 | static setEnum(key, value) {
80 | this._settings.set_enum(key, value);
81 | }
82 |
83 | static setString(key, value) {
84 | this._settings.set_string(key, value);
85 | }
86 |
87 | static setStrv(key, value) {
88 | this._settings.set_strv(key, value);
89 | }
90 |
91 | static setInt(key, value) {
92 | this._settings.set_int(key, value);
93 | }
94 |
95 | static setBoolean(key, value) {
96 | this._settings.set_boolean(key, value);
97 | }
98 |
99 | static setValue(key, value) {
100 | return this._settings.set_value(key, value);
101 | }
102 |
103 | static reset(key) {
104 | this._settings.reset(key);
105 | }
106 | }
107 |
108 | /**
109 | * A Singleton providing access to the shortcut keys except the
110 | * ones related to the Layouts.
111 | */
112 | export class Shortcuts {
113 | /**
114 | * @returns {string[]} the settings keys for the shortcuts in the same
115 | * order as they appear in the preference window.
116 | */
117 | static getAllKeys() {
118 | return [
119 | 'toggle-tiling-popup',
120 | 'tile-edit-mode',
121 | 'auto-tile',
122 | 'toggle-always-on-top',
123 | 'tile-maximize',
124 | 'tile-maximize-vertically',
125 | 'tile-maximize-horizontally',
126 | 'restore-window',
127 | 'center-window',
128 | 'tile-top-half',
129 | 'tile-bottom-half',
130 | 'tile-left-half',
131 | 'tile-right-half',
132 | 'tile-topleft-quarter',
133 | 'tile-topright-quarter',
134 | 'tile-bottomleft-quarter',
135 | 'tile-bottomright-quarter',
136 | 'tile-top-half-ignore-ta',
137 | 'tile-bottom-half-ignore-ta',
138 | 'tile-left-half-ignore-ta',
139 | 'tile-right-half-ignore-ta',
140 | 'tile-topleft-quarter-ignore-ta',
141 | 'tile-topright-quarter-ignore-ta',
142 | 'tile-bottomleft-quarter-ignore-ta',
143 | 'tile-bottomright-quarter-ignore-ta',
144 | 'debugging-show-tiled-rects',
145 | 'debugging-free-rects'
146 | ];
147 | }
148 | }
149 |
150 | export class DynamicKeybindings {
151 | // Order comes from prefs
152 | static DISABLED = 0;
153 | static FOCUS = 1;
154 | static TILING_STATE = 2;
155 | static TILING_STATE_WINDOWS = 3;
156 | static FAVORITE_LAYOUT = 4;
157 | }
158 |
159 | export const FocusHint = Object.freeze({
160 | DISABLED: 0,
161 | ANIMATED_OUTLINE: 1,
162 | ANIMATED_UPSCALE: 2,
163 | STATIC_OUTLINE: 3
164 | });
165 |
166 | export const FocusHintOutlineStyle = Object.freeze({
167 | SOLID_BG: 0,
168 | BORDER: 1
169 | });
170 |
171 | export class MoveModes {
172 | // Order comes from prefs
173 | static EDGE_TILING = 0;
174 | static ADAPTIVE_TILING = 1;
175 | static FAVORITE_LAYOUT = 2;
176 | static IGNORE_TA = 3;
177 | }
178 |
179 | export class Orientation {
180 | static H = 1;
181 | static V = 2;
182 | }
183 |
184 | export class Direction {
185 | static N = 1;
186 | static E = 2;
187 | static S = 4;
188 | static W = 8;
189 |
190 | static opposite(dir) {
191 | let opposite = 0;
192 | if (dir & this.N)
193 | opposite |= this.S;
194 | if (dir & this.S)
195 | opposite |= this.N;
196 | if (dir & this.W)
197 | opposite |= this.E;
198 | if (dir & this.E)
199 | opposite |= this.W;
200 |
201 | return opposite;
202 | }
203 | }
204 |
205 | // Classes for the layouts:
206 | // See src/prefs/layoutsPrefs.js for details on layouts.
207 | export class Layout {
208 | /**
209 | * @param {object} layout is the parsed object from the layouts file.
210 | */
211 | constructor(layout = null) {
212 | this._name = layout?._name ?? '';
213 | this._items = layout?._items ?? [];
214 | }
215 |
216 | /**
217 | * @returns {string}
218 | */
219 | getName() {
220 | return this._name;
221 | }
222 |
223 | /**
224 | * @param {string} name
225 | */
226 | setName(name) {
227 | this._name = name;
228 | }
229 |
230 | /**
231 | * @param {number} index
232 | * @returns {LayoutItem}
233 | */
234 | getItem(index) {
235 | return this._items[index];
236 | }
237 |
238 | /**
239 | * @param {LayoutItem|null} item
240 | * @returns {LayoutItem} the added item.
241 | */
242 | addItem(item = null) {
243 | item = item ?? new LayoutItem();
244 | this._items.push(item);
245 | return item;
246 | }
247 |
248 | /**
249 | * @param {number} index
250 | * @returns {LayoutItem|null} the removed item.
251 | */
252 | removeItem(index) {
253 | return this._items.splice(index, 1)[0];
254 | }
255 |
256 | /**
257 | * @param {boolean} filterOutEmptyRects
258 | * @returns {LayoutItem[]}
259 | */
260 | getItems(filterOutEmptyRects = true) {
261 | return filterOutEmptyRects
262 | ? this._items.filter(i => Object.keys(i.rect).length === 4)
263 | : this._items;
264 | }
265 |
266 | /**
267 | * @param {LayoutItem[]} items
268 | */
269 | setItems(items) {
270 | this._items = items;
271 | }
272 |
273 | /**
274 | * @param {boolean} filterOutEmptyRects
275 | * @returns {number}
276 | */
277 | getItemCount(filterOutEmptyRects = false) {
278 | return filterOutEmptyRects
279 | ? this.getItems().length
280 | : this._items.length;
281 | }
282 |
283 | /**
284 | * @returns {[boolean, string, number]} whether the layout has valid rects and
285 | * a potential error message.
286 | */
287 | validate() {
288 | const rects = this.getItems().map(i => i.rect);
289 | if (!rects.length)
290 | return [false, 'No valid rectangles defined.', -1];
291 |
292 | const getOverlapArea = (r1, r2) => {
293 | return Math.max(0, Math.min(r1.x + r1.width, r2.x + r2.width) - Math.max(r1.x, r2.x)) *
294 | Math.max(0, Math.min(r1.y + r1.height, r2.y + r2.height) - Math.max(r1.y, r2.y));
295 | };
296 |
297 | for (let i = 0; i < rects.length; i++) {
298 | const rect = rects[i];
299 |
300 | if (rect.width <= 0 || rect.width > 1)
301 | return [false, `Rectangle ${i} has an invalid width.`, i];
302 |
303 | if (rect.height <= 0 || rect.height > 1)
304 | return [false, `Rectangle ${i} has an invalid height.`, i];
305 |
306 | if (rect.x < 0 || rect.y < 0 || rect.x + rect.width > 1 || rect.y + rect.height > 1)
307 | return [false, `Rectangle ${i} extends beyond the screen.`, i];
308 |
309 | for (let j = i + 1; j < rects.length; j++) {
310 | if (getOverlapArea(rect, rects[j]) !== 0)
311 | return [false, `Rectangles ${i} and ${j} overlap.`, j];
312 | }
313 | }
314 |
315 | return [true, '', -1];
316 | }
317 | }
318 |
319 | var LayoutItem = class LayoutItem {
320 | constructor() {
321 | this.rect = {};
322 | this.appId = null;
323 | this.loopType = null;
324 | }
325 | };
326 |
327 | export function is_wayland_compositor() {
328 | return Meta.is_wayland_compositor === undefined ||
329 | Meta.is_wayland_compositor();
330 | }
331 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/schemas/org.gnome.shell.extensions.tiling-assistant.gschema.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | true
9 |
10 |
11 | false
12 |
13 |
14 | true
15 |
16 |
17 | false
18 |
19 |
20 |
21 | 0
22 |
23 |
24 | 0
25 |
26 |
27 | ''
28 |
29 |
30 | 8
31 |
32 |
33 | 8
34 |
35 |
36 |
37 | 0
38 |
39 |
40 | 0
41 |
42 |
43 | 0
44 |
45 |
46 | 0
47 |
48 |
49 | 0
50 |
51 |
52 | 0
53 |
54 |
55 | 0
56 |
57 |
58 | false
59 |
60 |
61 | true
62 |
63 |
64 |
65 |
66 |
67 | []
68 |
69 |
70 | []
71 |
72 |
73 | []
74 |
75 |
76 | []
77 |
78 |
79 | Up','KP_5']]]>
80 |
81 |
82 | []
83 |
84 |
85 | []
86 |
87 |
88 | Down']]]>
89 |
90 |
91 | []
92 |
93 |
94 | KP_8']]]>
95 |
96 |
97 | KP_2']]]>
98 |
99 |
100 | Left','KP_4']]]>
101 |
102 |
103 | Right','KP_6']]]>
104 |
105 |
106 | KP_7']]]>
107 |
108 |
109 | KP_9']]]>
110 |
111 |
112 | KP_1']]]>
113 |
114 |
115 | KP_3']]]>
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 |
144 |
145 |
146 | true
147 |
148 |
149 | false
150 |
151 |
152 | []
153 |
154 |
155 | -1
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 | false
225 |
226 |
227 | true
228 |
229 |
230 | true
231 |
232 |
233 | false
234 |
235 |
236 |
237 | 0
238 |
239 |
240 | false
241 |
242 |
243 | false
244 |
245 |
246 |
247 | 1
248 |
249 |
250 |
251 | 2
252 |
253 |
254 |
255 | 0
256 |
257 |
258 | 15
259 |
260 |
261 | 15
262 |
263 |
264 | 600
265 |
266 |
267 | false
268 |
269 |
270 | false
271 |
272 |
273 | []
274 |
275 |
276 | []
277 |
278 |
279 | -1
280 |
281 |
282 |
283 | []
284 |
285 |
286 |
287 |
--------------------------------------------------------------------------------
/eslint.config.js:
--------------------------------------------------------------------------------
1 | // Based on https://gitlab.gnome.org/GNOME/gnome-shell-extensions/-/blob/main/lint/eslintrc-gjs.yml#L67
2 |
3 | import js from "@eslint/js";
4 |
5 | export default [
6 | js.configs.recommended,
7 | {
8 | files: ["tiling-assistant@leleat-on-github/**/*.js"],
9 | languageOptions: {
10 | globals: {
11 | ARGV: "readonly",
12 | Debugger: "readonly",
13 | GIRepositoryGType: "readonly",
14 | globalThis: "readonly",
15 | global: "readonly",
16 | imports: "readonly",
17 | Intl: "readonly",
18 | log: "readonly",
19 | logError: "readonly",
20 | print: "readonly",
21 | printerr: "readonly",
22 | window: "readonly",
23 | TextEncoder: "readonly",
24 | TextDecoder: "readonly"
25 | }
26 | },
27 | rules: {
28 | "array-bracket-newline": [
29 | "error",
30 | "consistent"
31 | ],
32 | "array-bracket-spacing": [
33 | "error",
34 | "never"
35 | ],
36 | "array-callback-return": "error",
37 | "arrow-parens": [
38 | "error",
39 | "as-needed"
40 | ],
41 | "arrow-spacing": "error",
42 | "block-scoped-var": "error",
43 | "block-spacing": "error",
44 | "comma-dangle": "error",
45 | "comma-spacing": [
46 | "error",
47 | {
48 | "before": false,
49 | "after": true
50 | }
51 | ],
52 | "comma-style": [
53 | "error",
54 | "last"
55 | ],
56 | "computed-property-spacing": "error",
57 | "curly": [
58 | "error",
59 | "multi-or-nest",
60 | "consistent"
61 | ],
62 | "dot-location": [
63 | "error",
64 | "property"
65 | ],
66 | "eol-last": "error",
67 | "eqeqeq": "error",
68 | "func-call-spacing": "error",
69 | "func-name-matching": "error",
70 | "func-style": [
71 | "error",
72 | "declaration",
73 | {
74 | "allowArrowFunctions": true
75 | }
76 | ],
77 | "indent": [
78 | "error",
79 | 4,
80 | {
81 | "FunctionExpression": {
82 | "parameters": 2
83 | },
84 | "SwitchCase": 1,
85 | "ignoredNodes": ["CallExpression[callee.object.name=GObject][callee.property.name=registerClass] > ClassExpression:first-child"],
86 | "MemberExpression": "off"
87 |
88 | }
89 | ],
90 | "key-spacing": [
91 | "error",
92 | {
93 | "beforeColon": false,
94 | "afterColon": true
95 | }
96 | ],
97 | "keyword-spacing": [
98 | "error",
99 | {
100 | "before": true,
101 | "after": true
102 | }
103 | ],
104 | "linebreak-style": [
105 | "error",
106 | "unix"
107 | ],
108 | "max-nested-callbacks": "error",
109 | "max-statements-per-line": [
110 | "error",
111 | { "max": 2 }
112 | ],
113 | "new-parens": "error",
114 | "no-array-constructor": "error",
115 | "no-await-in-loop": "error",
116 | "no-caller": "error",
117 | "no-constant-condition": [
118 | "error",
119 | { "checkLoops": false }
120 | ],
121 | "no-div-regex": "error",
122 | "no-empty": [
123 | "error",
124 | { "allowEmptyCatch": true }
125 | ],
126 | "no-extra-bind": "error",
127 | "no-extra-boolean-cast": "off",
128 | "no-extra-parens": [
129 | "error",
130 | "all",
131 | {
132 | "conditionalAssign": false,
133 | "nestedBinaryExpressions": false,
134 | "returnAssign": false
135 | }
136 | ],
137 | "no-implicit-coercion": [
138 | "error",
139 | { "allow": ["!!"] }
140 | ],
141 | "no-iterator": "error",
142 | "no-label-var": "error",
143 | "no-lonely-if": "error",
144 | "no-loop-func": "error",
145 | "no-multiple-empty-lines": "error",
146 | "no-multi-spaces": "error",
147 | "no-nested-ternary": "error",
148 | "no-new-object": "error",
149 | "no-new-wrappers": "error",
150 | "no-octal-escape": "error",
151 | "no-proto": "error",
152 | "no-prototype-builtins": "off",
153 | "no-restricted-properties": [
154 | "error",
155 | {
156 | "object": "imports",
157 | "property": "format",
158 | "message": "Use template strings"
159 | },
160 | {
161 | "object": "pkg",
162 | "property": "initFormat",
163 | "message": "Use template strings"
164 | },
165 | {
166 | "object": "Lang",
167 | "property": "copyProperties",
168 | "message": "Use Object.assign()"
169 | },
170 | {
171 | "object": "Lang",
172 | "property": "bind",
173 | "message": "Use arrow notation or Function.prototype.bind()"
174 | },
175 | {
176 | "object": "Lang",
177 | "property": "Class",
178 | "message": "Use ES6 classes"
179 | }
180 | ],
181 | "no-return-assign": "error",
182 | "no-return-await": "error",
183 | "no-self-compare": "error",
184 | "no-shadow": "error",
185 | "no-shadow-restricted-names": "error",
186 | "no-spaced-func": "error",
187 | "no-tabs": "error",
188 | "no-template-curly-in-string": "error",
189 | "no-throw-literal": "error",
190 | "no-trailing-spaces": "error",
191 | "no-undef": "error",
192 | "no-unneeded-ternary": "error",
193 | "no-unused-vars": [
194 | "error",
195 | {
196 | "vars": "local",
197 | "varsIgnorePattern": "(^unused|_$)",
198 | "argsIgnorePattern": "^(unused|_)"
199 | }
200 | ],
201 | "no-useless-call": "error",
202 | "no-useless-computed-key": "error",
203 | "no-useless-concat": "error",
204 | "no-useless-constructor": "error",
205 | "no-useless-rename": "error",
206 | "no-useless-return": "error",
207 | "no-whitespace-before-property": "error",
208 | "no-with": "error",
209 | "nonblock-statement-body-position": [
210 | "error",
211 | "below"
212 | ],
213 | "object-curly-newline": [
214 | "error",
215 | {
216 | "consistent": true,
217 | "multiline": true
218 | }
219 | ],
220 | "object-curly-spacing": [
221 | "error",
222 | "always"
223 | ],
224 | "object-shorthand": "error",
225 | "operator-assignment": "error",
226 | "operator-linebreak": "error",
227 | "padded-blocks": [
228 | "error",
229 | "never"
230 | ],
231 | "prefer-numeric-literals": "error",
232 | "prefer-promise-reject-errors": "error",
233 | "prefer-rest-params": "error",
234 | "prefer-spread": "error",
235 | "prefer-template": "error",
236 | "quotes": [
237 | "error",
238 | "single",
239 | { "avoidEscape": true }
240 | ],
241 | "require-await": "error",
242 | "rest-spread-spacing": "error",
243 | "semi": [
244 | "error",
245 | "always"
246 | ],
247 | "semi-spacing": [
248 | "error",
249 | {
250 | "before": false,
251 | "after": true
252 | }
253 | ],
254 | "semi-style": "error",
255 | "space-before-blocks": [
256 | "error",
257 | "always"
258 | ],
259 | "space-before-function-paren": [
260 | "error",
261 | {
262 | "named": "never",
263 | "anonymous": "always",
264 | "asyncArrow": "always"
265 | }
266 | ],
267 | "space-in-parens": "error",
268 | "space-infix-ops": [
269 | "error",
270 | { "int32Hint": false }
271 | ],
272 | "space-unary-ops": "error",
273 | "switch-colon-spacing": "error",
274 | "symbol-description": "error",
275 | "template-curly-spacing": "error",
276 | "template-tag-spacing": "error",
277 | "unicode-bom": "error",
278 | "wrap-iife": [
279 | "error",
280 | "inside"
281 | ],
282 | "yield-star-spacing": "error",
283 | "yoda": "error"
284 | },
285 | }
286 | ];
287 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/prefs/layoutsPrefs.js:
--------------------------------------------------------------------------------
1 | import { Gio, GLib } from '../dependencies/prefs/gi.js';
2 |
3 | import { LayoutRow } from './layoutRow.js';
4 |
5 | /**
6 | * This class takes care of everything related to layouts (at least on the
7 | * preference side). It's only being instanced by prefs.js. After that, it
8 | * loads / saves layouts from / to the disk and loads the gui for managing
9 | * layouts. The gui is created by instancing a bunch of Gtk.ListBoxRows from
10 | * layoutGui.js for each layout and putting them into a Gtk.ListBox from the
11 | * prefs.ui file.
12 | *
13 | * A popup layout has a name (String) and an array of LayoutItems (JS Objects).
14 | * A LayoutItem has a rect (JS Objects), an optional (String) appId and optional
15 | * loopType (String). Only the rect is a mandatory. The name lets the user
16 | * search for a layout with the 'Search popup layout' keybinding. The rectangle's
17 | * properties range from 0 to 1 (-> relative scale to the monitor). After a layout
18 | * is activated by the user, the 'Tiling Popup' will appear at every LayoutItem's
19 | * rect and ask the user which of the open windows they want to tile to that rect.
20 | * If a loopType is set, the Tiling Popup will keep spawning at that spot and
21 | * all tiled windows will evenly share that rect until the user cancels the tiling
22 | * popup. Only then will we jump to the next LayoutItem. Possible loopTypes:
23 | * horizontal ('h') or vertical (any other non-empty string). This allows the
24 | * user to create 'Master and Stack' type of layouts. If an appId is defined,
25 | * instead of the Tiling Popup appearing, a new instance of the app will be
26 | * opened and tiled to that rect (or at least I tried to do that).
27 | *
28 | * By default, the settings for layouts are hidden behind the 'Advanced /
29 | * Experimental' switch because I used a lot of hacks / assumptions... and
30 | * I am not even using the layouts myself. However, I don't want to remove
31 | * an existing feature... thus it's hidden
32 | */
33 |
34 | export default class {
35 | constructor(settings, builder, path) {
36 | // Keep a reference to the settings for the shortcuts
37 | this._settings = settings;
38 |
39 | // The Gtk.ListBox, which LayoutRows are added to
40 | this._layoutsListBox = builder.get_object('layouts_listbox');
41 |
42 | // Unique button to save changes made to all layouts to the disk. For
43 | // simplicity, reload from file after saving to get rid of invalid input.
44 | this._saveLayoutsButton = builder.get_object('save_layouts_button');
45 | this._saveLayoutsButton.connect('clicked', () => {
46 | this._saveLayouts();
47 | this._loadLayouts();
48 | });
49 |
50 | // Unique button to load layouts from the disk
51 | // (discarding all tmp changes) without any user prompt
52 | this._reloadLayoutsButton = builder.get_object('reload_layouts_button');
53 | this._reloadLayoutsButton.connect('clicked', () => {
54 | this._loadLayouts();
55 | });
56 |
57 | // Unique button to add a new *tmp* LayoutRow
58 | this._addLayoutButton = builder.get_object('add_layout_button');
59 | this._addLayoutButton.connect('clicked', () => {
60 | const row = this._createLayoutRow(LayoutRow.getInstanceCount());
61 | row.toggleReveal();
62 | });
63 |
64 | // Bind the general layouts keyboard shortcuts.
65 | ['search-popup-layout'].forEach(key => {
66 | const shortcut = builder.get_object(key.replaceAll('-', '_'));
67 | shortcut.initialize(key, this._settings);
68 | });
69 |
70 | // Finally, load the existing settings.
71 | this._loadLayouts(path);
72 | }
73 |
74 | _loadLayouts(path) {
75 | this._applySaveButtonStyle('');
76 |
77 | this._forEachLayoutRow(row => row.destroy());
78 | LayoutRow.resetInstanceCount();
79 |
80 | // Try to load layouts file.
81 | const saveFile = this._makeFile();
82 | const [success, contents] = saveFile.load_contents(null);
83 | if (!success)
84 | return;
85 |
86 | let layouts = [];
87 |
88 | // Custom layouts are already defined in the file.
89 | if (contents.length) {
90 | layouts = JSON.parse(new TextDecoder().decode(contents));
91 | // Ensure at least 1 empty row otherwise the listbox won't have
92 | // a height but a weird looking shadow only.
93 | layouts.length
94 | ? layouts.forEach((layout, idx) => this._createLayoutRow(idx, layout))
95 | : this._createLayoutRow(0);
96 |
97 | // Otherwise import the examples... but only do it once!
98 | // Use a setting as a flag.
99 | } else {
100 | const importExamples = 'import-layout-examples';
101 | if (!this._settings.get_boolean(importExamples))
102 | return;
103 |
104 | this._settings.set_boolean(importExamples, false);
105 | const exampleFile = this._makeFile(`${path}/src`, 'layouts_example.json');
106 | const [succ, c] = exampleFile.load_contents(null);
107 | if (!succ)
108 | return;
109 |
110 | layouts = c.length ? JSON.parse(new TextDecoder().decode(c)) : [];
111 | layouts.forEach((layout, idx) => this._createLayoutRow(idx, layout));
112 | this._saveLayouts();
113 | }
114 | }
115 |
116 | _saveLayouts() {
117 | this._applySaveButtonStyle('');
118 |
119 | const layouts = [];
120 | this._forEachLayoutRow(layoutRow => {
121 | const lay = layoutRow.getLayout();
122 | if (lay) {
123 | layouts.push(lay);
124 |
125 | // Check, if all layoutRows were valid so far. Use getIdx()
126 | // instead of forEach's idx because a layoutRow may have been
127 | // deleted by the user.
128 | if (layoutRow.getIdx() === layouts.length - 1)
129 | return;
130 |
131 | // Invalid or empty layouts are ignored. For example, the user
132 | // defined a valid layout with a keybinding on row idx 3 but left
133 | // the row at idx 2 empty. When saving, the layout at idx 2 gets
134 | // removed and layout at idx 3 takes its place (i. e. becomes
135 | // idx 2). We need to update the keybindings to reflect that.
136 | const keys = this._settings.get_strv(`activate-layout${layoutRow.getIdx()}`);
137 | this._settings.set_strv(`activate-layout${layouts.length - 1}`, keys);
138 | this._settings.set_strv(`activate-layout${layoutRow.getIdx()}`, []);
139 | } else {
140 | // Remove keyboard shortcuts, if they aren't assigned to a
141 | // valid layout, because they won't be visible to the user
142 | // since invalid layouts get removed
143 | this._settings.set_strv(`activate-layout${layoutRow.getIdx()}`, []);
144 | }
145 | });
146 |
147 | const saveFile = this._makeFile();
148 | saveFile.replace_contents(
149 | JSON.stringify(layouts),
150 | null,
151 | false,
152 | Gio.FileCreateFlags.REPLACE_DESTINATION,
153 | null
154 | );
155 | }
156 |
157 | /**
158 | * @param {string} [parentPath=''] path to the parent directory.
159 | * @param {string} [fileName=''] name of the layouts file.
160 | * @returns {object} the Gio.File.
161 | */
162 | _makeFile(parentPath = '', fileName = '') {
163 | // Create directory structure, if it doesn't exist.
164 | const userConfigDir = GLib.get_user_config_dir();
165 | const dirLocation = parentPath ||
166 | GLib.build_filenamev([userConfigDir, '/tiling-assistant']);
167 | const parentDir = Gio.File.new_for_path(dirLocation);
168 |
169 | try {
170 | parentDir.make_directory_with_parents(null);
171 | } catch (e) {
172 | if (e.code !== Gio.IOErrorEnum.EXISTS)
173 | throw e;
174 | }
175 |
176 | // Create file, if it doesn't exist.
177 | const fName = fileName || 'layouts.json';
178 | const filePath = GLib.build_filenamev([dirLocation, '/', fName]);
179 | const file = Gio.File.new_for_path(filePath);
180 |
181 | try {
182 | file.create(Gio.FileCreateFlags.NONE, null);
183 | } catch (e) {
184 | if (e.code !== Gio.IOErrorEnum.EXISTS)
185 | throw e;
186 | }
187 |
188 | return file;
189 | }
190 |
191 | /**
192 | * @param {string} [actionName=''] possible styles: 'suggested-action'
193 | * or 'destructive-action'
194 | */
195 | _applySaveButtonStyle(actionName = '') {
196 | // The suggested-action is used to indicate that the user made
197 | // changes; the destructive-action, if saving will drop changes
198 | // (e. g. when changes were invalid)
199 | const actions = ['suggested-action', 'destructive-action'];
200 | const context = this._saveLayoutsButton.get_style_context();
201 | actions.forEach(a => a === actionName
202 | ? context.add_class(a)
203 | : context.remove_class(a));
204 | }
205 |
206 | /**
207 | * @param {number} index the index of the new layouts row.
208 | * @param {Layout} layout the parsed JS Object from the layouts file.
209 | */
210 | _createLayoutRow(index, layout = null) {
211 | // Layouts are limited to 20 since there are only
212 | // that many keybindings in the schemas.xml file
213 | if (index >= 20)
214 | return;
215 |
216 | const layoutRow = new LayoutRow(layout, this._settings);
217 | layoutRow.connect('changed', (row, ok) => {
218 | // Un / Highlight the save button, if the user made in / valid changes.
219 | this._applySaveButtonStyle(ok ? 'suggested-action' : 'destructive-action');
220 | });
221 | this._layoutsListBox.append(layoutRow);
222 | return layoutRow;
223 | }
224 |
225 | _forEachLayoutRow(callback) {
226 | for (let i = 0, child = this._layoutsListBox.get_first_child(); !!child; i++) {
227 | // Get a ref to the next widget in case the curr widget
228 | // gets destroyed during the function call.
229 | const nxtSibling = child.get_next_sibling();
230 | callback.call(this, child, i);
231 | child = nxtSibling;
232 | }
233 | }
234 | }
235 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/prefs.js:
--------------------------------------------------------------------------------
1 | import { Gdk, Gio, GLib, Gtk } from './src/dependencies/prefs/gi.js';
2 | import { ExtensionPreferences } from './src/dependencies/prefs.js';
3 |
4 | import LayoutPrefs from './src/prefs/layoutsPrefs.js';
5 | import { Shortcuts } from './src/common.js';
6 | import './src/prefs/shortcutListener.js';
7 |
8 | export default class Prefs extends ExtensionPreferences {
9 | fillPreferencesWindow(window) {
10 | // Load css file
11 | const provider = new Gtk.CssProvider();
12 | const path = GLib.build_filenamev([this.path, 'stylesheet.css']);
13 | provider.load_from_path(path);
14 | Gtk.StyleContext.add_provider_for_display(
15 | Gdk.Display.get_default(),
16 | provider,
17 | Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
18 | );
19 |
20 | window.set_can_navigate_back(true);
21 |
22 | const settings = this.getSettings();
23 | const builder = new Gtk.Builder();
24 | builder.set_translation_domain(this.uuid);
25 | builder.add_from_file(`${this.path}/src/ui/prefs.ui`);
26 |
27 | // Add general preference page
28 | window.add(builder.get_object('general'));
29 |
30 | // Add keybindings preference page
31 | window.add(builder.get_object('keybindings'));
32 |
33 | // Add layouts preference page on condition of advanced setting
34 | const layoutsPage = builder.get_object('layouts');
35 | settings.connect('changed::enable-advanced-experimental-features', () => {
36 | settings.get_boolean('enable-advanced-experimental-features')
37 | ? window.add(layoutsPage)
38 | : window.remove(layoutsPage);
39 | });
40 |
41 | if (settings.get_boolean('enable-advanced-experimental-features'))
42 | window.add(layoutsPage);
43 |
44 | // Bind settings to GUI
45 | this._bindSwitches(settings, builder);
46 | this._bindSpinbuttons(settings, builder);
47 | this._bindComboRows(settings, builder);
48 | this._bindRadioButtons(settings, builder);
49 | this._bindKeybindings(settings, builder);
50 | this._bindColorButtons(settings, builder);
51 |
52 | // LayoutPrefs manages everything related to layouts on the
53 | // prefs side (including the keyboard shortcuts)
54 | new LayoutPrefs(settings, builder, this.path);
55 |
56 | // Set visibility for deprecated settings
57 | this._setDeprecatedSettings(settings, builder);
58 |
59 | // Add a button into the headerbar with info
60 | this._addHeaderBarInfoButton(window, settings, builder);
61 | }
62 |
63 | /*
64 | * Bind GUI switches to settings.
65 | */
66 | _bindSwitches(settings, builder) {
67 | const switches = [
68 | 'enable-tiling-popup',
69 | 'tiling-popup-all-workspace',
70 | 'enable-raise-tile-group',
71 | 'tilegroups-in-app-switcher',
72 | 'maximize-with-gap',
73 | 'show-layout-panel-indicator',
74 | 'enable-advanced-experimental-features',
75 | 'disable-tile-groups',
76 | 'low-performance-move-mode',
77 | 'monitor-switch-grace-period',
78 | 'adapt-edge-tiling-to-favorite-layout',
79 | 'enable-tile-animations',
80 | 'enable-untile-animations',
81 | 'enable-hold-maximize-inverse-landscape',
82 | 'enable-hold-maximize-inverse-portrait'
83 | ];
84 |
85 | switches.forEach(key => {
86 | const widget = builder.get_object(key.replaceAll('-', '_'));
87 | settings.bind(key, widget, 'active', Gio.SettingsBindFlags.DEFAULT);
88 | });
89 | }
90 |
91 | /*
92 | * Bind GUI spinbuttons to settings.
93 | */
94 | _bindSpinbuttons(settings, builder) {
95 | const spinButtons = [
96 | 'window-gap',
97 | 'single-screen-gap',
98 | 'screen-top-gap',
99 | 'screen-left-gap',
100 | 'screen-right-gap',
101 | 'screen-bottom-gap',
102 | 'focus-hint-outline-size',
103 | 'focus-hint-outline-border-radius',
104 | 'toggle-maximize-tophalf-timer',
105 | 'vertical-preview-area',
106 | 'horizontal-preview-area'
107 | ];
108 |
109 | spinButtons.forEach(key => {
110 | const widget = builder.get_object(key.replaceAll('-', '_'));
111 | settings.bind(key, widget, 'value', Gio.SettingsBindFlags.DEFAULT);
112 | });
113 | }
114 |
115 | /*
116 | * Bind GUI AdwComboRows to settings.
117 | */
118 | _bindComboRows(settings, builder) {
119 | const comboRows = [
120 | 'focus-hint-outline-style',
121 | 'move-adaptive-tiling-mod',
122 | 'move-favorite-layout-mod',
123 | 'ignore-ta-mod'
124 | ];
125 |
126 | comboRows.forEach(key => {
127 | const widget = builder.get_object(key.replaceAll('-', '_'));
128 | settings.bind(key, widget, 'selected', Gio.SettingsBindFlags.DEFAULT);
129 | widget.set_selected(settings.get_int(key));
130 | });
131 | }
132 |
133 | /*
134 | * Bind GUI color buttons to settings.
135 | */
136 | _bindColorButtons(settings, builder) {
137 | const switches = [
138 | 'focus-hint-color'
139 | ];
140 |
141 | switches.forEach(key => {
142 | const widget = builder.get_object(`${key.replaceAll('-', '_')}_button`);
143 | widget.connect('color-set', () => {
144 | settings.set_string(key, widget.get_rgba().to_string());
145 | });
146 |
147 | // initialize color
148 | const rgba = new Gdk.RGBA();
149 | rgba.parse(settings.get_string(key));
150 | widget.set_rgba(rgba);
151 | });
152 | }
153 |
154 | /*
155 | * Bind radioButtons to settings.
156 | */
157 | _bindRadioButtons(settings, builder) {
158 | // These 'radioButtons' are basically just used as a 'fake ComboBox' with
159 | // explanations for the different options. So there is just *one* gsetting
160 | // (an int) which saves the current 'selection'.
161 | const radioButtons = [
162 | {
163 | key: 'dynamic-keybinding-behavior',
164 | rowNames: [
165 | 'dynamic_keybinding_disabled_row',
166 | 'dynamic_keybinding_window_focus_row',
167 | 'dynamic_keybinding_tiling_state_row',
168 | 'dynamic_keybinding_tiling_state_windows_row',
169 | 'dynamic_keybinding_favorite_layout_row'
170 | ]
171 | },
172 | {
173 | key: 'focus-hint',
174 | rowNames: [
175 | 'disabled_focus_hint_row',
176 | 'animated_outline_focus_hint_row',
177 | 'animated_upscale_focus_hint_row',
178 | 'static_outline_focus_hint_row'
179 | ]
180 | },
181 | {
182 | key: 'default-move-mode',
183 | rowNames: [
184 | 'edge_tiling_row',
185 | 'adaptive_tiling_row',
186 | 'favorite_layout_row',
187 | 'ignore_ta_row'
188 | ]
189 | }
190 | ];
191 |
192 | radioButtons.forEach(({ key, rowNames }) => {
193 | const currActive = settings.get_int(key);
194 |
195 | rowNames.forEach((name, idx) => {
196 | const row = builder.get_object(name.replaceAll('-', '_'));
197 | const checkButton = row.activatable_widget;
198 | checkButton.connect('toggled', () => settings.set_int(key, idx));
199 |
200 | // Set initial state
201 | if (idx === currActive)
202 | checkButton.activate();
203 | });
204 | });
205 | }
206 |
207 | /*
208 | * Bind keybinding widgets to settings.
209 | */
210 | _bindKeybindings(settings, builder) {
211 | const shortcuts = Shortcuts.getAllKeys();
212 | shortcuts.forEach(key => {
213 | const shortcut = builder.get_object(key.replaceAll('-', '_'));
214 | shortcut.initialize(key, settings);
215 | });
216 | }
217 |
218 | /**
219 | * Sets the visibility of deprecated settings. Those setting aren't visible
220 | * in the GUI unless they have a user set value. That means they aren't
221 | * discoverable through the GUI and need to first be set with the gsetting.
222 | * The normal rows should have the id of: GSETTING_WITH_UNDERSCORES_row.
223 | * ShortcutListeners have the format of GSETTING_WITH_UNDERSCORES.
224 | */
225 | _setDeprecatedSettings(settings, builder) {
226 | // Keybindings
227 | ['toggle-tiling-popup', 'auto-tile'].forEach(s => {
228 | const isNonDefault = settings.get_strv(s)[0] !== settings.get_default_value(s).get_strv()[0];
229 | builder.get_object(s.replaceAll('-', '_')).set_visible(isNonDefault);
230 | });
231 |
232 | // Switches
233 | ['tilegroups-in-app-switcher'].forEach(s => {
234 | const isNonDefault = settings.get_boolean(s) !== settings.get_default_value(s).get_boolean();
235 | builder.get_object(s.replaceAll('-', '_')).set_visible(isNonDefault);
236 | });
237 | }
238 |
239 | _addHeaderBarInfoButton(window, settings, builder) {
240 | // Add headerBar button for menu
241 | // TODO: is this a 'reliable' method to access the headerbar?
242 | const page = builder.get_object('general');
243 | const gtkStack = page
244 | .get_parent()
245 | .get_parent()
246 | .get_parent();
247 | const adwHeaderBar = gtkStack
248 | .get_next_sibling()
249 | .get_first_child()
250 | .get_first_child()
251 | .get_first_child();
252 |
253 | adwHeaderBar.pack_start(builder.get_object('info_menu'));
254 |
255 | // Setup menu actions
256 | const actionGroup = new Gio.SimpleActionGroup();
257 | window.insert_action_group('prefs', actionGroup);
258 |
259 | const bugReportAction = new Gio.SimpleAction({ name: 'open-bug-report' });
260 | bugReportAction.connect('activate', this._openBugReport.bind(this, window));
261 | actionGroup.add_action(bugReportAction);
262 |
263 | const userGuideAction = new Gio.SimpleAction({ name: 'open-user-guide' });
264 | userGuideAction.connect('activate', this._openUserGuide.bind(this, window));
265 | actionGroup.add_action(userGuideAction);
266 |
267 | const changelogAction = new Gio.SimpleAction({ name: 'open-changelog' });
268 | changelogAction.connect('activate', this._openChangelog.bind(this, window));
269 | actionGroup.add_action(changelogAction);
270 |
271 | const licenseAction = new Gio.SimpleAction({ name: 'open-license' });
272 | licenseAction.connect('activate', this._openLicense.bind(this, window));
273 | actionGroup.add_action(licenseAction);
274 |
275 | const hiddenSettingsAction = new Gio.SimpleAction({ name: 'open-hidden-settings' });
276 | hiddenSettingsAction.connect('activate', this._openHiddenSettings.bind(this, window, builder));
277 | actionGroup.add_action(hiddenSettingsAction);
278 |
279 | // Button to return to main settings page
280 | const returnButton = builder.get_object('hidden_settings_return_button');
281 | returnButton.connect('clicked', () => window.close_subpage());
282 | }
283 |
284 | _openBugReport(window) {
285 | Gtk.show_uri(window, 'https://github.com/Leleat/Tiling-Assistant/issues', Gdk.CURRENT_TIME);
286 | }
287 |
288 | _openUserGuide(window) {
289 | Gtk.show_uri(window, 'https://github.com/Leleat/Tiling-Assistant/wiki', Gdk.CURRENT_TIME);
290 | }
291 |
292 | _openChangelog(window) {
293 | Gtk.show_uri(window, 'https://github.com/Leleat/Tiling-Assistant/blob/main/CHANGELOG.md', Gdk.CURRENT_TIME);
294 | }
295 |
296 | _openLicense(window) {
297 | Gtk.show_uri(window, 'https://github.com/Leleat/Tiling-Assistant/blob/main/LICENSE', Gdk.CURRENT_TIME);
298 | }
299 |
300 | _openHiddenSettings(window, builder) {
301 | const hiddenSettingsPage = builder.get_object('hidden_settings');
302 | window.present_subpage(hiddenSettingsPage);
303 | }
304 | }
305 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/extension.js:
--------------------------------------------------------------------------------
1 | /* extension.js
2 | *
3 | * This program is free software: you can redistribute it and/or modify
4 | * it under the terms of the GNU General Public License as published by
5 | * the Free Software Foundation, either version 2 of the License, or
6 | * any later version.
7 | *
8 | * This program is distributed in the hope that it will be useful,
9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | * GNU General Public License for more details.
12 | *
13 | * You should have received a copy of the GNU General Public License
14 | * along with this program. If not, see .
15 | *
16 | * SPDX-License-Identifier: GPL-2.0-or-later
17 | */
18 |
19 | import { Gio, GLib, Meta } from './src/dependencies/gi.js';
20 | import { Extension, Main } from './src/dependencies/shell.js';
21 |
22 | import MoveHandler from './src/extension/moveHandler.js';
23 | import ResizeHandler from './src/extension/resizeHandler.js';
24 | import KeybindingHandler from './src/extension/keybindingHandler.js';
25 | import LayoutsManager from './src/extension/layoutsManager.js';
26 | import AltTabOverride from './src/extension/altTab.js';
27 | import FocusHintManager from './src/extension/focusHint.js';
28 | import { Rect } from './src/extension/utility.js';
29 |
30 | /**
31 | * 2 entry points:
32 | * 1. keyboard shortcuts:
33 | * => keybindingHandler.js
34 | * 2. Grabbing a window:
35 | * => moveHandler.js (when moving a window)
36 | * => resizeHandler.js (when resizing a window)
37 | */
38 |
39 | class SettingsOverrider {
40 | constructor(settingsSingleton) {
41 | this._settings = settingsSingleton;
42 | this._overrides = new Map();
43 | this._originalSettings = new Map();
44 | this._maybeNullValue = GLib.Variant.new_maybe(
45 | new GLib.VariantType('b'), null);
46 |
47 | const savedSettings = this._settings.getUserValue('overridden-settings');
48 | this._wasOverridden = savedSettings !== null;
49 | }
50 |
51 | _maybeUpdateOverriden(schemaId, key, value) {
52 | if (this._wasOverridden)
53 | return undefined;
54 |
55 | const savedSettings = this._settings.getValue(
56 | 'overridden-settings').deepUnpack();
57 | const prefKey = `${schemaId}.${key}`;
58 | const oldValue = savedSettings[prefKey];
59 |
60 | if (value !== undefined)
61 | savedSettings[prefKey] = value ?? this._maybeNullValue;
62 | else
63 | delete savedSettings[prefKey];
64 |
65 | this._settings.setValue('overridden-settings',
66 | new GLib.Variant('a{sv}', savedSettings));
67 |
68 | return oldValue;
69 | }
70 |
71 | add(settings, key, value) {
72 | this._originalSettings.set(settings.schemaId, settings);
73 | const userValue = settings.get_user_value(key);
74 |
75 | const values = this._overrides.get(settings.schemaId) ?? new Map();
76 | if (!values.size)
77 | this._overrides.set(settings.schemaId, values);
78 | values.set(key, userValue);
79 |
80 | settings.set_value(key, value);
81 |
82 | this._maybeUpdateOverriden(settings.schemaId, key,
83 | userValue ?? this._maybeNullValue);
84 | }
85 |
86 | remove(schema, key) {
87 | const settings = this._originalSettings.get(schema);
88 | if (!settings)
89 | return;
90 |
91 | const values = this._overrides.get(settings.schemaId);
92 | const value = values?.get(key);
93 |
94 | if (value === undefined)
95 | return;
96 |
97 | if (value)
98 | settings.set_value(key, value);
99 | else
100 | settings.reset(key);
101 |
102 | values.delete(key);
103 | this._maybeUpdateOverriden(settings.schemaId, key, undefined);
104 | }
105 |
106 | _clear() {
107 | if (this._wasOverridden) {
108 | const savedSettings = this._settings.getValue(
109 | 'overridden-settings').unpack();
110 |
111 | Object.entries(savedSettings).forEach(([path, value]) => {
112 | const splits = path.split('.');
113 | const key = splits.at(-1);
114 | const schemaId = splits.slice(0, -1).join('.');
115 |
116 | const settings = this._originalSettings.get(schemaId) ??
117 | new Gio.Settings({ schema_id: schemaId });
118 |
119 | value = value.get_variant();
120 | if (value.equal(this._maybeNullValue))
121 | settings.reset(key);
122 | else
123 | settings.set_value(key, value);
124 | });
125 | } else {
126 | this._originalSettings.forEach(settings => {
127 | this._overrides.get(settings.schemaId).forEach((value, key) => {
128 | if (value)
129 | settings.set_value(key, value);
130 | else
131 | settings.reset(key);
132 | });
133 | });
134 | }
135 |
136 | this._settings.reset('overridden-settings');
137 | }
138 |
139 | destroy() {
140 | this._clear();
141 | this._maybeNullValue = null;
142 | this._originalSettings = null;
143 | this._overrides = null;
144 | this._settings = null;
145 | }
146 | }
147 |
148 | export default class TilingAssistantExtension extends Extension {
149 | async enable() {
150 | this.settings = (await import('./src/common.js')).Settings;
151 | this.settings.initialize(this.getSettings());
152 | this._settingsOverrider = new SettingsOverrider(this.settings);
153 |
154 | const twmModule = await import('./src/extension/tilingWindowManager.js');
155 |
156 | this._twm = twmModule.TilingWindowManager;
157 | this._twm.initialize();
158 |
159 | this._moveHandler = new MoveHandler();
160 | this._resizeHandler = new ResizeHandler();
161 | this._keybindingHandler = new KeybindingHandler();
162 | this._layoutsManager = new LayoutsManager();
163 | this._focusHintManager = new FocusHintManager();
164 | this._altTabOverride = new AltTabOverride();
165 |
166 | // Disable native tiling.
167 | this._settingsOverrider.add(new Gio.Settings({
168 | schema_id: 'org.gnome.mutter'
169 | }), 'edge-tiling', new GLib.Variant('b', false));
170 |
171 | // Disable native keybindings for Super+Up/Down/Left/Right
172 | const gnomeMutterKeybindings = new Gio.Settings({
173 | schema_id: 'org.gnome.mutter.keybindings'
174 | });
175 | const gnomeDesktopKeybindings = new Gio.Settings({
176 | schema_id: 'org.gnome.desktop.wm.keybindings'
177 | });
178 | const emptyStrvVariant = new GLib.Variant('as', []);
179 |
180 | if (gnomeDesktopKeybindings.get_strv('maximize').includes('Up') &&
181 | this.settings.getStrv('tile-maximize').includes('Up')) {
182 | this._settingsOverrider.add(gnomeDesktopKeybindings,
183 | 'maximize', emptyStrvVariant);
184 | }
185 | if (gnomeDesktopKeybindings.get_strv('unmaximize').includes('Down') &&
186 | this.settings.getStrv('restore-window').includes('Down')) {
187 | this._settingsOverrider.add(gnomeDesktopKeybindings,
188 | 'unmaximize', emptyStrvVariant);
189 | }
190 | if (gnomeMutterKeybindings.get_strv('toggle-tiled-left').includes('Left') &&
191 | this.settings.getStrv('tile-left-half').includes('Left')) {
192 | this._settingsOverrider.add(gnomeMutterKeybindings,
193 | 'toggle-tiled-left', emptyStrvVariant);
194 | }
195 | if (gnomeMutterKeybindings.get_strv('toggle-tiled-right').includes('Right') &&
196 | this.settings.getStrv('tile-right-half').includes('Right')) {
197 | this._settingsOverrider.add(gnomeMutterKeybindings,
198 | 'toggle-tiled-right', emptyStrvVariant);
199 | }
200 |
201 | // Include tiled windows when dragging from the top panel.
202 | this._getDraggableWindowForPosition = Main.panel._getDraggableWindowForPosition;
203 | Main.panel._getDraggableWindowForPosition = function (stageX) {
204 | const workspaceManager = global.workspace_manager;
205 | const windows = workspaceManager.get_active_workspace().list_windows();
206 | const allWindowsByStacking = global.display.sort_windows_by_stacking(windows).reverse();
207 |
208 | return allWindowsByStacking.find(w => {
209 | const rect = w.get_frame_rect();
210 | const workArea = w.get_work_area_current_monitor();
211 | return w.is_on_primary_monitor() &&
212 | w.showing_on_its_workspace() &&
213 | w.get_window_type() !== Meta.WindowType.DESKTOP &&
214 | (w.maximized_vertically || w.tiledRect?.y === workArea.y) &&
215 | stageX > rect.x && stageX < rect.x + rect.width;
216 | });
217 | };
218 |
219 | // Restore tiled window properties after session was unlocked.
220 | this._loadAfterSessionLock();
221 |
222 | // Setting used for detection of a fresh install and do compatibility
223 | // changes if necessary...
224 | this.settings.setInt('last-version-installed', this.metadata.version);
225 | }
226 |
227 | disable() {
228 | // Save tiled window properties, if the session was locked to restore
229 | // them after the session is unlocked again.
230 | this._saveBeforeSessionLock();
231 |
232 | this._settingsOverrider.destroy();
233 | this._settingsOverrider = null;
234 | this._moveHandler.destroy();
235 | this._moveHandler = null;
236 | this._resizeHandler.destroy();
237 | this._resizeHandler = null;
238 | this._keybindingHandler.destroy();
239 | this._keybindingHandler = null;
240 | this._layoutsManager.destroy();
241 | this._layoutsManager = null;
242 | this._focusHintManager.destroy();
243 | this._focusHintManager = null;
244 |
245 | this._altTabOverride.destroy();
246 | this._altTabOverride = null;
247 |
248 | this._twm.destroy();
249 | this._twm = null;
250 |
251 | this.settings.destroy();
252 | this.settings = null;
253 |
254 | // Restore old functions.
255 | Main.panel._getDraggableWindowForPosition = this._getDraggableWindowForPosition;
256 | this._getDraggableWindowForPosition = null;
257 |
258 | // Delete custom tiling properties.
259 | const openWindows = global.display.get_tab_list(Meta.TabList.NORMAL, null);
260 | openWindows.forEach(w => {
261 | delete w.isTiled;
262 | delete w.tiledRect;
263 | delete w.untiledRect;
264 | });
265 | }
266 |
267 | /**
268 | * Extensions are disabled when the screen is locked. So save the custom tiling
269 | * properties of windows before locking the screen.
270 | */
271 | _saveBeforeSessionLock() {
272 | if (!Main.sessionMode.isLocked)
273 | return;
274 |
275 | this._wasLocked = true;
276 |
277 | const userPath = GLib.get_user_config_dir();
278 | const parentPath = GLib.build_filenamev([userPath, '/tiling-assistant']);
279 | const parent = Gio.File.new_for_path(parentPath);
280 |
281 | try {
282 | parent.make_directory_with_parents(null);
283 | } catch (e) {
284 | if (e.code !== Gio.IOErrorEnum.EXISTS)
285 | throw e;
286 | }
287 |
288 | const path = GLib.build_filenamev([parentPath, '/tiledSessionRestore2.json']);
289 | const file = Gio.File.new_for_path(path);
290 |
291 | try {
292 | file.create(Gio.FileCreateFlags.NONE, null);
293 | } catch (e) {
294 | if (e.code !== Gio.IOErrorEnum.EXISTS)
295 | throw e;
296 | }
297 |
298 | file.replace_contents(
299 | JSON.stringify({
300 | windows: Object.fromEntries(this._twm.getTileStates()),
301 | tileGroups: Object.fromEntries(this._twm.getTileGroups())
302 | }),
303 | null,
304 | false,
305 | Gio.FileCreateFlags.REPLACE_DESTINATION,
306 | null
307 | );
308 | }
309 |
310 | /**
311 | * Extensions are disabled when the screen is locked. After having saved them,
312 | * reload them here.
313 | */
314 | _loadAfterSessionLock() {
315 | if (!this._wasLocked)
316 | return;
317 |
318 | this._wasLocked = false;
319 |
320 | const userPath = GLib.get_user_config_dir();
321 | const path = GLib.build_filenamev([userPath, '/tiling-assistant/tiledSessionRestore2.json']);
322 | const file = Gio.File.new_for_path(path);
323 | if (!file.query_exists(null))
324 | return;
325 |
326 | try {
327 | file.create(Gio.FileCreateFlags.NONE, null);
328 | } catch (e) {
329 | if (e.code !== Gio.IOErrorEnum.EXISTS)
330 | throw e;
331 | }
332 |
333 | const [success, contents] = file.load_contents(null);
334 | if (!success || !contents.length)
335 | return;
336 |
337 | const states = JSON.parse(new TextDecoder().decode(contents));
338 | const keysAsNumbers = entries => entries.map(([key, value]) => [parseInt(key), value]);
339 | const tileGroups = new Map(keysAsNumbers(Object.entries(states.tileGroups)));
340 | const tileStates = new Map(keysAsNumbers(Object.entries(states.windows)));
341 | const openWindows = global.display.list_all_windows();
342 |
343 | this._twm.setTileGroups(tileGroups);
344 | this._twm.setTileStates(tileStates);
345 |
346 | openWindows.forEach(window => {
347 | const tileState = tileStates.get(window.get_id());
348 |
349 | if (tileState) {
350 | const { isTiled, tiledRect, untiledRect } = tileState;
351 | const jsToRect = jsRect => jsRect && new Rect(
352 | jsRect.x, jsRect.y, jsRect.width, jsRect.height
353 | );
354 |
355 | window.isTiled = isTiled;
356 | window.tiledRect = jsToRect(tiledRect);
357 | window.untiledRect = jsToRect(untiledRect);
358 | }
359 |
360 |
361 | if (tileGroups.has(window.get_id())) {
362 | const group = this._twm.getTileGroupFor(window);
363 | this._twm.updateTileGroup(group);
364 | }
365 | });
366 | }
367 | }
368 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/extension/tilingPopup.js:
--------------------------------------------------------------------------------
1 | import { Clutter, GObject, St } from '../dependencies/gi.js';
2 | import { Main } from '../dependencies/shell.js';
3 | import * as SwitcherPopup from '../dependencies/unexported/switcherPopup.js';
4 |
5 | import { Direction, Orientation, is_wayland_compositor } from '../common.js';
6 | import { Util } from './utility.js';
7 | import { TilingWindowManager as Twm } from './tilingWindowManager.js';
8 | import * as AltTab from './altTab.js';
9 |
10 | /**
11 | * Classes for the Tiling Popup, which opens when tiling a window
12 | * and there is free screen space to fill with other windows.
13 | * Mostly based on GNOME's altTab.js
14 | */
15 |
16 | export const TilingSwitcherPopup = GObject.registerClass({
17 | Signals: {
18 | // Bool indicates whether the Tiling Popup was canceled
19 | // (or if a window was tiled with this popup)
20 | 'closed': { param_types: [GObject.TYPE_BOOLEAN] }
21 | }
22 | }, class TilingSwitcherPopup extends AltTab.TilingAppSwitcherPopup {
23 | /**
24 | * @param {Meta.Window[]} openWindows an array of Meta.Windows, which this
25 | * popup offers to tile.
26 | * @param {Rect} freeScreenRect the Rect, which the popup will tile a window
27 | * to. The popup will be centered in this rect.
28 | * @param {boolean} allowConsecutivePopup allow the popup to create another
29 | * Tiling Popup, if there is still unambiguous free screen space after
30 | * this popup tiled a window.
31 | * @param {boolean} skipAnim
32 | */
33 | _init(openWindows, freeScreenRect, allowConsecutivePopup = true, skipAnim = false) {
34 | this._freeScreenRect = freeScreenRect;
35 | this._shadeBG = null;
36 | this._monitor = -1;
37 |
38 | SwitcherPopup.SwitcherPopup.prototype._init.call(this);
39 |
40 | this._thumbnails = null;
41 | this._thumbnailTimeoutId = 0;
42 | this._currentWindow = -1;
43 | this.thumbnailsVisible = false;
44 | // The window, which was tiled with the Tiling Popup after it's closed
45 | // or null, if the popup was closed with tiling a window
46 | this.tiledWindow = null;
47 | this._allowConsecutivePopup = allowConsecutivePopup;
48 | this._skipAnim = skipAnim;
49 |
50 | this._switcherList = new TSwitcherList(this, openWindows);
51 | this._items = this._switcherList.icons;
52 |
53 | // Destroy popup when touching outside of popup
54 | this.connect('touch-event', () => {
55 | if (is_wayland_compositor())
56 | this.fadeAndDestroy();
57 |
58 | return Clutter.EVENT_PROPAGATE;
59 | });
60 | }
61 |
62 | /**
63 | * @param {Array} tileGroup an array of Meta.Windows. When the popup
64 | * appears it will shade the background. These windows will won't
65 | * be affected by that.
66 | * @returns if the popup was successfully shown.
67 | */
68 | show(tileGroup) {
69 | this._monitor = tileGroup[0]?.get_monitor() ?? global.display.get_current_monitor();
70 |
71 | if (!this._items.length)
72 | return false;
73 |
74 | const grab = Main.pushModal(this);
75 | // We expect at least a keyboard grab here
76 | if ((grab.get_seat_state() & Clutter.GrabState.KEYBOARD) === 0) {
77 | Main.popModal(grab);
78 | return false;
79 | }
80 |
81 | this._grab = grab;
82 | this._haveModal = true;
83 |
84 | this._switcherList.connect('item-activated', this._itemActivated.bind(this));
85 | this._switcherList.connect('item-entered', this._itemEntered.bind(this));
86 | this._switcherList.connect('item-removed', this._itemRemoved.bind(this));
87 | this.add_child(this._switcherList);
88 |
89 | // Need to force an allocation so we can figure out
90 | // whether we need to scroll when selecting
91 | this.visible = true;
92 | this.get_allocation_box();
93 |
94 | this._select(0);
95 |
96 | Main.osdWindowManager.hideAll();
97 |
98 | this._shadeBackground(tileGroup);
99 | this.opacity = 0;
100 | this.ease({
101 | opacity: 255,
102 | duration: 200,
103 | mode: Clutter.AnimationMode.EASE_OUT_QUAD
104 | });
105 |
106 | return true;
107 | }
108 |
109 | _shadeBackground(tileGroup) {
110 | const tiledWindow = tileGroup[0];
111 | const activeWs = global.workspace_manager.get_active_workspace();
112 | const workArea = activeWs.get_work_area_for_monitor(this._monitor);
113 |
114 | this._shadeBG = new St.Widget({
115 | style: 'background-color : black',
116 | x: workArea.x,
117 | y: workArea.y,
118 | width: workArea.width,
119 | height: workArea.height,
120 | opacity: 0
121 | });
122 | global.window_group.add_child(this._shadeBG);
123 | this._shadeBG.ease({
124 | opacity: 180,
125 | duration: 200,
126 | mode: Clutter.AnimationMode.EASE_OUT_QUAD
127 | });
128 |
129 | if (!tiledWindow)
130 | return;
131 |
132 | // Clones to correctly shade the background for consecutive tiling.
133 | for (let i = 1; i < tileGroup.length; i++) {
134 | const wActor = tileGroup[i].get_compositor_private();
135 | const clone = new Clutter.Clone({
136 | source: wActor,
137 | x: wActor.x,
138 | y: wActor.y
139 | });
140 | global.window_group.add_child(clone);
141 | wActor.hide();
142 | this.connect('destroy', () => {
143 | wActor.show();
144 | clone.destroy();
145 | });
146 | }
147 |
148 | const tActor = tiledWindow.get_compositor_private();
149 | global.window_group.set_child_above_sibling(tActor, this._shadeBG);
150 | }
151 |
152 | vfunc_allocate(box) {
153 | this.set_allocation(box);
154 |
155 | const freeScreenRect = this._freeScreenRect;
156 | const childBox = new Clutter.ActorBox();
157 |
158 | const leftPadding = this.get_theme_node().get_padding(St.Side.LEFT);
159 | const rightPadding = this.get_theme_node().get_padding(St.Side.RIGHT);
160 | const hPadding = leftPadding + rightPadding;
161 |
162 | const [, childNaturalHeight] = this._switcherList.get_preferred_height(
163 | freeScreenRect.width - hPadding);
164 | const [, childNaturalWidth] = this._switcherList.get_preferred_width(childNaturalHeight);
165 |
166 | childBox.x1 = Math.max(freeScreenRect.x + leftPadding,
167 | freeScreenRect.x + Math.floor((freeScreenRect.width - childNaturalWidth) / 2));
168 | childBox.x2 = Math.min(freeScreenRect.x2 - rightPadding,
169 | childBox.x1 + childNaturalWidth);
170 | childBox.y1 = freeScreenRect.y + Math.floor((freeScreenRect.height - childNaturalHeight) / 2);
171 | childBox.y2 = childBox.y1 + childNaturalHeight;
172 |
173 | this._switcherList.allocate(childBox);
174 |
175 | if (this._thumbnails) {
176 | const cbox = this._switcherList.get_allocation_box();
177 | const monitor = global.display.get_monitor_geometry(this._monitor);
178 |
179 | const leftPadd = this.get_theme_node().get_padding(St.Side.LEFT);
180 | const rightPadd = this.get_theme_node().get_padding(St.Side.RIGHT);
181 | const bottomPadding = this.get_theme_node().get_padding(St.Side.BOTTOM);
182 | const hPadd = leftPadd + rightPadd;
183 |
184 | const icon = this._items[this._selectedIndex];
185 | const [posX] = icon.get_transformed_position();
186 | const thumbnailCenter = posX + icon.width / 2;
187 | const [, cNatWidth] = this._thumbnails.get_preferred_width(-1);
188 | cbox.x1 = Math.max(monitor.x + leftPadd,
189 | Math.floor(thumbnailCenter - cNatWidth / 2)
190 | );
191 | if (cbox.x1 + cNatWidth > monitor.x + monitor.width - hPadd) {
192 | const offset = cbox.x1 + cNatWidth - monitor.width + hPadd;
193 | cbox.x1 = Math.max(monitor.x + leftPadd, cbox.x1 - offset - hPadd);
194 | }
195 |
196 | const spacing = this.get_theme_node().get_length('spacing');
197 |
198 | cbox.x2 = cbox.x1 + cNatWidth;
199 | if (cbox.x2 > monitor.x + monitor.width - rightPadd)
200 | cbox.x2 = monitor.x + monitor.width - rightPadd;
201 | cbox.y1 = this._switcherList.allocation.y2 + spacing;
202 | this._thumbnails.addClones(monitor.y + monitor.height - bottomPadding - cbox.y1);
203 | const [, cNatHeight] = this._thumbnails.get_preferred_height(-1);
204 | cbox.y2 = cbox.y1 + cNatHeight;
205 |
206 | this._thumbnails.allocate(cbox);
207 | }
208 | }
209 |
210 | vfunc_button_press_event(buttonEvent) {
211 | const btn = buttonEvent.get_button();
212 | if (btn === Clutter.BUTTON_MIDDLE || btn === Clutter.BUTTON_SECONDARY) {
213 | this._finish(global.get_current_time());
214 | return Clutter.EVENT_PROPAGATE;
215 | }
216 | }
217 |
218 | _keyPressHandler(keysym) {
219 | const moveUp = Util.isDirection(keysym, Direction.N);
220 | const moveDown = Util.isDirection(keysym, Direction.S);
221 | const moveLeft = Util.isDirection(keysym, Direction.W);
222 | const moveRight = Util.isDirection(keysym, Direction.E);
223 |
224 | if (this._thumbnailsFocused) {
225 | if (moveLeft)
226 | this._select(this._selectedIndex, this._previousWindow());
227 | else if (moveRight)
228 | this._select(this._selectedIndex, this._nextWindow());
229 | else if (moveUp || moveDown)
230 | this._select(this._selectedIndex, null, true);
231 | else
232 | return Clutter.EVENT_PROPAGATE;
233 | } else if (moveLeft) {
234 | this._select(this._previous());
235 | } else if (moveRight) {
236 | this._select(this._next());
237 | } else if (moveDown || moveUp) {
238 | this._select(this._selectedIndex, 0);
239 | } else {
240 | return Clutter.EVENT_PROPAGATE;
241 | }
242 |
243 | return Clutter.EVENT_STOP;
244 | }
245 |
246 | _windowActivated(thumbnailSwitcher, n) {
247 | const window = this._items[this._selectedIndex].cachedWindows[n];
248 | this._tileWindow(window);
249 | this.fadeAndDestroy();
250 | }
251 |
252 | _finish(timestamp) {
253 | const appIcon = this._items[this._selectedIndex];
254 | const window = appIcon.cachedWindows[Math.max(0, this._currentWindow)];
255 | this._tileWindow(window);
256 | SwitcherPopup.SwitcherPopup.prototype._finish.call(this, timestamp);
257 | }
258 |
259 | fadeAndDestroy() {
260 | if (this._alreadyDestroyed)
261 | return;
262 |
263 | this._alreadyDestroyed = true;
264 |
265 | const canceled = !this.tiledWindow;
266 | this.emit('closed', canceled);
267 |
268 | this._shadeBG?.destroy();
269 | this._shadeBG = null;
270 | super.fadeAndDestroy();
271 | }
272 |
273 | _tileWindow(window) {
274 | let rect = this._freeScreenRect;
275 |
276 | // Halve the tile rect.
277 | // If isShiftPressed, then put the window at the top / left side;
278 | // if isAltPressed, then put it at the bottom / right side.
279 | // The orientation depends on the available screen space.
280 | const isShiftPressed = Util.isModPressed(Clutter.ModifierType.SHIFT_MASK);
281 | const isAltPressed = Util.isModPressed(Clutter.ModifierType.MOD1_MASK);
282 | if (isShiftPressed || isAltPressed) {
283 | // Prefer vertical a bit more (because screens are usually horizontal)
284 | const vertical = rect.width >= rect.height * 1.25;
285 | const size = vertical ? 'width' : 'height';
286 | const orientation = vertical ? Orientation.V : Orientation.H;
287 | const idx = isShiftPressed ? 0 : 1;
288 | rect = rect.getUnitAt(idx, rect[size] / 2, orientation);
289 | }
290 |
291 | this.tiledWindow = window;
292 |
293 | window.change_workspace(global.workspace_manager.get_active_workspace());
294 |
295 | // We want to activate/focus the window after it was tiled with the
296 | // Tiling Popup. Calling activate/focus() after tile() doesn't seem to
297 | // work for GNOME Terminal if it is maximized before trying to tile it.
298 | // It won't be tiled properly in that case for some reason... Instead
299 | // activate first but clear the tiling signals before so that the old
300 | // tile group won't be accidentally raised.
301 | Twm.clearTilingProps(window.get_id());
302 | window.activate(global.get_current_time());
303 | Twm.tile(window, rect, {
304 | monitorNr: this._monitor,
305 | openTilingPopup: this._allowConsecutivePopup,
306 | skipAnim: this._skipAnim
307 | });
308 | }
309 |
310 | // Dont _finish(), if no mods are pressed
311 | _resetNoModsTimeout() {
312 | }
313 | });
314 |
315 | const TSwitcherList = GObject.registerClass(
316 | class TilingSwitcherList extends AltTab.TilingAppSwitcher {
317 | _setIconSize() {
318 | let j = 0;
319 | while (this._items.length > 1 && this._items[j].style_class !== 'item-box')
320 | j++;
321 |
322 | const themeNode = this._items[j].get_theme_node();
323 | this._list.ensure_style();
324 |
325 | const iconPadding = themeNode.get_horizontal_padding();
326 | const iconBorder = themeNode.get_border_width(St.Side.LEFT) +
327 | themeNode.get_border_width(St.Side.RIGHT);
328 | const [, labelNaturalHeight] = this.icons[j].label.get_preferred_height(-1);
329 | const iconSpacing = labelNaturalHeight + iconPadding + iconBorder;
330 | const totalSpacing = this._list.spacing * (this._items.length - 1);
331 |
332 | const freeScreenRect = this._altTabPopup._freeScreenRect;
333 | const parentPadding = this.get_parent().get_theme_node().get_horizontal_padding();
334 | const availWidth = freeScreenRect.width - parentPadding -
335 | this.get_theme_node().get_horizontal_padding();
336 |
337 | const scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
338 | const baseIconSizes = [96, 64, 48, 32, 22];
339 | const iconSizes = baseIconSizes.map(s => s * scaleFactor);
340 | let iconSize = baseIconSizes[0];
341 |
342 | if (this._items.length > 1) {
343 | for (let i = 0; i < baseIconSizes.length; i++) {
344 | iconSize = baseIconSizes[i];
345 | const height = iconSizes[i] + iconSpacing;
346 | const w = height * this._items.length + totalSpacing;
347 | if (w <= availWidth)
348 | break;
349 | }
350 | }
351 |
352 | this._iconSize = iconSize;
353 |
354 | for (let i = 0; i < this.icons.length; i++)
355 | this.icons[i].set_size(iconSize);
356 | }
357 | });
358 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## [53] - 2025-09-01
4 |
5 | ### Added
6 |
7 | - Port to GNOME 49 by 3v1n0 and Ser82-png (#409 and #411)
8 | - Add Slovak translation by jose1711 (#414)
9 |
10 | ## [52] - 2025-05-01
11 |
12 | ### Added
13 |
14 | - More Russian translation by Ser82-png (#399)
15 | - More Ukrainian translation by xalt7x (#395)
16 |
17 | ### Fixed
18 |
19 | - Fixed maximized windows not being tilable via DND (#402)
20 |
21 | ## [51] - 2025-02-16
22 |
23 | ### Added
24 |
25 | - Port to GNOME 48 (#388)
26 |
27 | ### Fixed
28 |
29 | - Don't show tile preview for unresizable and skip_taskbar windows (#389)
30 |
31 | ## [50] - 2025-01-27
32 |
33 | ### Added
34 |
35 | - Add Russian translation by Ser82-png (#367)
36 | - Add Polish translation by alewicki95 (#369)
37 | - Add Italian translation by albanobattistella (#377)
38 | - Add Ukrainian translation by xalt7x (#379)
39 |
40 | ### Fixed
41 |
42 | - Added option to make the Outline Focus Hint an actual outline to improve the compatibility with transparent windows (#384)
43 | - Workaround retiling already tiled windows freezing by disabling animations for them (#385)
44 | - Fixed some compatibility issues with AATWS (#386)
45 |
46 | ## [49] - 2024-08-11
47 |
48 | ### Added
49 |
50 | - Port to GNOME 47 (#363)
51 |
52 | ### Changed
53 |
54 | - Replace the active window hint with https://github.com/Leleat/focus-indicator-prototype. It is disabled by default (#344)
55 |
56 | ## [48] - 2024-08-10
57 |
58 | ### Added
59 |
60 | - Add more Italian translation by albanobattistella (#352)
61 | - Add translations comments (#338)
62 |
63 | ### Fixed
64 |
65 | - Ignore unused mods for determining the MoveModes (#340)
66 | - Don't spam logs that a config file exists when un/locking the screen by jtojnar (#346)
67 | - Mark 'Preferences' in the PanelButton for translation by ChrisLauinger77 (#351)
68 | - Maximize windows vertically/horizontally without gaps (#353)
69 | - Mark 'Disabled' for translation in prefs by ChrisLauinger77 (#356)
70 | - Work around a possible mutter assertion when trying to tile an app that crashed (#360)
71 | - Work around a possible crash when un/locking the screen (#361)
72 |
73 | ## [47] - 2024-04-21
74 |
75 | ### Fixed
76 |
77 | - Don't untile a window on a single click by taoky (#328)
78 |
79 | ### Changed
80 |
81 | - Use native AdwSwitchRow and AdwSpinRow (#334)
82 |
83 | ### Removed
84 |
85 | - Removed restore-window-size-on-grab-start/end setting since it should be no longer needed (#334)
86 |
87 | ## [46] - 2024-03-24
88 |
89 | ### Added
90 |
91 | - Brazilian Portuguese translation by nunseik (#310)
92 | - Italian translation by albanobattistella (#312)
93 | - Ukrainian translation by xalt7x (#317)
94 | - Support for GNOME 46 by sergio-costas (#319)
95 |
96 | ### Fixed
97 |
98 | - Rework arch PKGBUILD to compile completely from source to enable building inside a docker-container by VeldoraTheDragon (#296, #301)
99 | - Handle change of window action key while the extension is enabled (#321)
100 |
101 | ### Changed
102 |
103 | - Disable animations when using layouts as a workaround for freezing windows according to #304 (#321)
104 |
105 | ## [44] - 2023-09-18
106 |
107 | ### Added
108 |
109 | - support for GNOME 45 (#281)
110 |
111 | ## [43] - 2023-09-17
112 |
113 | ### Fixed
114 |
115 | - Window not resizing correctly when it enters another monitor - by domferr (#290)
116 |
117 | ## [42] - 2023-09-03
118 |
119 | ### Added
120 |
121 | - Italian translation by albanobattistella (#271)
122 |
123 | ### Fixed
124 |
125 | - Move modes update correctly when the grabbed window changes the monitor (#279)
126 |
127 | ## [41] - 2023-05-17
128 |
129 | ### Fixed
130 |
131 | - Tiling Popup not appearing under some circumstances (#259)
132 | - Properly restore tiling props on all workspaces (#262)
133 |
134 | ## [40] - 2023-04-13
135 |
136 | ### Added
137 |
138 | - Support for GNOME Shell 44 by 3v1n0 (mostly #234)
139 | - Github CI: linting and spell checking
140 | - Spanish translations by IngrownMink4 (#216)
141 | - Dutch translations by flipflop97 (#215)
142 | - Italian translations by albanobattistella (#220)
143 | - German translations by affengeist (#231)
144 | - Hungarian translations by infeeeee (#236)
145 |
146 | ### Fixed
147 |
148 | - The position of the fix-search-a-layout popup now appears correctly on multi-monitor setups (#247)
149 | - Fix tiling when there are always-on-top windows (#240)
150 | - Fix non-extension maximization window-restore position (#251)
151 |
152 | ### Changed
153 |
154 | - Move UserGuide.MD into the [github wiki](https://github.com/Leleat/Tiling-Assistant/wiki)
155 | - Update Scripts and a bugfix by SubOptimal (#248, #249, #250)
156 |
157 | ## [39] - 2022-11-23
158 |
159 | ### Fixed
160 |
161 | - Clean up settings signals properly (technically only relevant for the active hint since it may be destroyed before the settings singleton)
162 |
163 | ## [38] - 2022-11-23
164 |
165 | ### Fixed
166 |
167 | - Issue with always active window hint (there is still a problem with GTK4 popups on Wayland)
168 |
169 | ## [37] - 2022-11-22
170 |
171 | ### Added
172 |
173 | - Added active window hint. By default the `Minimal` option will be chosen (#210)
174 | - Added an option to not use T-A features (Tiling Popup and grouping) when DNDing a window via a modifier and via additional keyboard shortcuts. Features are hidden behind the advanced settings (#212)
175 | - Added setting for a single/uniform screen gap instead of splitting it into edges (each edge is still available, if the advanced settings are enabled)
176 |
177 | ### Changed
178 |
179 | - Increased possible maximum of gaps to 500 (#205)
180 | - Changed/shuffled some of the preferences around
181 |
182 | ## [36] - 2022-09-04
183 |
184 | ### Added
185 |
186 | - Support GNOME 43
187 |
188 | ### Changed
189 |
190 | - Removed the 'row'-look of shortcuts in the layouts
191 |
192 | ### Fixed
193 |
194 | - Consider monitor scale when calculating window gaps (#196)
195 |
196 | ## [35] - 2022-07-23
197 |
198 | ### Added
199 |
200 | - Added setting to disable multi-monitor grace period (#189)
201 |
202 | ### Changed
203 |
204 | - Make the 'improved performance behavior' opt-in (in the advanced settings) since it impacts the precision of the tile preview (#190)
205 |
206 | ### Fixed
207 |
208 | - Fixed issue about windows maximizing to wrong monitor under some circumstances setups (#188)
209 |
210 | ### Removed
211 |
212 | - Removed in-app changelog
213 |
214 | ## [34] - 2022-07-13
215 |
216 | ### Added
217 |
218 | - Added setting to completely disable tile groups. That means no resizing, raising or suggestions anymore (#180)
219 | - Added the ability to only resize the absolutely necessary windows in a tile group when holding `Ctrl` before resizing started (#155)
220 |
221 | ### Changed
222 |
223 | - Improved performance when dragging a window around for lower performance machines (#181)
224 | - Split the screen gap setting into top, bottom, left and right parts by CharlieQLe (#146)
225 | - Don't open the changelog window after an extension update in the prefs by default anymore
226 |
227 | ### Fixed
228 |
229 | - Added a workaround for a multi-monitor bug where windows may untile incorrectly under Wayland (#137)
230 | - Fixed issue with RMB as a `Move Mode Activator` under Wayland (#170)
231 | - Added Meta as a `Move Mode Activator` and set it as default, if `Alt` is the default window action key (#172)
232 |
233 | ## [33] - 2022-05-07
234 |
235 | ### Added
236 |
237 | - German (Switzerland) tl by MrReSc #152
238 | - German (Germany) tl by pjanze #161
239 | - Italian translation by starise #164
240 | - Spanish translation by fjsevilla-dev #168
241 |
242 | ### Changed
243 |
244 | - Port to GNOME 42 and drop support for older versions
245 | - Brazilian Portuguese tl by ItzJaum #157
246 | - If an app is attached to a layout rect, try to tile an existing window instance first before opening a new one
247 |
248 | ### Removed
249 |
250 | - Deprecate 'App Switcher and Tiling Popup' setting
251 | - Hacky partial touch 'support'
252 |
253 | ### Fixed
254 |
255 | - Override GNOME's default shortcuts only if they are set in Tiling Assistant
256 |
257 | ## [32] - 2022-01-22
258 |
259 | ### Added
260 |
261 | - Added new keyboard shortcuts:
262 | - Restore window size (#134)
263 | - Toggle Vertical Maximization
264 | - Toggle Horizontal Maximization
265 | - Move Window to Center (#132)
266 | - Toggle `Always on Top`
267 | - Added ability to move tile groups to a new workspace/monitor using the Tile Editing Mode:
268 | - `Shift`+`Directions` moves the tile group to a new monitor
269 | - `Shift`+`Alt`+`Directions` moves the tile group to a new workspace
270 | - Tiled windows will untile themselves if they change workspaces
271 | - Allow one action to have multiple keyboard shortcuts (press `Enter` or `Space` when listening for a new keyboard shortcut to append shortcuts to existing ones)
272 | - Added GNOME's native tiling behavior (`Super`+`Up`/`Down`/`Left`/`Right`) to the default shortcuts
273 |
274 | ### Changed
275 |
276 | - Adapt edge-tiling only if it doesn't cover existing tiles. Use `Ctrl`-drag (mouse) or the `Tile Editing Mode` (keyboard) to 'replace/cover' existing tiles. That way 1 window can be part of multiple tile groups
277 | - Reworked tile group detection when a window is tiled
278 | - Renamed `Split Tiles` mode to `Adaptive Tiling`. This is the mode when moving a window around while holding `Ctrl`
279 | - Disabled grouping tiled windows in the app switcher by default and mark that setting as experimental
280 | - Introduce concept of deprecated settings and deprecate the `Toggle Tiling Popup` and `Auto-Tile` keyboard shortcuts
281 | - Deprecated settings won't be visible in the prefs window anymore unless they have a non-default value set
282 |
283 | ### Fixed
284 |
285 | - Fixed a compatibility issue introduced in v31 with other alt-Tab extensions (#126)
286 | - Fixed the Tiling Popup ignoring the Tile Group setting `App Switcher and Tiling Popup`
287 | - Shortcuts may no longer change unintentionally after using the clear-shortcut-button
288 | - Fixed the URLs in the prefs' popup menu freezing the prefs - Wayland only (#136)
289 |
290 | ## [31] - 2021-12-10
291 |
292 | ### Fixed
293 |
294 | - Fixed crash introduced in v28 (#125)
295 |
296 | ## [30] - 2021-12-10
297 |
298 | ### Fixed
299 | - Fixed crash introduced in v28 (#124)
300 |
301 | ## [29] - 2021-12-09
302 |
303 | ### Fixed
304 | - Removed timer sources according to EGO review
305 |
306 | ## [28] - 2021-12-09
307 |
308 | ### Added
309 |
310 | - Added a Panel Indicator for the layouts (disabled by default). With it you can activate a layout with your pointer or change your `Favorite Layout` (per monitor)
311 | - Added a setting to group tileGroups in the AppSwitcher (altTab) and Tiling Popup
312 | - When dnd-ing a window, hold `Super` to make the tile preview span multiple rectangles. This only works in the `Favorite Layout` or `Split Tiles` preview modes
313 | - Added a `hidden` setting to not adapt the Edge-Tiling to the favorite layouts
314 |
315 | ### Removed
316 |
317 | - Removed the `Change favorite layouts` keyboard shortcut (Use the Panel Indicator instead)
318 | - Removed the favorite button from the `Layouts` in the preferences (Use the Panel Indicator instead)
319 |
320 | ### Changed
321 |
322 | - Show the entire Layout when moving a window with the `Favorite Layout` preview mode
323 | - Updated the jp translation (by k-fog #112)
324 | - Untile tiled windows, if they are moved to a new monitor or workspace (#114)
325 | - `Tile Editing Mode`: Pressing `Space` will always open the Tiling Popup (even if there is already a window in that spot)
326 | - Visual tweaks to the preference window
327 |
328 | ### Fixed
329 |
330 | - When dragging a window to a new monitor there is a short `Grace Period` (150 ms), in which, if the grab is released, the window will tile to the old monitor. Fix: The `Tiling Popup` will appear on the correct monitor now.
331 | - Fixed artifacts due to the rounded corners of the `Changelog Dialog` (only works on Wayland)
332 | - Fixed animations being skipped, if an animation was already running (#58)
333 |
334 | ## [27] - 2021-11-01
335 |
336 | ### Added
337 |
338 | - `Favorite Layout`, a new window movement mode, as an alternative to the default Edge Tiling (issue #94)
339 | - It allows users to dnd a window to a predefined layout (Check out the `GUIDE.md` for details)
340 | - It also adapts the keyboard shortcuts and edge previews to the favorite layout
341 | - Changelog dialog to prefs window on new extension version (deactivatable in `Hidden Settings`)
342 |
343 | ### Removed
344 |
345 | - The color selection for the Tile Editing Mode because now we can always follow the system's native Tile-Preview style
346 |
347 | ### Changed
348 |
349 | - Split gaps into `Window Gaps` and `Screen Gaps` (i. e. when windows are touching the screen edges) (discussion #109)
350 | - `Tile to top` & `Toggle Maximization` cycle between top tiling and maximization in `Tiling State` and `Tiling State (Windows)`
351 | - Reworked the preference window to follow GNOME's HIG a bit more closely
352 | - Moved the `Inverse Top Screen Edge Action` settings to the `Hidden Setting`
353 | - Moved the `Include apps from all workspaces` for the Tiling Popup to the general settings
354 | - And some other minor settings tweaks
355 |
356 | ## [26] - 2021-10-14
357 |
358 | ### Added
359 |
360 | - AUR package (not by me, see #85)
361 |
362 | ### Changed
363 |
364 | - Hid the `Layouts` behind the 'Advanced / Experimental Settings' switch (in `Hidden Settings`)
365 | - Renamed `Layout` to `Popup Layout` since just `Layout` may be misleading
366 | - Tile Editing Mode's resizing now follows GNOME native keyboard resizing style (see `Alt` + `F8`)
367 | - Removed the PieMenu
368 | - Removed support for GNOME < 40
369 | - Refactored code & created scripts to automate stuff like building, updating translations...
370 |
371 | ## [25] - 2021-09-27
372 |
373 | ### Fixed
374 |
375 | - Bug when PieMenu is enabled
376 |
377 | ## [24] - 2021-09-27
378 |
379 | ### Added
380 |
381 | - Clear-keybindings button
382 | - Dutch translation (by Vistaus #95)
383 | - Partial japanese translation (by k-fog #89)
384 | - Added Brazilian Portuguese translation (by msmafra #92)
385 | - Windows-like minimize option for the dynamic keybindings
386 | - Hidden settings: choose secondary mode (tile preview) activator and option to default to secondary mode (#90)
387 |
388 | ### Fixed
389 |
390 | - GNOME Shell 41: use new function, which got replaced in GS
391 |
392 | ## [23]
393 |
394 | ### Added
395 |
396 | - Partial Traditional Chinese translation for users in Taiwan (by laichiaheng #84)
397 | - Added dynamic tiling options: disabled, focus & tiling states (#87)
398 | - Added the 'layout selector' as an option for the pieMenu
399 |
400 | ### Changed
401 |
402 | - Moved 'Tile Editing Mode: Focus Color' to the 'Hidden Settings'
403 | - Removed experimental semi-autotiling mode (#70)
404 | - Simplify tl file (removed duplicates)
405 |
406 | ### Fixed
407 |
408 | - Multimonitor: wrong position for the focus indicator of the tile editing mode
409 | - Multimonitor: wrong position for the layout selector
410 | - Multimonitor: inconsistent behavior for tiling a window via DND within the 'grace period'
411 |
412 | ## [22]
413 |
414 | ### Added
415 |
416 | - Link to a list of known incompatible apps/extensions (github issue #61)
417 | - Czech translation (by pervoj #81)
418 |
419 | ### Fixed
420 |
421 | - Correctly position PieMenu on multimonitor setup (#78)
422 | - Wrong tilePreview, if window was at the very top display edge
423 | - Stop an extension crash, if ~/.config/tiling-assistant didn't exist, when the screen got locked (#80)
424 |
425 | ## [21]
426 |
427 | ### Fixed
428 |
429 | - Re-enable focus on prefs40.ui
430 | - Correctly use pointer position when moving window with keyboard `Alt` + `F7` + `Arrow` keys (#76)
431 |
432 | ## [20]
433 |
434 | ### Added
435 |
436 | - Tile Editing Mode: add option to 'equalize' window sizes (see 6bfbc07)
437 | - Layouts: add dynamic rectangles to enable layouts like Master & Stack (see the tooltip in the `Layouts` tab of the settings)
438 | - Experimental: Semi Tiling Mode (see 'Hidden Settings')
439 | - Setup `translations/` for translations
440 |
441 | ### Changed
442 |
443 | - Remove `User Guide` and `Changelog` tabs from the settings page (instead create .md files in repo)
444 |
445 | ### Fixed
446 |
447 | - Restore tile states properly after a screen lock
448 |
449 | ## [17] - [19]
450 |
451 | ### Added
452 |
453 | - Experimental: app attachments to layouts
454 |
455 | ### Changed
456 |
457 | - Layouts: move layouts file from the extension folder to $XDG_CONFIG_HOME/tiling-assistant/layouts.json (#68)
458 |
459 | ### Fixed
460 |
461 | - Raise tileGroups with sloppy mouse focus mode only on click
462 |
463 | ## [16]
464 |
465 | ### Added
466 |
467 | - Pie menu: Super + RMB a window
468 | - Settings: gaps on maximized windows (off by default)
469 | - Settings: 'restore window size on grab end' (workaround for Wayland)
470 | - Experimental: Tile Editing Mode
471 |
472 | ## [13] - [15]
473 |
474 | ### Added
475 |
476 | - Dynamic tiling ('focus and tiling')
477 | - Ctrl-dragging a window now also works for multiple windows (by dragging the window to the very edges of other windows/free screen rects)
478 | - Inverse top screen edge action (by c-ridgway)
479 | - Multi-monitor: the tile preview will stick to the old monitor when changing monitors for a short period to easier tile quickly on the old monitor (by c-ridgway)
480 | - Default keybindings with the numpad for tiling (by c-ridgway)
481 | - Dynamic numbers of layouts & layout selector
482 | - Add 'User Guide' and 'Changelog' settings tab
483 |
484 | ### Changed
485 |
486 | - Other minor settings additions/removals/changes
487 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 |
294 | Copyright (C)
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | , 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/extension/altTab.js:
--------------------------------------------------------------------------------
1 | import {
2 | Atk,
3 | Clutter,
4 | Gio,
5 | GLib,
6 | GObject,
7 | Meta,
8 | Shell,
9 | St
10 | } from '../dependencies/gi.js';
11 | import {
12 | Extension,
13 | Main
14 | } from '../dependencies/shell.js';
15 | import {
16 | AppSwitcherPopup,
17 | AppIcon as BaseAppIcon,
18 | baseIconSizes,
19 | APP_ICON_HOVER_TIMEOUT
20 | } from '../dependencies/unexported/altTab.js';
21 | import * as SwitcherPopup from '../dependencies/unexported/switcherPopup.js';
22 |
23 | import { Settings } from '../common.js';
24 | import { TilingWindowManager as Twm } from './tilingWindowManager.js';
25 |
26 | /**
27 | * Optionally, override GNOME's altTab / appSwitcher to group tileGroups
28 | */
29 | export default class AltTabOverride {
30 | constructor() {
31 | if (Settings.getBoolean('tilegroups-in-app-switcher'))
32 | this._overrideNativeAppSwitcher();
33 |
34 | this._settingsId = Settings.changed('tilegroups-in-app-switcher', () => {
35 | if (Settings.getBoolean('tilegroups-in-app-switcher'))
36 | this._overrideNativeAppSwitcher();
37 | else
38 | this._restoreNativeAppSwitcher();
39 | });
40 | }
41 |
42 | destroy() {
43 | Settings.disconnect(this._settingsId);
44 | this._restoreNativeAppSwitcher();
45 | }
46 |
47 | _overrideNativeAppSwitcher() {
48 | Main.wm.setCustomKeybindingHandler(
49 | 'switch-applications',
50 | Shell.ActionMode.NORMAL,
51 | this._startSwitcher.bind(this)
52 | );
53 | }
54 |
55 | _restoreNativeAppSwitcher() {
56 | Main.wm.setCustomKeybindingHandler(
57 | 'switch-applications',
58 | Shell.ActionMode.NORMAL,
59 | Main.wm._startSwitcher.bind(Main.wm)
60 | );
61 | }
62 |
63 | /**
64 | * Copy-pasta from windowManager.js. Removed unused stuff...
65 | *
66 | * @param {*} display -
67 | * @param {*} window -
68 | * @param {*} binding -
69 | */
70 | _startSwitcher(display, window, binding) {
71 | if (Main.wm._workspaceSwitcherPopup !== null)
72 | Main.wm._workspaceSwitcherPopup.destroy();
73 |
74 | const tabPopup = new TilingAppSwitcherPopup();
75 |
76 | if (!tabPopup.show(binding.is_reversed(), binding.get_name(), binding.get_mask()))
77 | tabPopup.destroy();
78 | }
79 | }
80 |
81 | export const TilingAppSwitcherPopup = GObject.registerClass(
82 | class TilingAppSwitcherPopup extends AppSwitcherPopup {
83 | _init() {
84 | SwitcherPopup.SwitcherPopup.prototype._init.call(this);
85 |
86 | const settings = new Gio.Settings({ schema_id: 'org.gnome.shell.app-switcher' });
87 | const workspace = settings.get_boolean('current-workspace-only')
88 | ? global.workspace_manager.get_active_workspace()
89 | : null;
90 | const windows = global.display.get_tab_list(Meta.TabList.NORMAL, workspace);
91 |
92 | this._switcherList = new TilingAppSwitcher(this, windows);
93 | this._items = this._switcherList.icons;
94 | }
95 |
96 | // Called when closing an entire app / tileGroup
97 | _quitApplication(index) {
98 | const item = this._items[index];
99 | if (!item)
100 | return;
101 |
102 | item.cachedWindows.forEach(w => w.delete(global.get_current_time()));
103 | item.cachedWindows = [];
104 | this._switcherList._removeIcon(item);
105 | }
106 |
107 | // Called when closing a window with the thumbnail switcher
108 | // meaning that .cachedWindow of an item was updated via signals
109 | _windowRemoved(thumbnailSwitcher, n) {
110 | const item = this._items[this._selectedIndex];
111 | if (!item)
112 | return;
113 |
114 | if (item.cachedWindows.length) {
115 | const newIndex = Math.min(n, item.cachedWindows.length - 1);
116 | this._select(this._selectedIndex, newIndex);
117 | }
118 |
119 | item.updateAppIcons();
120 | }
121 | });
122 |
123 | export const TilingAppSwitcher = GObject.registerClass(
124 | class TilingAppSwitcher extends SwitcherPopup.SwitcherList {
125 | _init(altTabPopup, windows) {
126 | // Don't make the SwitcherButtons squares since 1 SwitcherButton
127 | // may contain multiple AppIcons for a tileGroup.
128 | super._init(false);
129 |
130 | this.icons = [];
131 | this._arrows = [];
132 | this._apps = [];
133 | this._altTabPopup = altTabPopup;
134 | this._delayedHighlighted = -1;
135 | this._mouseTimeOutId = 0;
136 |
137 | const winTracker = Shell.WindowTracker.get_default();
138 | let groupedWindows;
139 |
140 | // Group windows based on their tileGroup, if tileGroup.length > 1.
141 | // Otherwise group them based on their respective apps.
142 | if (Settings.getBoolean('tilegroups-in-app-switcher')) {
143 | groupedWindows = windows.reduce((allGroups, w) => {
144 | for (const group of allGroups) {
145 | if (w.isTiled && Twm.getTileGroupFor(w).length > 1) {
146 | if (Twm.getTileGroupFor(w).includes(group[0])) {
147 | group.push(w);
148 | return allGroups;
149 | }
150 | } else if ((!group[0].isTiled || group[0].isTiled && Twm.getTileGroupFor(group[0]).length <= 1) &&
151 | winTracker.get_window_app(group[0]) === winTracker.get_window_app(w)) {
152 | group.push(w);
153 | return allGroups;
154 | }
155 | }
156 | const newGroup = [w];
157 | allGroups.push(newGroup);
158 | return allGroups;
159 | }, []);
160 |
161 | // Group windows based on apps
162 | } else {
163 | groupedWindows = windows.reduce((allGroups, w) => {
164 | for (const group of allGroups) {
165 | if (winTracker.get_window_app(group[0]) === winTracker.get_window_app(w)) {
166 | group.push(w);
167 | return allGroups;
168 | }
169 | }
170 |
171 | const newGroup = [w];
172 | allGroups.push(newGroup);
173 | return allGroups;
174 | }, []);
175 | }
176 |
177 | // Construct the AppIcons and add them to the popup.
178 | groupedWindows.forEach(group => {
179 | const item = new AppSwitcherItem(group);
180 | item.connect('all-icons-removed', () => this._removeIcon(item));
181 | this._addIcon(item);
182 | });
183 |
184 | // Listen for the app stop state in case the app got closed outside
185 | // of the app switcher along with closing via the app switcher
186 | const allApps = windows.map(w => winTracker.get_window_app(w));
187 | this._apps = [...new Set(allApps)];
188 | this._stateChangedIds = this._apps.map(app => app.connect('notify::state', () => {
189 | if (app.state !== Shell.AppState.RUNNING)
190 | this.icons.forEach(item => item.removeApp(app));
191 | }));
192 |
193 | this.connect('destroy', this._onDestroy.bind(this));
194 | }
195 |
196 | _onDestroy() {
197 | if (this._mouseTimeOutId !== 0)
198 | GLib.source_remove(this._mouseTimeOutId);
199 |
200 | this._stateChangedIds?.forEach((id, index) => this._apps[index].disconnect(id));
201 | this._stateChangedIds = [];
202 | this._apps = [];
203 | }
204 |
205 | _setIconSize() {
206 | let j = 0;
207 | while (this._items.length > 1 && this._items[j].style_class !== 'item-box')
208 | j++;
209 |
210 | let themeNode = this._items[j].get_theme_node();
211 | this._list.ensure_style();
212 |
213 | let iconPadding = themeNode.get_horizontal_padding();
214 | let iconBorder = themeNode.get_border_width(St.Side.LEFT) + themeNode.get_border_width(St.Side.RIGHT);
215 | let [, labelNaturalHeight] = this.icons[j].label.get_preferred_height(-1);
216 | let iconSpacing = labelNaturalHeight + iconPadding + iconBorder;
217 | let totalSpacing = this._list.spacing * (this._items.length - 1);
218 |
219 | // We just assume the whole screen here due to weirdness happening with the passed width
220 | let primary = Main.layoutManager.primaryMonitor;
221 | let parentPadding = this.get_parent().get_theme_node().get_horizontal_padding();
222 | let availWidth = primary.width - parentPadding - this.get_theme_node().get_horizontal_padding();
223 |
224 | let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
225 | let iconSizes = baseIconSizes.map(s => s * scaleFactor);
226 | let iconSize = baseIconSizes[0];
227 |
228 | if (this._items.length > 1) {
229 | for (let i = 0; i < baseIconSizes.length; i++) {
230 | iconSize = baseIconSizes[i];
231 | let height = iconSizes[i] + iconSpacing;
232 | let w = height * this._items.length + totalSpacing;
233 | if (w <= availWidth)
234 | break;
235 | }
236 | }
237 |
238 | this._iconSize = iconSize;
239 |
240 | for (let i = 0; i < this.icons.length; i++) {
241 | // eslint-disable-next-line eqeqeq
242 | if (this.icons[i].icon != null)
243 | break;
244 | this.icons[i].set_size(iconSize);
245 | }
246 | }
247 |
248 | vfunc_get_preferred_height(forWidth) {
249 | if (!this._iconSize)
250 | this._setIconSize();
251 |
252 | return super.vfunc_get_preferred_height(forWidth);
253 | }
254 |
255 | vfunc_allocate(box) {
256 | // Allocate the main list items
257 | super.vfunc_allocate(box);
258 |
259 | let contentBox = this.get_theme_node().get_content_box(box);
260 |
261 | let arrowHeight = Math.floor(this.get_theme_node().get_padding(St.Side.BOTTOM) / 3);
262 | let arrowWidth = arrowHeight * 2;
263 |
264 | // Now allocate each arrow underneath its item
265 | let childBox = new Clutter.ActorBox();
266 | for (let i = 0; i < this._items.length; i++) {
267 | let itemBox = this._items[i].allocation;
268 | childBox.x1 = contentBox.x1 + Math.floor(itemBox.x1 + (itemBox.x2 - itemBox.x1 - arrowWidth) / 2);
269 | childBox.x2 = childBox.x1 + arrowWidth;
270 | childBox.y1 = contentBox.y1 + itemBox.y2 + arrowHeight;
271 | childBox.y2 = childBox.y1 + arrowHeight;
272 | this._arrows[i].allocate(childBox);
273 | }
274 | }
275 |
276 | // We override SwitcherList's _onItemMotion method to delay
277 | // activation when the thumbnail list is open
278 | _onItemMotion(item) {
279 | if (item === this._items[this._highlighted] ||
280 | item === this._items[this._delayedHighlighted])
281 | return Clutter.EVENT_PROPAGATE;
282 |
283 | const index = this._items.indexOf(item);
284 |
285 | if (this._mouseTimeOutId !== 0) {
286 | GLib.source_remove(this._mouseTimeOutId);
287 | this._delayedHighlighted = -1;
288 | this._mouseTimeOutId = 0;
289 | }
290 |
291 | if (this._altTabPopup.thumbnailsVisible) {
292 | this._delayedHighlighted = index;
293 | this._mouseTimeOutId = GLib.timeout_add(
294 | GLib.PRIORITY_DEFAULT,
295 | APP_ICON_HOVER_TIMEOUT,
296 | () => {
297 | this._enterItem(index);
298 | this._delayedHighlighted = -1;
299 | this._mouseTimeOutId = 0;
300 | return GLib.SOURCE_REMOVE;
301 | });
302 | GLib.Source.set_name_by_id(this._mouseTimeOutId, '[gnome-shell] this._enterItem');
303 | } else {
304 | this._itemEntered(index);
305 | }
306 |
307 | return Clutter.EVENT_PROPAGATE;
308 | }
309 |
310 | _enterItem(index) {
311 | let [x, y] = global.get_pointer();
312 | let pickedActor = global.stage.get_actor_at_pos(Clutter.PickMode.ALL, x, y);
313 | if (this._items[index].contains(pickedActor))
314 | this._itemEntered(index);
315 | }
316 |
317 | // We override SwitcherList's highlight() method to also deal with
318 | // the AppSwitcher->ThumbnailSwitcher arrows. Apps with only 1 window
319 | // will hide their arrows by default, but show them when their
320 | // thumbnails are visible (ie, when the app icon is supposed to be
321 | // in justOutline mode). Apps with multiple windows will normally
322 | // show a dim arrow, but show a bright arrow when they are
323 | // highlighted.
324 | highlight(n, justOutline) {
325 | if (this.icons[this._highlighted]) {
326 | if (this.icons[this._highlighted].cachedWindows.length === 1)
327 | this._arrows[this._highlighted].hide();
328 | else
329 | this._arrows[this._highlighted].remove_style_pseudo_class('highlighted');
330 | }
331 |
332 | super.highlight(n, justOutline);
333 |
334 | if (this._highlighted !== -1) {
335 | if (justOutline && this.icons[this._highlighted].cachedWindows.length === 1)
336 | this._arrows[this._highlighted].show();
337 | else
338 | this._arrows[this._highlighted].add_style_pseudo_class('highlighted');
339 | }
340 | }
341 |
342 | _addIcon(appIcon) {
343 | this.icons.push(appIcon);
344 | let item = this.addItem(appIcon, appIcon.label);
345 |
346 | appIcon.app.connectObject('notify::state', app => {
347 | if (app.state !== Shell.AppState.RUNNING)
348 | this._removeIcon(app);
349 | }, this);
350 |
351 | let arrow = new St.DrawingArea({ style_class: 'switcher-arrow' });
352 | arrow.connect('repaint', () => SwitcherPopup.drawArrow(arrow, St.Side.BOTTOM));
353 | this.add_child(arrow);
354 | this._arrows.push(arrow);
355 |
356 | if (appIcon.cachedWindows.length === 1)
357 | arrow.hide();
358 | else
359 | item.add_accessible_state(Atk.StateType.EXPANDABLE);
360 | }
361 |
362 | _removeIcon(item) {
363 | const index = this.icons.findIndex(i => i === item);
364 | if (index === -1)
365 | return;
366 |
367 | this._arrows[index].destroy();
368 | this._arrows.splice(index, 1);
369 |
370 | this.icons.splice(index, 1);
371 | this.removeItem(index);
372 | }
373 | });
374 |
375 | /**
376 | * Replace AltTab.AppIcon and insert this into the TilingAppSwitcher instead.
377 | * This may contain multiple AppIcons to represent a tileGroup with chain icons
378 | * between the AppIcons.
379 | */
380 | const AppSwitcherItem = GObject.registerClass({
381 | Signals: { 'all-icons-removed': {} }
382 | }, class AppSwitcherItem extends St.BoxLayout {
383 | _init(windows) {
384 | super._init({ vertical: false });
385 |
386 | // A tiled window in a tileGroup of length 1, doesn't get a separate
387 | // AppSwitcherItem. It gets added to the non-tiled windows' AppSwitcherItem
388 | const tileGroup = windows[0].isTiled && Twm.getTileGroupFor(windows[0]);
389 | this.isTileGroup = tileGroup && tileGroup.every(w => windows.includes(w)) && tileGroup?.length > 1;
390 | this.cachedWindows = windows;
391 | this.appIcons = [];
392 | this.chainIcons = [];
393 |
394 | // Compatibility with AltTab.AppIcon
395 | this.set_size = size => this.appIcons.forEach(i => i.set_size(size));
396 | this.label = null;
397 | this.app = {
398 | // Only raise the first window since we split up apps and tileGroups
399 | activate_window: (window, timestamp) => {
400 | Main.activateWindow(this.cachedWindows[0], timestamp);
401 | },
402 | // Listening to the app-stop now happens in the custom _init func
403 | // So prevent signal connection. here.. careful in case signal
404 | // connection in the future is used for more...
405 | connectObject: () => {}
406 | };
407 |
408 | this.updateAppIcons();
409 | }
410 |
411 | // Re/Create the AppIcons based on the cached window list
412 | updateAppIcons() {
413 | this.appIcons.forEach(i => i.destroy());
414 | this.appIcons = [];
415 | this.chainIcons.forEach(i => i.destroy());
416 | this.chainIcons = [];
417 |
418 | const winTracker = Shell.WindowTracker.get_default();
419 | const path = Extension.lookupByURL(import.meta.url)
420 | .dir.get_child('media/insert-link-symbolic.svg')
421 | .get_path();
422 | const icon = new Gio.FileIcon({ file: Gio.File.new_for_path(path) });
423 |
424 | const apps = this.isTileGroup
425 | // All apps (even duplicates)
426 | ? this.cachedWindows.map(w => winTracker.get_window_app(w))
427 | // Only unique apps
428 | : this.cachedWindows.reduce((allApps, w) => {
429 | const a = winTracker.get_window_app(w);
430 | !allApps.includes(a) && allApps.push(a);
431 | return allApps;
432 | }, []);
433 |
434 | apps.forEach((app, idx) => {
435 | // AppIcon
436 | const appIcon = new AppIcon(app);
437 | this.add_child(appIcon);
438 | this.appIcons.push(appIcon);
439 |
440 | // Add chain to the right AppIcon except for the last AppIcon
441 | if (idx >= apps.length - 1)
442 | return;
443 |
444 | // Chain
445 | const chain = new St.Icon({
446 | gicon: icon,
447 | icon_size: 18
448 | });
449 | this.add_child(chain);
450 | this.chainIcons.push(chain);
451 | });
452 |
453 | if (!this.appIcons.length) {
454 | this.emit('all-icons-removed');
455 | return;
456 | }
457 |
458 | this.label = this.appIcons[0].label;
459 | }
460 |
461 | // Remove an AppIcon to the corresponding app.
462 | // This doesn't update cached window list!
463 | removeApp(app) {
464 | for (let i = this.appIcons.length - 1; i >= 0; i--) {
465 | const appIcon = this.appIcons[i];
466 | if (appIcon.app !== app)
467 | continue;
468 |
469 | this.appIcons.splice(i, 1);
470 | appIcon.destroy();
471 | const chain = this.chainIcons.splice(Math.max(0, i - 1), 1)[0];
472 | chain?.destroy();
473 | }
474 |
475 | if (!this.appIcons.length)
476 | this.emit('all-icons-removed');
477 | }
478 | });
479 |
480 | const AppIcon = GObject.registerClass(
481 | class AppIcon extends BaseAppIcon {
482 | // Don't make the SwitcherButtons squares since 1 SwitcherButton
483 | // may contain multiple AppIcons for a tileGroup.
484 | vfunc_get_preferred_width() {
485 | return this.get_preferred_height(-1);
486 | }
487 | });
488 |
--------------------------------------------------------------------------------
/tiling-assistant@leleat-on-github/src/extension/layoutsManager.js:
--------------------------------------------------------------------------------
1 | import { Clutter, Gio, GObject, Meta, Shell, St } from '../dependencies/gi.js';
2 | import {
3 | _,
4 | Extension,
5 | Main,
6 | PanelMenu,
7 | PopupMenu
8 | } from '../dependencies/shell.js';
9 |
10 | import { Layout, Settings } from '../common.js';
11 | import { Rect, Util } from './utility.js';
12 | import { TilingWindowManager as Twm } from './tilingWindowManager.js';
13 |
14 | /**
15 | * Here are the classes to handle PopupLayouts on the shell / extension side.
16 | * See src/prefs/layoutsPrefs.js for more details and general info about layouts.
17 | * In summary, a Layout is an array of LayoutItems. A LayoutItem is a JS Object
18 | * and has a rect, an appId and a loopType. Only the rect is mandatory. AppId may
19 | * be null or a String. Same for the LoopType. If a layout is activated, we will
20 | * loop / step through each LayoutItem and spawn a Tiling Popup one after the
21 | * other for the rects and offer to tile a window to that rect. If an appId is
22 | * defined, instead of calling the Tiling Popup, we tile (a new Instance of)
23 | * the app to the rect. If a LoopType is defined, instead of going to the next
24 | * item / rect, we spawn a Tiling Popup on the same item / rect and all the
25 | * tiled windows will share that spot evenly (a la 'Master and Stack').
26 | *
27 | * Additionally, there the user can select a 'favorite' layout among the
28 | * PopupLayouts. That layout will then be used as an fixed alternative mode to
29 | * the Edge Tiling.
30 | */
31 |
32 | export default class TilingLayoutsManager {
33 | constructor() {
34 | // this._items is an array of LayoutItems (see explanation above).
35 | // this._currItem is 1 LayoutItem. A LayoutItem's rect only hold ratios
36 | // from 0 - 1. this._currRect is a Rect scaled to the workArea.
37 | this._items = [];
38 | this._currItem = null;
39 | this._currRect = null;
40 |
41 | // Preview to show where the window will tile to, similar
42 | // to the tile preview when dnding to the screen edges
43 | this._rectPreview = null;
44 |
45 | // Keep track of the windows which were already tiled with the current
46 | // layout and the remaining windows. Special-case windows, which were tiled
47 | // within a loop since they need to be re-adjusted for each new window
48 | // tiled to the same spot. The looped array is cleared after each 'step' /
49 | // LayoutItem change.
50 | this._tiledWithLayout = [];
51 | this._tiledWithLoop = [];
52 | this._remainingWindows = [];
53 |
54 | // Bind the keyboard shortcuts for each layout and the layout searchers
55 | this._keyBindings = [];
56 |
57 | for (let i = 0; i < 20; i++) {
58 | this._keyBindings.push(`activate-layout${i}`);
59 | Main.wm.addKeybinding(
60 | `activate-layout${i}`,
61 | Settings.getGioObject(),
62 | Meta.KeyBindingFlags.IGNORE_AUTOREPEAT,
63 | Shell.ActionMode.NORMAL,
64 | this.startLayouting.bind(this, i)
65 | );
66 | }
67 |
68 | this._keyBindings.push('search-popup-layout');
69 | Main.wm.addKeybinding(
70 | 'search-popup-layout',
71 | Settings.getGioObject(),
72 | Meta.KeyBindingFlags.IGNORE_AUTOREPEAT,
73 | Shell.ActionMode.NORMAL,
74 | this.openPopupSearch.bind(this)
75 | );
76 |
77 | // Add panel indicator
78 | this._panelIndicator = new PanelIndicator();
79 | Main.panel.addToStatusArea(
80 | 'tiling-assistant@leleat-on-github',
81 | this._panelIndicator);
82 | this._settingsId = Settings.changed('show-layout-panel-indicator', () => {
83 | this._panelIndicator.visible = Settings.getBoolean('show-layout-panel-indicator');
84 | });
85 | this._panelIndicator.visible = Settings.getBoolean('show-layout-panel-indicator');
86 | this._panelIndicator.connect('layout-activated', (src, idx) => this.startLayouting(idx));
87 | }
88 |
89 | destroy() {
90 | Settings.disconnect(this._settingsId);
91 | this._finishLayouting();
92 | this._keyBindings.forEach(key => Main.wm.removeKeybinding(key));
93 | this._panelIndicator.destroy();
94 | this._panelIndicator = null;
95 | }
96 |
97 | /**
98 | * Opens a popup window so the user can activate a layout by name
99 | * instead of the keyboard shortcut.
100 | */
101 | openPopupSearch() {
102 | const layouts = Util.getLayouts();
103 | if (!layouts.length) {
104 | // Translators: This is a notification that pops up when a keyboard shortcut to activate a user-defined tiling layout is activated but no layout was defined by the user.
105 | Main.notify('Tiling Assistant', _('No valid layouts defined.'));
106 | return;
107 | }
108 |
109 | const search = new LayoutSearch(layouts);
110 | search.connect('item-activated', (s, index) => this.startLayouting(index));
111 | }
112 |
113 | /**
114 | * Starts tiling to a Popup Layout.
115 | *
116 | * @param {number} index the index of the layout we start tiling to.
117 | */
118 | startLayouting(index) {
119 | const layout = Util.getLayouts()?.[index];
120 | if (!layout)
121 | return;
122 |
123 | const allWs = Settings.getBoolean('tiling-popup-all-workspace');
124 | this._remainingWindows = Twm.getWindows(allWs);
125 | this._items = new Layout(layout).getItems();
126 | this._currItem = null;
127 |
128 | const activeWs = global.workspace_manager.get_active_workspace();
129 | const monitor = global.display.get_current_monitor();
130 | const workArea = activeWs.get_work_area_for_monitor(monitor);
131 | this._rectPreview?.destroy();
132 | this._rectPreview = new St.Widget({
133 | style_class: 'tile-preview',
134 | opacity: 0,
135 | x: workArea.x + workArea.width / 2,
136 | y: workArea.y + workArea.height / 2
137 | });
138 | Main.layoutManager.addChrome(this._rectPreview);
139 |
140 | this._step();
141 | }
142 |
143 | _finishLayouting() {
144 | this._items = [];
145 | this._currItem = null;
146 | this._currRect = null;
147 |
148 | this._rectPreview?.destroy();
149 | this._rectPreview = null;
150 |
151 | this._tiledWithLayout = [];
152 | this._tiledWithLoop = [];
153 | this._remainingWindows = [];
154 | }
155 |
156 | _step(loopType = null) {
157 | // If we aren't looping on the current item, we need to prepare for the
158 | // step by getting the next item / rect. If we are looping, we stay on
159 | // the current item / rect and open a new Tiling Popup for that rect.
160 | if (!loopType) {
161 | // We're at the last item and not looping, so there are no more items.
162 | if (this._currItem === this._items.at(-1)) {
163 | this._finishLayouting();
164 | return;
165 | }
166 |
167 | const currIdx = this._items.indexOf(this._currItem);
168 | this._currItem = this._items[currIdx + 1];
169 |
170 | // Scale the item's rect to the workArea
171 | const activeWs = global.workspace_manager.get_active_workspace();
172 | const monitor = global.display.get_current_monitor();
173 | const workArea = new Rect(activeWs.get_work_area_for_monitor(monitor));
174 | const rectRatios = this._currItem.rect;
175 | this._currRect = new Rect(
176 | workArea.x + Math.floor(rectRatios.x * workArea.width),
177 | workArea.y + Math.floor(rectRatios.y * workArea.height),
178 | Math.ceil(rectRatios.width * workArea.width),
179 | Math.ceil(rectRatios.height * workArea.height)
180 | );
181 |
182 | // Try to compensate possible rounding errors when scaling up the
183 | // rect by aligning it with the rects, which were already tiled
184 | // using this layout and the workArea.
185 | this._tiledWithLayout.forEach(w => this._currRect.tryAlignWith(w.tiledRect));
186 | this._currRect.tryAlignWith(workArea);
187 | }
188 |
189 | const appId = this._currItem.appId;
190 | appId ? this._openAppTiled(appId) : this._openTilingPopup();
191 | }
192 |
193 | _openAppTiled(appId) {
194 | const app = Shell.AppSystem.get_default().lookup_app(appId);
195 | if (!app) {
196 | // Translators: This is a notification that pops up when a keyboard shortcut to activate a user-defined tiling layout is activated and the user attached an app to a tile so that a new instance of that app will automatically open in the tile. But that app seems to have been uninstalled since the definition of the layout.
197 | Main.notify('Tiling Assistant', _('Popup Layouts: App not found.'));
198 | this._finishLayouting();
199 | return;
200 | }
201 |
202 | const winTracker = Shell.WindowTracker.get_default();
203 | const idx = this._remainingWindows.findIndex(w => winTracker.get_window_app(w) === app);
204 | const window = this._remainingWindows[idx];
205 | idx !== -1 && this._remainingWindows.splice(idx, 1);
206 |
207 | if (window) {
208 | Twm.tile(window, this._currRect, {
209 | openTilingPopup: false,
210 | skipAnim: true
211 | });
212 | } else if (app.can_open_new_window()) {
213 | Twm.openAppTiled(app, this._currRect);
214 | }
215 |
216 | this._step();
217 | }
218 |
219 | async _openTilingPopup() {
220 | // There are no open windows left to tile using the Tiling Popup.
221 | // However there may be items with appIds, which we want to open.
222 | // So continue...
223 | if (!this._remainingWindows.length) {
224 | this._step();
225 | return;
226 | }
227 |
228 | // Animate the rect preview
229 | this._rectPreview.ease({
230 | x: this._currRect.x,
231 | y: this._currRect.y,
232 | width: this._currRect.width,
233 | height: this._currRect.height,
234 | opacity: 255,
235 | duration: 200,
236 | mode: Clutter.AnimationMode.EASE_OUT_QUAD
237 | });
238 |
239 | // Create the Tiling Popup
240 | const TilingPopup = await import('./tilingPopup.js');
241 | const popup = new TilingPopup.TilingSwitcherPopup(
242 | this._remainingWindows,
243 | this._currRect,
244 | // If this._currItem is the last item and we don't loop over it,
245 | // allow the Tiling Popup itself to spawn another instance of
246 | // a Tiling Popup, if there is free screen space.
247 | this._currItem === this._items.at(-1) && !this._currItem.loopType,
248 | true
249 | );
250 | const stacked = global.display.sort_windows_by_stacking(this._tiledWithLayout);
251 | const tileGroup = stacked.reverse();
252 | if (!popup.show(tileGroup)) {
253 | popup.destroy();
254 | this._finishLayouting();
255 | return;
256 | }
257 |
258 | popup.connect('closed', this._onTilingPopupClosed.bind(this));
259 | }
260 |
261 | _onTilingPopupClosed(tilingPopup, canceled) {
262 | if (canceled) {
263 | if (this._currItem.loopType) {
264 | this._tiledWithLoop = [];
265 | this._step();
266 | } else {
267 | this._finishLayouting();
268 | }
269 | } else {
270 | const tiledWindow = tilingPopup.tiledWindow;
271 | this._tiledWithLayout.push(tiledWindow);
272 | const i = this._remainingWindows.indexOf(tiledWindow);
273 | this._remainingWindows.splice(i, 1);
274 |
275 | // Make all windows, which were tiled during the current loop,
276 | // share the current rect evenly -> like the 'Stack' part of a
277 | // 'Master and Stack'
278 | if (this._currItem.loopType) {
279 | this._tiledWithLoop.push(tiledWindow);
280 | this._tiledWithLoop.forEach((w, idx) => {
281 | const rect = this._currRect.copy();
282 | const [pos, dimension] = this._currItem.loopType === 'h'
283 | ? ['y', 'height']
284 | : ['x', 'width'];
285 | rect[dimension] /= this._tiledWithLoop.length;
286 | rect[pos] += idx * rect[dimension];
287 | Twm.tile(w, rect, { openTilingPopup: false, skipAnim: true });
288 | });
289 | }
290 |
291 | this._step(this._currItem.loopType);
292 | }
293 | }
294 | }
295 |
296 | /**
297 | * The GUI class for the Layout search.
298 | */
299 | const LayoutSearch = GObject.registerClass({
300 | Signals: { 'item-activated': { param_types: [GObject.TYPE_INT] } }
301 | }, class TilingLayoutsSearch extends St.Widget {
302 | _init(layouts) {
303 | const activeWs = global.workspace_manager.get_active_workspace();
304 | super._init({
305 | reactive: true,
306 | x: Main.uiGroup.x,
307 | y: Main.uiGroup.y,
308 | width: Main.uiGroup.width,
309 | height: Main.uiGroup.height
310 | });
311 | Main.uiGroup.add_child(this);
312 |
313 | const grab = Main.pushModal(this);
314 | // We expect at least a keyboard grab here
315 | if ((grab.get_seat_state() & Clutter.GrabState.KEYBOARD) === 0) {
316 | Main.popModal(grab);
317 | return false;
318 | }
319 |
320 | this._grab = grab;
321 | this._haveModal = true;
322 | this._focused = -1;
323 | this._items = [];
324 |
325 | this.connect('button-press-event', () => this.destroy());
326 |
327 | const popup = new St.BoxLayout({
328 | style_class: 'switcher-list',
329 | vertical: true,
330 | width: 500
331 | });
332 | this.add_child(popup);
333 |
334 | const fontSize = 16;
335 | const entry = new St.Entry({
336 | style: `font-size: ${fontSize}px;\
337 | border-radius: 16px;
338 | margin-bottom: 12px;`,
339 | // Translators: This is the placeholder text for a search field.
340 | hint_text: ` ${_('Type to search...')}`
341 | });
342 | const entryClutterText = entry.get_clutter_text();
343 | entryClutterText.connect('key-press-event', this._onKeyPressed.bind(this));
344 | entryClutterText.connect('text-changed', this._onTextChanged.bind(this));
345 | popup.add_child(entry);
346 |
347 | this._items = layouts.map(layout => {
348 | const item = new SearchItem(layout._name, fontSize);
349 | item.connect('button-press-event', this._onItemClicked.bind(this));
350 | popup.add_child(item);
351 | return item;
352 | });
353 |
354 | if (!this._items.length) {
355 | this.destroy();
356 | return;
357 | }
358 |
359 | const monitor = global.display.get_current_monitor();
360 | const workArea = activeWs.get_work_area_for_monitor(monitor);
361 | popup.set_position(workArea.x + workArea.width / 2 - popup.width / 2,
362 | workArea.y + workArea.height / 2 - popup.height / 2);
363 |
364 | entry.grab_key_focus();
365 | this._focus(0);
366 | }
367 |
368 | destroy() {
369 | if (this._haveModal) {
370 | Main.popModal(this._grab);
371 | this._haveModal = false;
372 | }
373 |
374 | super.destroy();
375 | }
376 |
377 | _onKeyPressed(clutterText, event) {
378 | const keySym = event.get_key_symbol();
379 | if (keySym === Clutter.KEY_Escape) {
380 | this.destroy();
381 | return Clutter.EVENT_STOP;
382 | } else if (keySym === Clutter.KEY_Return ||
383 | keySym === Clutter.KEY_KP_Enter ||
384 | keySym === Clutter.KEY_ISO_Enter) {
385 | this._activate();
386 | return Clutter.EVENT_STOP;
387 | } else if (keySym === Clutter.KEY_Down) {
388 | this._focusNext();
389 | return Clutter.EVENT_STOP;
390 | } else if (keySym === Clutter.KEY_Up) {
391 | this._focusPrev();
392 | return Clutter.EVENT_STOP;
393 | }
394 |
395 | return Clutter.EVENT_PROPAGATE;
396 | }
397 |
398 | _onTextChanged(clutterText) {
399 | const filterText = clutterText.get_text();
400 | this._items.forEach(item => {
401 | item.text.toLowerCase().includes(filterText.toLowerCase())
402 | ? item.show()
403 | : item.hide();
404 | });
405 | const nextVisibleIdx = this._items.findIndex(item => item.visible);
406 | this._focus(nextVisibleIdx);
407 | }
408 |
409 | _onItemClicked(item) {
410 | this._focused = this._items.indexOf(item);
411 | this._activate();
412 | }
413 |
414 | _focusPrev() {
415 | this._focus((this._focused + this._items.length - 1) % this._items.length);
416 | }
417 |
418 | _focusNext() {
419 | this._focus((this._focused + 1) % this._items.length);
420 | }
421 |
422 | _focus(newIdx) {
423 | const prevItem = this._items[this._focused];
424 | const newItem = this._items[newIdx];
425 | this._focused = newIdx;
426 |
427 | prevItem?.remove_style_class_name('tiling-layout-search-highlight');
428 | newItem?.add_style_class_name('tiling-layout-search-highlight');
429 | }
430 |
431 | _activate() {
432 | this._focused !== -1 && this.emit('item-activated', this._focused);
433 | this.destroy();
434 | }
435 | });
436 |
437 | /**
438 | * An Item representing a Layout within the Popup Layout search.
439 | */
440 | const SearchItem = GObject.registerClass(
441 | class TilingLayoutsSearchItem extends St.Label {
442 | _init(text, fontSize) {
443 | super._init({
444 | // Translators: This is the text that will be displayed as the name of the user-defined tiling layout if it hasn't been given a name.
445 | text: ` ${text || _('Nameless layout...')}`,
446 | style: `font-size: ${fontSize}px;\
447 | text-align: left;\
448 | padding: 8px\
449 | margin-bottom: 2px`,
450 | reactive: true
451 | });
452 | }
453 | });
454 |
455 | /**
456 | * A panel indicator to activate and favoritize a layout.
457 | */
458 | const PanelIndicator = GObject.registerClass({
459 | Signals: { 'layout-activated': { param_types: [GObject.TYPE_INT] } }
460 | }, class PanelIndicator extends PanelMenu.Button {
461 | _init() {
462 | super._init(0.0, 'Layout Indicator (Tiling Assistant)');
463 |
464 | const path = Extension.lookupByURL(import.meta.url)
465 | .dir
466 | .get_child('media/preferences-desktop-apps-symbolic.svg')
467 | .get_path();
468 | const gicon = new Gio.FileIcon({ file: Gio.File.new_for_path(path) });
469 | this.add_child(new St.Icon({
470 | gicon,
471 | style_class: 'system-status-icon'
472 | }));
473 |
474 | const menuAlignment = 0.0;
475 | this.setMenu(new PopupMenu.PopupMenu(this, menuAlignment, St.Side.TOP));
476 | }
477 |
478 | vfunc_event(event) {
479 | if (this.menu &&
480 | (event.type() === Clutter.EventType.TOUCH_BEGIN ||
481 | event.type() === Clutter.EventType.BUTTON_PRESS)
482 | ) {
483 | this._updateItems();
484 | this.menu.toggle();
485 | }
486 |
487 | return Clutter.EVENT_PROPAGATE;
488 | }
489 |
490 | _updateItems() {
491 | this.menu.removeAll();
492 |
493 | const layouts = Util.getLayouts();
494 | if (!layouts.length) {
495 | // Translators: This is a placeholder text within a popup, if the user didn't define a tiling layout.
496 | const item = new PopupMenu.PopupMenuItem(_('No valid layouts defined.'));
497 | item.setSensitive(false);
498 | this.menu.addMenuItem(item);
499 | } else {
500 | // Update favorites with monitor count and fill with '-1', if necessary
501 | const tmp = Settings.getStrv('favorite-layouts');
502 | const count = Math.max(Main.layoutManager.monitors.length, tmp.length);
503 | const favorites = [...new Array(count)].map((m, monitorIndex) => {
504 | return tmp[monitorIndex] ?? '-1';
505 | });
506 | Settings.setStrv('favorite-layouts', favorites);
507 |
508 | // Create popup menu items
509 | layouts.forEach((layout, idx) => {
510 | const name = layout._name || `Layout ${idx + 1}`;
511 | const item = new PopupFavoriteMenuItem(name, idx);
512 | item.connect('activate', () => {
513 | Main.overview.hide();
514 | this.emit('layout-activated', idx);
515 | });
516 | item.connect('favorite-changed', this._updateItems.bind(this));
517 | this.menu.addMenuItem(item);
518 | });
519 | }
520 |
521 | this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
522 |
523 | const settingsButton = new PopupMenu.PopupImageMenuItem(_('Preferences'), 'emblem-system-symbolic');
524 | // Center button without changing the size (for the hover highlight)
525 | settingsButton._icon.set_x_expand(true);
526 | settingsButton.label.set_x_expand(true);
527 | settingsButton.connect('activate',
528 | () => Extension.lookupByURL(import.meta.url).openPreferences());
529 | this.menu.addMenuItem(settingsButton);
530 | }
531 | });
532 |
533 | /**
534 | * A PopupMenuItem for the PopupMenu of the PanelIndicator.
535 | */
536 | const PopupFavoriteMenuItem = GObject.registerClass({
537 | Signals: { 'favorite-changed': { param_types: [GObject.TYPE_INT] } }
538 | }, class PopupFavoriteMenuItem extends PopupMenu.PopupBaseMenuItem {
539 | _init(text, layoutIndex) {
540 | super._init();
541 |
542 | this.add_child(new St.Label({
543 | text,
544 | x_expand: true
545 | }));
546 |
547 | const favorites = Settings.getStrv('favorite-layouts');
548 | Main.layoutManager.monitors.forEach((m, monitorIndex) => {
549 | const favoriteButton = new St.Button({
550 | child: new St.Icon({
551 | icon_name: favorites[monitorIndex] === `${layoutIndex}` ? 'starred-symbolic' : 'non-starred-symbolic',
552 | style_class: 'popup-menu-icon'
553 | })
554 | });
555 | this.add_child(favoriteButton);
556 |
557 | // Update gSetting with new Favorite (act as a toggle button)
558 | favoriteButton.connect('clicked', () => {
559 | const currFavorites = Settings.getStrv('favorite-layouts');
560 | currFavorites[monitorIndex] = currFavorites[monitorIndex] === `${layoutIndex}` ? '-1' : `${layoutIndex}`;
561 | Settings.setStrv('favorite-layouts', currFavorites);
562 | this.emit('favorite-changed', monitorIndex);
563 | });
564 | });
565 | }
566 | });
567 |
--------------------------------------------------------------------------------