Compare commits

...

1672 Commits

Author SHA1 Message Date
Ivan Molodetskikh 8ba57fcf25 Bump version to 25.05.1 2025-05-25 08:45:41 +03:00
Ivan Molodetskikh 126ca37d96 Rename Un/Set/ToggleUrgent to Un/Set/ToggleWindowUrgent
Overlooked this when reviewing. This change is not cfg-breaking (since you
can't bind these directly), but it does break calling these actions through
IPC. I don't imagine they are widely used though, and the original PR author
who also implemented urgency for bars said he didn't use these actions either.
2025-05-25 08:43:27 +03:00
Ivan Molodetskikh e6bd60fbb1 wiki: Remove note about numlock issue
It's been fixed.
2025-05-25 08:36:33 +03:00
Ivan Molodetskikh a605a3f016 Account for hidden pointer in move_cursor() 2025-05-23 23:08:51 +03:00
Ivan Molodetskikh ef44adea69 Set pointer contents straight to nothing when disabling pointer 2025-05-23 23:08:51 +03:00
Duncan Overbruck 7fdb918cd0 input: do not revert fully invisible cursor to hidden (#1650)
* input: do not force redraw to hide an already hidden cursor

* more

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-05-23 05:24:24 +00:00
Ivan Molodetskikh 8347cc20dc Update Smithay (pen tilt, num lock, keymap spam) 2025-05-22 18:05:17 +03:00
alex-huff 51a176ec4a layer-shell: only reset 'initial_configure_sent' for mapped surfaces 2025-05-22 08:02:56 -07:00
alex-huff d618daf6b9 layer-shell: don't dismiss popups because of unmapped layer surfaces
Fixes #1640
2025-05-22 07:55:29 -07:00
Ivan Molodetskikh 357f9157cc wiki/packaging: Mention RUN_SLOW_TESTS 2025-05-22 11:37:09 +03:00
Ivan Molodetskikh c4a759e620 wiki/packaging: Document limiting test threads 2025-05-22 11:35:12 +03:00
Ivan Molodetskikh f369a0f810 input: Add missing check for output under 2025-05-22 08:55:01 +03:00
Ivan Molodetskikh 71251a7003 input: Add missing redraws on urgency actions
The layout urgent colors update even without window rule changes.
2025-05-21 19:50:13 +03:00
alex-huff 2415346caa layer-shell: properly handle re-map
According to the zwlr_layer_surface_v1 documentation: Unmapping a
layer_surface means that the surface cannot be shown by the compositor
until it is explicitly mapped again. The layer_surface returns to the
state it had right after layer_shell.get_layer_surface. The client can
re-map the surface by performing a commit without any buffer attached,
waiting for a configure event and handling it as usual.

Before this commit, no configure event was sent when a client performed
a commit without any buffer attached.
2025-05-21 07:25:22 -07:00
Ivan Molodetskikh 3f2b7e63ba Improve comment in on-demand layer-shell keyboard alive check 2025-05-19 09:18:07 +03:00
Ivan Molodetskikh ae89cb6017 Update README.md 2025-05-17 15:59:05 +03:00
Ivan Molodetskikh b6fc4d0455 wiki/Overview: Link the new video 2025-05-17 14:38:24 +03:00
Federico Ceratto d8265ad34e Stop including broken LFS files in source tarball 2025-05-17 04:29:46 -07:00
Ivan Molodetskikh 3b864dc104 Bump version to 25.05 2025-05-17 13:50:36 +03:00
Ivan Molodetskikh 15093221ed wiki/Overview: Update wording 2025-05-17 13:44:55 +03:00
Ivan Molodetskikh ac7b3fbf19 wiki: Link to issue in numlock
https://github.com/YaLTeR/niri/issues/1501
2025-05-17 07:58:52 +03:00
Ivan Molodetskikh bb8eb377c7 Update dependencies more carefully
No winit deadlock in this update.
2025-05-16 22:54:37 +03:00
Ivan Molodetskikh 6169c0312a Revert "Update dependencies"
Something is causing winit deadlock on nested niri exit.

This reverts commit 2ae99224ab.

This reverts commit 0d6843ea67.
2025-05-16 22:53:54 +03:00
Ivan Molodetskikh 2ae99224ab Update dependencies 2025-05-16 22:29:09 +03:00
Ivan Molodetskikh 4f63e13385 Deal with new Clippy warnings 2025-05-16 22:21:14 +03:00
Ivan Molodetskikh 46a8f81160 ipc/client: Make compositor version check for JSON parsing errors
These can happen when adding new fields to returned structs.
2025-05-15 09:08:53 +03:00
Ivan Molodetskikh 0d6843ea67 Update dependencies 2025-05-13 17:13:35 +03:00
Ivan Molodetskikh 6d083ea497 layout: Fix workspace swipe to same workspace forgetting previous id
This manifested much more prominently in the overview.
2025-05-13 08:17:15 +03:00
Ivan Molodetskikh 7a42140d6c dependabot: Change to weekly
Let's see if this fixes it missing from the GitHub UI.
2025-05-12 20:05:33 +03:00
Ivan Molodetskikh eeb411bef5 wiki: Add Since for touchpad drag 2025-05-12 20:05:10 +03:00
Ivan Molodetskikh defd4c5c4d Add center-visible-columns action 2025-05-12 14:13:51 +03:00
dependabot[bot] 7227e64149 build(deps): bump clap in the rust-dependencies group
Bumps the rust-dependencies group with 1 update: [clap](https://github.com/clap-rs/clap).


Updates `clap` from 4.5.37 to 4.5.38
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.37...clap_complete-v4.5.38)

---
updated-dependencies:
- dependency-name: clap
  dependency-version: 4.5.38
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-12 02:58:56 -07:00
Ivan Molodetskikh c98537a2b0 Implement baba-is-float for layers 2025-05-12 09:10:59 +03:00
Ivan Molodetskikh 9c103f1f1d Add missing "to" in comment 2025-05-12 08:26:39 +03:00
Ivan Molodetskikh 2aff1ec71a ipc/socket: Support multiple requests 2025-05-11 21:51:26 -07:00
Jon Heinritz 3466fc0a66 ipc: document the new socket behavior 2025-05-11 21:51:26 -07:00
Jon Heinritz f917932b3e ipc: support long living sockets 2025-05-11 21:51:26 -07:00
Ivan Molodetskikh 89b7423ee5 Print urgent status in niri msg windows 2025-05-10 23:43:00 +03:00
Ivan Molodetskikh a2efaf2816 Add is-urgent window rule matcher 2025-05-10 22:49:55 +03:00
Ivan Molodetskikh 5816691460 Add urgent color support to tab indicators 2025-05-10 22:42:45 +03:00
Ivan Molodetskikh 4b5e9e6cb0 wiki: Document urgent-color 2025-05-10 22:42:45 +03:00
Duncan Overbruck a8259b4cea add WindowUrgencyChanged ipc event 2025-05-10 12:14:41 -07:00
Duncan Overbruck 9d3d7cb0e9 add {toggle,set,unset}-urgent cli actions 2025-05-10 12:14:41 -07:00
Duncan Overbruck 398bc78ea0 add urgent border color and gradient 2025-05-10 12:14:41 -07:00
Duncan Overbruck caa6189448 add workspace urgency ipc event 2025-05-10 12:14:41 -07:00
Duncan Overbruck 86f57c2ec7 add window urgency through xdg-activation-v1
urgency is done through activation requests without a serial from a
previous interaction.

https://gitlab.freedesktop.org/wayland/wayland-protocols/-/issues/150
2025-05-10 12:14:41 -07:00
Charlie Le 3cc67897af Implement IPC for the overview state (#1526)
* Implement IPC for the overview state

* Update Overview IPC to maintain naming consistency, renamed OverviewToggled to be more clear, simplify overview state request on the server, consolidate ipc refresh

* Fix Overview is_open in IPC client

* Change opened to is_open

* Update niri-ipc/src/lib.rs

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* Update niri-ipc/src/state.rs

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* Update src/ipc/client.rs

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* Update src/ipc/client.rs

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* Add overview state to EventStreamStatePart replicate and apply

* Fix formatting

* Rename Overview to OverviewState

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-05-09 18:01:01 +03:00
dependabot[bot] a99489c6c0 build(deps): bump clap_complete in the rust-dependencies group
Bumps the rust-dependencies group with 1 update: [clap_complete](https://github.com/clap-rs/clap).


Updates `clap_complete` from 4.5.49 to 4.5.50
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.49...clap_complete-v4.5.50)

---
updated-dependencies:
- dependency-name: clap_complete
  dependency-version: 4.5.50
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-09 07:38:04 -07:00
Ivan Molodetskikh 0763c7e196 Add a clickable button to capture the screenshot
Allows tablet-, touch- and mouse-only confirmation.
2025-05-09 15:42:23 +03:00
Ivan Molodetskikh fb5c5204e8 Extract confirm_screenshot() 2025-05-09 15:41:57 +03:00
Ivan Molodetskikh d207cd385b screenshot_ui: Refactor mouse down + touch slot state 2025-05-09 15:10:00 +03:00
Ivan Molodetskikh 99bf2df2b4 Silence new zvariant De/SerializeDict deprecations
Questionable exercise converting to serde with much more boilerplate, and
breaking compat with older zvariant versions. Plus maybe this will be
undeprecated back.
2025-05-09 10:35:16 +03:00
Ivan Molodetskikh 09be90f4e6 Add touch selection support to the screenshot UI 2025-05-09 10:28:20 +03:00
Ivan Molodetskikh dfc42b9d82 Split ScreenshotUi::pointer_down() and up() 2025-05-09 10:28:20 +03:00
Ivan Molodetskikh e2b9838d89 Extract evt.slot() 2025-05-09 10:28:20 +03:00
Ivan Molodetskikh 816a0d479c Rename touch_location to pos 2025-05-09 10:28:20 +03:00
Ivan Molodetskikh 84323d10a4 Support tablet input for screenshot UI selection 2025-05-09 10:28:20 +03:00
Ivan Molodetskikh b956f2775c Use early return 2025-05-09 10:28:20 +03:00
Ivan Molodetskikh 9ff2f83db0 Simplify ScreenshotUi::pointer_button() 2025-05-09 10:28:20 +03:00
James Sully 7a10f71ee5 refactor(main): eliminate a mut from config load code in main
I think this makes for marginally better readability, since you don't
have to wonder whether config_errored is set anywhere else. It's also
slightly terser.
2025-05-09 00:25:54 -07:00
James Sully ea7add3563 fix: don't try to create a default config at path that exists
Currently this bug has no actual consequences, we just continue silently
on AlreadyExists in main()
(this line: https://github.com/YaLTeR/niri/blob/e9c6f08906143c3fec1ad1301d538bef4cbc1978/src/main.rs#L151).

This commit just eliminates the redundant attempt.
2025-05-08 21:52:39 -07:00
Ivan Molodetskikh e9c6f08906 Add a resize transaction client-server test 2025-05-07 22:59:57 +03:00
Ivan Molodetskikh 17343a6740 wiki: Fix Until note location 2025-05-06 17:42:14 +03:00
Ivan Molodetskikh 140d726cd3 wiki: Clarify that layers within backdrop ignore input 2025-05-06 17:40:52 +03:00
Ivan Molodetskikh c37d3b3442 wiki: Link to output backdrop-color from overview {} 2025-05-06 17:34:40 +03:00
Ivan Molodetskikh 497f186422 Add layout background-color setting 2025-05-06 17:34:40 +03:00
Ivan Molodetskikh 3e31c134a6 Implement place-within-backdrop layer rule 2025-05-06 17:34:40 +03:00
Ivan Molodetskikh fe682938db Simplify exclusive focus on layer check 2025-05-06 17:34:40 +03:00
Ivan Molodetskikh 6142922ca4 wiki: Mention Overview behavior on layer-shell page 2025-05-06 17:34:40 +03:00
Ivan Molodetskikh 4b44fba14c wiki: Clarify FAQ question about border with background 2025-05-06 17:34:40 +03:00
dependabot[bot] 57639ca84c build(deps): bump the rust-dependencies group across 1 directory with 3 updates
Bumps the rust-dependencies group with 3 updates in the / directory: [clap_complete](https://github.com/clap-rs/clap), [glam](https://github.com/bitshifter/glam-rs) and [zbus](https://github.com/dbus2/zbus).


Updates `clap_complete` from 4.5.48 to 4.5.49
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.48...clap_complete-v4.5.49)

Updates `glam` from 0.30.2 to 0.30.3
- [Changelog](https://github.com/bitshifter/glam-rs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/bitshifter/glam-rs/compare/0.30.2...0.30.3)

Updates `zbus` from 5.5.0 to 5.6.0
- [Release notes](https://github.com/dbus2/zbus/releases)
- [Commits](https://github.com/dbus2/zbus/compare/zbus-5.5.0...zbus-5.6.0)

---
updated-dependencies:
- dependency-name: clap_complete
  dependency-version: 4.5.49
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: glam
  dependency-version: 0.30.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: zbus
  dependency-version: 5.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-06 01:38:03 -07:00
Ivan Molodetskikh ec88aae77d wiki: Add Since to numlock 2025-05-05 20:29:55 +03:00
Ivan Molodetskikh 6c9705dd4b layout/scrolling: Update view offset on config update
Fix always-centering not applied right away. No other changes intended.
2025-05-01 21:37:34 +03:00
Aberter Yan eb590c5346 Implement --focus for MoveColumnToWorkspace/Up/Down 2025-05-01 11:06:34 -07:00
Ivan Molodetskikh 02baad91ac wiki: Clarify how key bindings are resolved 2025-05-01 16:28:28 +03:00
Ivan Molodetskikh 68589cd5a1 wiki: Remove "experimental" from custom shaders
They've been around for a while.
2025-05-01 11:19:38 +03:00
Ivan Molodetskikh f2c690802b Adjust the workspace shadow defaults some more 2025-05-01 11:04:47 +03:00
Ivan Molodetskikh 9d6037b94c Normalize workspace shadows to 1080 px tall screen, adjust defaults
Workspace gaps are dependent on screen size, so it makes sense to make shadows
depend on the screen size to, to avoid them filling more or less of the gap.
2025-05-01 10:33:53 +03:00
Ivan Molodetskikh 7b4cf094ef Draw workspace shadows behind all workspaces 2025-05-01 10:10:11 +03:00
Ivan Molodetskikh 446bc155ce Add workspace-shadow {} config to overview {} 2025-05-01 09:45:38 +03:00
Ivan Molodetskikh 3289324ce4 wiki: Use subheadings for overview settings 2025-05-01 09:36:39 +03:00
Ivan Molodetskikh 9fb02b9571 layout: Fix DnD scroll not stopping when interactive moving unfullscreen to floating 2025-04-30 20:32:56 +03:00
erdii 0e9496b01e chore(wiki): document numlock setting
Co-Authored-By: Ivan Molodetskikh <yalterz@gmail.com>
Signed-off-by: erdii <me@erdii.engineering>
2025-04-30 09:54:19 -07:00
erdii 82dabc21f3 feat: implement support to enable numlock at startup
Signed-off-by: erdii <me@erdii.engineering>
2025-04-30 09:54:19 -07:00
erdii 39b3d62873 chore: bump smithay 2025-04-30 09:54:19 -07:00
dependabot[bot] af080a03cd build(deps): bump the rust-dependencies group with 3 updates
Bumps the rust-dependencies group with 3 updates: [wayland-backend](https://github.com/smithay/wayland-rs), [insta](https://github.com/mitsuhiko/insta) and [wayland-client](https://github.com/smithay/wayland-rs).


Updates `wayland-backend` from 0.3.9 to 0.3.10
- [Release notes](https://github.com/smithay/wayland-rs/releases)
- [Changelog](https://github.com/Smithay/wayland-rs/blob/master/historical_changelog.md)
- [Commits](https://github.com/smithay/wayland-rs/commits)

Updates `insta` from 1.43.0 to 1.43.1
- [Release notes](https://github.com/mitsuhiko/insta/releases)
- [Changelog](https://github.com/mitsuhiko/insta/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mitsuhiko/insta/compare/1.43.0...1.43.1)

Updates `wayland-client` from 0.31.9 to 0.31.10
- [Release notes](https://github.com/smithay/wayland-rs/releases)
- [Changelog](https://github.com/Smithay/wayland-rs/blob/master/historical_changelog.md)
- [Commits](https://github.com/smithay/wayland-rs/commits)

---
updated-dependencies:
- dependency-name: wayland-backend
  dependency-version: 0.3.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: insta
  dependency-version: 1.43.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: wayland-client
  dependency-version: 0.31.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-30 01:46:05 -07:00
Ivan Molodetskikh 5f117c61dc animation/spring: Guard against numerical instability 2025-04-29 10:51:53 +03:00
Christian Meissl cb857e32e4 Bump Smithay and others
Presentation subsurface fix, popup unconstrain resize fix, cursor shape fix, refactors.
2025-04-29 08:53:25 +03:00
dependabot[bot] 199be26947 build(deps): bump the rust-dependencies group across 1 directory with 5 updates
Bumps the rust-dependencies group with 5 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [anyhow](https://github.com/dtolnay/anyhow) | `1.0.97` | `1.0.98` |
| [clap](https://github.com/clap-rs/clap) | `4.5.34` | `4.5.37` |
| [glam](https://github.com/bitshifter/glam-rs) | `0.30.1` | `0.30.2` |
| [libc](https://github.com/rust-lang/libc) | `0.2.171` | `0.2.172` |
| [insta](https://github.com/mitsuhiko/insta) | `1.42.2` | `1.43.0` |



Updates `anyhow` from 1.0.97 to 1.0.98
- [Release notes](https://github.com/dtolnay/anyhow/releases)
- [Commits](https://github.com/dtolnay/anyhow/compare/1.0.97...1.0.98)

Updates `clap` from 4.5.34 to 4.5.37
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.34...clap_complete-v4.5.37)

Updates `glam` from 0.30.1 to 0.30.2
- [Changelog](https://github.com/bitshifter/glam-rs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/bitshifter/glam-rs/compare/0.30.1...0.30.2)

Updates `libc` from 0.2.171 to 0.2.172
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Changelog](https://github.com/rust-lang/libc/blob/0.2.172/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.171...0.2.172)

Updates `insta` from 1.42.2 to 1.43.0
- [Release notes](https://github.com/mitsuhiko/insta/releases)
- [Changelog](https://github.com/mitsuhiko/insta/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mitsuhiko/insta/compare/1.42.2...1.43.0)

---
updated-dependencies:
- dependency-name: anyhow
  dependency-version: 1.0.98
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: clap
  dependency-version: 4.5.37
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: glam
  dependency-version: 0.30.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: libc
  dependency-version: 0.2.172
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: insta
  dependency-version: 1.43.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-28 22:35:11 -07:00
Ivan Molodetskikh d5c0c74d2c Fix hot corners preventing focus even when disabled 2025-04-29 08:24:45 +03:00
Ivan Molodetskikh 9bb292ec82 default-config: Set repeat=off for the Overview bind 2025-04-28 12:05:55 +03:00
Ivan Molodetskikh a1ba6bcaa0 wiki: Update backdrop-color examples 2025-04-28 09:32:44 +03:00
Ivan Molodetskikh fd389af6d8 Add backdrop-color setting to overview {} 2025-04-28 09:14:43 +03:00
Ivan Molodetskikh db09727b18 Replace Smithay's SolidColor elements with ours
Must've forgotten about these back when I replaced others.
2025-04-28 09:05:55 +03:00
Ivan Molodetskikh c9d6478c3c wiki: Rename Configuration: Overview page to Introduction 2025-04-28 07:54:02 +03:00
bogdanov 758cca5432 Fix pointer hiding so that it is no longer annoying (#1426)
* replace `pointer_hidden` with `pointer_visiblity`

* disable hidden pointer after content underneath has changed

* fixes

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-04-27 06:25:36 +00:00
Ivan Molodetskikh 78e3daf5f8 overview: Activate window upon dropping from interactive move 2025-04-26 13:29:36 +03:00
Mitchel Stewart a99a0b2492 Steam Black Screen system-composer 2025-04-26 00:38:48 -07:00
Ivan Molodetskikh bfd42c74f4 layout/tab_indicator: Fix negative gap
Regressed in a recent commit that added max1.
2025-04-26 09:25:31 +03:00
Ivan Molodetskikh 501ea47128 wiki/Overview: Mention backdrop-color 2025-04-25 17:56:17 +03:00
Ivan Molodetskikh d2a1cf53b4 Fix panic when interactively moving to invisible workspace
Introduced in the interactive move between workspaces commit.
2025-04-25 16:55:36 +03:00
Ivan Molodetskikh 62d47d77d5 wiki: Document backdrop-color and overview-open-close animation 2025-04-25 15:29:42 +03:00
Ivan Molodetskikh 85cd64e830 Document the Overview and other new things 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 55c14eebf2 hotkey_overlay: Show the ToggleOverview bind 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 3fe67549b4 default-config: Bind Mod+O to toggle-overview 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 1835b532d9 Implement interactive move to a new workspace above/between 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh e6d82d3ee3 Implement top-left hot corner to toggle the Overview
Compared to third-party implementations such as waycorner:

- It works during interactive window move (no surfaces receive pointer
  focus in this case, so this cannot work through layer-shell).
- It works during drag-and-drop.
- It disables itself over fullscreen windows.
- It does not prevent direct scanout.
2025-04-25 02:00:18 -07:00
Ivan Molodetskikh fae3a27641 Implement DnD hold to activate window or workspace 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 31e76cf451 overview: Add DnD up/down scrolling 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh b8a9be542f overview: Add touchscreen gestures 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 59de6918b3 overview: Add two-finger touchpad scroll 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh bd3d554389 overview: Add hardcoded mouse scroll binds 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh af1fca35bb Implement an Overview 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 9571d149b2 Render workspaces separately with gaps between
This design makes more sense spatially, and is required for the
Overview. Gaps also make it clear how clipping windows to workspace
bounds works.

Background and bottom layer-shell surfaces get duplicated for each
workspace, while top and overlay stay "on top".
2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 99358e36b3 layout/monitor: Extract activate_workspace_with_anim_config() 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 8b878f355f Put interactively moved window on top of background and bottom layer popups 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 395b6d9a4f layout: Extract interactive_moved_window_under() and add output check
Fixes interactively moved window getting input on every output rather
than just its own.
2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 25f24f668c Extract mapped_hit_data() 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 929eaf0d69 Pass target workspace to view offset grab 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh ce3103949f layout/scrolling: Support view offset anim during gesture
Brings back moving the newly active window into focus upon interactive
move dragging out.
2025-04-25 02:00:18 -07:00
Ivan Molodetskikh ef60dd81d7 layout/monitor: Cache scale, view_size, working_area 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 7671a5d833 layout/monitor: Don't consider workspace switch in active_tile_visual_rectangle()
This only did something when in the middle of a touchpad gesture, and it
didn't really make sense for that edge case.
2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 3f09352067 layout/monitor: Extract add_workspace_at() 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 5059cce886 Add with_alpha() to shader and shadow element 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh b20dd226c0 layout: Move insert hint from ScrollingSpace to Monitor 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh acb69c3b4d layout: Return floating and scrolling elems separately from Workspace 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh dbe0a9e293 layout/tab_indicator: Use round_max1 where appropriate 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh d3a79faeec layout/monitor: Extract workspace_render_idx() 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 21630ddb5e layout/monitor: Extract workspaces_render_geo() 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 9e5e0c85bb Simplify condition 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 5cd8040d1a Extract is_layout_obscured_under() 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 86351938f2 Put the top layer above bottom and background layer popups
Makes it consistent with how window popups are below the top layer, also
will make more sense for the overview.
2025-04-25 02:00:18 -07:00
Ivan Molodetskikh ee4c5e23ab Reformat scroll factor computation 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh ffd6acc0aa layout/monitor: Extract WorkspaceSwitchGesture::min_max() 2025-04-25 02:00:18 -07:00
Ivan Molodetskikh cee11dc329 layout/monitor: Keep track of workspace switch gesture start idx
Fixes jump when "catching" an animation with a gesture.
2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 59a42249a4 Remove cancellation from swipe gestures
It only worked for workspace switch, and even there it was more confusing than
helpful.
2025-04-25 02:00:18 -07:00
Ivan Molodetskikh 74b016202b Add missing bounds checks to move-workspace actions
Fixes panics.
2025-04-25 10:54:09 +03:00
Ivan Molodetskikh 6ab055a4b9 niri.spec.rpkg: Recommend waybar
Now it's spawned by the default config.
2025-04-22 22:51:56 +03:00
Ivan Molodetskikh 98bd9b7abb niri.spec.rpkg: Fix License 2025-04-22 22:51:56 +03:00
Ivan Molodetskikh f36e1c2ef2 default-config: Spawn waybar at startup
Make it a bit less of an empty screen.
2025-04-22 22:51:56 +03:00
Ivan Molodetskikh 2243615fe9 default-config: Set titles for the default-bound apps 2025-04-22 22:51:56 +03:00
Ivan Molodetskikh 7884d3bfea layout: Extract Monitor::update_shaders() 2025-04-17 11:31:34 +03:00
Ivan Molodetskikh fdbc485d78 layout: Remove width and is_full_width from InsertHint
They were unused.
2025-04-17 11:31:34 +03:00
Ivan Molodetskikh 7e253d2687 layout: Don't pass scale to render unnecessarily
These parts of the layout already know their scale.
2025-04-17 11:31:34 +03:00
Ivan Molodetskikh 15ba2ab300 Rename render_floating_for_output to render_interactive_move_for_output 2025-04-17 11:31:34 +03:00
Ivan Molodetskikh 37840a418a animation: Extract value_at() and fix animations off difference 2025-04-17 11:31:34 +03:00
Ivan Molodetskikh 4a4c972ffb animation: Add more getters 2025-04-17 11:31:34 +03:00
Ivan Molodetskikh ba933773ab animation: Fix restarted() Spring using old from/to 2025-04-16 07:46:10 +03:00
Ivan Molodetskikh f1cca1a6ca Back out "chore: update smithay"
This backs out commit 763cd564e3.

There are graphical glitches and a panic.
2025-04-16 07:46:10 +03:00
Simonas Kazlauskas 763cd564e3 chore: update smithay 2025-04-15 13:01:24 -07:00
Ivan Molodetskikh 95eafba346 README: Add link to RustCon talk 2025-04-12 19:38:57 +03:00
Ivan Molodetskikh df94662435 layout: Take into account idle time between last gesture event and end
Fixes cases like: do a quick movement with mouse, then hold it in-place for a
while (no events generated), then release the gesture (it uses all that
built-up speed). This also happens with DnD scroll and makes it go further than
intended.
2025-04-10 10:49:35 +03:00
Ivan Molodetskikh 430b155929 Fix typo in comment 2025-04-06 10:04:40 +03:00
Ivan Molodetskikh c359d24825 layout: Avoid calling interactive_move_end() in the middle of interactive_move_update() 2025-04-05 09:42:38 +03:00
Ivan Molodetskikh e8da89a430 input: Fix move-workspace-to-index being one off 2025-04-04 16:51:09 +03:00
Ivan Molodetskikh feae8c15e6 input: Don't panic on resize edge None when window is Some
This can already happen with the tab indicator, it will happen more onwards.
2025-04-04 16:04:18 +03:00
Ivan Molodetskikh b49f7dcb4d layout/scrolling: Use slice::fill()
Fix new Clippy warning.
2025-04-03 19:25:56 +03:00
Ivan Molodetskikh 60034a57ef wiki: Document baba-is-float 2025-04-01 10:35:17 +03:00
Ivan Molodetskikh 2adbf33fb6 Update issue template and contact links 2025-04-01 08:55:14 +03:00
Ivan Molodetskikh 28cc84fbd1 wiki: Remove excessive links 2025-03-31 14:35:20 +03:00
Ivan Molodetskikh e10b968eb0 layout: Reset unfullscreen view offset when starting interactive resize 2025-03-31 14:33:02 +03:00
LunarEclipse 3b1bf34e21 Allow negative shadow spread 2025-03-31 14:13:20 +03:00
LunarEclipse bd927b54e0 Improved layout shadow documentation 2025-03-31 13:47:47 +03:00
Ivan Molodetskikh 66d3a3bd82 Fix ToggleKeyboardShortcutsInhibit comment 2025-03-31 13:34:49 +03:00
sodiboo 36489f1daa add toggle-keyboard-shortcuts-inhibit to CLI/IPC (#1366)
* add toggle-keyboard-shortcuts-inhibit to CLI/IPC

missed it in ef8d5274b8
or https://github.com/YaLTeR/niri/pull/630
or 0584dd2f1e
or whatever

* Update niri-ipc/src/lib.rs

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-03-31 05:00:10 +00:00
peelz b2c34e7fe9 Fix typo in comment 2025-03-29 07:56:47 -07:00
peelz dcc291d701 wiki: fix typo natuilus -> nautilus 2025-03-29 07:56:47 -07:00
lualeet 8d43efe4ac Add option 'focus-at-startup' to focus a chosen output on start (#1323)
* Implement default-output

* Fix incorrect wiki string

* Center mouse on start

* Move default-output to Output.focus-at-startup

* fixes

---------

Co-authored-by: lualeet <lualeet@null.null>
Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-03-29 10:13:59 +00:00
Ivan Molodetskikh 3bb7e60311 layout: Remove duplicated function 2025-03-29 12:50:16 +03:00
Ivan Molodetskikh d639eb0032 wiki: Document Steam black screen workaround 2025-03-29 11:26:31 +03:00
Ivan Molodetskikh d91499486e Make move-window-to-workspace focus=false work across monitors too 2025-03-29 11:17:38 +03:00
Ivan Molodetskikh f7106f9658 Update dependencies 2025-03-29 10:56:30 +03:00
Ivan Molodetskikh 835490c59a Update Smithay (protocol sanity checks) 2025-03-29 10:55:41 +03:00
dependabot[bot] 5cde00f6c6 build(deps): bump the rust-dependencies group across 1 directory with 2 updates
Bumps the rust-dependencies group with 2 updates in the / directory: [clap](https://github.com/clap-rs/clap) and [log](https://github.com/rust-lang/log).


Updates `clap` from 4.5.32 to 4.5.34
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.32...clap_complete-v4.5.34)

Updates `log` from 0.4.26 to 0.4.27
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.26...0.4.27)

---
updated-dependencies:
- dependency-name: clap
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: log
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-29 00:46:51 -07:00
nyx 7dc015e16b screenshot: make selection area modifiable via move/resize keybinds (#1279)
* screenshot: make selection area modifiable via keybinds

* input: run fmt

* Reimplement screenshot UI binds in a better way

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-03-29 07:40:21 +00:00
nyx 0db48e2f1b Add focus argument to move-window-to-workspace (#1332)
* layout: add focus flag to move-window-to-workspace

* lib: update comment

* misc: minor dup refactor

* input: format code

* layout: minor nit

* layout: update comment

* input: remove unnecessary conditionals

* misc: replace boolean

* tests: fix the failing one

* layout: change to smart

* ipc: Option<bool> -> bool

* lib: format code

* Rewrite focus doc comment

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-03-29 06:40:08 +00:00
Gavin Zhao 7cfecf4b1b wiki: Mention file chooser dependency and settings for portals (#1344)
* wiki: Mention file chooser dependency and settings for portals

* Update wiki/Important-Software.md

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-03-26 12:37:00 -07:00
Ivan Chernov 3142838e9e wiki: Documented flags for Electron based applications (#1302)
* wiki: Documented flags for Electron based applications

* Update wiki/Application-Issues.md

Co-authored-by: Kent Daleng <lolexplode@gmail.com>

* wiki: remove Arch specific files for Electron

* Apply suggestions from code review

---------

Co-authored-by: Kent Daleng <lolexplode@gmail.com>
Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-03-26 20:56:24 +03:00
Maya Nordland 4534d37266 wiki: Document window rule for steam notifications (#1341)
* wiki: Document window rule for steam notifications

* Update wiki/Application-Issues.md

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-03-25 07:39:59 +03:00
sodiboo ec5112d779 nix: update flake inputs and use new libgbm
fixes #1312
like
https://github.com/sodiboo/niri-flake/commit/0d54ea3f208f785b29f8396996b6bc8596d11a45
2025-03-23 12:21:55 -07:00
Ivan Molodetskikh c709696237 Don't block things out for pick-color
It's interactive so it's fine.
2025-03-23 11:45:54 +03:00
Ivan Molodetskikh b271409509 dbus/gnome_shell_screenshot: Fix pick_color return type 2025-03-23 09:31:51 +03:00
Ivan Molodetskikh 500dcca9b7 input: Suppress release from Pick grab clicks
Otherwise, it would trigger something inside the window.
2025-03-22 23:14:51 -07:00
nnyyxxxx 7210045b2a feat: support color picker functionality
chore: format code

refactor: improve quality

feat: implement gnomes PickColor method

refactor: minor code extraction

misc: fix reviews

fixes
2025-03-22 23:14:51 -07:00
Ivan Molodetskikh ed20822ce9 layout: Reset unfullscreen view offset when removing window
Another old bug found by randomized tests after I expanded the testing mock
window.
2025-03-22 13:57:37 +03:00
Jon Heinritz e88dfae46f main: Log to stderr instead of stdout
Currently we can't use logging in paths like niri msg that have meaningful
stdout. Logging to stderr makes that possible. Even if we don't want to log
anything in niri msg code paths, it's easy to have something accidentally log.
2025-03-22 12:29:11 +03:00
dependabot[bot] f95d5a82df build(deps): bump the rust-dependencies group across 1 directory with 2 updates
Bumps the rust-dependencies group with 2 updates in the / directory: [clap_complete](https://github.com/clap-rs/clap) and [glam](https://github.com/bitshifter/glam-rs).


Updates `clap_complete` from 4.5.46 to 4.5.47
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.46...clap_complete-v4.5.47)

Updates `glam` from 0.30.0 to 0.30.1
- [Changelog](https://github.com/bitshifter/glam-rs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/bitshifter/glam-rs/compare/0.30.0...0.30.1)

---
updated-dependencies:
- dependency-name: clap_complete
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: glam
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-22 01:13:47 -07:00
Florian Finkernagel 7f72c358d5 Add option to warp-mouse-to-focus to always center 2025-03-22 01:00:43 -07:00
Ivan Molodetskikh 0d4f0f00c0 wiki: Document mod-key, mod-key-nested 2025-03-22 00:03:33 -07:00
peelz f2663c738c hotkey_overlay: rename ISO_Level{3,5}_Shift to Mod{5,3} 2025-03-22 00:03:33 -07:00
peelz c3609efb7a Add mod-key and mod-key-nested settings 2025-03-22 00:03:33 -07:00
Florian Finkernagel fd1f43673c Workspace-doc: reference set-workspace-name 2025-03-21 00:37:37 -07:00
Ivan Molodetskikh 9d10def7e8 wiki: Add Workspaces page 2025-03-21 09:26:21 +03:00
Ivan Molodetskikh e251ca7340 wiki: Document windowed fullscreen 2025-03-18 08:43:20 +03:00
Ivan Molodetskikh 9a527cc571 Track uncommitted windowed fullscreen state
Alright, this is the proper implementation. No more flickering.
2025-03-17 22:31:19 -07:00
Ivan Molodetskikh 39f52b7585 Implement toggle-windowed-fullscreen
Windowed, or fake, or detached, fullscreen, is when a window thinks that it's
fullscreen, but the compositor treats it as a normal window.
2025-03-17 22:31:19 -07:00
Ivan Molodetskikh b447b1f4de layout: Rename argument from window to id 2025-03-17 22:31:19 -07:00
Ivan Molodetskikh 1a0fab05b6 layout: Don't forget to call on_commit() for the interactively moved window 2025-03-17 22:31:19 -07:00
Ivan Molodetskikh fbb399f01d layout/tests: Implement going into fullscreen state 2025-03-17 22:31:19 -07:00
Ivan Molodetskikh 6a80ec4704 layout/tile: Don't take fullscreen into account in min/max size
They are used strictly for non-fullscreen size computation.
2025-03-17 22:31:19 -07:00
Ivan Molodetskikh e8b158641b layout: Verify moved tile invariants 2025-03-17 22:31:19 -07:00
Ivan Molodetskikh 27a715aded layout: Test that interactively moved window is not pending fullscreen 2025-03-17 22:31:19 -07:00
Ivan Molodetskikh 926e63a5f3 Refactor request_fullscreen() to be an argument on request_size() 2025-03-17 22:31:19 -07:00
Ivan Molodetskikh e879199880 layout: Switch two places to workspaces_mut() 2025-03-17 22:31:19 -07:00
Cole Leavitt 5b6b6a5fe1 Add wait-for-frame-completion-in-pipewire debug flag for NVIDIA screencasts 2025-03-17 12:03:43 -07:00
Johannes Horner e11af089aa nix: Install shell completions (#1280) 2025-03-17 17:16:39 +03:00
Kent Daleng 5e549e1323 ci/wiki: check that (local) links are well formed (#1282)
* add check-links step, fix some links

* don't depend on build right now

* fix fragment

* reintroduce dependency for build

* don't only check links on push to main

* maybe this is a more sensible dependency tree for this stuff

* change commented suggestions, try v2.0.2 for action

* describe why we're on v2.0.2

* revert to %E2%80%90 (works with lychee anyway)
2025-03-16 20:15:37 +03:00
Ivan Molodetskikh 287480b541 Keep buffer size when switching dynamic cast to Nothing
Otherwise, we won't actually clear it because it'll become Pending.
2025-03-16 08:32:45 +03:00
Hilmar Wiegand a022fedd51 nix: Update flake.lock 2025-03-15 11:44:51 -07:00
Ivan Molodetskikh a4b8e100c0 Update Smithay & deps (fix panic during monitor hotplugging) 2025-03-15 20:42:22 +03:00
Ivan Molodetskikh 62576796be wiki: Add a Screencasting page 2025-03-15 19:58:18 +03:00
Ivan Molodetskikh 31891e6642 Implement dynamic screencast target 2025-03-15 09:55:46 -07:00
Kent Daleng 392fc27de1 Use anchors on the wiki (#1266)
* wiki testing

* wiki updates

* use .md with anchors, revert sidebar

* bump wiki action

* add some more anchors, fix some language

* change links to be more descriptive by themselves
2025-03-15 15:42:05 +00:00
Ivan Molodetskikh 9e560e7e60 Move CastTarget to src/niri.rs 2025-03-15 11:22:30 +03:00
Ivan Molodetskikh cee2ec7ab7 Use windows() instead of with_windows() 2025-03-15 11:18:54 +03:00
Ivan Molodetskikh 8c4ebb00a1 Store cast Stream ID, use it for Redraw request
Unlike StopCast, Redraw targets a specific Cast. Use the stream ID to
identify it.
2025-03-15 10:23:00 +03:00
Duncan Overbruck f6aa8c1793 Add move-column-to-index action 2025-03-14 12:57:33 -07:00
Duncan Overbruck a5d58d670b Add focus-column (by index) action 2025-03-14 12:57:33 -07:00
dependabot[bot] b4922086ce build(deps): bump the smithay group with 2 updates
Bumps the smithay group with 2 updates: [smithay](https://github.com/Smithay/smithay) and [smithay-drm-extras](https://github.com/Smithay/smithay).


Updates `smithay` from `a503d98` to `796c41c`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/a503d981d1be9a54b286ab5e160e4b9edddb500f...796c41c0294ccc195b0f59228d6467cc6c8f5de8)

Updates `smithay-drm-extras` from `a503d98` to `796c41c`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/a503d981d1be9a54b286ab5e160e4b9edddb500f...796c41c0294ccc195b0f59228d6467cc6c8f5de8)

---
updated-dependencies:
- dependency-name: smithay
  dependency-type: direct:production
  dependency-group: smithay
- dependency-name: smithay-drm-extras
  dependency-type: direct:production
  dependency-group: smithay
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-14 01:39:00 -07:00
Ivan Molodetskikh fd3b1f2b6c layout: Preserve previous view offset on consume-left 2025-03-14 08:50:29 +03:00
Ivan Molodetskikh ee0e2c7f1b Try default when configured xkb keymap fails to compile
Fixes panic at startup.
2025-03-13 21:39:07 +03:00
Ivan Molodetskikh 4f16be9e4d Wait for lock surfaces before locking
Fixes the red flash when locking.
2025-03-13 19:09:32 +03:00
Ivan Molodetskikh 0f30306fe5 Extract utils::is_mapped() 2025-03-13 18:56:35 +03:00
Ivan Molodetskikh 1c6037e612 Add tiled-state window rule, update the tiled state live 2025-03-13 14:14:54 +03:00
dbeley fed86fdb5d feat(trackpoint): document left-handed option 2025-03-13 03:36:20 -07:00
dbeley 3e21585861 feat(trackpoint): add left-handed option support 2025-03-13 03:36:20 -07:00
dependabot[bot] 9f9c4a99af build(deps): bump libc in the rust-dependencies group
Bumps the rust-dependencies group with 1 update: [libc](https://github.com/rust-lang/libc).


Updates `libc` from 0.2.170 to 0.2.171
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Changelog](https://github.com/rust-lang/libc/blob/0.2.171/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.170...0.2.171)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-12 06:34:54 -07:00
dependabot[bot] b220cdbe7e build(deps): bump the smithay group with 2 updates (#1243)
Bumps the smithay group with 2 updates: [smithay](https://github.com/Smithay/smithay) and [smithay-drm-extras](https://github.com/Smithay/smithay).


Updates `smithay` from `3219a0f` to `a503d98`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/3219a0f02a30de359f460ab165682a51cb13b7a5...a503d981d1be9a54b286ab5e160e4b9edddb500f)

Updates `smithay-drm-extras` from `3219a0f` to `a503d98`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/3219a0f02a30de359f460ab165682a51cb13b7a5...a503d981d1be9a54b286ab5e160e4b9edddb500f)

---
updated-dependencies:
- dependency-name: smithay
  dependency-type: direct:production
  dependency-group: smithay
- dependency-name: smithay-drm-extras
  dependency-type: direct:production
  dependency-group: smithay
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-11 12:08:11 +03:00
dependabot[bot] df219b5134 build(deps): bump the rust-dependencies group with 2 updates (#1242)
Bumps the rust-dependencies group with 2 updates: [clap](https://github.com/clap-rs/clap) and [clap_complete](https://github.com/clap-rs/clap).


Updates `clap` from 4.5.31 to 4.5.32
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/v4.5.31...clap_complete-v4.5.32)

Updates `clap_complete` from 4.5.45 to 4.5.46
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.45...clap_complete-v4.5.46)

---
updated-dependencies:
- dependency-name: clap
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: clap_complete
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-11 12:07:29 +03:00
dependabot[bot] 8cdabe8adf build(deps): bump serde in the rust-dependencies group (#1239)
Bumps the rust-dependencies group with 1 update: [serde](https://github.com/serde-rs/serde).


Updates `serde` from 1.0.218 to 1.0.219
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.218...v1.0.219)

---
updated-dependencies:
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-11 09:22:26 +03:00
Annika Hannig 8737067af5 added move window to monitor by id 2025-03-10 23:17:36 -07:00
Annika Hannig 50a99f6356 Implemented move-window-to-monitor and move-column-to-monitor 2025-03-10 23:17:36 -07:00
Annika Hannig 993c5ce8af Implement focus-monitor to focus a specific monitor by output. 2025-03-10 23:17:36 -07:00
Toby Bridle 47dd338340 feat: 🎉 add show-pointer for Screenshot and ScreenshotScreen 2025-03-10 22:31:50 -07:00
Jon Heinritz 87b6c12625 Add Shell completions (#1226)
* feat(cli): add subcommand to generate shell completions

* Update src/cli.rs

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-03-10 20:14:34 +00:00
Ivan Molodetskikh b351f6ff22 Keep track of RenderElementStates in offscreens
This both avoids sending frame callbacks to surfaces invisible on the offscreen
(fixing Firefox with subsurface compositing in the process), and fixes
searching for split popups during the resize animation.
2025-03-10 07:59:14 +03:00
Ivan Molodetskikh 12817a682d Store offscreen element id on Mapped instead of user data
We don't need user data for this.
2025-03-10 07:59:14 +03:00
Ivan Molodetskikh 88614c08fe Make interactively moved window semitransparent 2025-03-10 07:59:14 +03:00
Ivan Molodetskikh 4f5c8e745b Offscreen semitransparent tiles
Now that offscreen does damage tracking, we can reasonably do this. Note this
only affects full-tile opacity, not window opacity.
2025-03-10 07:59:14 +03:00
Ivan Molodetskikh f30413a744 layout/tile: Use animated tile size for open anim geo
This is the right value to use as the texture will also match the animated
size.
2025-03-10 07:59:14 +03:00
Ivan Molodetskikh 3b8ce12316 tile: Use OffscreenBuffer for resize anims
OffscreenBuffer knows how to avoid recreating the texture every frame.
2025-03-10 07:59:14 +03:00
Ivan Molodetskikh 880386e563 render_helpers/resize: Fix logic to allow for partially-filled texture
"texture geo" defines offset and src size, rather than the full texture size.
2025-03-10 07:59:14 +03:00
Ivan Molodetskikh 266c6c3878 offscreen: Don't recreate if size decreased 2025-03-10 07:59:14 +03:00
Ivan Molodetskikh 7b033aa7c6 offscreen: Track and return damage
This is the second part of the damage equation: now the offscreen element
itself reports correct damage, so partial redraws to the texture don't cause
full redraws of the texture element itself.
2025-03-10 07:59:14 +03:00
Ivan Molodetskikh efd8372b20 offscreen: Take damage into account when rendering
Does not yet signal the damage outside, but does skip rerendering if there was
no damage.
2025-03-10 07:59:14 +03:00
Ivan Molodetskikh 74a30be10b Cache texture in OpenAnimation
Don't recreate it unless the size changes. This lays the groundwork for also
tracking damage in the future.
2025-03-10 07:59:14 +03:00
Ivan Molodetskikh 1c521e4831 Update Smithay (Framebuffer type) 2025-03-10 07:59:14 +03:00
Jon Heinritz eda43b2b93 doc: fix wrongly formatted link that rustdoc kept complaining about 2025-03-09 04:24:24 -07:00
LunarEclipse 593241d2f0 Added missing "Since: 25.02" to clipboard config documentation 2025-03-08 21:27:08 -08:00
Ivan Molodetskikh 69627bdc64 wiki: Document toggle-keyboard-shortcuts-inhibit and allow-inhibiting 2025-03-08 21:47:37 +03:00
Ivan Molodetskikh 3fa373c720 wiki: Add since to toggle-window-rule-opacity 2025-03-08 21:47:37 +03:00
Ivan Molodetskikh 083a56c729 wiki: Update the wording on the configuration breaking change policy 2025-03-08 14:54:34 +03:00
Ivan Molodetskikh 88fcf0c2a9 README: Mention tabs in features 2025-03-06 14:36:36 +03:00
dependabot[bot] 26618f8d50 build(deps): bump the rust-dependencies group with 5 updates
Bumps the rust-dependencies group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [anyhow](https://github.com/dtolnay/anyhow) | `1.0.96` | `1.0.97` |
| [bitflags](https://github.com/bitflags/bitflags) | `2.8.0` | `2.9.0` |
| [bytemuck](https://github.com/Lokathor/bytemuck) | `1.21.0` | `1.22.0` |
| [serde_json](https://github.com/serde-rs/json) | `1.0.139` | `1.0.140` |
| [insta](https://github.com/mitsuhiko/insta) | `1.42.1` | `1.42.2` |


Updates `anyhow` from 1.0.96 to 1.0.97
- [Release notes](https://github.com/dtolnay/anyhow/releases)
- [Commits](https://github.com/dtolnay/anyhow/compare/1.0.96...1.0.97)

Updates `bitflags` from 2.8.0 to 2.9.0
- [Release notes](https://github.com/bitflags/bitflags/releases)
- [Changelog](https://github.com/bitflags/bitflags/blob/main/CHANGELOG.md)
- [Commits](https://github.com/bitflags/bitflags/compare/2.8.0...2.9.0)

Updates `bytemuck` from 1.21.0 to 1.22.0
- [Changelog](https://github.com/Lokathor/bytemuck/blob/main/changelog.md)
- [Commits](https://github.com/Lokathor/bytemuck/compare/v1.21.0...v1.22.0)

Updates `serde_json` from 1.0.139 to 1.0.140
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.139...v1.0.140)

Updates `insta` from 1.42.1 to 1.42.2
- [Release notes](https://github.com/mitsuhiko/insta/releases)
- [Changelog](https://github.com/mitsuhiko/insta/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mitsuhiko/insta/compare/1.42.1...1.42.2)

---
updated-dependencies:
- dependency-name: anyhow
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: bitflags
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: bytemuck
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: serde_json
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: insta
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-03 03:36:44 -08:00
Ivan Molodetskikh 9f205d465c mapped: Omit popups from animation snapshot
It's used only for resizes, and those render popups on top.
2025-03-02 10:01:52 +03:00
Alex David d6e736aaf0 Allow disabling tap-and-drag (#1107)
* Allow disabling tap-and-drag

Similar to https://github.com/YaLTeR/niri/pull/1088, this adds a new
touchpad `drag` configuration option that configures tap-and-drag
behavior.

Currently tap-and-drag is always enabled when the `tap` setting is
enabled, but other compositors allow setting this separately.

* Update wiki/Configuration:-Input.md

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-03-02 10:01:34 +03:00
Martino Ferrari 36b28d9b96 Added top, left, bottom and right floating windows alignement (#1169)
* feat: added top, left, bottom, right alignement options

* feat: implemented extra alignement

* feat: added example

* doc: updated documentation with extra alignements

* doc: moved example in wiki and typo correction

* fix: relative position should be positive and not negative

* fixes

---------

Co-authored-by: Martino Ferrari <martinogiordano.ferrari@iter.org>
Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-03-01 17:46:27 +00:00
Ivan Molodetskikh 66113d7d76 wiki/FAQ: Remove mention of Waybar popups
This had been fixed a while ago.
2025-02-28 16:39:06 +03:00
dependabot[bot] aa2e8b402c build(deps): bump the smithay group with 2 updates
Bumps the smithay group with 2 updates: [smithay](https://github.com/Smithay/smithay) and [smithay-drm-extras](https://github.com/Smithay/smithay).


Updates `smithay` from `c24b431` to `25cf3cf`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/c24b431cc44458172f31276ca0fbade1ae09bdd9...25cf3cf41c5027ffeb55f90c683736726a81d71f)

Updates `smithay-drm-extras` from `c24b431` to `25cf3cf`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/c24b431cc44458172f31276ca0fbade1ae09bdd9...25cf3cf41c5027ffeb55f90c683736726a81d71f)

---
updated-dependencies:
- dependency-name: smithay
  dependency-type: direct:production
  dependency-group: smithay
- dependency-name: smithay-drm-extras
  dependency-type: direct:production
  dependency-group: smithay
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-28 00:45:33 -08:00
lanastara 311f3be5d8 wiki: remove wezterm issues (#1182)
* wiki: added note about nightly wezterm

* Update wiki/Application-Issues.md

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-02-27 19:16:27 +00:00
Ivan Molodetskikh 70dcd229cf Extract encompassing_geo() 2025-02-27 10:38:36 +03:00
Ivan Molodetskikh 26fe4a489a render_helpers: Use upscale(-1) 2025-02-27 09:54:26 +03:00
Ivan Molodetskikh 2363cf48e7 layout/monitor: Remove unused function 2025-02-27 08:21:05 +03:00
Ivan Molodetskikh 848294c09b layout/monitor: Remove redundant passthrough functions 2025-02-27 08:21:05 +03:00
Ivan Molodetskikh 693d935538 Add honor-xdg-activation-with-invalid-serial debug flag 2025-02-26 19:33:58 +03:00
bbb651 🇮🇱 16405b9b2b Implement niri msg pick-window
* feat: `niri msg pick-window`

* fixes

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-02-26 15:22:27 +03:00
Ivan Molodetskikh 4719cc6d59 cursor: Extract get_render_cursor_named() 2025-02-26 15:10:18 +03:00
Ivan Molodetskikh 98b92d4db7 wiki: Add off to touch {} 2025-02-26 14:33:16 +03:00
nnyyxxxx 1bdded7a44 feat(input): add off option to touch device 2025-02-26 03:32:21 -08:00
dependabot[bot] 9bfe90dee1 build(deps): bump the rust-dependencies group across 1 directory with 3 updates
Bumps the rust-dependencies group with 3 updates in the / directory: [clap](https://github.com/clap-rs/clap), [portable-atomic](https://github.com/taiki-e/portable-atomic) and [schemars](https://github.com/GREsau/schemars).


Updates `clap` from 4.5.30 to 4.5.31
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.30...v4.5.31)

Updates `portable-atomic` from 1.10.0 to 1.11.0
- [Release notes](https://github.com/taiki-e/portable-atomic/releases)
- [Changelog](https://github.com/taiki-e/portable-atomic/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/portable-atomic/compare/v1.10.0...v1.11.0)

Updates `schemars` from 0.8.21 to 0.8.22
- [Release notes](https://github.com/GREsau/schemars/releases)
- [Changelog](https://github.com/GREsau/schemars/blob/master/CHANGELOG.md)
- [Commits](https://github.com/GREsau/schemars/compare/v0.8.21...v0.8.22)

---
updated-dependencies:
- dependency-name: clap
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: portable-atomic
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: schemars
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-26 02:43:00 -08:00
dependabot[bot] c153349c62 build(deps): bump the smithay group with 2 updates
Bumps the smithay group with 2 updates: [smithay](https://github.com/Smithay/smithay) and [smithay-drm-extras](https://github.com/Smithay/smithay).


Updates `smithay` from `0cd3345` to `c24b431`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/0cd3345c59f7cb139521f267956a1a4e33248393...c24b431cc44458172f31276ca0fbade1ae09bdd9)

Updates `smithay-drm-extras` from `0cd3345` to `c24b431`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/0cd3345c59f7cb139521f267956a1a4e33248393...c24b431cc44458172f31276ca0fbade1ae09bdd9)

---
updated-dependencies:
- dependency-name: smithay
  dependency-type: direct:production
  dependency-group: smithay
- dependency-name: smithay-drm-extras
  dependency-type: direct:production
  dependency-group: smithay
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-25 01:33:51 -08:00
Ivan Molodetskikh 5b6b5536fd Also check pointer for activation token validity
This actually doesn't matter in most cases currently, because it more or less
checks for *anything* to have a keyboard focus, so if you have some focused
window while clicking on a mako notification, that already qualifies.

Signed-off-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-02-24 22:34:30 +03:00
dependabot[bot] bac22dfe9f build(deps): bump the rust-dependencies group across 1 directory with 2 updates
Bumps the rust-dependencies group with 2 updates in the / directory: [libc](https://github.com/rust-lang/libc) and [log](https://github.com/rust-lang/log).


Updates `libc` from 0.2.169 to 0.2.170
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Changelog](https://github.com/rust-lang/libc/blob/0.2.170/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.169...0.2.170)

Updates `log` from 0.4.25 to 0.4.26
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.25...0.4.26)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: log
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-24 02:33:11 -08:00
Ivan Molodetskikh bca6545288 wiki: Add gestures to the list in configuration overview 2025-02-22 22:12:28 +03:00
Ivan Molodetskikh b94a5db879 Bump version to 25.02 2025-02-21 09:05:26 +03:00
Ivan Molodetskikh 4a4dcb85ef Update dependencies 2025-02-21 08:03:48 +03:00
Ivan Molodetskikh 7b70cb66bc wiki: Add Since to xkb file 2025-02-20 22:26:40 +03:00
Ivan Molodetskikh cd6522bcc6 wiki: Mention screenshow-screen/window write-to-disk=false 2025-02-20 22:26:40 +03:00
dependabot[bot] 8885233c7e build(deps): bump the rust-dependencies group with 4 updates
Bumps the rust-dependencies group with 4 updates: [anyhow](https://github.com/dtolnay/anyhow), [glam](https://github.com/bitshifter/glam-rs), [serde](https://github.com/serde-rs/serde) and [serde_json](https://github.com/serde-rs/json).


Updates `anyhow` from 1.0.95 to 1.0.96
- [Release notes](https://github.com/dtolnay/anyhow/releases)
- [Commits](https://github.com/dtolnay/anyhow/compare/1.0.95...1.0.96)

Updates `glam` from 0.29.2 to 0.30.0
- [Changelog](https://github.com/bitshifter/glam-rs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/bitshifter/glam-rs/compare/0.29.2...0.30.0)

Updates `serde` from 1.0.217 to 1.0.218
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.217...v1.0.218)

Updates `serde_json` from 1.0.138 to 1.0.139
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.138...v1.0.139)

---
updated-dependencies:
- dependency-name: anyhow
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: glam
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: serde_json
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-20 01:08:29 -08:00
Ivan Molodetskikh 7478784343 Change default DnD scroll delay-ms to 100 2025-02-19 07:49:29 +03:00
Ivan Molodetskikh dca187de37 Don't snap after DnD scroll if view position didn't change
Otherwise, any DnD breaks temporarily centered columns.
2025-02-18 19:06:40 +03:00
Ivan Molodetskikh fe660a253b Don't activate window when pressing the Mod+MMB view gesture
Avoid unnecessary movement.
2025-02-18 19:06:40 +03:00
dependabot[bot] ad49e5820a build(deps): bump clap in the rust-dependencies group
Bumps the rust-dependencies group with 1 update: [clap](https://github.com/clap-rs/clap).


Updates `clap` from 4.5.29 to 4.5.30
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.29...clap_complete-v4.5.30)

---
updated-dependencies:
- dependency-name: clap
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-18 01:50:42 -08:00
dependabot[bot] 4c40e6ce06 build(deps): bump ordered-float from 4.6.0 to 5.0.0
Bumps [ordered-float](https://github.com/reem/rust-ordered-float) from 4.6.0 to 5.0.0.
- [Release notes](https://github.com/reem/rust-ordered-float/releases)
- [Commits](https://github.com/reem/rust-ordered-float/compare/v4.6.0...v5.0.0)

---
updated-dependencies:
- dependency-name: ordered-float
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-18 01:50:32 -08:00
Ivan Molodetskikh 44c9797844 Take tab indicators into account in expand-column-to-available-width 2025-02-17 22:36:30 +03:00
Ivan Molodetskikh 652d2923bb Use toggle_full_width() for expand-column-to-available-width edge case 2025-02-17 21:57:35 +03:00
Ivan Molodetskikh 85349ce475 Fix expand-column-to-available-width for always-center 2025-02-17 21:48:00 +03:00
Ivan Molodetskikh 92cc2b89f7 Implement expand-column-to-available-width 2025-02-17 21:30:23 +03:00
dependabot[bot] 078383ea82 build(deps): bump pango in the rust-dependencies group
Bumps the rust-dependencies group with 1 update: [pango](https://github.com/gtk-rs/gtk-rs-core).


Updates `pango` from 0.20.7 to 0.20.9
- [Release notes](https://github.com/gtk-rs/gtk-rs-core/releases)
- [Changelog](https://github.com/gtk-rs/gtk-rs-core/blob/main/CHANGELOG.md)
- [Commits](https://github.com/gtk-rs/gtk-rs-core/compare/0.20.7...0.20.9)

---
updated-dependencies:
- dependency-name: pango
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-17 02:18:38 -08:00
Ivan Molodetskikh d27d6a504d Make idle notify lazy 2025-02-17 09:09:59 +03:00
Ivan Molodetskikh ec5144feca Make pointer inactivity timer reset lazy 2025-02-17 09:04:07 +03:00
David 05e0e44a77 Fix link in Application-Issues.md 2025-02-16 09:16:59 -08:00
Ivan Molodetskikh 108e88e211 Enable fancy miette errors for the main binary
Seems there's not much dependency/binary size impact now, compared to when I
first made the KDL config.
2025-02-16 19:37:37 +03:00
Ivan Molodetskikh a693f64c41 Add blank line 2025-02-16 10:26:59 +03:00
Ivan Molodetskikh 5c0468d469 wiki: Document the DnD edge view scroll gesture and config 2025-02-16 10:18:00 +03:00
Ivan Molodetskikh f2b1fc66f2 Make DnD edge view scroll configurable 2025-02-16 10:18:00 +03:00
Ivan Molodetskikh 22302bf224 config: Deindent the snapshot 2025-02-16 10:18:00 +03:00
Ivan Molodetskikh bb6663ebac config: Convert parse test to a snapshot test
Updating it by hand got really old tbh
2025-02-16 10:18:00 +03:00
Ivan Molodetskikh c6e98d5a96 Add a small delay to DnD view scrolling 2025-02-16 10:18:00 +03:00
Ivan Molodetskikh d077350ae4 layout: Remove unused method 2025-02-16 10:18:00 +03:00
w-jablonski f01c840ebe Slightly clearer wording in Tabs.md 2025-02-15 05:15:07 -08:00
Ivan Molodetskikh ca1500ae90 Implement scrolling the view during DnD
DnD is external to the layout, so we just inform it when one is ongoing.
2025-02-15 13:28:57 +03:00
Ivan Molodetskikh d7f3ca00c7 Implement scrolling the view during interactive move 2025-02-15 13:28:57 +03:00
Ivan Molodetskikh fd8140e091 Hook up are_transitions_ongoing() for floating and tiles
Don't spoil it
2025-02-15 13:28:57 +03:00
Ivan Molodetskikh d94fbe9895 layout: Check move output in are_animations_ongoing() 2025-02-15 13:28:57 +03:00
Ivan Molodetskikh 7816f20e6a Implement ext-data-control 2025-02-14 09:03:20 +03:00
Ivan Molodetskikh 0d3610416c Update Smithay (idle-notify 2) 2025-02-14 09:03:20 +03:00
Ivan Molodetskikh 377ad54016 wiki: Document calibration-matrix 2025-02-14 09:03:20 +03:00
Ivan Chinenov 9e794f358b feat: support for setting tablet calibration matrix; this allows for rotating tablet inputs (#1122)
* feat: support for setting tablet calibration matrix

* Change default matrix
2025-02-14 05:15:45 +00:00
dependabot[bot] 4e17cbb9ea build(deps): bump clap in the rust-dependencies group
Bumps the rust-dependencies group with 1 update: [clap](https://github.com/clap-rs/clap).


Updates `clap` from 4.5.28 to 4.5.29
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.28...clap_complete-v4.5.29)

---
updated-dependencies:
- dependency-name: clap
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-13 21:05:26 -08:00
rustN00b 4c98b87486 Add missing period to doc comment 2025-02-13 10:39:25 +03:00
rustN00b 5b753be213 Add missing periods to action doc comments 2025-02-13 10:37:41 +03:00
Ivan Molodetskikh a605e7f622 Implement custom hotkey overlay titles 2025-02-13 10:30:33 +03:00
Ivan Molodetskikh 513488f6b8 hotkey overlay: Add pretty for space 2025-02-13 10:30:33 +03:00
Ivan Molodetskikh 43ea4a172a hotkey overlay: Put Ctrl and Shift before Alt
They are commonly written this way.
2025-02-13 10:30:33 +03:00
Ivan Molodetskikh d47b59879a animation/spring: Add a check for from = to in duration()
The overdamped code below was dividing by zero in this case and triggering a
panic.
2025-02-13 08:47:23 +03:00
Ivan Molodetskikh ef80bcc834 Parse the config on the file watcher thread
It takes a while, so let's not block the main thread.
2025-02-12 20:56:32 +03:00
Ivan Molodetskikh eb8bd3894a watcher: Allow running a processing function on the thread 2025-02-12 20:56:32 +03:00
Ivan Molodetskikh 7e552333a9 tab indicator: Add corner-radius setting 2025-02-12 07:59:46 +03:00
Ivan Molodetskikh 213eafa203 wiki: Add Since to drag-lock 2025-02-11 18:24:17 +03:00
Ivan Molodetskikh 7b18ff8870 input: Intercept Enter key when confirming the exit dialog 2025-02-11 13:22:11 +03:00
Ivan Molodetskikh 5246e2ff25 wiki: Add note that is-window-cast-target doesn't match monitor casts 2025-02-11 10:40:51 +03:00
Ivan Molodetskikh dde9214ae4 wiki: Move sentence to a better spot 2025-02-11 10:35:15 +03:00
Ivan Molodetskikh 29b7a41692 Implement is-window-cast-target window rule matcher 2025-02-11 10:31:12 +03:00
Ivan Molodetskikh 216753678a wiki: Add a page for tabs 2025-02-11 08:30:03 +03:00
dependabot[bot] b9e67f6565 build(deps): bump zbus in the rust-dependencies group across 1 directory
Bumps the rust-dependencies group with 1 update in the / directory: [zbus](https://github.com/dbus2/zbus).


Updates `zbus` from 5.3.1 to 5.5.0
- [Release notes](https://github.com/dbus2/zbus/releases)
- [Commits](https://github.com/dbus2/zbus/compare/zbus-5.3.1...zbus-5.5.0)

---
updated-dependencies:
- dependency-name: zbus
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-10 21:04:23 -08:00
Mikołaj Lercher 3a481b5250 wiki: describe running games with gamescope (#1112)
* wiki: describe running games with gamescope

* Update wiki/Application-Issues.md

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-02-11 07:52:53 +03:00
Ivan Molodetskikh 20769b4c2f tab indicator: Animate opening 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 14ac2cff4c tab indicator: Dim colors when column is inactive 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh fde627d955 Implement MulAssign<f32> for Color 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 6942ecc13a Implement clicking on tab to switch 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 963ff14ed0 Store hit type in PointContents 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 96a3ded2ec scrolling: Extract tab_indicator_area() 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh a21196ec54 tab indicator: Extract tab_rects() 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 0b83d9932b tab indicator: Use full column height 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 6bd92ab926 tab indicator: Fix gradient area computation
The gradient area should be relative to each tab's geometry. In most cases
these geometries will all match, but not when some tabs have a different size,
for example when they have a fixed size.
2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 02eccf7762 layout: Fix/add animations around tabbed columns 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 89cf276779 tests: Mark window_opening/target_size as slow 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh bc701cd529 mapped: Force a frame callback on configure
Lets hidden windows respond to events like resizes immediately. This is mainly
relevant for tabbed columns.

This commit doesn't actually force sending the frame callbacks in case we don't
redraw. We'll see if this is a problem or not.
2025-02-10 07:29:33 -08:00
Ivan Molodetskikh bfd81fc290 Make send_frame() a function on Mapped
We'll add some extra logic there.
2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 0dd8e883b0 tab indicator: Add gaps-between-tabs 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh c31b58e2c9 tab indicator: Implement place-within-column setting 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh b163045757 wiki: Add hide-when-single-tab to default-column-display example 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 41e9ec1364 wiki: Document tab indicators 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 64544a5726 tab indicator: Add position setting 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh d7d5a7f8f6 tab indicator: Add hide-when-single-tab 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh a451f75917 Implement tab indicators 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 1515410012 Add default-column-display window rule 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 8f9e0d029c Add set-column-display action 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 90f24da631 Move ColumnDisplay to niri-ipc 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh df70140b36 Allow tabbed columns to go fullscreen 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh f90eb0cbe4 Implement tabbed column display mode 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 55e2ea0c3b layout: Extract tile.hit(), HitType::hit_tile() 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 1d883931b4 Account for border in contents_under()
Fixes pointer clicks going through window borders to a layer surface below,
also fixes window not getting activated in all cases from a border click.
2025-02-10 07:29:33 -08:00
Ivan Molodetskikh b65fad09d8 Remove unnecessary mut 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 09a559d3c9 layout: Fix variable names 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 9fc749f3d4 layout/tile: Rename variable 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh f836d1c28a layout/scrolling: Extract activate_idx() 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 4f05a74aa8 Add alpha parameter to shaders
Lets us add extra opacity.
2025-02-10 07:29:33 -08:00
Ivan Molodetskikh c30f522ef2 shader: Return real alpha from alpha() 2025-02-10 07:29:33 -08:00
Ivan Molodetskikh 397e704d64 layout/scrolling: Extract variable 2025-02-07 10:03:38 +03:00
Ivan Molodetskikh acc9d3e409 layout/scrolling: Extract variable 2025-02-07 10:03:38 +03:00
Ivan Molodetskikh 0c59fc304c layout/scrolling: Use early return in tiles_origin() 2025-02-07 10:03:38 +03:00
Ivan Molodetskikh abd7f1dce3 layout/scrolling: Extract two variables 2025-02-07 10:03:38 +03:00
Ivan Molodetskikh 1d87da00b7 layout/scrolling: Extract two variables 2025-02-07 10:02:25 +03:00
Ivan Molodetskikh 91515ac6dc layout/scrolling: Extract resolve_* as methods on Column 2025-02-07 10:02:25 +03:00
Ivan Molodetskikh 7ec771f7ec layout: Rename toplevel_bounds() to new_window_toplevel_bounds() 2025-02-07 09:26:43 +03:00
Ivan Molodetskikh a42a5ac696 layout: Remove redundant () 2025-02-07 08:03:39 +03:00
Ivan Molodetskikh b31c0359eb layout: Extract col variable 2025-02-06 10:30:03 +03:00
Ivan Molodetskikh 934e5a6033 layout: Preserve focused window in column when window above is closed
Might be the longest standing bug in niri?
2025-02-06 09:41:15 +03:00
peelz 690d635505 Initialize tracing_subscriber earlier 2025-02-05 18:06:46 +03:00
Ivan Molodetskikh a444efd0eb Add focus-window-in-column (by index) action 2025-02-05 17:25:57 +03:00
Ivan Molodetskikh c41f93a468 Add focus-window-top/bottom/down-or-top/up-or-bottom actions 2025-02-05 17:25:51 +03:00
Mathias Zhang 900da597e4 input: add touchpad drag-lock setting 2025-02-05 13:35:13 +03:00
Ivan Molodetskikh d320833f40 Update Smithay (text-input double input fix) 2025-02-05 12:54:25 +03:00
dependabot[bot] c384b2489f build(deps): bump clap in the rust-dependencies group
Bumps the rust-dependencies group with 1 update: [clap](https://github.com/clap-rs/clap).


Updates `clap` from 4.5.27 to 4.5.28
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.27...clap_complete-v4.5.28)

---
updated-dependencies:
- dependency-name: clap
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-05 12:52:57 +03:00
Ivan Molodetskikh ddcac86d1d mapped: Add needs_configure flag
Allows to de-duplicate configures from requests that require one.
2025-02-05 09:36:58 +03:00
Ivan Molodetskikh 734e3a6d3c Fix find_window_and_output() returning None with no outputs
As far as I can tell, this would mess up a ton of the logic. Not sure
how anything worked with no outputs before?
2025-02-05 09:35:10 +03:00
Ivan Molodetskikh f18b1a7043 mapped: Document RequestSizeOnce 2025-02-05 08:41:40 +03:00
Ivan Molodetskikh 7d24ad23c2 layout/scrolling: Extract tiles_origin() 2025-02-04 10:42:44 +03:00
Ivan Molodetskikh 691bc064bb wiki: Fix copy-paste typo 2025-02-04 10:42:44 +03:00
dependabot[bot] 553b1ba852 build(deps): bump the rust-dependencies group with 3 updates
Bumps the rust-dependencies group with 3 updates: [wayland-backend](https://github.com/smithay/wayland-rs), [wayland-scanner](https://github.com/smithay/wayland-rs) and [wayland-client](https://github.com/smithay/wayland-rs).


Updates `wayland-backend` from 0.3.7 to 0.3.8
- [Release notes](https://github.com/smithay/wayland-rs/releases)
- [Changelog](https://github.com/Smithay/wayland-rs/blob/master/historical_changelog.md)
- [Commits](https://github.com/smithay/wayland-rs/commits)

Updates `wayland-scanner` from 0.31.5 to 0.31.6
- [Release notes](https://github.com/smithay/wayland-rs/releases)
- [Changelog](https://github.com/Smithay/wayland-rs/blob/master/historical_changelog.md)
- [Commits](https://github.com/smithay/wayland-rs/commits)

Updates `wayland-client` from 0.31.7 to 0.31.8
- [Release notes](https://github.com/smithay/wayland-rs/releases)
- [Changelog](https://github.com/Smithay/wayland-rs/blob/master/historical_changelog.md)
- [Commits](https://github.com/smithay/wayland-rs/commits)

---
updated-dependencies:
- dependency-name: wayland-backend
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: wayland-scanner
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: wayland-client
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-03 13:42:47 +03:00
Ivan Molodetskikh d5592743cb Add impl From<Color> for Gradient 2025-02-02 09:55:40 +03:00
Jesse Hallett 019e75955d document interaction between hide-when-typing and wine wayland (#1076)
* document interaction between hide-when-typing and wine wayland

* Update wiki/Configuration:-Miscellaneous.md

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-02-02 04:53:16 +00:00
Ivan Molodetskikh 32ad545f84 layout: Extract max_tile_height 2025-02-01 13:05:07 +03:00
Ivan Molodetskikh 4eddcef1be layout: Inline variable 2025-02-01 13:05:07 +03:00
Ivan Molodetskikh 68776f1cee layout: Verify that individual tiles don't get sized taller than working area 2025-02-01 10:48:16 +03:00
Ivan Molodetskikh a0e2a15c60 Take border into account for fixed preset-column-width for tiled windows 2025-01-31 21:30:22 +03:00
Ivan Molodetskikh 88c6778771 Extract SizeChange::from(PresetSize) 2025-01-31 21:15:43 +03:00
Ivan Molodetskikh 73f6d3366e wiki: Remove foot mention
This issue has been fixed in foot.
2025-01-31 20:42:50 +03:00
Ivan Molodetskikh 48a4d5c8a3 Fix typo in comment 2025-01-31 19:24:42 +03:00
Ivan Molodetskikh 6f2f7fa259 layout: Update module comment 2025-01-31 18:05:09 +03:00
Ivan Molodetskikh 49ddf66c2f layout: Move tests to separate file
This way changing just the tests won't rebuild the main library.
2025-01-31 17:56:43 +03:00
fable a169e0335d adjust horizontal view movement gestures snap points for center-focused-column "on-overflow" (#1052)
* Adjust snap points for center-focused-column "on-overflow"

* fix outer gaps not being accounted for in is_overflowing
2025-01-30 17:17:16 +03:00
may e412a0fc6b add option to set xkb config from file (#1062)
* add option to set xkb config from file

* Apply suggestions from code review

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-01-30 13:50:05 +00:00
dependabot[bot] fb5fedbf24 build(deps): bump pipewire from 86df391 to fd3d8f7
Bumps pipewire from `86df391` to `fd3d8f7`.

---
updated-dependencies:
- dependency-name: pipewire
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-30 13:57:34 +03:00
bbb651 6b04b1e454 misc: Use helper function for restriced protocol filters
I looked at cosmic-comp as a sanity check and they do the same thing,
I ended up yoinking their function name because it reads better,
not sure about "unrestricted" vs "privileged".
2025-01-30 07:18:42 +03:00
bbb651 0c340ec5ea misc: Use CursorImageSurfaceData type alias
instead of `Mutex<CursorImageAttributes>`
2025-01-30 07:18:42 +03:00
bbb651 34679c75a4 misc: Fix typos
Using [`typos`](https://github.com/crate-ci/typos) cli
2025-01-30 07:18:42 +03:00
Ivan Molodetskikh 1d3820a064 layout: Do not update original output for named workspaces upon adding windows
The way named workspaces are generally used makes them more "attached" to their
original output.

For example, you have a two-monitor setup with named workspaces on both. When
you disconnect the monitor to go somewhere and work for a while, then return,
you probably want your named workspaces to return to where they were on your
second monitor.

This is in contrast to unnamed workspaces which are more transient and should
more easily follow you wherever you're working.
2025-01-29 13:56:26 +03:00
Ivan Molodetskikh 1c749f578c layout: Update workspace original output on moving even if same monitor
Moving is an explicit action that puts the workspace on a specific monitor. It
makes sense to update the original output even if the workspace already happens
to be on the target monitor.
2025-01-29 13:56:26 +03:00
Ivan Molodetskikh 3a887a6e49 wiki/named-workspaces: Mention un/set-workspace-name 2025-01-29 13:56:26 +03:00
dependabot[bot] beef2da628 build(deps): bump the rust-dependencies group across 1 directory with 2 updates
Bumps the rust-dependencies group with 2 updates in the / directory: [serde_json](https://github.com/serde-rs/json) and [insta](https://github.com/mitsuhiko/insta).


Updates `serde_json` from 1.0.137 to 1.0.138
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.137...v1.0.138)

Updates `insta` from 1.42.0 to 1.42.1
- [Release notes](https://github.com/mitsuhiko/insta/releases)
- [Changelog](https://github.com/mitsuhiko/insta/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mitsuhiko/insta/compare/1.42.0...1.42.1)

---
updated-dependencies:
- dependency-name: serde_json
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: insta
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-29 11:28:39 +03:00
Ivan Molodetskikh 9b4d73f13a spec: Don't set XDG_RUNTIME_DIR
It should once again no longer be necessary.
2025-01-27 08:34:12 +03:00
Ivan Molodetskikh 0226d9aec2 Don't create on-disk sockets in tests 2025-01-27 08:30:22 +03:00
Ivan Molodetskikh 902222675a Use Niri::insert_client() in tests 2025-01-27 08:16:09 +03:00
Ivan Molodetskikh ec43493522 Extract Niri::insert_client() 2025-01-27 08:06:33 +03:00
Evgeny Zemtsov baa0518912 Extend switch-layout action to accept layout index (#1045)
* Extend switch-layout action to accept layout index

* Update src/input/mod.rs

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-01-26 19:09:01 +00:00
Ivan Molodetskikh d665079b84 CI: Don't forget to build randomized tests in release 2025-01-26 09:54:40 +03:00
Ivan Molodetskikh f0d935dee1 CI: Further reduce the number of proptest cases 2025-01-26 09:39:04 +03:00
Ivan Molodetskikh 314b82caa0 CI: Reduce number of proptest cases 2025-01-26 09:20:49 +03:00
Ivan Molodetskikh 8f79139b78 CI: Add a randomized tests job 2025-01-26 08:37:25 +03:00
Ivan Molodetskikh c5296b870a CI: Write out dependencies once at the top 2025-01-26 08:37:24 +03:00
Ivan Molodetskikh 78697d1cea Switch Smithay back to git
Release currently has an unfortunate merge that breaks IMEs.
2025-01-25 11:51:45 +03:00
Kirottu 852da5714a Add move-workspace-to-index and move-workspace-to-monitor actions (#1007)
* Added move-workspace-to-index and move-workspace-to-monitor IPC actions

* Added redraws to the workspace handling actions, fixed tests that panicked, fixed other mentioned problems.

* Fixed workspace focusing and handling numbered workspaces with `move-workspace-to-index`

* Fixed more inconsistencies with move-workspace-to-monitor

* Added back `self.workspace_switch = None`

* Reordered some workspace cleanup logic

* Fix formatting

* Add missing blank lines

* Fix moving workspace to same monitor and wrong current index updating

* Move function up and add fixme comment

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-01-25 08:49:51 +00:00
Ivan Molodetskikh 4f79303811 CI: Remove version string from msrv job
Required checks on GitHub need to be updated every time otherwise.
2025-01-25 10:54:07 +03:00
Ivan Molodetskikh f294d527e1 wiki: Add clipboard section 2025-01-25 10:52:43 +03:00
peelz 54a1cd5069 Add clipboard disable-primary setting 2025-01-25 10:36:36 +03:00
Ivan Molodetskikh 748d90b443 Update Smithay to a crates.io version
What a time to be alive
2025-01-24 08:42:11 +03:00
bbb651 128b01e049 Add scroll-factor window rule 2025-01-23 12:07:32 +03:00
Ivan Molodetskikh 788c9c6c54 Add find_root_shell_surface() that goes through popups 2025-01-23 12:07:32 +03:00
Ivan Molodetskikh a10705fb20 Add toggle-window-rule-opacity action 2025-01-23 11:13:55 +03:00
dependabot[bot] b01b8afa8c build(deps): bump clap in the rust-dependencies group
Bumps the rust-dependencies group with 1 update: [clap](https://github.com/clap-rs/clap).


Updates `clap` from 4.5.26 to 4.5.27
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.26...clap_complete-v4.5.27)

---
updated-dependencies:
- dependency-name: clap
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-21 11:56:26 +03:00
Ivan Molodetskikh acd4cb51aa Implement shadows for layer surfaces 2025-01-21 11:31:30 +03:00
Ivan Molodetskikh 5ebcae997e wiki: Add missing property to window rules example 2025-01-21 11:31:30 +03:00
Ivan Molodetskikh 2511a98e8b Extract Niri::update_shaders() 2025-01-21 11:31:30 +03:00
Ivan Molodetskikh a7692d10c4 Add update_render_elements() to MappedLayer 2025-01-21 11:31:30 +03:00
Ivan Molodetskikh c892f04c96 tile: Rename update() to update_render_elements() 2025-01-21 11:31:30 +03:00
Ivan Molodetskikh 3aad5a39ea Fix two comments 2025-01-21 11:31:30 +03:00
dependabot[bot] 7f025da5b6 build(deps): bump the rust-dependencies group with 2 updates
Bumps the rust-dependencies group with 2 updates: [sd-notify](https://github.com/lnicola/sd-notify) and [serde_json](https://github.com/serde-rs/json).


Updates `sd-notify` from 0.4.4 to 0.4.5
- [Changelog](https://github.com/lnicola/sd-notify/blob/master/CHANGELOG.md)
- [Commits](https://github.com/lnicola/sd-notify/compare/v0.4.4...v0.4.5)

Updates `serde_json` from 1.0.135 to 1.0.137
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.135...v1.0.137)

---
updated-dependencies:
- dependency-name: sd-notify
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: serde_json
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-20 13:53:29 +03:00
dependabot[bot] 01285bdbbe build(deps): bump the smithay group with 2 updates
Bumps the smithay group with 2 updates: [smithay](https://github.com/Smithay/smithay) and [smithay-drm-extras](https://github.com/Smithay/smithay).


Updates `smithay` from `fe31867` to `953959e`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/fe31867e3afac2543c4016fb8ed99df3e11eb6da...953959e6069b3e14dba96fdaa46c65990c21d5c9)

Updates `smithay-drm-extras` from `fe31867` to `953959e`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/fe31867e3afac2543c4016fb8ed99df3e11eb6da...953959e6069b3e14dba96fdaa46c65990c21d5c9)

---
updated-dependencies:
- dependency-name: smithay
  dependency-type: direct:production
  dependency-group: smithay
- dependency-name: smithay-drm-extras
  dependency-type: direct:production
  dependency-group: smithay
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-20 13:51:41 +03:00
Ivan Molodetskikh 8182484572 Remove Vec from Shadow::render() 2025-01-18 17:43:58 +03:00
sodiboo 0584dd2f1e implement keyboard-shortcuts-inhibit and wlr-virtual-pointer (#630)
* stub keyboard-shortcuts-inhibit and virtual-pointer impls

* implement keyboard-shortcuts-inhibit

* implement virtual-pointer

* deal with supressed key release edge-case; add allow-inhibiting property

* add toggle-keyboard-shortcuts-inhibit bind

* add InputBackend extensions; use Device::output() for absolute pos events

* add a `State` parameter to the backend exts and better document future intent

* Add some tests for is_inhibiting_shortcuts

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-01-18 17:26:42 +03:00
Ivan Molodetskikh bd559a2660 Implement window shadows 2025-01-17 23:10:01 +03:00
dependabot[bot] b4add625b2 build(deps): bump sd-notify in the rust-dependencies group
Bumps the rust-dependencies group with 1 update: [sd-notify](https://github.com/lnicola/sd-notify).


Updates `sd-notify` from 0.4.3 to 0.4.4
- [Changelog](https://github.com/lnicola/sd-notify/blob/master/CHANGELOG.md)
- [Commits](https://github.com/lnicola/sd-notify/compare/v0.4.3...v0.4.4)

---
updated-dependencies:
- dependency-name: sd-notify
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-17 11:34:41 +03:00
Val Packett 890bbff007 dbus: DisplayConfig: implement apply_monitors_config
This enables gnome-control-center to apply display configuration
changes. Only temporarily, persistence is ignored currently.
2025-01-17 11:16:10 +03:00
Val Packett b853d5b124 dbus: DisplayConfig: report fractional scales as supported 2025-01-17 11:16:10 +03:00
Val Packett 693e0e09f7 dbus: DisplayConfig: report disabled monitors in get_current_state
This is required for gnome-control-center to be able to turn
monitors back on.
2025-01-17 11:16:10 +03:00
Val Packett d52356b131 dbus: DisplayConfig: add properties required by display settings panel 2025-01-17 11:16:10 +03:00
dependabot[bot] b11b995d03 build(deps): bump the rust-dependencies group with 2 updates
Bumps the rust-dependencies group with 2 updates: [bitflags](https://github.com/bitflags/bitflags) and [log](https://github.com/rust-lang/log).


Updates `bitflags` from 2.7.0 to 2.8.0
- [Release notes](https://github.com/bitflags/bitflags/releases)
- [Changelog](https://github.com/bitflags/bitflags/blob/main/CHANGELOG.md)
- [Commits](https://github.com/bitflags/bitflags/compare/2.7.0...2.8.0)

Updates `log` from 0.4.22 to 0.4.25
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.22...0.4.25)

---
updated-dependencies:
- dependency-name: bitflags
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: log
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-16 12:51:04 +03:00
Ivan Molodetskikh 99ba295082 Remove obsolete comment 2025-01-15 15:18:11 +03:00
Ivan Molodetskikh 8c2b5957eb Rename FoIPosition to FloatingPosition 2025-01-15 14:29:35 +03:00
dependabot[bot] 4472164447 build(deps): bump the smithay group with 2 updates
Bumps the smithay group with 2 updates: [smithay](https://github.com/Smithay/smithay) and [smithay-drm-extras](https://github.com/Smithay/smithay).


Updates `smithay` from `2a0d430` to `fe31867`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/2a0d4307430dc478b0b2f278bc5dc56ec02aa5ca...fe31867e3afac2543c4016fb8ed99df3e11eb6da)

Updates `smithay-drm-extras` from `2a0d430` to `fe31867`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/2a0d4307430dc478b0b2f278bc5dc56ec02aa5ca...fe31867e3afac2543c4016fb8ed99df3e11eb6da)

---
updated-dependencies:
- dependency-name: smithay
  dependency-type: direct:production
  dependency-group: smithay
- dependency-name: smithay-drm-extras
  dependency-type: direct:production
  dependency-group: smithay
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-15 12:32:32 +03:00
Ivan Molodetskikh a3cbe3514b clipped_surface: Store complete uniforms in the struct
This mistake shall never happen again.
2025-01-14 21:25:17 +03:00
Ivan Molodetskikh efa7c862a4 Add missing clipped surface uniform 2025-01-14 21:19:05 +03:00
Gustav Sörnäs 0df7a085de add write-to-disk argument to screenshot actions 2025-01-14 13:39:52 +03:00
dependabot[bot] 6ae51f287c build(deps): bump the smithay group with 2 updates
Bumps the smithay group with 2 updates: [smithay](https://github.com/Smithay/smithay) and [smithay-drm-extras](https://github.com/Smithay/smithay).


Updates `smithay` from `e1a863b` to `2a0d430`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/e1a863b3ffc2d560007e3b89e5bbe9500c69221e...2a0d4307430dc478b0b2f278bc5dc56ec02aa5ca)

Updates `smithay-drm-extras` from `e1a863b` to `2a0d430`
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/e1a863b3ffc2d560007e3b89e5bbe9500c69221e...2a0d4307430dc478b0b2f278bc5dc56ec02aa5ca)

---
updated-dependencies:
- dependency-name: smithay
  dependency-type: direct:production
  dependency-group: smithay
- dependency-name: smithay-drm-extras
  dependency-type: direct:production
  dependency-group: smithay
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-14 11:35:00 +03:00
Erica Z 36076d5279 make niri-session POSIX compatible (#970)
* make niri-session POSIX compatible

* Update resources/niri-session

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-01-14 09:41:50 +03:00
dependabot[bot] 427c4e3982 build(deps): bump directories from 5.0.1 to 6.0.0
Bumps [directories](https://github.com/soc/directories-rs) from 5.0.1 to 6.0.0.
- [Commits](https://github.com/soc/directories-rs/commits)

---
updated-dependencies:
- dependency-name: directories
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-13 13:36:17 +03:00
dependabot[bot] 1632ce87a5 build(deps): bump zbus in the rust-dependencies group
Bumps the rust-dependencies group with 1 update: [zbus](https://github.com/dbus2/zbus).


Updates `zbus` from 5.2.0 to 5.3.0
- [Release notes](https://github.com/dbus2/zbus/releases)
- [Commits](https://github.com/dbus2/zbus/compare/zbus-5.2.0...zbus-5.3.0)

---
updated-dependencies:
- dependency-name: zbus
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-13 13:35:10 +03:00
bbb651 c523c80598 Support WAYLAND_SOCKET in winit backend
I know of a single compositor that supports `WAYLAND_SOCKET` but not
`WAYLAND_DISPLAY`: https://gitlab.freedesktop.org/mstoeckl/windowtolayer

This should also make niri more robust against accidentally setting
`WAYLAND_SOCKET` when starting as a session, before programs could fail
if they preffered `WAYLAND_SOCKET` over `WAYLAND_DISPLAY`
2025-01-13 08:19:17 +03:00
mrheinen 0bd6df507b Highlight that the path in niri.service should be checked (#962)
* Highlight that the path in niri.service should be checked

Having just installed niri I ran into this issue.  When building from source on Ubuntu the install location using the instructions in this document is /usr/local//bin/niri.

However niri.service pointed to /usr/bin/niri so my session would not start at all. Hopefully this update helps

* Update wiki/Getting-Started.md

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-01-13 06:59:21 +03:00
sodiboo 6e41220dbf use standard padding syntax instead of implementing our own
the padding of the two-digit-month can be implemented much more
concisely using `std::fmt` syntax.
2025-01-12 21:38:51 +03:00
Ivan Molodetskikh e05bc269e6 README: Update screenshot 2025-01-11 19:53:25 +03:00
Ivan Molodetskikh d574341f1f wiki: Add missing period 2025-01-11 09:10:45 +03:00
Ivan Molodetskikh 481958f8f7 wiki: Document version string in Packaging 2025-01-11 09:09:25 +03:00
Ivan Molodetskikh 4094469d59 README: Replace next release with version 2025-01-11 09:00:15 +03:00
Ivan Molodetskikh 2261fcb631 wiki: Add Packaging niri page 2025-01-11 08:59:39 +03:00
Ivan Molodetskikh 279c8b6aa2 Back out "rpkg: Print license summary"
This backs out commit 89c991b636.
2025-01-10 17:10:21 +03:00
Ivan Molodetskikh e35c630c1d Format version as calver automatically 2025-01-10 16:37:46 +03:00
Ivan Molodetskikh d3047afa7f rpkg: Set NIRI_BUILD_COMMIT in cargo.toml 2025-01-10 16:19:06 +03:00
Ivan Molodetskikh a03783f54c CI: Add permission to release 2025-01-10 16:04:19 +03:00
Ivan Molodetskikh cbf0d6190d rpkg: Update licenses 2025-01-10 16:02:30 +03:00
Ivan Molodetskikh 89c991b636 rpkg: Print license summary 2025-01-10 15:59:22 +03:00
Ivan Molodetskikh bbbd35e9ef CI: Fix grep check 2025-01-10 15:42:22 +03:00
Ivan Molodetskikh c308be315d wiki: Put version in Since: next release 2025-01-10 15:39:02 +03:00
Ivan Molodetskikh d825e3125e CI: Add a prepare-release workflow 2025-01-10 15:28:50 +03:00
Ivan Molodetskikh 64288de04e rpkg: Use NIRI_BUILD_COMMIT 2025-01-10 15:25:49 +03:00
Ivan Molodetskikh fb4471e69d Add NIRI_BUILD_COMMIT env variable override 2025-01-10 15:20:27 +03:00
Ivan Molodetskikh 8be8694f5f Add NIRI_BUILD_VERSION_STRING env variable to override the version 2025-01-10 15:17:04 +03:00
Ivan Molodetskikh 60b78dc2cd Bump version to 25.01 2025-01-10 15:16:36 +03:00
Ivan Molodetskikh 80fe5a8167 CI: Rearrange some dependencies 2025-01-10 15:15:50 +03:00
dependabot[bot] df58c49876 build(deps): bump the rust-dependencies group with 2 updates
Bumps the rust-dependencies group with 2 updates: [bitflags](https://github.com/bitflags/bitflags) and [clap](https://github.com/clap-rs/clap).


Updates `bitflags` from 2.6.0 to 2.7.0
- [Release notes](https://github.com/bitflags/bitflags/releases)
- [Changelog](https://github.com/bitflags/bitflags/blob/main/CHANGELOG.md)
- [Commits](https://github.com/bitflags/bitflags/compare/2.6.0...2.7.0)

Updates `clap` from 4.5.24 to 4.5.26
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.24...clap_complete-v4.5.26)

---
updated-dependencies:
- dependency-name: bitflags
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: clap
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-10 11:40:45 +03:00
Ivan Molodetskikh 7dee2f6995 Fix two manual let-else 2025-01-10 09:11:31 +03:00
Ivan Molodetskikh 623687e59b Fix new Clippy warnings 2025-01-10 09:11:31 +03:00
rustn00b 5958d3be62 Allow workspace names to be changed dynamically (#904)
* Add un/set workspace name actions

* Add SetWorkspaceName reference to proptests

* Simplify unname_workspace

* Add ewaf version of set first workspace name test

* Simplify more

* Fix comment

* Make workspace in set-workspace-name a positional option

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-01-10 06:03:19 +00:00
Ivan Molodetskikh 142e57450d Add missing interactively moved window check in center_window 2025-01-09 11:55:01 +03:00
rustn00b 80815a1591 Add a window swap operation (#899)
Swap the active window with the a neighboring column's active window.


---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
Take into account PR comments

- no longer behave like an expel when a swap is made in a direction
  where there is no column to swap with
- fix janky animation
2025-01-09 08:29:36 +00:00
Ivan Molodetskikh 8412bfb813 Add missing cursor warp when focusing floating/tiling 2025-01-09 10:49:24 +03:00
Ivan Molodetskikh a0f279691a Update dependencies 2025-01-09 10:23:44 +03:00
Ivan Molodetskikh 92aeddb9fe Force-update insta snapshots
1.42.0 reverted a 1.41.0 change to snapshot metadata.
2025-01-09 10:22:39 +03:00
dependabot[bot] d7da88853b build(deps): bump the rust-dependencies group across 1 directory with 4 updates
Bumps the rust-dependencies group with 4 updates in the / directory: [clap](https://github.com/clap-rs/clap), [libdisplay-info](https://github.com/Smithay/libdisplay-info-rs), [serde_json](https://github.com/serde-rs/json) and [insta](https://github.com/mitsuhiko/insta).


Updates `clap` from 4.5.23 to 4.5.24
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.23...clap_complete-v4.5.24)

Updates `libdisplay-info` from 0.1.0 to 0.2.2
- [Release notes](https://github.com/Smithay/libdisplay-info-rs/releases)
- [Commits](https://github.com/Smithay/libdisplay-info-rs/compare/v0.1.0...v0.2.2)

Updates `serde_json` from 1.0.134 to 1.0.135
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.134...v1.0.135)

Updates `insta` from 1.41.1 to 1.42.0
- [Release notes](https://github.com/mitsuhiko/insta/releases)
- [Changelog](https://github.com/mitsuhiko/insta/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mitsuhiko/insta/compare/1.41.1...1.42.0)

---
updated-dependencies:
- dependency-name: clap
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: libdisplay-info
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: serde_json
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: insta
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-08 08:55:36 +00:00
Frans Skarman 89678c7b1e Set is-active-in-column to true for unmapped windows (#934)
* Set is-active-in-column to true for unmapped windows

* Update wiki/Configuration:-Window-Rules.md

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2025-01-05 13:38:26 +03:00
Ivan Molodetskikh 098c826095 Search for connector duplicates across all devices 2025-01-04 23:32:09 +03:00
Ivan Molodetskikh befbdc3ae5 default-config: Fix typo 2025-01-04 20:56:45 +03:00
Ivan Molodetskikh dca0364f4c Unname connector if a duplicate is detected 2025-01-04 18:03:08 +03:00
Ivan Molodetskikh 37771259d9 Fetch monitor name from EDID only once
Reduce spam when it's unavailable. Assume the name cannot change at runtime;
before if it changed, bad things would probably happen anyway.
2025-01-04 17:56:13 +03:00
Ivan Molodetskikh 4618e4851c Default to unrestricted primary plane scanout 2025-01-04 13:02:22 +03:00
Ivan Molodetskikh b2ca280c49 Restart PipeWire on errors
This lets you restart pipewire and then get a screencast successfully.
2025-01-04 12:23:25 +03:00
Ivan Molodetskikh bf6995f759 CI: Fix MSRV 2025-01-04 11:49:27 +03:00
Ivan Molodetskikh ab0cce7cb7 Add Xrgb/Xbgr to color formats
At least until the scanout check is fixed in Smithay again.
2025-01-04 11:22:56 +03:00
Ivan Molodetskikh 2e422fc026 Update dependencies 2025-01-04 11:22:56 +03:00
Ivan Molodetskikh a2f9d132a0 Migrate to new Rectangle functions 2025-01-04 11:22:56 +03:00
Ivan Molodetskikh 1973b97cc2 Upgrade Smithay (DrmCompositor changes) 2025-01-04 11:22:56 +03:00
Ivan Molodetskikh b3c6f0e661 Add floating binds to the hotkey overlay 2025-01-03 17:26:36 +03:00
Ivan Molodetskikh 6998b17f9e wiki: Update default hotkeys 2025-01-03 17:23:29 +03:00
Ivan Molodetskikh ed9932d70d wiki: Update the layer-shell components page 2025-01-03 17:02:18 +03:00
Ivan Molodetskikh a5f3b2a949 Clear on-demand layer-shell focus in more cases 2025-01-03 17:00:13 +03:00
Ivan Molodetskikh 152ed59502 Allow keyboard focus for bottom and background layers 2025-01-03 16:41:39 +03:00
Ivan Molodetskikh 8e16be9e11 Allow pop-up grabs for bottom and background layers 2025-01-03 16:24:23 +03:00
Ivan Molodetskikh 300701f44e Render layer-shell pop-ups on top 2025-01-03 15:57:59 +03:00
Ivan Molodetskikh d1370622d8 wiki: Expand application issues a bit 2025-01-03 12:30:17 +03:00
Ivan Molodetskikh 0134166009 README: Expand Status a bit 2025-01-03 11:11:11 +03:00
Ivan Molodetskikh ddb9084260 wiki/Xwayland: Add a labwc section 2025-01-03 10:50:02 +03:00
Ivan Molodetskikh 0224452cef wiki/Xwayland: Clarify xwayland-satellite 2025-01-03 10:50:02 +03:00
Julian Schuler c17d4dc050 Add actions to focus/move to next/previous monitor 2025-01-02 15:15:23 +03:00
bbb651 4e33f45522 Add Mouse{Left,Right,Middle,Back,Forward} binds 2025-01-02 14:59:15 +03:00
Christian Meissl b16d7abb35 skip keyboard focus for layer shell surfaces not...
...requesting keyboard interactivity
2025-01-02 14:24:39 +03:00
Christian Meissl 2f17a30157 xdg: do not focus unmapped popup on grab
a grab is requested for an unmapped popup,
delay focusing the popup until the first keyboard
interaction
2025-01-02 14:24:39 +03:00
Ivan Molodetskikh 0dbd14ebdc Update dependencies 2025-01-02 11:50:51 +03:00
Ivan Molodetskikh 8b3d8ccb47 Update dependabot.yml 2025-01-02 11:34:04 +03:00
Ivan Molodetskikh f8ff2e4e28 Update dependabot.yml 2025-01-02 11:32:34 +03:00
Ivan Molodetskikh 044f0d41a5 Update dependabot.yml 2025-01-02 11:31:37 +03:00
Ivan Molodetskikh 4089bebd83 Create dependabot.yml 2025-01-02 11:30:01 +03:00
Ivan Molodetskikh d4787c75fd Delete dependabot.yml 2025-01-02 11:26:49 +03:00
Ivan Molodetskikh 3bf0a57b82 Create dependabot.yml 2025-01-02 11:20:47 +03:00
Ivan Molodetskikh cc505ae49f Delete dependabot.yml
Let's see if re-creating fixes it.
2025-01-02 11:19:20 +03:00
dependabot[bot] 2f6de136dd build(deps): bump the rust-dependencies group with 19 updates
Bumps the rust-dependencies group with 19 updates:

| Package | From | To |
| --- | --- | --- |
| [anyhow](https://github.com/dtolnay/anyhow) | `1.0.93` | `1.0.95` |
| [bytemuck](https://github.com/Lokathor/bytemuck) | `1.19.0` | `1.21.0` |
| [calloop](https://github.com/Smithay/calloop) | `0.14.1` | `0.14.2` |
| [clap](https://github.com/clap-rs/clap) | `4.5.20` | `4.5.23` |
| [fastrand](https://github.com/smol-rs/fastrand) | `2.2.0` | `2.3.0` |
| [libc](https://github.com/rust-lang/libc) | `0.2.162` | `0.2.169` |
| [ordered-float](https://github.com/reem/rust-ordered-float) | `4.5.0` | `4.6.0` |
| [pango](https://github.com/gtk-rs/gtk-rs-core) | `0.20.4` | `0.20.7` |
| [pangocairo](https://github.com/gtk-rs/gtk-rs-core) | `0.20.4` | `0.20.7` |
| [png](https://github.com/image-rs/image-png) | `0.17.14` | `0.17.16` |
| [portable-atomic](https://github.com/taiki-e/portable-atomic) | `1.9.0` | `1.10.0` |
| [serde](https://github.com/serde-rs/serde) | `1.0.214` | `1.0.217` |
| [serde_json](https://github.com/serde-rs/json) | `1.0.132` | `1.0.134` |
| [tracing](https://github.com/tokio-rs/tracing) | `0.1.40` | `0.1.41` |
| [tracy-client](https://github.com/nagisa/rust_tracy_client) | `0.17.4` | `0.17.6` |
| [url](https://github.com/servo/rust-url) | `2.5.3` | `2.5.4` |
| [proptest](https://github.com/proptest-rs/proptest) | `1.5.0` | `1.6.0` |
| [proptest-derive](https://github.com/proptest-rs/proptest) | `0.5.0` | `0.5.1` |
| [xshell](https://github.com/matklad/xshell) | `0.2.6` | `0.2.7` |


Updates `anyhow` from 1.0.93 to 1.0.95
- [Release notes](https://github.com/dtolnay/anyhow/releases)
- [Commits](https://github.com/dtolnay/anyhow/compare/1.0.93...1.0.95)

Updates `bytemuck` from 1.19.0 to 1.21.0
- [Changelog](https://github.com/Lokathor/bytemuck/blob/main/changelog.md)
- [Commits](https://github.com/Lokathor/bytemuck/compare/v1.19.0...v1.21.0)

Updates `calloop` from 0.14.1 to 0.14.2
- [Release notes](https://github.com/Smithay/calloop/releases)
- [Changelog](https://github.com/Smithay/calloop/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Smithay/calloop/compare/v0.14.1...v0.14.2)

Updates `clap` from 4.5.20 to 4.5.23
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.20...clap_complete-v4.5.23)

Updates `fastrand` from 2.2.0 to 2.3.0
- [Release notes](https://github.com/smol-rs/fastrand/releases)
- [Changelog](https://github.com/smol-rs/fastrand/blob/master/CHANGELOG.md)
- [Commits](https://github.com/smol-rs/fastrand/compare/v2.2.0...v2.3.0)

Updates `libc` from 0.2.162 to 0.2.169
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Changelog](https://github.com/rust-lang/libc/blob/0.2.169/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.162...0.2.169)

Updates `ordered-float` from 4.5.0 to 4.6.0
- [Release notes](https://github.com/reem/rust-ordered-float/releases)
- [Commits](https://github.com/reem/rust-ordered-float/compare/v4.5.0...v4.6.0)

Updates `pango` from 0.20.4 to 0.20.7
- [Release notes](https://github.com/gtk-rs/gtk-rs-core/releases)
- [Changelog](https://github.com/gtk-rs/gtk-rs-core/blob/main/CHANGELOG.md)
- [Commits](https://github.com/gtk-rs/gtk-rs-core/compare/0.20.4...0.20.7)

Updates `pangocairo` from 0.20.4 to 0.20.7
- [Release notes](https://github.com/gtk-rs/gtk-rs-core/releases)
- [Changelog](https://github.com/gtk-rs/gtk-rs-core/blob/main/CHANGELOG.md)
- [Commits](https://github.com/gtk-rs/gtk-rs-core/compare/0.20.4...0.20.7)

Updates `png` from 0.17.14 to 0.17.16
- [Changelog](https://github.com/image-rs/image-png/blob/master/CHANGES.md)
- [Commits](https://github.com/image-rs/image-png/compare/v0.17.14...v0.17.16)

Updates `portable-atomic` from 1.9.0 to 1.10.0
- [Release notes](https://github.com/taiki-e/portable-atomic/releases)
- [Changelog](https://github.com/taiki-e/portable-atomic/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/portable-atomic/compare/v1.9.0...v1.10.0)

Updates `serde` from 1.0.214 to 1.0.217
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.214...v1.0.217)

Updates `serde_json` from 1.0.132 to 1.0.134
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.132...v1.0.134)

Updates `tracing` from 0.1.40 to 0.1.41
- [Release notes](https://github.com/tokio-rs/tracing/releases)
- [Commits](https://github.com/tokio-rs/tracing/compare/tracing-0.1.40...tracing-0.1.41)

Updates `tracy-client` from 0.17.4 to 0.17.6
- [Commits](https://github.com/nagisa/rust_tracy_client/compare/tracy-client-v0.17.4...tracy-client-v0.17.6)

Updates `url` from 2.5.3 to 2.5.4
- [Release notes](https://github.com/servo/rust-url/releases)
- [Commits](https://github.com/servo/rust-url/compare/v2.5.3...v2.5.4)

Updates `proptest` from 1.5.0 to 1.6.0
- [Release notes](https://github.com/proptest-rs/proptest/releases)
- [Changelog](https://github.com/proptest-rs/proptest/blob/main/CHANGELOG.md)
- [Commits](https://github.com/proptest-rs/proptest/commits)

Updates `proptest-derive` from 0.5.0 to 0.5.1
- [Release notes](https://github.com/proptest-rs/proptest/releases)
- [Changelog](https://github.com/proptest-rs/proptest/blob/0.5.1/CHANGELOG.md)
- [Commits](https://github.com/proptest-rs/proptest/compare/proptest-derive-0.5.0...0.5.1)

Updates `xshell` from 0.2.6 to 0.2.7
- [Changelog](https://github.com/matklad/xshell/blob/master/CHANGELOG.md)
- [Commits](https://github.com/matklad/xshell/compare/v0.2.6...v0.2.7)

---
updated-dependencies:
- dependency-name: anyhow
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: bytemuck
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: calloop
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: clap
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: fastrand
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: ordered-float
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: pango
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: pangocairo
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: png
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: portable-atomic
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: serde_json
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: tracing
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: tracy-client
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: url
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: proptest
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: rust-dependencies
- dependency-name: proptest-derive
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
- dependency-name: xshell
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: rust-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-02 11:15:11 +03:00
dependabot[bot] da21b50137 build(deps): bump smithay-drm-extras from c3f3ac8 to 5186cf7
Bumps [smithay-drm-extras](https://github.com/Smithay/smithay) from `c3f3ac8` to `5186cf7`.
- [Release notes](https://github.com/Smithay/smithay/releases)
- [Commits](https://github.com/Smithay/smithay/compare/c3f3ac8dc0776d47bc50f9a1911b613a56e6e04b...5186cf7dec2472a91e3c248772954b1141dab7f2)

---
updated-dependencies:
- dependency-name: smithay-drm-extras
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-02 10:59:24 +03:00
Ivan Molodetskikh a38a5c529f Create dependabot.yml
Copied from Helix.
2025-01-02 10:44:27 +03:00
Ivan Molodetskikh 44b5612697 Remove notify-rust dependency
It uses outdated zbus.
2025-01-02 09:33:54 +03:00
bbb651 0113292cf6 Upgrade zbus and async-io 2025-01-02 08:50:48 +03:00
Ivan Molodetskikh 4741ab2e04 spec: Set XDG_RUNTIME_DIR for tests 2024-12-30 22:15:44 +03:00
Ivan Molodetskikh 08fb9435fd Fix width shrinking when going from floating to scrolling 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 793e92e9d6 Add default-floating-position relative-to property 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh a7c57f4faf Add toggle-window-width by-id action 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 8409107a5b Implement default-window-height for scrolling windows 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 9089c3fb02 Fix move-window-to-workspace panic when wrong monitor is active 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 6c897d5201 Add center-window by-id action 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 6cb5135f34 Clamp single tiled window height
Now that we have floating for taller-than-screen windows.
2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 44bf45794e Dump post-unfullscreen configure in snapshot tests 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh d6da9f47d8 tests: Respond to post-initial configures 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh be05b66ac3 Hide focus ring for unfocused layout and under interactive move 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh d1998ae3fa Disable double-resize-click for floating windows 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 3c2e1554c6 Add default-floating-position window rule 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 744955ba69 floating: Remove initial offset when always-centering 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 7af33f9e6a wiki: Add some floating window documentation 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 3c0705b0ae Implement buffer delta for toplevels 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 4ea4d2bd3b layout: Add animate arg to move_floating_window() 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 6c52077d92 Add move-floating-window action 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 73bf7b1730 Allow hyphen values for set-window-width/height arg
Make args like set-window-height -10 parse as is, without having to insert a --.
2024-12-30 20:12:37 +03:00
Ivan Molodetskikh b394cb6379 floating: Cancel resize when moving or changing size 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 60854e180e Add is_floating to Window IPC 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 5b4750a009 Add focus-floating/tiling actions 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh ad50dd21fe Add move-window-to-floating/tiling actions 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 8b0cb0bb57 Add set-window-width action 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh a24a6e4e3c Implement is-floating window rule matcher 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 6fba4c371e Implement default-window-height window rule
Only works for floats that aren't initially fullscreen atm.
2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 27911431db tests: Rename DefaultWidth to DefaultSize 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh db6447ed79 floating: Support default-column-width in most cases
open-fullscreen + open-floating default width is still not supported in this
commit.
2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 99c0fabee6 layout: Use new helper function 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh fc99724aba Add open-focused window rule 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 88fbc62b1d wiki: Update Firefox window rules to match non-Flatpak 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh e8027d571f layout: Implement next-to + open-fullscreen 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh daaee43be3 layout: Refactor window opening targets 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 0d71cb93af Add window opening size client-server tests 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh e5e50e82d5 wiki: Clarify that preset width doesn't take borders into account only in tiling 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 7e852124a5 floating: Fix window position constraining with non-zero working area loc 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh f66a49bc42 floating: Constrain popups to working area 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh baf78ccda2 floating: Remove TODO on tile removing width 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 31f0e66f45 floating: Comment on toggle-full-width status 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 28b78a563b layout: Pass and store view_size on a Tile 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 2f380de73b floating: Take into account non-fixed min/max size window rule 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh e3a9a39c9a floating: Implement the rest of set-window-width/height 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 1710bb78df floating: Implement toggle-width/height actions 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 3e13fc3e70 floating: Change from getters to pub(super)
These fields are just data storage. They won't have any logic in
getters/setters.
2024-12-30 20:12:37 +03:00
Ivan Molodetskikh befc399506 default-config: Make Firefox PiP floating 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 88116b9fb1 Preserve tile when moving across monitors 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 53e1c58cc5 Remember floating window position 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 4b9ecdd11d Render fullscreen scrolling windows on top of floating 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh e31e409ee8 tests: Fix spelling mistake in wfs Display 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 5488aaf69f floating: Don't use fullscreen size as floating size 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 96e493d8b1 Restore floating size during interactive move 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh e409453fbd floating: Update stored size only on removal 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 309bf1348c floating: Improve expected size requests to avoid (0, 0) and duplicates 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 76a5635298 layout: Preserve the Tile when moving across workspaces 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh f4f2a1f6de floating: Remember and restore window size 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh a440805ea1 Add floating sizing tests 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh c359672bd2 floating: Request size only once
Let floating windows resize themselves and keep that size.
2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 38350935e6 layout: Rename update_interactive_resize() to on_commit() 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 421cd89a0f layout: Accept &mut self in request_fullscreen() 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 5ce3369aa6 layout: Support fullscreen for auto-floating windows 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh f38acfe988 layout: Remember whether to unfullscreen back into floating 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 965619d096 layout: Move toggle_fullscreen() impl to Workspace 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 9f017e834c wiki: Document new floating window rule and gesture 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 3c67b08488 floating: Implement directional move 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 4add755a4d layout/floating: Extract move_and_animate() 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 56e249aee6 floating: Implement center_window() 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 6a7c8fcfd5 floating: Implement directional focus 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 14b1003c62 layout: Implement focus_right_or_first() generically 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 43a4bae010 Extract center_preferring_top_left_in_area() 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 9c205f77a2 layout/floating: Move a function higher up
Let's group action functions together. Activate is an action and set
width/height too.
2024-12-30 20:12:37 +03:00
Ivan Molodetskikh c2e4cfd832 Stub out actions when floating is active
Make sure they don't go to the unfocused scrolling layout at least.
2024-12-30 20:12:37 +03:00
Ivan Molodetskikh c008e1c5bc floating: Implement smarter clamping for window location
A small part of the window always remains on-screen regardless of the working
area changes.

Interactive move lets the user position the window anywhere; automatic actions
like toggle-window-floating and dialog opening try to put the window fully
on-screen.

The size-fraction canonical floating window position remains unclamped, and
clamping happens when recomputing the logical position.
2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 1aa60f0da3 Make right click during move toggle floating 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh bd1fd8383c Stop move grab when the start button is released
Rather than when all buttons are released.
2024-12-30 20:12:37 +03:00
Ivan Molodetskikh aac54d0ea1 Implement floating child stacking above parents 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 4fe718581b layout: Extract TestWindowParams 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 71842f07bd Make interactive move keep in the same layout (floating/tiling) 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh f2bec1f82f Always honor min height in new window size 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 10460191b9 Honor min/max size in more places like initial configure 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh c5fffd6e2c Initial WIP floating window implementation 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 951f63b6fd temp: Use patched Smithay (fix VRR cursor-plane-only) 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh e6d8932b3b Update for Smithay VRR changes 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 70f96cca0a Update Smithay (presentation-time v2) 2024-12-30 20:12:37 +03:00
Ivan Molodetskikh 4e357e9659 config: Fix border rule on -> off merging 2024-12-27 15:42:56 +03:00
Ivan Molodetskikh 1f8aed6732 config: Add a test for border rule on/off merging 2024-12-27 15:42:55 +03:00
Maximilian Huber fa2bace3cd Fix nix flake for client-server tests (#896)
This was suggested by @sodiboo in
https://github.com/YaLTeR/niri/issues/894#issuecomment-2562153840 and
was copied from https://github.com/sodiboo/niri-flake/commit/350e6b68c70f5002a75e10521f5e66ace4b5eed1i

Signed-off-by: Maximilian Huber <gh@maxhbr.de>
2024-12-26 14:44:07 +00:00
Nathan 955039b5ea Update Configuration:-Key-Bindings.md (#893)
* Update Configuration:-Key-Bindings.md

Added Leve5 notes with scant instruction on how to use.

* Update wiki/Configuration:-Key-Bindings.md

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-12-23 21:08:56 +03:00
Ivan Molodetskikh 771ea1e815 Implement client-server test infra and window opening tests
These tests make a real Niri instance and real Wayland clients (via manual
wayland-rs implementation), both on the same event loop local to the test. This
allows testing the full Wayland interaction, including arbitrary event ordering
and delays.

To start off, add a massive powerset test for the settings that influence where
a window may open.
2024-12-22 15:19:46 +03:00
Ivan Molodetskikh d38bfc4aff Add test-only single-pixel-buffer support 2024-12-22 15:19:46 +03:00
Ivan Molodetskikh fbb0054232 Add a Headless backend for tests
Rendering and stuff is unimplemented.
2024-12-22 15:19:46 +03:00
Ivan Molodetskikh 2d3c36edae Switch from k9 to insta for snapshot testing
We'll need some advanced features from insta.
2024-12-22 15:19:46 +03:00
Ivan Molodetskikh 8dcc41a54d Initialize PipeWire lazily
This helps with:
- System setups starting PipeWire late (after niri startup, but before any
  screencast).
- Tests which don't even want to start PipeWire.
2024-12-22 15:19:46 +03:00
bbb651 ba3d2e36c8 Bump MSRV to 1.80
It should be old enough for most distros, and allows upgrading to `zbus 5.x`
2024-12-22 15:19:46 +03:00
bbb651 b51047ffcc Avoid implicit feature names 2024-12-22 15:19:46 +03:00
Rémi Labeyrie b1c40a9079 fix: check for layer surface under cursor when clicking 2024-12-22 15:13:17 +03:00
Ivan Molodetskikh b014c267ae README: Replace Matrix badge with static
The dynamic one broke recently.
2024-12-20 23:07:19 +03:00
Ivan Molodetskikh 6b16cc52db Add force-pipewire-invalid-modifier debug flag 2024-12-17 17:08:14 +03:00
Ivan Molodetskikh d35ad73e35 wiki: Change Since 0.1.11 to Since next release 2024-12-15 16:44:35 +03:00
Ivan Molodetskikh 2a1af3d9ae Add missing blank line 2024-12-15 10:40:09 +03:00
Ivan Molodetskikh 82e30246c1 Use gtk Notification portal
xdg-gnome 47 now implements notifications via GNOME Shell API which we don't
have. So force the gtk portal to make notifications work again.
2024-12-11 21:39:58 +03:00
Salman Farooq bb3a05bb3f Activate monitors on session unlock (#858)
So that e.g. unlocking by touching the fingerprint reader powers on the monitors.

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
Co-authored-by: Salman Farooq <46742354+SalmanFarooqShiekh@users.noreply.github.com>
2024-12-11 03:53:41 -08:00
Ivan Molodetskikh 40fa82275c Extract rules.apply_{min,max}_size() 2024-12-09 13:25:52 +03:00
Ivan Molodetskikh 9824321fc9 layout: Return instead of breaking
There's no code past this, and we want to break out of all loops.
2024-12-08 09:25:39 +03:00
Ivan Molodetskikh 27e607ab82 layout: Return bool from activate_window()
Avoid an extra has_window() call.
2024-12-08 09:25:27 +03:00
Ivan Molodetskikh a2b27b8790 layout: Ignore more actions during interactive move
The interactively moved window is the active window, so this makes sense.
2024-12-07 19:38:48 +03:00
Ivan Molodetskikh 396089ef0e layout: Extract Tile::verify_invariants() 2024-12-07 19:38:48 +03:00
Ivan Molodetskikh df98b5021d layout: Mark accessors as cfg(test) 2024-12-07 19:38:48 +03:00
sodiboo 34ce6d0b02 nix: update flake.lock 2024-12-03 05:53:48 -08:00
sodiboo 7af937b08e nix: clang -> rustPlatform.bindgenHook 2024-12-03 05:53:48 -08:00
Ivan Molodetskikh 8665003269 layout: Extract ScrollingSpace
Leave the Workspace to do the workspace parts, and extract the scrolling parts
into a new file. This is a pre-requisite for things like the floating layer
(which will live in a workspace alongside the scrolling layer).

As part of this huge refactor, I found and fixed at least these issues:
- Wrong horizontal popup unconstraining for a smaller window in an
  always-centered column.
- Wrong workspace switch in focus_up_or_right().
2024-12-01 22:24:21 -08:00
Ivan Molodetskikh 1e76716819 layout: Add a test for windows on other workspace remaining activated 2024-12-01 22:24:21 -08:00
Ivan Molodetskikh 91a42fdf58 layout: Fix windows on other workspaces losing activated state
This erroneous check was introduced in interactive move.
2024-12-01 22:24:21 -08:00
Ivan Molodetskikh 5ed5243be6 layout: Fix possible crash when dropping move on different, animating output 2024-12-01 22:24:21 -08:00
Ivan Molodetskikh 4560251e64 layout: Correct variable names 2024-12-01 22:24:21 -08:00
Ivan Molodetskikh 2020dca3e0 layout: Use tiles_mut() in Workspace::clear_unmap_snapshot() 2024-12-01 22:24:21 -08:00
Ivan Molodetskikh 7fc2121454 layout: Extract Workspace::tiles() 2024-12-01 22:24:21 -08:00
Ivan Molodetskikh 8b84afbd38 Add strict-new-window-focus-policy debug flag 2024-11-29 21:57:36 -08:00
Christian Meissl 305fc3b557 Activate newly mapped windows with a valid activation token
most of the time the activation token is passed
while the window is still unmapped. in this case
store the intend to activate the window for
later retrieval on map.
2024-11-29 21:57:36 -08:00
Christian Meissl 61f2ac01d7 xdg: startup activation
pass an activation token to process spawned through actions
2024-11-29 21:57:36 -08:00
Ivan Molodetskikh 39a9f55205 Fix new warnings 2024-11-29 09:33:08 +03:00
FluxTape 11f351dbeb Implement empty-workspace-above-first (#745)
* Implement empty-workspace-above-first option

* add two failing tests

* fix interactive_move_onto_empty_output_ewaf and
interactive_move_onto_first_empty_workspace tests

* Add two failing ewaf option toggle tests

* Fix adding/removing first empty workspace on option toggle

* Don't remove first empty workspace if focused

* Stop workspace switch when enabling ewaf

* layout/monitor: Offset workspace switch on adding workspace above

* Fix some initial active workspace ids with ewaf

* wiki: Document empty-workspace-above-first

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-11-29 08:46:13 +03:00
Ivan Molodetskikh 815fa379ea layout: Stop workspace switch when moving workspaces to primary
Okay, this might be one of the oldest layout issues to have remained uncaught.
Well, maybe as I add more randomized tests, I'll catch even more of those.
2024-11-27 20:55:20 +03:00
Ivan Molodetskikh 4c480a1ea3 layout/tests: Add post option update to randomized test
Will help to catch cases where updating options doesn't update the state
correctly.
2024-11-26 22:02:46 +03:00
Ivan Molodetskikh fa4aa0e06d layout: Fix adjusting for scale for moved tile when reloading config 2024-11-26 22:01:26 +03:00
Ivan Molodetskikh e2a6374bf5 layout/tests: Return Layout from check_ops()
Cuts down on boilerplate in a few places.
2024-11-26 22:00:44 +03:00
Ivan Molodetskikh dc14554053 layout: Extract update_options() 2024-11-26 21:59:05 +03:00
Ivan Molodetskikh 985ca7b643 layout/tests: Allow AddWindowRightOf interactive moved window
Guess I forgot this.
2024-11-26 15:24:28 +03:00
Ivan Molodetskikh 60624d64fa layout/tests: Standardize on usize for output id in tests 2024-11-26 15:24:28 +03:00
Ivan Molodetskikh 2935dae89e wiki: Add animation timing page 2024-11-25 04:07:59 -08:00
Ivan Molodetskikh 4c22c3285d Refactor animation timing to use lazy clocks 2024-11-25 04:07:59 -08:00
Ivan Molodetskikh 93cee2994a Refactor animations to take explicit current time 2024-11-25 04:07:59 -08:00
Ivan Molodetskikh 9c7e8d04d2 Extract Niri::advance_animations() 2024-11-23 15:09:16 +03:00
Ivan Molodetskikh 1e6b8906e0 layout/monitor: Extract add_workspace_bottom() 2024-11-23 15:07:52 +03:00
Ivan Molodetskikh 6c5b92e5c0 Add interactive_move_onto_empty_output test
Tests the add_workspace_bottom() in Monitor::add_tile().
2024-11-23 15:07:35 +03:00
Ivan Molodetskikh 38c515e12e pw: Fix potential crash when disconnecting output 2024-11-23 15:07:09 +03:00
Ivan Molodetskikh c239937fac Focus target window/output on DnD
In sway, focus-follows-mouse keeps working during DnD, but not in niri.
So it can be surprising when you DnD something into another app, but it
doesn't get automatically focused. This commit fixes that.

Even if the DnD is not validated, or if there's no target surface (e.g.
dropped on the niri background), focus the target output, since that's
how Firefox's drag-tab-into-new-window works for example.
2024-11-22 09:37:26 +03:00
Ivan Molodetskikh bafa574784 wiki: Link layer rules from block-out-from window rules 2024-11-21 14:57:41 +03:00
Ivan Molodetskikh 199a5854a8 wiki: Add Since to layer rules 2024-11-21 14:57:41 +03:00
Ridan Vandenbergh a74a578198 Add focus-window-previous action (#811)
* Add `FocusWindowPrevious` action

* remove [`

* track previous focus in Niri instead of every window

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-11-21 14:48:51 +03:00
Ivan Molodetskikh 7de752ec56 Bump CI image versions 2024-11-20 13:16:02 +03:00
Ivan Molodetskikh 0a833171ac Update Smithay (popup grab fix) 2024-11-20 08:34:19 +03:00
Ivan Molodetskikh 1a0612cbfd Implement layer rules: opacity and block-out-from 2024-11-14 12:05:30 +03:00
Ivan Molodetskikh fbbd3ba349 niri: Extract render_layer() 2024-11-14 10:24:04 +03:00
Ivan Molodetskikh 1028639186 config: Add RegexEq util type instead of manual PartialEq 2024-11-14 09:44:07 +03:00
Ivan Molodetskikh 0e5e764c78 Add niri msg layers 2024-11-12 21:44:00 +03:00
Ivan Molodetskikh db1faecc95 Guard against closed screenshot UI in its binds
They can trigger with closed screenshot UI via key repeat.
2024-11-12 19:26:44 +03:00
Ivan Molodetskikh c2c415d2e8 wiki/sidebar: Update application issues title 2024-11-12 10:11:41 +03:00
Ivan Molodetskikh d193928f31 Add PID to Window IPC 2024-11-12 09:37:25 +03:00
Ivan Molodetskikh 17861e0003 Change expel-window-from-column to expel the bottom window
This way, expel becomes symmetric with consume. This is also how it
works in PaperWM. Though, in PaperWM if the expelled window was focused,
it will remain focused, while in this commit it is never focused, making
it the exact opposite of consume.

Use consume-or-expel-window-right for the old expel behavior.
2024-11-11 18:07:41 +03:00
Ivan Molodetskikh 97fe964e00 Make consume-or-expel binds more prominent
I find myself using them much more than regular consume or expel.
2024-11-11 17:56:35 +03:00
Ivan Molodetskikh 9debb5db23 wiki: Mention Ghidra in application issues 2024-11-11 10:06:23 +03:00
Ramses 494b438151 Unhide the pointer on scroll events (#797)
* Unhide the pointer on scroll events

Since we reset the surface under the pointer when we hide the pointer
(see update_pointer_contents), scroll events don't work when the pointer
is hidden.
So to make scrolling work, we make sure that we unhide the pointer when
a scrolling event occurs.

* Update src/input/mod.rs

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-11-11 06:08:29 +00:00
Ivan Molodetskikh 010a236882 Start interactive move on Mod+Touch 2024-11-10 09:47:03 +03:00
Ivan Molodetskikh 1951d2a9f2 Fix scrolling not working with missing mouse config 2024-11-10 09:14:22 +03:00
Ivan Molodetskikh 9d8f640503 niri-ipc: Document features 2024-11-09 17:57:52 +03:00
Ivan Molodetskikh b18cfbae23 niri-ipc: Add README and Cargo.toml metadata 2024-11-09 17:57:34 +03:00
Ivan Molodetskikh f64e7e14c3 Bump version to 0.1.10 2024-11-09 17:35:31 +03:00
Ivan Molodetskikh e8c9bfc06a wiki: Add scroll-button to mouse and touchpad overview 2024-11-09 17:23:59 +03:00
Ivan Molodetskikh 07452f50a8 Update dependencies 2024-11-09 15:57:17 +03:00
Ivan Molodetskikh 642c5acebb wiki: Remove outdated info from Application Issues 2024-11-09 11:04:39 +03:00
Ivan Molodetskikh 0886dedff1 wiki: Mention Xwayland on other pages 2024-11-09 11:04:39 +03:00
Ivan Molodetskikh cc88a7d42e default-config: Bind Ctrl-Alt-Del to quit
This seems to be a shared bind across compositors.
2024-11-09 10:29:13 +03:00
Ivan Molodetskikh c0829087da Lock session right away with no outputs 2024-11-08 16:25:06 +03:00
Ivan Molodetskikh b6f6d6a7c2 wiki: Update getting started 2024-11-08 09:43:43 +03:00
Ivan Molodetskikh 5ff8b89aaf Rework output connection to always go through on_output_config_changed()
This has the following benefits:
1. connector_connected() is now more closely mirroring
   connector_disconnected() in that it merely lights up the connector,
   and doesn't check if the connector should be off from the config.
2. We can use more complex on/off logic that depends on multiple
   connectors. For example, this commit adds logic to only disable the
   laptop panel on lid close if there are other connected outputs.

We don't want to disable the laptop panel on lid close if it's the only
connected output because it causes screen lockers to create their
surface from scratch on normal laptop unsuspend, which is undesirable
and also confuses some screen lockers.
2024-11-08 09:11:56 +03:00
Ivan Molodetskikh 927abad4b4 Only call on_output_config_changed() on lid switch
We don't need to reload the niri output config.
2024-11-08 09:11:28 +03:00
Ivan Molodetskikh 3d31f9860a Extract format_make_model_serial() 2024-11-08 09:10:54 +03:00
Ivan Molodetskikh 8867a4f84c Add disable-monitor-names debug flag 2024-11-06 08:42:22 +03:00
Ivan Molodetskikh 88f4c1d610 layout: Preserve active workspace for removed outputs 2024-11-05 21:52:02 +03:00
Ivan Molodetskikh ddcb5c5e10 layout: Move some types further down 2024-11-05 21:08:50 +03:00
Ivan Molodetskikh cd90dfc7be Disable laptop panel when the lid is closed 2024-11-05 10:03:51 +03:00
Ivan Molodetskikh a778ab3897 Extract is_laptop_panel() to utils 2024-11-05 09:40:12 +03:00
Ivan Molodetskikh 4c2f49d566 wiki: Add Since to switch events 2024-11-03 23:00:18 +03:00
Ivan Molodetskikh 49d7052bb3 wiki: Add trackball section to config overview 2024-11-03 22:58:18 +03:00
Ivan Molodetskikh 07be7e7eae wiki: Add Since to scroll-button 2024-11-03 22:56:49 +03:00
Ivan Molodetskikh 97c8717d1e wiki: Mention insert-hint config on the gestures page 2024-11-03 22:52:49 +03:00
Ivan Molodetskikh 3ac0a751fe wiki: Add Since to scroll-factor 2024-11-03 22:50:15 +03:00
elipp 8b39f986d9 Implement scroll_factor mouse and touchpad setting (#730)
* Implement scroll_factor mouse and touchpad setting

* Change to FloatOrInt, add docs

* Also change v120 values

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-11-03 18:43:03 +00:00
Christian Meissl 354c365a03 xdg: cleanup activation tokens
valid tokens will stay around until explicitly cleaned-up.
remove the token after it has been successfully used
or we consider it timed out to prevent leaking the memory
used by the activation tokens
2024-11-03 09:13:41 -08:00
Ivan Molodetskikh e0ebf1bdff Remove pointer_grab_ongoing in favor of checking the actual grab 2024-11-03 10:23:21 +03:00
Ivan Molodetskikh 11633aef98 Use is() instead of downcast().is_some() 2024-11-03 10:15:19 +03:00
Ivan Molodetskikh 9193245871 Correct pointer constraint activation logic
Internally it uses the pointer focus, so make sure we have up-to-date
focus before setting it.
2024-11-03 10:15:19 +03:00
Ivan Molodetskikh 7baf10b751 Clarify redraw in refresh_pointer_focus() 2024-11-03 10:15:19 +03:00
Ivan Molodetskikh f5d91c5ecc Rename pointer_focus to pointer_contents, clarify comments
This is not pointer focus and it shouldn't be pointer focus, let's be
clear about it.
2024-11-03 10:15:19 +03:00
Ivan Molodetskikh 69e3edb5a3 Rename surface_under_and_global_space() to contents_under() 2024-11-03 08:50:17 +03:00
LoipesMas d58bb4eaa3 flake: set RUSTFLAGS instead of CARGO_BUILD_RUSTFLAGS 2024-11-02 12:35:04 -07:00
LoipesMas c5fe25f422 flake: libseat has been renamed to seatd 2024-11-02 12:35:04 -07:00
Ivan Molodetskikh 600cffb009 Update Smithay (lock leak fix) 2024-11-02 18:55:56 +03:00
Christian Meissl b9d14a9eda portal: prefer gtk for access portal
using gnome for the access portal does not work,
so just override by directly using the gtk one
2024-11-02 07:55:37 -07:00
Ivan Molodetskikh 0e7e398df3 Replace current_state() with with_toplevel_role()
Avoid microallocations that happen in current_state().
2024-11-02 10:53:55 +03:00
Ivan Molodetskikh 86bdc6898b Add with_toplevel_role() util function 2024-11-02 10:53:55 +03:00
Ivan Molodetskikh e5ca335115 Add Tracy allocation profiling feature flag 2024-11-02 10:53:55 +03:00
Ivan Molodetskikh fce5d66878 Follow window corner radius in insert hint 2024-11-02 10:53:55 +03:00
Ivan Molodetskikh 05d218113c Add gradient support for the insert hint
Implement it via FocusRing which already handles SolidColor vs. Border
render element.
2024-11-02 10:53:55 +03:00
Ivan Molodetskikh ef6af6adc1 Change TODO to FIXME 2024-11-02 10:53:55 +03:00
Ivan Molodetskikh 6632699e00 Remove obsolete TODO 2024-11-02 10:53:55 +03:00
Ivan Molodetskikh d3e72245b0 Don't show the cursor on programmatic movement
For keyboard-only use, especially with warp-mouse-to-focus, the
intention is that the cursor stays hidden from keyboard and other
automatic actions, and only shows up with an actual mouse movement.
2024-10-29 21:52:03 -07:00
Ivan Molodetskikh 13fe9c8ac3 [cfg-breaking] Rename hide-on-key-press to hide-when-typing
I originally preferred on-key-press, but when-typing feels more natural
and matches sway. This setting had not been in a stable release yet so
this is not stable release cfg breaking.
2024-10-29 21:52:03 -07:00
Ivan Molodetskikh 6ecbf2db8a Deny toplevel move from DnD grabs
Work around https://gitlab.gnome.org/GNOME/gtk/-/issues/7113
2024-10-28 21:12:58 +03:00
Ivan Molodetskikh c9be9056ef Update Smithay 2024-10-28 21:12:58 +03:00
Ivan Molodetskikh 0866990b7d wiki/Gestures: Add interactive move 2024-10-27 23:07:39 -07:00
Ivan Molodetskikh f04befb567 wiki: Document insert-hint config 2024-10-27 23:07:39 -07:00
Ivan Molodetskikh da3e5c4424 Implement touch interactive resize 2024-10-27 23:07:39 -07:00
Ivan Molodetskikh 26ab4dfb87 Implement touch interactive move 2024-10-27 23:07:39 -07:00
Rasmus Eneman e887ee93a3 Implement interactive window move 2024-10-27 23:07:39 -07:00
Ivan Molodetskikh d640e85158 Require Clone for LayoutElement::Id
Now that we have MappedId, this could really be Copy. But it's quite a
big refactor, so for now just require Clone as I'll need it.
2024-10-27 23:07:39 -07:00
gmorer c8044a9b5d ShaderRenderElement use borrowed Uniforms to minimize copy (#756) 2024-10-24 07:42:19 +03:00
Ivan Molodetskikh 289ae3604d tty: Guard against output disappearing immediately after connection
Fixes https://github.com/YaLTeR/niri/issues/739
2024-10-20 20:18:56 +03:00
Ivan Molodetskikh 55fb885256 Use new Smithay method for turning off DPMS 2024-10-20 20:18:56 +03:00
Ivan Molodetskikh 73a531f8bc Update dependencies (wl_output.scale fix) 2024-10-20 20:18:56 +03:00
Ivan Molodetskikh 10f04fd19d layout: Update tile config in Column::add_tile_at() 2024-10-19 12:33:44 +03:00
Christian Meissl 79fd309d6c support binding actions to switches (#747)
* support spawn action on switch events

this adds a new config section named `switch-events`
that allows to bind `spawn` action to certain switch
toggles.

* Expand docs

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-10-18 14:00:40 +00:00
Ivan Molodetskikh dd8b2be044 layout: Add missing active idx check before setting activate prev on removal 2024-10-18 10:06:09 +03:00
Ivan Molodetskikh 8d08782eba Set CLOEXEC on logind inhibit fd
Don't leak it to child processes.
2024-10-17 08:59:06 +03:00
Ivan Molodetskikh 8555f37dbf layout: Use remove_column_by_idx in remove_tile_by_idx 2024-10-17 08:59:06 +03:00
Ivan Molodetskikh 4b837f429c layout: Accept anim_config in remove_column_by_idx 2024-10-17 08:59:06 +03:00
chillinbythetree a480087618 Add scroll-button property for Touchpad, Mouse, Trackpoint, Trackball (#744) 2024-10-17 05:43:47 +00:00
tazjin 84655d3b26 Implement input configuration for trackballs (#743)
* niri-config: add trackball configuration struct

The available options are mostly the same as for mice. I've verified that each
option is applicable to trackballs in the libinput CLI.

* input: apply trackball config settings
2024-10-16 13:51:56 +00:00
Ivan Molodetskikh 40843cbda1 layout/monitor: Extract workspace_under() 2024-10-16 09:39:34 +03:00
Ivan Molodetskikh a13b9298c6 Draw the layout as inactive when layer-shell has focus 2024-10-15 11:11:57 +03:00
Christian Meissl 0c5e046820 input: apply output transform for tablet input (#737)
when mapping a tablet input to an output apply
the output transform just like we already do for
touch input.
2024-10-15 11:11:15 +03:00
Ivan Molodetskikh 907ebc4977 Add boxed_union proptest-derive feature
Our Op enum grew large enough to trigger a stack overflow in
proptest-derive's generated code. Thankfully, this feature works around
the problem.
2024-10-15 10:06:55 +03:00
sodiboo e4161be1bf flake: use nightly rust-analyzer and add rust-src component (#735)
this also improves the application of overlays to be more uniform; what
was previously done was just Wrong
2024-10-15 08:21:49 +03:00
Ivan Molodetskikh be7fbd418f layout: Return Tile + info upon removal 2024-10-14 18:08:44 +03:00
Ivan Molodetskikh 06ec9eecdb layout/tests: Use existing method 2024-10-14 17:39:55 +03:00
Ivan Molodetskikh 79eef5ee90 layout: Remove unnecessary vec lookup 2024-10-14 17:36:00 +03:00
Ivan Molodetskikh 29602ca995 layout: Extract Monitor::workspaces_with_render_positions() 2024-10-14 11:08:44 +03:00
Mark Karlinsky d7156df842 Add support for running as a dinit service (#728)
* Added dinit services

* Added dinit support to niri-session

* Replaced shutdown script for dinit with a single command execution

* Added dinit service files to Getting Started install tables

* Fix typo in resources/dinit/niri

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* Fixed mistakes in wiki/Getting-Started.md

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* niri-session does not start dinit anymore

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-10-13 12:26:16 +00:00
Ivan Molodetskikh 33b39913c7 layout: Fix expel animation of the smaller window in column 2024-10-12 09:58:03 +03:00
Ivan Molodetskikh d5cbc35811 Implement ConsumeOrExpelWindow{Left,Right} by id 2024-10-12 09:58:03 +03:00
Ivan Molodetskikh a038c5aaab layout/workspace: Add add_tile_to_column() 2024-10-12 09:58:03 +03:00
Ivan Molodetskikh c9c985c927 Support empty column in tile_offsets
Will be needed for the new inserting tile code.
2024-10-11 11:00:50 +03:00
Ivan Molodetskikh 859c0be0e5 layout: Add clarifying comment 2024-10-10 10:44:18 +03:00
Ivan Molodetskikh 810ea245f9 layout: Deduplicate default width resolution 2024-10-10 10:40:59 +03:00
Ivan Molodetskikh 58fc5f3b06 layout: Replace move_window_to_output with move_to_output 2024-10-10 10:28:55 +03:00
Ivan Molodetskikh 7d4e99b760 layout/workspace: Reduce code duplication in adding windows 2024-10-10 10:17:16 +03:00
Ivan Molodetskikh ab7d81aae0 layout: Reduce field visibility
The outside code isn't supposed to mess with the fields.
2024-10-10 09:24:20 +03:00
Winter e24723125f added power-on-monitors (#723) 2024-10-09 08:50:06 +00:00
Ivan Molodetskikh 03c603918d Document the new cursor hide settings 2024-10-06 22:09:19 -07:00
Ivan Molodetskikh 6fb60dacd2 Rework pointer inactivity hide as a timer
The previous way was prone to triggering late due to compositor idling
and therefore never calling the check function.
2024-10-06 22:09:19 -07:00
yzy-1 42a9daec9d Implement hide cursor on key press and on timeout 2024-10-06 22:09:19 -07:00
Ivan Molodetskikh 1ba2be3928 Show hidden pointer on mouse press
Feels like this should be the case.
2024-10-06 22:09:19 -07:00
sodiboo 66be000410 implement locked cursor position hints (#685)
* implement cursor position hints

* Remove redundant fully qualified path

* Find root surface

* Convert nesting to if-return

* Manually wrap error messages

* Remove error!() prints

* Add queue redraw

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-10-06 20:36:49 +03:00
sodiboo 5fc669c282 remove redundant pointer casts in shader code 2024-10-05 22:26:47 -07:00
sodiboo 9b78b15ba5 use CStr literals over calling CStr::from_bytes_with_nul 2024-10-05 22:26:47 -07:00
sodiboo b9fd0a405e use if let Some() over match with None => () 2024-10-05 22:26:47 -07:00
seth 1b44e0cd20 flake: add overlay output 2024-10-05 12:09:24 -07:00
seth b3d4d4eacc flake: use rust-overlay in dev shell
This allows `niri-visual-tests` to still be built and run in the dev
shell where it's necessary, as well as brings back the nightly `rustfmt`
used by the project

We can't use `fenix` again though as it doesn't wrap `ld` like nixpkgs
and rust-overlay do; without it, the way we link `dlopen()`'d libraries
breaks
2024-10-05 12:09:24 -07:00
seth a835bdc940 ci: nix build -> nix flake check
The (debug) package is already set as a check and will still be built
with this, but Nix will now also check other outputs automatically --
such as the dev shell
2024-10-05 12:09:24 -07:00
seth b258fd69d2 flake: improve packaging
Some highlights include:

- Removing some unnecessary dependencies of the package itself
- Allowing for overriding the package
- Adding Cargo feature toggles
- Installing all niri-related resources
- Avoiding `LD_LIBRARY_PATH` hacks
2024-10-05 12:09:24 -07:00
seth 3ab3e778ab flake: drop most external inputs
Previously, inputs like Crane and Fenix were used to only build the
`niri` package. This isn't really required, and can easily be replaced
by nixpkgs' `rustPlatform` -- which will also lead to less dependencies
being pulled into user's lockfiles
2024-10-05 12:09:24 -07:00
seth e6203313ce flake: format with nixfmt 2024-10-05 12:09:24 -07:00
seth 938061dd5e flake: use nixfmt 2024-10-05 12:09:24 -07:00
Ivan Molodetskikh 0cca7a2116 default-config: Add more comments to prefer-no-csd 2024-10-01 13:28:28 +03:00
Ivan Molodetskikh 39b46b3326 default-config: Add rounded corner window rule example 2024-10-01 13:28:16 +03:00
Ivan Molodetskikh 2aebd6bdbb default-config: Add comments to consume/expel binds 2024-10-01 13:20:38 +03:00
Ivan Molodetskikh b501a9b303 Upgrade dependencies 2024-09-30 15:27:36 +03:00
Ivan Molodetskikh 94e5408f46 Update Smithay 2024-09-30 15:24:50 +03:00
Christian Meissl eb190e3f94 handle role specific buffer offset 2024-09-30 05:04:58 -07:00
spazzylemons 80bb0d5876 Remove one unnecessary .clone() call and reorder another 2024-09-30 00:45:44 -07:00
Marwin Kreuzig c04ccafd0a fix focus_up_or_right 2024-09-28 05:18:22 -07:00
sodiboo 6ee5b5afa7 flake: update inputs and remove crane.inputs.nixpkgs override
the input was removed in https://github.com/ipetkov/crane/pull/692
2024-09-15 08:05:05 -07:00
Ivan Molodetskikh 6a48728ffb Bump version to 0.1.9 2024-09-14 11:55:52 +03:00
Ivan Molodetskikh 9cb89ff26c wiki: Update default hotkeys list 2024-09-14 10:17:27 +03:00
Ivan Molodetskikh 4e5f392c50 wiki: Document always-center-focused-column 2024-09-14 09:48:59 +03:00
Ivan Molodetskikh e35d9e760b default-config: Uncomment BracketLeft/BracketRight
These are fairly useful.
2024-09-13 21:51:56 +03:00
Ivan Molodetskikh 22fee7b003 Add NIRI_DISABLE_SYSTEM_MANAGER_NOTIFY env
Useful for UWSM I guess.
2024-09-13 15:45:30 +03:00
Ivan Molodetskikh e95d28e148 README: Remove NVIDIA note 2024-09-13 15:10:25 +03:00
Ivan Molodetskikh 7a65a0b79f wiki: Delete unstable JSON output note 2024-09-13 15:06:20 +03:00
Ivan Molodetskikh ca30315deb Set rust-version in Cargo.toml 2024-09-13 15:05:41 +03:00
Ivan Molodetskikh 9538e8f916 Upgrade dependencies 2024-09-13 15:05:33 +03:00
Ivan Molodetskikh 8b3715eabf Update Smithay 2024-09-13 14:59:32 +03:00
Ivan Molodetskikh d0f2b9abd0 Fix formatting 2024-09-12 20:54:44 +03:00
Ivan Molodetskikh 43578e21b1 Always clamp non-auto window height with >1 windows in column 2024-09-12 19:31:47 +03:00
Ivan Molodetskikh 55a798bd8b Prevent unintended focus-follows-mouse during workspace switch 2024-09-12 16:48:29 +03:00
Ivan Molodetskikh cdcd5a2835 Update comments 2024-09-12 13:36:08 +03:00
Ivan Molodetskikh 737e99ec69 Add preset window heights to wiki & default config 2024-09-12 02:32:44 -07:00
Ivan Molodetskikh c3cb42f04d Add SwitchPresetWindowHeight by id 2024-09-12 02:32:44 -07:00
Christian Rieger d0e624e615 Implement preset window heights 2024-09-12 02:32:44 -07:00
Ivan Molodetskikh 087a50a19c wiki/Xwayland: Add note about existing DISPLAY 2024-09-10 11:33:08 +03:00
Ivan Molodetskikh 0bed253835 tty: Try connecting with invalid modifier on fail 2024-09-10 11:12:24 +03:00
Ivan Molodetskikh 6b6a84e55b Avoid panics on more wrong VBlank events 2024-09-10 10:48:45 +03:00
Ivan Molodetskikh 7d5785e96f Give focus to on-demand layer surfaces on map 2024-09-10 10:14:34 +03:00
Ivan Molodetskikh 70fa38fadf Possibly fix some unsync subsurfaces not redrawing output 2024-09-10 09:52:31 +03:00
Ivan Molodetskikh 3514cd2e36 Prefer exclusive layer focus to on-demand on the same layer 2024-09-10 09:10:03 +03:00
Ivan Molodetskikh 96083847fb ipc: Clarify some things in the docs 2024-09-09 08:51:03 +03:00
Ivan Molodetskikh d25d6ce337 Arrange layer map after sending new scale/transform
I think that should be a slightly better ordering of events.
2024-09-08 22:33:09 +03:00
Ivan Molodetskikh bb044075fa Inform layer surfaces of scale/transform changes
How'd I miss this and then never catch it?
2024-09-08 22:05:56 +03:00
Ivan Molodetskikh 370fd4e172 ipc: Convert all Action unit variants to unit struct variants
This is a breaking change, but likely nobody uses this through raw JSON
yet, and this allows us to add fields to any action later on without
another breaking change.
2024-09-06 18:32:51 +03:00
Ivan Molodetskikh 7dea3822a3 Fix set-window-height SetProportion scale 2024-09-06 18:32:51 +03:00
Ivan Molodetskikh 7d11ef0abb Extract print_window() 2024-09-06 18:32:51 +03:00
Ivan Molodetskikh dcb29efce5 Implement by-id window addressing in IPC and CLI, fix move-column-to-workspace
This is a JSON-breaking change for the IPC actions that changed from
unit variants to struct variants. Unfortunately, I couldn't find a way
with serde to both preserve a single variant, and make it serialize to
the old value when the new field is None. I don't think anyone is using
these actions from JSON at the moment, so this breaking change is fine.
2024-09-06 18:32:41 +03:00
Ivan Molodetskikh cb5d97f600 Fix new Clippy warning
This was stabilized in 1.76 so we can use it now.
2024-09-05 20:40:11 +03:00
Ivan Molodetskikh 608ab7d8b1 Change output sorting to match make/model/serial first
We can do this now that we have libdisplay-info.
2024-09-05 20:10:01 +03:00
elkowar fd8ebb9d06 implement always_center_single_column layout option 2024-09-05 01:01:41 -07:00
Ivan Molodetskikh 952916fd1c layout: Prevent view gesture snap beyond first/last column 2024-09-04 21:46:08 +03:00
Ivan Molodetskikh a0592e8f53 layout: Extract snap_points() 2024-09-04 21:45:47 +03:00
Ivan Molodetskikh 5460c792bd Fix missing KeyboardLayoutSwitched event on XKB switch 2024-09-04 20:54:11 +03:00
sodiboo e5ecd27bbe flake: add libdisplay-info to buildInputs 2024-09-04 09:39:22 -07:00
Ivan Molodetskikh 4543873dae wiki/IPC: Link to the online rustdoc 2024-09-04 13:15:43 +03:00
Ivan Molodetskikh a2c855315c ci: Add niri-ipc rustdoc generation 2024-09-04 12:39:23 +03:00
Ivan Molodetskikh 6c4e4b374a ipc: Write some more docs 2024-09-04 12:29:26 +03:00
Ivan Molodetskikh 9ab887bec8 ipc: Don't re-export socket types 2024-09-04 12:03:13 +03:00
Ivan Molodetskikh 268591f343 wiki: Add Since note to other open-on-output properties 2024-09-03 14:36:23 +03:00
Ivan Molodetskikh a42717bcac wiki/Xwayland: Mention adding DISPLAY to config environment 2024-09-03 14:12:28 +03:00
Ivan Molodetskikh 6b013a08fc wiki: Update package list 2024-09-03 13:51:24 +03:00
Ivan Molodetskikh b65a243fc9 Remove warning about missing output config 2024-09-03 13:48:08 +03:00
Ivan Molodetskikh f0157e03e7 Use libdisplay-info for make/model/serial parsing, implement throughout 2024-09-03 13:48:08 +03:00
Ivan Molodetskikh 4b7c16b04a Read config from /etc/niri/config.kdl too 2024-09-02 13:10:45 +03:00
Ivan Molodetskikh aafd5ab70f wiki: Use $NIRI_SOCKET in example 2024-09-02 12:38:33 +03:00
Ivan Molodetskikh d8d6b5a5e0 wiki: Fix niri-ipc links 2024-09-02 10:05:59 +03:00
Ivan Molodetskikh a1fd4b396f wiki: Fix code block formatting 2024-09-02 10:04:43 +03:00
Ivan Molodetskikh 5521cdda63 wiki: Add the word IPC to the sidebar 2024-09-02 10:03:44 +03:00
Ivan Molodetskikh 12b16a9d7e wiki: Document IPC programmatic access 2024-09-01 23:47:19 -07:00
Ivan Molodetskikh f7181fb066 Implement by-id workspace action addressing
It's not added to clap because there's no convenient mutually-exclusive
argument enum derive yet (to have either the current <REFERENCE> or an
--id <ID>). It's not added to config parsing because I don't see how it
could be useful there. As such, it's only accessible through raw IPC.
2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 17ac52e1d4 Fix spelling mistake 2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 64a9351921 Add niri msg windows 2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 332af8b062 Rearrange some CLI and IPC enum values 2024-09-01 23:47:19 -07:00
Ivan Molodetskikh b7901579d5 Change IdCounter to be backed by an AtomicU64
Let's see if anyone complains.
2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 138c2a3bfd Change OutputId::get() to return u64 2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 446a9f1e06 Make WorkspaceId inner field private 2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 52265e2e19 utils/id: Use a Relaxed atomic op 2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 0f522f209b Change MappedIt::get() to return u64 2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 30b213601a Implement the event stream IPC 2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 8eb34b2e18 Animate focus-workspace by idx/back and forth/previous
Deleting the test because it only made sense when no-animation was
special cased.
2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 74d1b1f406 layout: Cache monitor output name 2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 2b3d196876 Remove unused function 2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 397b7e4bb9 ipc: Read only a single line on the client
Allow extensibility.
2024-09-01 23:47:19 -07:00
Ivan Molodetskikh 598b27f83c flake: Remove maintainer comment
Effectively other contributors maintain it now.
2024-08-26 18:15:39 +03:00
Ivan Molodetskikh da53e79d07 wiki: Add hotkey overlay skip to FAQ 2024-08-26 10:35:00 +03:00
Ivan Molodetskikh 2907d5af3e wiki: Mark FAQ snippet as KDL 2024-08-26 10:35:00 +03:00
sodiboo dd919fe01b fix cargo run on nixos
this boils down to adding some extra dependencies to the shell
environment. they're also inherited from craneArgs because the ones from
the package are actually transformed into the WRONG outputs of the
packages. also refactors to use craneLib.devShell because it's somewhat
cleaner.
2024-08-25 15:42:25 +03:00
Ivan Molodetskikh f86a9bed1a layout: Break out early on min size 2024-08-25 11:46:04 +03:00
Ivan Molodetskikh cfa87d508e layout: Fix rounding in height distribution
Rounding before checking min height could artificially increase the
window height that we check, leading to an incorrectly satisfied min
constraint.
2024-08-25 10:16:37 +03:00
Ivan Molodetskikh f19e1711a7 Add niri msg keyboard-layouts 2024-08-25 09:38:45 +03:00
Ivan Molodetskikh 20cd4f5d04 layout: Clamp window height to max available in column
When the window is alone in its column this logic intentionally isn't
triggered. Until we have a floating layer, there's no other way to get a
window larger than the screen, which I need.
2024-08-25 08:46:34 +03:00
Ivan Molodetskikh b2c7d3ad40 Rework PW screencast frame timing
- Remove the 0.5 ms hack.
- Add redraw scheduling to fix stuck frame if the last redrawn frame
  happened too soon.
2024-08-24 10:49:32 +03:00
Ivan Molodetskikh 4832924483 Update Smithay (layer-shell popup fix) 2024-08-24 07:22:57 +03:00
Ivan Molodetskikh 28a8a9ace2 Register deadline timer for closing transaction 2024-08-23 19:09:18 +03:00
Ivan Molodetskikh a4f1caab1d wiki: Update transaction list 2024-08-23 15:53:01 +03:00
Ivan Molodetskikh c8839f7658 Implement window close transaction
Mainly visible with disabled animations.
2024-08-23 15:41:06 +03:00
Ivan Molodetskikh dfe3580607 animation: Use saturating_sub in value() 2024-08-23 15:39:57 +03:00
Ivan Molodetskikh 1c02552e92 animation: Make restarted() take by-ref 2024-08-23 15:39:45 +03:00
Ivan Molodetskikh ff7cbb97df Fix screen transition across scale/transform changes 2024-08-23 12:54:07 +03:00
Ivan Molodetskikh 09f3d3fb12 Extract Niri::update_render_elements() 2024-08-23 12:54:07 +03:00
Ivan Molodetskikh 63defc25d2 Fix Clippy warnings 2024-08-23 12:21:47 +03:00
Ivan Molodetskikh db39fc95f4 pw_utils: Re-create damage tracker on scale change 2024-08-23 11:14:24 +03:00
Ivan Molodetskikh 471dc714aa Add damage check to PW screencasts
Avoids unnecessary frames.
2024-08-23 11:02:34 +03:00
Ivan Molodetskikh fef665df73 tty: Wait for sync on needs_sync()
How did I never add this back?
2024-08-23 09:26:42 +03:00
Ivan Molodetskikh 7bfdf87bf0 Implement resize transactions 2024-08-22 15:19:11 +03:00
Ivan Molodetskikh cf357d7058 Implement window resize throttling 2024-08-22 14:40:40 +03:00
Ivan Molodetskikh 618fa08aa5 Update Smithay (apply state in post commit) 2024-08-22 14:15:04 +03:00
Ivan Molodetskikh a40e7b4470 Handle dmabuf blocker separately in toplevel pre-commit
Will be needed for transactions.
2024-08-22 13:13:28 +03:00
Michael Yang f1894f6f9a feature: add on-demand vrr (#586)
* feature: add on-demand vrr

* Don't require connector::Info in try_to_set_vrr

* Improve VRR help message

* Rename connector_handle => connector

* Fix tracy span name

* Move on demand vrr flag set higher

* wiki: Mention on-demand VRR

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-08-22 11:58:07 +03:00
Ivan Molodetskikh dfc2d452c5 layout: Do not recompute total_weight every iteration 2024-08-15 11:46:13 +03:00
Ivan Molodetskikh 66f23c3980 layout: Implement weighted height distribution
The intention is to make columns add up to the working area height most
of the time, while still preserving the ability to have one fixed-height
window.

Automatic heights are now distributed according to their weight, rather
than evenly. This is similar to flex-grow in CSS or fraction in Typst.

Resizing one window in a column still makes that window fixed, however
it changes all other windows to automatic height, computing their
weights in such a way as to preserve their apparent heights.
2024-08-15 10:50:38 +03:00
Ivan Molodetskikh 7a6ab31ad7 layout: Pre-subtract gaps during height distribution
Same result, but code a bit clearer.
2024-08-15 10:46:39 +03:00
Ivan Molodetskikh 2f73dd5b59 wiki: Use real em-dash 2024-08-14 18:33:43 +03:00
Ivan Molodetskikh c658424c9f wiki: Document invisible state 2024-08-14 18:32:50 +03:00
Ivan Molodetskikh bb58f2d162 wiki: Clarify named workspaces example 2024-08-14 18:18:05 +03:00
Fea f54297f242 flake: Update flake inputs 2024-08-14 10:49:54 +03:00
Fea b72d946062 Fix nix build 2024-08-14 10:49:54 +03:00
Ivan Molodetskikh 883763c172 Implement stub mutter-x11-interop
Allows xdp-gnome dialogs to work with X11 clients.

Fixes https://github.com/YaLTeR/niri/issues/594
2024-08-13 09:15:57 +03:00
Ivan Molodetskikh 9063a5dbdc spec: Add mesa-libEGL dependency
Closes https://github.com/YaLTeR/niri/issues/554
2024-08-10 14:55:56 +03:00
Ivan Molodetskikh 892e848985 Update README 2024-08-10 12:55:47 +03:00
Ivan Molodetskikh 0edb90bab2 README: Add similar projects 2024-08-10 12:55:38 +03:00
Ivan Molodetskikh 8f71f8958e Bump version to 0.1.8 2024-08-10 12:55:24 +03:00
Ivan Molodetskikh fcb97cfd5e Update dependencies (Smithay Xwayland Nvidia freeze fix) 2024-08-09 19:58:07 +03:00
Ivan Molodetskikh 2983eb3113 wiki: Bump xwl-satellite higher up 2024-08-08 15:26:06 +03:00
Ivan Molodetskikh a968b1abc0 Fix redundant cast after upgrading csscolorparser 2024-08-08 15:12:48 +03:00
Ivan Molodetskikh 47c964d6fb Upgrade dependencies 2024-08-08 15:06:55 +03:00
Michael Yang 22cb657ef1 fix: change precision to highp 2024-08-08 15:06:23 +03:00
Ivan Molodetskikh bb15d1e850 screencopy: Change integer to fractional scale
That *was* wrong after all.
2024-08-08 13:54:28 +03:00
Ivan Molodetskikh 47680e43c5 screencopy: Wait for SyncPoint before submitting 2024-08-08 13:32:37 +03:00
Ivan Molodetskikh 0f1e44aac6 screencopy: Fix transformed damage calculation 2024-08-08 13:32:37 +03:00
Ivan Molodetskikh 66aae91bca screencopy: Clarify the use of integer scale 2024-08-08 13:32:37 +03:00
Ivan Molodetskikh 07bd76e219 screencopy: Use monotonic time
This way it matches up with presentation-time.
2024-08-08 13:32:37 +03:00
Michael Yang b6a7b3e9e4 feat: update screencopy to version 3 2024-08-08 13:32:37 +03:00
Ivan Molodetskikh 1cf5cfce06 Bump MSRV to 1.77.0
New pipewire-rs requires it.
2024-08-06 18:17:43 +03:00
Ivan Molodetskikh 8ff90c4fc2 Implement PipeWire DMA-BUF modifier negotiation 2024-08-06 18:01:52 +03:00
Ivan Molodetskikh 908c8eb42a wiki: Use HTML dark/light image
Apparently GitHub Markdown is not supported on GitHub Wiki.
2024-08-01 18:26:17 +03:00
Ivan Molodetskikh 0078293d4c wiki: Document the redraw loop 2024-08-01 17:52:34 +03:00
Jeff Peeler 9728dbeeac add mod3 key binding support (#565)
* add support for iso_level5_shift modifier

* update Cargo.lock

bumps smithay to de94e8f59e202b605c35dfe1fef1857bad427e8c
2024-07-31 15:00:35 +00:00
Ivan Molodetskikh 324029ca3b Deal with Clippy warnings 2024-07-28 11:41:09 +03:00
Ivan Molodetskikh 73be5b2ba1 CI: Switch leftover action to dtolnay/rust-toolchain
Missed this I guess.
2024-07-28 11:04:02 +03:00
Ivan Molodetskikh af904d23ac tty: Add check for vblank on idle 2024-07-27 13:43:27 +03:00
Ivan Molodetskikh ad84fc1479 wiki: Fix em-dash 2024-07-27 10:14:06 +03:00
Ivan Molodetskikh d5a8074b53 Add profile-with-tracy-ondemand feature
Finally this can be added without disabling frames.

manual-lifetime is needed to avoid initializing Tracy for CLI commands,
since that is quite slow.
2024-07-27 09:51:44 +03:00
Ivan Molodetskikh c506fecc87 Upgrade dependencies 2024-07-27 09:28:40 +03:00
Ivan Molodetskikh d777810911 pw: Don't require LINEAR buffer
It's not needed and apparently doesn't work on NVIDIA together with the
rendering flag.
2024-07-26 16:06:33 +03:00
Ivan Molodetskikh bbdc07ee6c wiki: Document output background-color 2024-07-26 11:51:29 +03:00
Anant Sharma 689338f059 Add background color option for output 2024-07-26 11:51:29 +03:00
Ivan Molodetskikh eee770514f wiki: Mention nightly COPR 2024-07-22 13:49:43 +03:00
Ivan Molodetskikh 5a0bda7ec4 wiki: Document negative struts 2024-07-22 13:12:42 +03:00
Ivan Molodetskikh b454fd5d9e Add negative struts to tests 2024-07-22 13:12:42 +03:00
Salman Farooq 2a830ed498 feat: negative struts (to remove outer gaps) 2024-07-22 13:12:42 +03:00
Ivan Molodetskikh e98d1ec5a7 Add an rpkg spec template 2024-07-17 22:08:15 +03:00
Ivan Molodetskikh 3ace97660f Implement gradient color interpolation option (#548)
* Added the better color averaging code (tested & functional)

* rustfmt

* Make Color f32 0..1, clarify premul/unpremul

* Fix imports and test name

* Premultiply gradient colors matching CSS

* Fix indentation

* fixup

* Add gradient image

---------

Co-authored-by: K's Thinkpad <K.T.Kraft@protonmail.com>
2024-07-16 07:22:03 +00:00
Ivan Molodetskikh 0824737757 border: Fix reversed gradient at angle = 90 2024-07-13 19:02:04 +03:00
Ivan Molodetskikh 8fdea033bc Fix Clippy warnings 2024-07-13 07:48:07 +03:00
Ivan Molodetskikh 2e906fc5fa Add middle-emulation libinput flag 2024-07-13 07:34:22 +03:00
Tglman a5a34934df feat: add metadata for generate deb package with cargo deb 2024-07-12 16:58:30 +03:00
Ivan Molodetskikh 08a8a0f29a Update Cargo.lock 2024-07-12 10:44:02 +03:00
Oli Strik 519611c6c8 Add schemars::JsonSchema trait to ipc types (#536)
* feat: add schemars JsonSchema trait to ipc types

* niri-ipc: use feature-flag for deriving schemars::JsonSchema

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-07-12 05:21:52 +00:00
Winter a283c34dbb Add move-column-{left/right}-or-to-monitor-{left/right} (#528)
* feature added, move-column-left-or-monitor-left and move-column-right-or-monitor-right

* fixed stupid mistake

* yalter's fixes

* fixed names

* fixed a stupid mistake

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-07-10 04:52:48 +00:00
Ivan Molodetskikh f9fe86ee3e Restore VRR on TTY switch 2024-07-09 14:25:02 +04:00
Ivan Molodetskikh 2e67152941 Fix view offset anim restart on switching focus 2024-07-09 09:50:46 +04:00
Ivan Molodetskikh 22bfec7259 Add tolerance to view offset anim restart check
It was getting tripped by tiny differences.
2024-07-09 09:43:43 +04:00
Suyashtnt 1af9f9bd95 niri-config: update wiki parses test to test all codeblocks
This makes sure the failing codeblocks do fail. This also optimizes the algorithm a bit by removing a `.collect()`

Signed-off-by: Suyashtnt <suyashtnt@gmail.com>
2024-07-08 19:43:07 +03:00
Suyashtnt 926451c8be wiki: update no-test comments in wiki
Signed-off-by: Suyashtnt <suyashtnt@gmail.com>
2024-07-08 19:43:07 +03:00
Suyashtnt 7b3bef124d niri-config: add test to see if all snippets inside of the wiki compile
Signed-off-by: Suyashtnt <suyashtnt@gmail.com>
2024-07-08 17:42:09 +03:00
Suyashtnt 3be6e38af3 wiki: update wiki kdl snippets
Signed-off-by: Suyashtnt <suyashtnt@gmail.com>
2024-07-08 17:42:09 +03:00
Suyashtnt f2290a43d9 flake: update nix flake
Signed-off-by: Suyashtnt <suyashtnt@gmail.com>
2024-07-08 17:42:09 +03:00
Ivan Molodetskikh 4513663084 screenshot-ui: Animate opening 2024-07-08 11:24:08 +04:00
Ivan Molodetskikh 092cf6cfaf solid_color: Fix alpha handling
It wasn't getting redrawn on alpha changes.
2024-07-08 11:11:06 +04:00
Ivan Molodetskikh 236f96e676 screenshot-ui: Add a help panel 2024-07-08 10:54:21 +04:00
Ivan Molodetskikh 887ca971ab Use is_alive() 2024-07-08 10:06:06 +04:00
Ivan Molodetskikh 4cc195b681 screenshot-ui: Pre-compute PrimaryGpuTexture 2024-07-08 10:04:43 +04:00
Ivan Molodetskikh fc2be2b8d0 Upgrade dependencies 2024-07-08 09:38:18 +04:00
Christian Meissl 570bf1cb3c bump smithay 2024-07-08 08:30:00 +03:00
Ivan Molodetskikh 6ec9c72539 Clear pointer grab upon opening the screenshot UI
Gets rid of DND surfaces.
2024-07-07 09:54:19 +04:00
Ivan Molodetskikh 1a1086206c Extract capture_screenshots() 2024-07-07 09:48:19 +04:00
Ivan Molodetskikh f2766b103d Implement toggling pointer for the screenshot UI 2024-07-07 09:23:59 +04:00
Ivan Molodetskikh 62c9d44b04 screenshot-ui: Fix last selection preservation
Another missed thing from the fractional scale refactor...
2024-07-07 09:22:39 +04:00
Ivan Molodetskikh e394a7ff20 Implement on-demand layer-shell keyboard focus 2024-07-06 18:20:19 +04:00
Ivan Molodetskikh 921ed63204 Add LayerSurface to PointerFocus 2024-07-06 18:17:48 +04:00
Ivan Molodetskikh 77dafb819f Fix screenshot UI selection pointer clamping 2024-07-06 09:46:37 +04:00
Ivan Molodetskikh 1da99f4003 Implement focus-follows-mouse max-scroll-amount 2024-07-05 20:53:11 +04:00
Ivan Molodetskikh 120eaa6c56 wiki: Fix repeat since annotation 2024-07-05 20:30:27 +04:00
Ivan Molodetskikh fb636ef98d Refactor and simplify new view offset calculation
* Split new offset computation from starting the animation.
* Simplify new column on empty workspace logic.
2024-07-05 20:30:27 +04:00
Ivan Molodetskikh 6147a31b48 wiki: Add Since to repeat=false 2024-07-05 12:04:23 +04:00
Ivan Molodetskikh 3f8707496f layout: Remove todo!() when activating window with no monitors 2024-07-05 11:56:45 +04:00
Ivan Molodetskikh de6caec685 Recompute current pointer focus for focus-follows-mouse
Fixes https://github.com/YaLTeR/niri/issues/377.
2024-07-05 10:13:50 +04:00
Ivan Molodetskikh c8411e55d9 wiki: Mention bind key repeat 2024-07-05 08:40:25 +03:00
Salman Farooq d3aebdbec4 Implement key repeat for compositor binds 2024-07-05 08:40:25 +03:00
TheAngusMcFire a56e4ff436 Added Commnads to focus windows or Monitors above/below the active window (#497)
* Implement focus-window-up/down-or-monitor calls

* Fixed wrong naming of focus-window-or-monitor commands

* fix copy pase errors for focusing direction

* Fixed wrong behaviour when the current workspace is empty

* Cleanup navigation code to reduce complexity

* Fix wrong comments and add testcases for FocusWindowOrMonitorUp/Down

---------

Co-authored-by: Christian Rieger <christian.rieger@student.tugraz.at>
2024-07-05 04:55:04 +00:00
Ivan Molodetskikh 9dcc9160b3 Put Outputs config into a dedicated struct 2024-07-05 07:35:01 +03:00
tet 43df7fad46 Implement wlr-output-management protocol
fix: wlr_output_management use WeakOutput
2024-07-05 07:35:01 +03:00
Ivan Molodetskikh d2087a2cd9 Add output ID tracking 2024-07-05 07:35:01 +03:00
Nick Hastings c681198179 Add install location instructions for manual installation (#489)
* wiki: Update install location instructions

Provide file install destinations for both packages and manual
installations.

* wiki: split install instructions into two sections

* Update wiki/Getting-Started.md

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* Update wiki/Getting-Started.md

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* Update wiki/Getting-Started.md

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* Update wiki/Getting-Started.md

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* Update wiki/Getting-Started.md

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-07-02 08:30:39 +00:00
it-a-me 105938df0b Keep monitors powered off upon connecting a new one (#488)
* Keep monitors powered off upon connecting a new one

Update src/backend/tty.rs

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

Update src/backend/tty.rs

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

fix tests

* Update

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-07-02 01:21:07 -07:00
Ivan Molodetskikh 7b6fa12854 Enable subpixel glyph positioning in Pango
Makes things scale more smoothly.
2024-07-01 09:47:31 +04:00
Ivan Molodetskikh e7c201abba Update README 2024-06-29 10:27:38 +04:00
Ivan Molodetskikh 4fd04951e6 Bump version to 0.1.7 2024-06-29 08:39:13 +04:00
Salman Farooq 747c186293 add-in-wiki-xwayland-run-as-a-solution-to-run-X-apps (#477) 2024-06-28 21:18:29 -07:00
Filipe Paniguel bdf9894020 feat: add focus-column-or-monitor-left, focus-column-or-monitor-right (#456)
* feat: add support for focus-window-or-monitor

* addresses output without window case

* refactor: reduce verbosity

* update this..

* refactor: rename `maybe_focus_window` functions

* refactor: flip focus_window_or_output return logic

* Update src/layout/mod.rs

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* refactor: rename to Column

* move blocks next to other Column variables

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-06-28 07:44:24 -07:00
sodiboo d180e60e05 Implement support for $NIRI_CONFIG environment variable 2024-06-28 14:00:26 +03:00
sodiboo 65addefd09 wiki: Fix $XDG_CONFIG_HOME/.config/ that should be $XDG_CONFIG_HOME/ 2024-06-28 14:00:26 +03:00
Ivan Molodetskikh 697fcbac12 wiki: Add rounded corners to the FAQ 2024-06-28 14:39:04 +04:00
Ivan Molodetskikh a8e281e95f wiki: Fix links 2024-06-28 14:38:58 +04:00
Ivan Molodetskikh 4d60eae82e Fix blocked-out + popups and rounded corners window screencasts 2024-06-28 12:35:12 +04:00
Ivan Molodetskikh 2b5215c244 Show ISO_Level3_Shift in the hotkey overlay 2024-06-28 11:28:40 +04:00
Ivan Molodetskikh a43f30b7f5 Ignore compositor opacity for window screencasts
When using opacity as unfocused indicator, it will show up on the
screencast, which is undesired.

This is not a problem for window screen*shot*s where the window is
focused.
2024-06-28 10:39:36 +04:00
Ivan Molodetskikh 88f7b08e56 Add transparency support to window screencasts
Turns out it needed to be in a separate pod.
2024-06-28 10:39:35 +04:00
Ivan Molodetskikh dc92d80b9f Implement initial window screencasting 2024-06-28 10:39:35 +04:00
Ivan Molodetskikh 0757ad08e7 id: Start from 1 2024-06-28 10:39:35 +04:00
Ivan Molodetskikh 5577021475 wiki: Mention wait for completion NVIDIA flickering workaround 2024-06-28 10:39:35 +04:00
Ivan Molodetskikh 40aff3a094 Implement org/gnome/shell/Introspect/GetWindows 2024-06-28 10:39:35 +04:00
Ivan Molodetskikh 6c5f10035a mapped: Add id 2024-06-28 10:39:35 +04:00
Ivan Molodetskikh 96d2baa2b5 mapped: Make is_active_in_column private 2024-06-28 10:39:35 +04:00
aspizu 5d2754f831 Fix dead links and add FAQ entry (#475)
* Fix dead links and add FAQ entry

* Update wiki/FAQ.md

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* Update wiki/Important-Software.md

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-06-27 23:23:52 -07:00
itsjunetime ebaf1b0620 Update winit to fix failing build on arm linux 2024-06-22 18:21:15 +03:00
Ivan Molodetskikh 589e5a600c Keep screencast running through size changes 2024-06-21 11:05:28 +03:00
Ivan Molodetskikh 198b5a502d Update dependencies 2024-06-21 08:55:46 +03:00
Ivan Molodetskikh cb0ebd35ce Make tablet without specific output map to union of outputs 2024-06-19 23:02:45 +03:00
Ivan Molodetskikh 29cf80a3dd wiki: Mention workspace switch mouse gesture 2024-06-19 22:22:34 +03:00
Ivan Molodetskikh db89d4d3dd Implement vertical middle mouse gesture 2024-06-19 21:55:39 +03:00
Kirill Chibisov 226273f660 Handle KDE decorations in Mapped::has_ssd
This fixes an issue with default CSD border being drawn for SSD
rendering firefox, because only xdg decorations were checked.
2024-06-19 17:42:29 +03:00
Ivan Molodetskikh c0ded35783 Somewhat fix height distribution logic
This got a bit broken with fractional layout. The current logic seems to
give exact results for integer scales again, but for fractional scales
sometimes the resulting height goes beyond the maximum, even clearly by
more than one logical pixel. Not entirely sure why that is.
2024-06-19 08:51:19 +03:00
FreeFull 39632e9c1e Add regex syntax link to Configuration:-Window-Rules.md 2024-06-18 14:31:57 +03:00
Ivan Molodetskikh 66202992c9 Fix blurry rounded corners on high scales 2024-06-18 14:01:34 +03:00
Ivan Molodetskikh eb59b10050 config: Remove obsolete FIXME 2024-06-18 14:01:34 +03:00
Ivan Molodetskikh 986f2c14ab Make scale use FloatOrInt 2024-06-18 14:01:34 +03:00
Ivan Molodetskikh 793e1bdbc5 Animate xdg-activation and foreign-toplevel workspace switches
These are a bit jarring without an animation.
2024-06-18 14:01:34 +03:00
Ivan Molodetskikh d62721d5f8 Queue redraw after activation in xdg-activation 2024-06-18 14:01:34 +03:00
Ivan Molodetskikh d54619e1d1 Remove unnecessary return 2024-06-18 14:01:34 +03:00
Ivan Molodetskikh 8425493ef5 Allow scale below 1 2024-06-18 14:01:34 +03:00
Ivan Molodetskikh 6121e64338 Add fractional scales to auto scale guessing 2024-06-18 14:01:34 +03:00
Ivan Molodetskikh 33b5beaeee Round scale to closest representable 2024-06-18 14:01:34 +03:00
Ivan Molodetskikh 1dae45c58d Refactor layout to fractional-logical
Lets borders, gaps, and everything else stay pixel-perfect even with
fractional scale. Allows setting fractional border widths, gaps,
struts.

See the new wiki .md for more details.
2024-06-18 14:01:28 +03:00
Ivan Molodetskikh 997119c443 Enable fractional scaling 2024-06-18 12:23:50 +03:00
Ivan Molodetskikh 032589446a Fix cached data not updating on config change 2024-06-17 09:02:22 +03:00
Ivan Molodetskikh 9ae98e09cb Update Smithay 2024-06-17 09:02:22 +03:00
Ivan Molodetskikh 2ffa1ae705 layout: Cache scale and transform on the workspace 2024-06-17 09:02:22 +03:00
Ivan Molodetskikh fee72b87cf niri-config: Add pretty-assertions to tests
The config parse test is pretty big and it's impossible to tell the
difference from the normal assert.
2024-06-17 09:02:22 +03:00
Ivan Molodetskikh 6c47bd6e80 Rename apply_scale to to_physical_precise_round
Consistency with Smithay.
2024-06-17 09:02:22 +03:00
Ivan Molodetskikh 02c2972e74 ui/config_error_notification: Store TextureBuffers
Avoids re-importing every frame.
2024-06-17 09:02:22 +03:00
Ivan Molodetskikh 4b830ee7ff ui/screenshot_ui: Correct fractional scaled behavior 2024-06-10 18:08:01 +03:00
Ivan Molodetskikh 8e41568ffd Add SolidColor{Buffer,RenderElement} 2024-06-10 18:08:01 +03:00
Ivan Molodetskikh dbe810d3d8 Move apply_scale() to utils 2024-06-10 18:08:01 +03:00
Ivan Molodetskikh a1563b9132 ui/config_error_notification: Make fractional-scaling aware 2024-06-10 18:08:01 +03:00
Ivan Molodetskikh 98aea9579f ui/exit_confirm_dialog: Make fractional-scaling aware 2024-06-10 18:08:01 +03:00
Ivan Molodetskikh 7019172b67 Add MemoryBuffer 2024-06-10 18:08:00 +03:00
Ivan Molodetskikh be62bd123a ui/hotkey_overlay: Make fractional-scaling aware 2024-06-10 18:08:00 +03:00
Ivan Molodetskikh 3c63be6261 Implement our own TextureBuffer/RenderElement
Supports fractional texture scale + has some getters.
2024-06-10 18:08:00 +03:00
Ivan Molodetskikh e3406ac255 Signal fractional scale to clients
Doesn't do anything yet because we don't bind the fractional scale
manager and don't allow fractional scales.
2024-06-10 18:08:00 +03:00
Ivan Molodetskikh 22a948cc75 Update dependencies 2024-06-10 18:07:51 +03:00
Peter Collingbourne bc3d6cac80 Implement xdg_activation_v1
Fixes #30.
2024-06-10 18:06:34 +03:00
James Sully a55e385b12 Add focus-column-right-or-first, focus-column-left-or-last (#391)
* add focus-column-right-or-first

* add focus-column-left-or-last
2024-06-09 11:14:51 +00:00
Ujp8LfXBJ6wCPR af6d84a7f8 Fix typos (#429)
* Fix typos reported by "typos" crate

https://github.com/crate-ci/typos

* Ignore typo datas -> data

See https://github.com/crate-ci/typos?tab=readme-ov-file#false-positives
for more configureability.

---------

Co-authored-by: Carl Hjerpe <git@hjerpe.xyz>
Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-06-09 10:50:22 +00:00
Ivan Molodetskikh f203c8729a Use generic Atomic for rlim_t
rlim_t is different between platforms.
2024-06-09 08:48:36 +03:00
galister dbf0dddfcc PointerMotionAbsolute: use union rect of all outputs 2024-06-07 19:50:48 +03:00
Ivan Molodetskikh c6c17cccac Add missing fullscreen check
Fixes crash when a window in a column requests to be unfullscreened.
2024-06-04 19:46:19 +03:00
Ivan Molodetskikh b5ad0e12fd Preserve empty named workspaces upon output removal
Not sure how we missed this.
2024-06-02 08:21:19 +03:00
Yuya Nishihara c8e46b9d17 Add "off" and "disabled-on-external-mouse" properties to input devices
This is called "events <mode>" in Sway, but we decided to use more abstracted
form for consistency with the other config items. "disabled-on-external-mouse"
is added only to touchpads, but there might be other devices that support this
option.

I think "off" also applies to keyboards, but I'm not going to add the one
because we don't have libinput machinery for the keyboard config, and it's
unlikely that user wants to disable _all_ keyboards. OTOH, pointer devices can
be disabled per type. Perhaps, this should be revisited after implementing #371.
2024-05-29 16:41:03 +03:00
Yuya Nishihara f2ce84b243 Fix copy-paste error in scroll-method error message 2024-05-28 15:35:45 +03:00
rustysec ae7fb4c4f4 Add niri msg focused-output 2024-05-26 21:29:22 +04:00
Yuya Nishihara 4746a0da7d Add scroll-method property to pointer devices
My use case is to enable middle-button scroll on my keyboard with pointing
stick. The device is recognized as USB mouse.
2024-05-26 16:49:40 +03:00
Ivan Molodetskikh 2ac8d84034 Update Smithay (NVIDIA 555 fix) 2024-05-24 16:47:55 +04:00
Micah N Gorrell eb0f7aa429 Added actions to allow focusing up or down as normal but to wrap to the column to the left or right if there is no window above or below 2024-05-24 16:44:20 +04:00
Ivan Molodetskikh bcca03cce7 Increase RLIMIT_NOFILE to maximum
Fixes Xwayland + RustRover crashing.

See similar changes:
* https://gitlab.gnome.org/GNOME/mutter/-/merge_requests/2235
* https://github.com/swaywm/sway/pull/6629
2024-05-23 09:59:34 +04:00
Ivan Molodetskikh efb39e466b default-config: Clarify spawn comments 2024-05-21 22:33:50 +04:00
Ivan Molodetskikh 14d637f4ef wiki: Mention left-handed 2024-05-21 11:06:52 +04:00
Ivan Molodetskikh c9d90afe59 Add left-handed input property
Closes https://github.com/YaLTeR/niri/issues/366
2024-05-21 10:10:11 +04:00
Ivan Molodetskikh d088ce248f wiki: Mention xwayland-satellite 2024-05-21 08:17:57 +04:00
Ivan Molodetskikh f4cdde1f4f Fix no outputs case handling in a few places 2024-05-20 15:36:08 +04:00
Ivan Molodetskikh 56e02a398d Add Default impl for niri_config::Keyboard
Fixes https://github.com/YaLTeR/niri/issues/357
2024-05-19 17:55:54 +04:00
lpnh 2552b129c4 refactor: make example ready to copy and paste 2024-05-18 20:17:39 +03:00
Ivan Molodetskikh d96a66ddff Update README 2024-05-18 15:00:39 +04:00
Ivan Molodetskikh bfaf9ae060 Bump version to 0.1.6 2024-05-18 14:35:42 +04:00
Ivan Molodetskikh 2da0aaace8 wiki: Update different-corner-radius image 2024-05-18 10:50:11 +04:00
Ivan Molodetskikh ee12bbc9ed wiki: Change two instances of Telegram to Fractal 2024-05-18 09:44:48 +04:00
Ivan Molodetskikh cc4026f588 wiki: Add since to interactive resize 2024-05-18 08:59:11 +04:00
Ivan Molodetskikh aa74120143 wiki: Fix typo 2024-05-18 08:50:17 +04:00
Ivan Molodetskikh 473ef22de2 Redraw on lock surface children commits 2024-05-17 15:59:49 +04:00
Ivan Molodetskikh d76b213e03 Update Smithay (session-lock fix) 2024-05-17 15:49:02 +04:00
Ivan Molodetskikh 4dc7a6ceb8 Rearrange CLI subcommands a bit 2024-05-17 10:33:00 +03:00
rustysec 36d3e70f11 Implement niri msg workspaces 2024-05-17 10:33:00 +03:00
Ivan Molodetskikh a2f74c9bff Update Smithay (buffer leak and crash fix) 2024-05-17 07:54:56 +04:00
Ivan Molodetskikh 0ce08b598c Bump package versions 2024-05-16 18:04:18 +04:00
Ivan Molodetskikh ae63773737 Update Smithay and other deps 2024-05-16 18:00:28 +04:00
Ivan Molodetskikh c5ca412829 wiki: Add since to named workspaces 2024-05-16 13:04:51 +04:00
Ivan Molodetskikh cbfc682f9a Implement at-startup window rule 2024-05-16 12:27:09 +04:00
Ivan Molodetskikh c64d9e5223 Fix missing check in Match PartialEq 2024-05-16 12:27:09 +04:00
Ivan Molodetskikh 4e31f7e047 wiki: Document named workspaces 2024-05-16 01:24:34 -07:00
Ivan Molodetskikh 109d99fe82 Make workspace names case-insensitive 2024-05-16 01:24:34 -07:00
Gergely Nagy eb9bbe3352 Implement named workspaces
This is an implementation of named, pre-declared workspaces. With this
implementation, workspaces can be declared in the configuration file by
name:

```
workspace "name" {
  open-on-output "winit"
}
```

The `open-on-output` property is optional, and can be skipped, in which
case the workspace will open on the primary output.

All actions that were able to target a workspace by index can now target
them by either an index, or a name. In case of the command line, where
we do not have types available, this means that workspace names that
also pass as `u8` cannot be switched to by name, only by index.

Unlike dynamic workspaces, named workspaces do not close when they are
empty, they remain static. Like dynamic workspaces, named workspaces are
bound to a particular output. Switching to a named workspace, or moving
a window or column to one will also switch to, or move the thing in
question to the output of the workspace.

When reloading the configuration, newly added named workspaces will be
created, and removed ones will lose their name. If any such orphaned
workspace was empty, they will be removed. If they weren't, they'll
remain as a dynamic workspace, without a name. Re-declaring a workspace
with the same name later will create a new one.

Additionally, this also implements a `open-on-workspace "<name>"` window
rule. Matching windows will open on the given workspace (or the current
one, if the named workspace does not exist).

Signed-off-by: Gergely Nagy <niri@gergo.csillger.hu>
2024-05-16 01:24:34 -07:00
Ivan Molodetskikh 229ca90507 wiki: Mention where to find shader compile warnings 2024-05-15 22:15:39 +04:00
Ivan Molodetskikh 17a71bd424 wiki: Add expanding circle example to window-open 2024-05-15 21:24:18 +04:00
Ivan Molodetskikh a39aaa312d wiki: Add fall_and_rotate window-close custom shader example 2024-05-15 20:55:16 +04:00
Ivan Molodetskikh 3f802d0193 Clarify surface destroyed comment 2024-05-15 20:30:02 +04:00
Ivan Molodetskikh df36eac25b Fix render elements looking off on screenshots 2024-05-15 20:09:49 +04:00
Ivan Molodetskikh 609b1a02d0 Change resize shader geo size to logical pixels
Consistent with the others.
2024-05-15 19:52:11 +04:00
Ivan Molodetskikh 5335ef454b Implement custom shader for window-open 2024-05-15 19:38:29 +04:00
Ivan Molodetskikh 496cd59df9 Use correct function name in comment 2024-05-15 16:51:43 +04:00
Ivan Molodetskikh 3e385d5c48 Clear fd flags before sending selection 2024-05-15 16:49:46 +04:00
Ivan Molodetskikh b87fba2182 tty: Relax device checks on removal 2024-05-15 08:14:09 +04:00
Ivan Molodetskikh 3d63f5e644 tty: Try harder to find a GBM device 2024-05-15 08:13:56 +04:00
Ivan Molodetskikh 1096f0cf0e wiki: Mention kmsro in getting started 2024-05-15 00:30:20 +04:00
Ivan Molodetskikh 78978219a0 tty: Relax primary render node check 2024-05-14 23:39:22 +04:00
Ivan Molodetskikh 5999ba6a5e Avoid changing the view offset if size didn't change 2024-05-14 23:39:19 +04:00
Ivan Molodetskikh 94a9b48a0f Improve interactive resize end edge cases and animations 2024-05-14 20:41:10 +04:00
Ivan Molodetskikh d776ab7763 Fix interactive resize cancelling
The interactive resize may have ended, but we're still waiting for the
last commit of the respective window. When cancelling, we should cancel
those ones too.
2024-05-14 16:29:03 +04:00
Ivan Molodetskikh 5f40221051 Refactor column and tile offsets, fix a few issues 2024-05-14 15:35:43 +04:00
Ivan Molodetskikh b14405904a Draw closing windows in the right order 2024-05-14 14:52:13 +04:00
Ivan Molodetskikh e06776c5d4 wiki: Expand design principles a bit 2024-05-13 08:35:19 +04:00
Ivan Molodetskikh 55e550262d wiki: Fix custom shader examples 2024-05-12 10:08:06 +04:00
Ivan Molodetskikh e5ccc9332c wiki: Fix shader example links 2024-05-12 10:06:26 +04:00
Ivan Molodetskikh 36a54615ca Add crossfade_or_crop_next resize shader example 2024-05-12 09:56:11 +04:00
Ivan Molodetskikh 9004c83954 Implement custom shader for window-close anim 2024-05-12 09:52:36 +04:00
Ivan Molodetskikh 29c7552852 Add linear animation curve 2024-05-12 09:50:16 +04:00
Ivan Molodetskikh d2ed42a157 closing_window: Pass geo size and view rect 2024-05-12 08:46:02 +04:00
Ivan Molodetskikh 4073f9f522 closing_window: Remove starting_alpha/scale 2024-05-12 08:42:43 +04:00
Ivan Molodetskikh 464441f9eb closing_window: Store textures directly 2024-05-11 17:54:27 +04:00
Ivan Molodetskikh bc29256b9d Implement Mod+MMB view offset gesture 2024-05-11 14:02:37 +04:00
Ivan Molodetskikh beba87354a Group input-related things in a subfolder 2024-05-11 13:21:05 +04:00
Ivan Molodetskikh 078724369d wiki: List debug key binds 2024-05-11 12:56:34 +04:00
Ivan Molodetskikh 75393faca3 wiki: Add a few missing things 2024-05-11 12:55:18 +04:00
Ivan Molodetskikh 22cdd044d3 Reset double click timer on gesture trigger 2024-05-11 11:21:57 +04:00
Ivan Molodetskikh 719270854a Update resize commit unconditionally 2024-05-11 10:59:46 +04:00
Ivan Molodetskikh 8900960e76 Don't pass double-resize-right click to window 2024-05-11 10:52:21 +04:00
TheZoq2 47a8e75fd5 Add is_active_in_column
Add missing ```

Fix tests
2024-05-11 10:42:49 +04:00
Ivan Molodetskikh 6d9cfe2882 Don't start a resize if edges is empty 2024-05-11 10:30:51 +04:00
Ivan Molodetskikh de0ad85711 Set cursor for niri-initiated interactive resize 2024-05-11 10:28:38 +04:00
Ivan Molodetskikh f091e64b12 wiki: Add gestures page 2024-05-11 10:09:49 +04:00
Ivan Molodetskikh e454cd6282 Implement double-resize-click to reset height/toggle full width 2024-05-11 10:02:48 +04:00
Ivan Molodetskikh 1c14a0a2a9 Add a reset-window-height action 2024-05-11 09:33:23 +04:00
Ivan Molodetskikh 2fd9a03bd7 Stop confining the pointer during resize grab 2024-05-11 09:26:49 +04:00
Ivan Molodetskikh b101f9b5f8 Render tiles flush to the right when left-resizing
This really needs a refactor...
2024-05-11 09:00:03 +04:00
Ivan Molodetskikh 34bcc6ea93 Split get resize data from update 2024-05-11 08:26:49 +04:00
Ivan Molodetskikh 9dfa121b8e Implement interactive mouse resizing 2024-05-10 20:23:08 +04:00
Ivan Molodetskikh c4ebb9f58e Start Tracy manual-lifetime after niri msg 2024-05-09 11:08:15 +04:00
Ivan Molodetskikh 38e329aab9 Make async-channel non-optional 2024-05-08 08:57:37 +04:00
Ivan Molodetskikh 95a1a01fdc wiki: Add Since to do-screen-transition 2024-05-08 08:43:01 +04:00
Ivan Molodetskikh c61940c40e ipc: Wait until action is processed before returning 2024-05-08 08:30:49 +04:00
Ivan Molodetskikh ed2b6d3894 Mark screen transition texture transparent 2024-05-08 08:21:15 +04:00
Ivan Molodetskikh 47925948a3 Add trace span to do_screen_transition 2024-05-08 08:21:04 +04:00
Ivan Molodetskikh 5248e53499 Implement do-screen-transition action 2024-05-07 22:19:11 +04:00
Ivan Molodetskikh 9847a652af ipc: Respect --json for msg output 2024-05-05 13:08:29 +04:00
Ivan Molodetskikh 96823eea38 Make output name matching case-insensitive 2024-05-05 12:55:57 +04:00
Ivan Molodetskikh ea59091869 Print message when output was not found 2024-05-05 12:50:18 +04:00
Ivan Molodetskikh 2e4a2e13b1 Make missing scale = automatic selection
That was the intention, but I missed it before.
2024-05-05 12:39:20 +04:00
Ivan Molodetskikh df0ee996ee Don't unwrap client
If Smithay posts an error, client will become None immediately, even
while the surface may still receive events.
2024-05-05 11:14:46 +04:00
Ivan Molodetskikh 65b9c74f62 Implement niri msg output 2024-05-05 10:19:47 +04:00
Ivan Molodetskikh 2dff674470 Don't expand zero radius per corner
So that radii like 8 8 0 0 look properly.
2024-05-05 07:43:21 +04:00
Ivan Molodetskikh 23850e1c60 wiki: Try to fix link 2024-05-04 21:16:43 +04:00
Ivan Molodetskikh 641b44e006 Fix blocked-out surfaces on scaled outputs 2024-05-04 20:13:53 +04:00
Ivan Molodetskikh 1394afaae9 wiki: Mention nixos and nvidia issues in getting started 2024-05-04 16:27:14 +04:00
Ivan Molodetskikh 314ad9d3e5 Fix rounded corners on blocked-out resizes 2024-05-04 11:54:52 +04:00
Ivan Molodetskikh 99eb1227b1 Extract RenderTarget::should_block_out() 2024-05-04 11:51:27 +04:00
Ivan Molodetskikh 79093baeee Extract rules out 2024-05-04 11:45:39 +04:00
Ivan Molodetskikh 7093385b4d Update tile before taking unmap snapshot 2024-05-04 11:37:58 +04:00
Ivan Molodetskikh 3748f6cd6a Fix border/focus ring options not applying right away 2024-05-04 11:11:01 +04:00
Ivan Molodetskikh 73cc0079d6 Split update_render_elements() from advance_animations()
advance_animations() is called from places like input, whereas
update_render_elements() is strictly for rendering.
2024-05-04 11:10:02 +04:00
Ivan Molodetskikh 69aeba2a4d shader_element: Store and set location separately 2024-05-04 09:49:32 +04:00
Ivan Molodetskikh 7aab413048 shader_element: Remove size
It's not actually needed.
2024-05-04 09:15:17 +04:00
Ivan Molodetskikh 74996a2416 Make BorderRenderElement scale-agnostic 2024-05-03 21:49:47 +04:00
Ivan Molodetskikh 8ab50f9d1c shader_element: Store program type instead of shader 2024-05-03 21:23:32 +04:00
Ivan Molodetskikh 5c32031111 shader_element: Make shader optional
The element is long-lived, but the shader itself isn't.
2024-05-03 20:20:36 +04:00
Ivan Molodetskikh 85680a57da Reduce unnecessary damage to borders 2024-05-03 13:46:33 +04:00
Ivan Molodetskikh 1a8d6b1f1d Add a semi-working debug-toggle-damage binding 2024-05-03 10:33:31 +04:00
Ivan Molodetskikh 185f294200 wiki: Mention new debug option 2024-05-03 10:23:48 +04:00
Ivan Molodetskikh c6d64dae7a Add debug-toggle-opaque-regions 2024-05-02 17:52:06 +04:00
Ivan Molodetskikh 5dddc850fc wiki: Clarify getting started 2024-05-02 14:27:53 +04:00
Ivan Molodetskikh 2f42f8ac75 Damage window on corner radius changes 2024-05-02 14:27:53 +04:00
Ivan Molodetskikh 42cef79c69 Implement rounded window corners 2024-05-02 14:27:53 +04:00
Ivan Molodetskikh d86df5025c Add Tracy span to Tile::render_inner 2024-05-01 19:04:47 +04:00
Ivan Molodetskikh 9309b3be61 Split rendering between popups and window surface 2024-05-01 19:04:11 +04:00
Ivan Molodetskikh c5be2dd549 Add Tracy span to Tile::render 2024-05-01 19:00:54 +04:00
Ivan Molodetskikh 365dbacae7 Move unmap snapshot from Mapped to Tile 2024-05-01 19:00:19 +04:00
Ivan Molodetskikh af9caa1d9b wiki: Warn against --all-features in getting started 2024-05-01 12:10:38 +04:00
Michael Forster 68ff36f683 Add libXcursor and libXi to nix flake
In my tests this was necessary to develop Niri using non-NixOS Nix.
Otherwise Niri panics with this error message: called `Result::unwrap()`
on an `Err` value: EventLoopCreation(NotSupported(NotSupportedError)).
2024-04-30 02:19:28 -07:00
Ivan Molodetskikh c0d5001e90 Update Smithay 2024-04-29 14:27:38 +04:00
Ivan Molodetskikh f3ded0c2e6 Move shader get out of ResizeRenderElement::new 2024-04-29 14:27:38 +04:00
Ivan Molodetskikh f43fa55526 Fix fullscreen backdrop rendering below focus ring 2024-04-28 06:48:48 +04:00
Ivan Molodetskikh c1c43c5393 Fix size_curr_geo in resize shader 2024-04-27 13:12:21 +04:00
Ivan Molodetskikh 5899010c96 Extract mat3_uniform 2024-04-27 13:11:25 +04:00
Ivan Molodetskikh 9f3715b731 Add distro to issue template 2024-04-27 07:44:51 +04:00
Ivan Molodetskikh 8d99e3c015 Add disable-direct-scanout debug flag 2024-04-25 22:10:52 +04:00
Ivan Molodetskikh 9df71bcb5d Add fixme comment 2024-04-25 08:48:35 +04:00
Ivan Molodetskikh 04c5b9ad74 Only give keyboard focus to exclusive layer-shell surfaces
Workaround until we properly support on-demand.

See: https://github.com/YaLTeR/niri/issues/308
2024-04-25 08:43:37 +04:00
Ivan Molodetskikh fd6c8c7790 Implement focus-ring window rule 2024-04-24 22:17:53 +04:00
Ivan Molodetskikh 3e598c565e Implement border window rule 2024-04-24 22:01:26 +04:00
Ivan Molodetskikh e261b641ed Filter out the Intel CCS modifiers 2024-04-24 12:26:59 +04:00
Ivan Molodetskikh dc1d2b706c Implement ideal scale factor guessing 2024-04-24 12:26:59 +04:00
Ivan Molodetskikh f9b008163c Fix spelling mistake 2024-04-23 00:09:42 -07:00
Kirill Chibisov 279659ac90 Unconstrain InputMethod's PopupSurface
Make IME popup to be visible inside the parent and not obscure the
text input rectangle region.

Fixes https://github.com/YaLTeR/niri/issues/221
2024-04-23 00:09:42 -07:00
Kirill Chibisov c2d03d82ce Use PopupKind instead of PopupSurface 2024-04-23 00:09:42 -07:00
Ivan Molodetskikh 5299590290 Improve cropping logic in resize shader example
The previous logic failed to the left of the geometry.
2024-04-22 22:37:47 +04:00
Ivan Molodetskikh 1681ed16d9 Change custom-shader to a prelude-epilogue system 2024-04-22 19:05:11 +04:00
Ivan Molodetskikh d4bed70884 Advertise Abgr8888 and Xbgr8888 in shm 2024-04-22 17:47:12 +04:00
Ivan Molodetskikh 49f5402669 Implement window-resize custom-shader 2024-04-21 20:16:54 +04:00
Ivan Molodetskikh 2ecbb3f6f8 Remove obsolete comment 2024-04-21 12:28:49 +04:00
Ivan Molodetskikh 6a80078259 README: Bring back NVIDIA issues note 2024-04-20 17:45:17 +04:00
Ivan Molodetskikh 303c51ee20 README: Update demo video 2024-04-20 17:30:35 +04:00
Ivan Molodetskikh 37a836f462 Bump version to 0.1.5 2024-04-20 16:55:39 +04:00
Ivan Molodetskikh 361ede4bcd wiki: Mention border background window rule in the FAQ 2024-04-20 16:52:51 +04:00
Ivan Molodetskikh 4fc80124ad Move info from README to Getting Started wiki page 2024-04-20 11:24:33 +04:00
Ivan Molodetskikh ba44aeda4a wiki: Add a FAQ page 2024-04-20 10:24:20 +04:00
sodiboo b5f7e4bd83 niri_ipc::Socket; niri msg version; version checking on IPC (#278)
* Implement version checking in IPC

implement version checking; streamed IPC

streamed IPC will allow multiple requests per connection

add nonsense request

change inline struct to json macro

only check version if request actually fails

fix usage of inspect_err (MSRV 1.72.0; stabilized 1.76.0)

"nonsense request" -> "return error"

oneshot connections

* Change some things around

* Unqualify niri_ipc::Transform

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-04-19 13:02:32 +00:00
Ivan Molodetskikh b98b95883d wiki: Attempt to fix broken tip 2024-04-19 14:47:06 +04:00
Ivan Molodetskikh 568c35ff87 Synchronize column removal anim on consume left/right
Visible when consuming left/right when always-centered and differing
horizontal view anim.
2024-04-19 13:48:39 +04:00
Ivan Molodetskikh c4f600bded wiki: Add missing newline 2024-04-19 12:49:11 +04:00
Ivan Molodetskikh 2c8d1030ab Separate tile X and Y movement animations
Helps with the jank caused by lack of transactions when consuming to the
left/right. Resize triggers a few frames later and restarts the
movement. Now it only restarts the vertical and not the horizontal
movement.
2024-04-19 12:44:24 +04:00
Ivan Molodetskikh f51dd67f2d wiki: Add Since to allow-when-locked 2024-04-19 11:29:01 +04:00
Ivan Molodetskikh 3509de6fbf default-config: Add mic mute bind 2024-04-19 11:14:51 +04:00
Ivan Molodetskikh 0477986a0d wiki: Move overdamped spring warning higher 2024-04-19 10:50:30 +04:00
Ivan Molodetskikh 914237fa11 Add allow-when-locked=true spawn bind property 2024-04-19 10:49:46 +04:00
Ivan Molodetskikh 0b93c46ce8 animation: Scale initial velocity by slowdown 2024-04-18 21:55:01 +04:00
Ivan Molodetskikh 0fcd981b86 Fix crop + crossfade artifacts 2024-04-18 21:39:27 +04:00
Ivan Molodetskikh 5c4153e26b wiki: Add a warning about overdamped springs 2024-04-18 20:51:25 +04:00
Ivan Molodetskikh 4d010b7943 animation: Clamp spring value
I've had an overdamped spring return an extreme value and trip up
an integer overflow check.
2024-04-18 20:45:37 +04:00
Ivan Molodetskikh 65c342f2cb config: Rearrange animations in struct 2024-04-18 17:36:12 +04:00
Ivan Molodetskikh 47f6c85f64 Preserve tile move config on animation restarts
This fixes a problem where consume-into-column would use resize
animation config instead of the window-movement config in most cases
(since a resize comes very shortly after the move starts).

A similar change to the column movement anim is more detrimental than
it's worth.
2024-04-18 00:30:12 +04:00
Ivan Molodetskikh 3b37f1a557 Sync expel animations 2024-04-17 18:03:17 +04:00
Ivan Molodetskikh dee0abb713 wiki: Clarify animations 2024-04-17 15:10:42 +04:00
Ivan Molodetskikh bbb4a64126 Use correct animation config for tile removal 2024-04-17 14:38:34 +04:00
Ivan Molodetskikh dfe49aa705 Use movement anim for view anim during movement 2024-04-17 14:29:22 +04:00
Ivan Molodetskikh 7ca39baf9e Add view anim functions with config argument 2024-04-17 14:23:47 +04:00
Ivan Molodetskikh 73e9ef5fe2 Resolve animation defaults during parsing 2024-04-17 14:06:32 +04:00
Ivan Molodetskikh c40d4f3268 Include resized window in left move 2024-04-17 10:35:46 +04:00
Ivan Molodetskikh 1b496ee21f Clamp animated window size 2024-04-16 17:44:06 +04:00
Ivan Molodetskikh bde46dab52 wiki: Mention consume/expel in window-movement anims 2024-04-16 11:02:21 +04:00
Ivan Molodetskikh 21ef5aded8 Remove jumps on consume/expel animation start 2024-04-16 10:48:54 +04:00
Ivan Molodetskikh b288102866 Implement consume/expel animations 2024-04-16 09:58:39 +04:00
Ivan Molodetskikh ff42f9b9d3 Start move animations from add/remove window/column 2024-04-16 08:59:15 +04:00
Ivan Molodetskikh c163e58167 Animate movement and resize on window closing in a column 2024-04-16 08:16:34 +04:00
Ivan Molodetskikh a9094b43d4 wiki: Mention niri msg outputs for VRR 2024-04-16 07:56:32 +04:00
Ivan Molodetskikh 9e33320b11 wiki: Clarify window-movement animation 2024-04-15 23:07:14 +04:00
Ivan Molodetskikh c40de5364d Add vrr_supported/enabled to output IPC 2024-04-15 22:29:25 +04:00
Ivan Molodetskikh 69f723d68a Implement vertical window move animations 2024-04-15 21:19:09 +04:00
Ivan Molodetskikh 568fbe26fe Avoid continuous redrawing during horizontal gesture 2024-04-14 14:29:41 +04:00
Ivan Molodetskikh f8412ecff3 wiki: Add since to VRR 2024-04-14 13:15:52 +04:00
Ivan Molodetskikh 3c6d8062c5 Add variable-refresh-rate flag 2024-04-14 09:37:42 +04:00
Ivan Molodetskikh 40374942db tty: Shorten non-desktop check 2024-04-14 08:08:09 +04:00
Ivan Molodetskikh 2c873044e8 Restore view offset upon unfullscreening 2024-04-13 20:07:37 +04:00
Ivan Molodetskikh 1336a581a6 tile: Fix returned snapshot size 2024-04-13 18:05:56 +04:00
Ivan Molodetskikh 8b0dc1902c Set window-resize animation config for view-offset anim caused by resize 2024-04-13 14:57:55 +04:00
Ivan Molodetskikh 9d5f1c7ef7 Unify Animation- and RenderSnapshot 2024-04-13 14:16:07 +04:00
Ivan Molodetskikh 71be19b234 Implement window resize animations 2024-04-13 11:07:23 +04:00
Ivan Molodetskikh 4fd9300bdb Fix typo 2024-04-13 10:58:32 +04:00
Ivan Molodetskikh 2bb6dd8c48 Move unmapped check to a pre-commit hook 2024-04-13 09:12:32 +04:00
Ivan Molodetskikh 7319f37f7a Add render_to_encompassing_texture() 2024-04-12 20:38:51 +04:00
Ivan Molodetskikh 0cd149c939 animation: Tweak clamped duration logic 2024-04-10 12:09:54 +04:00
Ivan Molodetskikh 5383a0591f Use clamped animations where it makes sense 2024-04-10 11:28:49 +04:00
Ivan Molodetskikh 0c68609063 animation: Implement clamped value and duration 2024-04-10 11:28:02 +04:00
Ivan Molodetskikh 6cd3f96a10 Fix building on stable 2024-04-10 09:26:56 +04:00
Ivan Molodetskikh 1888696567 Reimplement window closing anim in an efficient way
- Keep a root surface cache to be accessible in surface destroyed()
- Only snapshot during / right before closing, rather than every frame
- Store textures rather than elements to handle scale and alpha properly
2024-04-10 09:14:04 +04:00
Ivan Molodetskikh b9e789619f wiki: Fix wrong since annotation spot 2024-04-09 23:56:40 +04:00
Ivan Molodetskikh dd011f1012 Implement window closing animations 2024-04-09 23:42:01 +04:00
Ivan Molodetskikh 301a2c0661 layout: Fix view jumps when removing a window on the left 2024-04-09 23:42:01 +04:00
Ivan Molodetskikh 956bf7c0a8 Add missing mouse warp to commit unmap 2024-04-09 23:42:01 +04:00
Ivan Molodetskikh 209492e700 Add ease-out-quad curve 2024-04-09 23:42:01 +04:00
Ivan Molodetskikh 7e0d3d31f7 Update Smithay 2024-04-09 19:06:13 +04:00
Ivan Molodetskikh e448cfb0ef Adjust view offset anim together with offset
Not doing this caused quickly moving a column right and left to base the
final view position on an incorrect view offset.
2024-04-08 22:16:35 +04:00
Ivan Molodetskikh 6aceb3a798 Render active column in front
Rather than just the active window. This is visible on the new window
movement animations.
2024-04-08 19:48:52 +04:00
Ivan Molodetskikh 4856522a7a Implement window open shift in terms of window-movement
This removes the quite unobvious visual size, and fixes jerking when
opening multiple windows in quick succession.
2024-04-08 19:25:45 +04:00
Ivan Molodetskikh c1432bfa96 Implement column movement animation 2024-04-08 19:11:25 +04:00
Ivan Molodetskikh ec0531264e Avoid move_left() in expel-left 2024-04-08 19:11:25 +04:00
Ivan Molodetskikh 03fc439150 layout: Fix view_offset value when moving column 2024-04-08 17:34:39 +04:00
Ivan Molodetskikh 83aec41df3 Hide pointer on touch interaction 2024-04-06 10:57:12 -07:00
Ivan Molodetskikh 8be9381974 wiki: Add gamescope to the Xwayland page 2024-04-03 17:21:36 +04:00
Ivan Molodetskikh dc56f9885c wiki: Improve Xwayland page 2024-04-03 17:16:53 +04:00
Ivan Molodetskikh 2b3a80b477 wiki: Document IPC backwards compatibility 2024-04-02 09:08:36 +04:00
Ivan Molodetskikh 294f16f76c Fix typo in comment 2024-04-02 08:44:08 +04:00
Ivan Molodetskikh 4f56ff16f9 Fix and add missing calls to DRM leasing 2024-04-01 08:30:27 +04:00
Ivan Molodetskikh fe79a6a4e2 Clarify PipeWire error message 2024-03-31 11:36:04 +04:00
Ivan Molodetskikh 950fcf6328 Set SIGPIPE to SIG_DFL before printing in niri msg 2024-03-31 09:10:15 +04:00
Ivan Molodetskikh 7ff2de19b9 wiki: Update block-out-from-screencast img 2024-03-30 13:25:54 +04:00
Ivan Molodetskikh f81b51f4c0 Bump version to 0.1.4 2024-03-30 11:39:12 +04:00
Ivan Molodetskikh a90221d924 Fix crash when stopping screencast session twice 2024-03-30 10:50:02 +04:00
Ivan Molodetskikh ab22816521 wiki: Fix default config link 2024-03-29 14:23:28 +04:00
Ivan Molodetskikh 56a55f1ad1 Improve README 2024-03-29 14:20:51 +04:00
Ivan Molodetskikh f7fde74a8d input: Add Tracy span to notify activity 2024-03-29 14:13:08 +04:00
Ivan Molodetskikh 0470a833a1 Move IPC into wiki 2024-03-29 14:13:01 +04:00
Ivan Molodetskikh 092420ec5a tty: Try to proceed when can't get render node
This is a workaround that should make split display/render devices work.
2024-03-29 09:09:33 +04:00
Ivan Molodetskikh f46e937949 wiki: Improvements 2024-03-28 21:07:48 +04:00
Ivan Molodetskikh c9a47f8283 wiki: Mention creating screenshot directory 2024-03-28 21:01:26 +04:00
Ivan Molodetskikh 9b7ed57d37 Create screenshot directory if it doesn't exist 2024-03-28 20:59:42 +04:00
Ivan Molodetskikh cf409a4ea6 wiki: Link all sections from the overview 2024-03-28 20:53:26 +04:00
Ivan Molodetskikh 83bd2317ee wiki: Add miscellaneous 2024-03-28 20:53:15 +04:00
Ivan Molodetskikh 0f19003611 default-config: Link layout wiki 2024-03-28 20:48:27 +04:00
Ivan Molodetskikh 470d65a060 wiki: Improve Layout 2024-03-28 17:50:34 +04:00
Ivan Molodetskikh 4f421907cd wiki: Add Layout 2024-03-28 17:35:36 +04:00
Ivan Molodetskikh b4eaaed19e Upgrade dependencies 2024-03-28 17:35:27 +04:00
Ivan Molodetskikh d3d178fac7 wiki: Mention niri msg focused-window 2024-03-28 13:47:27 +04:00
Ivan Molodetskikh 3091102365 Implement niri msg focused-window 2024-03-28 13:45:24 +04:00
Ivan Molodetskikh a7b3819214 tty: Add check for zero gamma size 2024-03-28 07:47:57 +04:00
Ivan Molodetskikh 1eff5aeb75 wiki: Add one more bind example 2024-03-27 21:48:19 +04:00
Ivan Molodetskikh 9f0566b1ab wiki: Fix em-dash 2024-03-27 21:47:08 +04:00
Ivan Molodetskikh 3c75082df2 wiki: Add key bindings 2024-03-27 21:46:11 +04:00
Ivan Molodetskikh 9927c15f68 Replace config transform with ipc 2024-03-27 17:03:17 +04:00
Ivan Molodetskikh cf87a185a9 Add logical output info and preferred modes to IPC 2024-03-27 14:54:24 +04:00
Ivan Molodetskikh e276c906bf Expose more info in DisplayConfig impl
Needed for the new xdp-gnome.
2024-03-27 09:46:18 +04:00
Ivan Molodetskikh 571768af43 Make ipc_outputs Arc Mutex 2024-03-27 08:27:14 +04:00
Ivan Molodetskikh c09d5eb048 wiki: Clarify refresh rate in outputs 2024-03-26 21:29:47 +04:00
Ivan Molodetskikh 1a3e31a5cf wiki: Fix order in outputs 2024-03-26 21:28:09 +04:00
Ivan Molodetskikh 62f14d42dc wiki: Add outputs section 2024-03-26 21:26:43 +04:00
Ivan Molodetskikh ce644852d2 wiki: Fix wording in Animations 2024-03-26 21:02:07 +04:00
Ivan Molodetskikh ffe9a03b58 wiki: Remove anchored link from debug page
The github wiki action rewriter can't deal with them.
2024-03-26 20:01:37 +04:00
Ivan Molodetskikh 3c84de5215 wiki: Document debug options 2024-03-26 19:53:58 +04:00
Ivan Molodetskikh cd555bbad7 wiki: Clarify config breaking change between releases 2024-03-26 19:40:23 +04:00
Ivan Molodetskikh 287d9b6b3f wiki: Clarify breaking change policy 2024-03-26 18:47:16 +04:00
Ivan Molodetskikh 9bd812c37a wiki: Add config breaking change policy 2024-03-26 18:44:42 +04:00
Ivan Molodetskikh 0845eef326 wiki: Add easing example 2024-03-26 18:35:48 +04:00
Ivan Molodetskikh 4d8cb3a6e3 wiki: Add animations page 2024-03-26 18:33:53 +04:00
Ivan Molodetskikh 48b009ba63 CI: Depend on a later commit of the github wiki action 2024-03-26 17:32:06 +04:00
Ivan Molodetskikh addd1f5267 wiki: Replace links with relative 2024-03-26 17:24:17 +04:00
Ivan Molodetskikh b30f8fb2cc wiki: Use relative links in sidebar 2024-03-26 17:21:40 +04:00
Ivan Molodetskikh f5c97faf4a wiki: Improve window rules formatting 2024-03-26 13:35:37 +04:00
Ivan Molodetskikh 8f1bbea863 wiki: Expand fullscreen rule example 2024-03-26 13:25:01 +04:00
Ivan Molodetskikh 5e7eafb2fd wiki: Add is-focused example 2024-03-26 13:21:20 +04:00
Ivan Molodetskikh 41b13aa881 wiki: Expand window rules 2024-03-26 13:18:30 +04:00
Ivan Molodetskikh fd7f2287f0 wiki: Clarify Overview 2024-03-26 13:18:18 +04:00
Ivan Molodetskikh 1635337504 wiki: Clarify screenshot UI blocking out 2024-03-26 11:25:09 +04:00
Ivan Molodetskikh b677592f11 wiki: Mention inability to unset rule 2024-03-26 11:17:40 +04:00
Ivan Molodetskikh ad2795bb27 wiki: Clarify window rule matching example 2024-03-26 11:11:26 +04:00
Ivan Molodetskikh 7826003a81 wiki: Sets->Set for consistency 2024-03-26 11:05:47 +04:00
Ivan Molodetskikh 768fbea14d CI: Download LFS files in publish-wiki 2024-03-26 10:55:10 +04:00
Ivan Molodetskikh e46003f91f default-config: Delete some input and window rule settings
Replace them with links to the wiki.
2024-03-26 10:49:49 +04:00
Ivan Molodetskikh 5360ddb320 wiki: Fix missing backtick 2024-03-26 10:44:23 +04:00
Ivan Molodetskikh d4b271fead wiki: Document window rules 2024-03-26 10:40:19 +04:00
Ivan Molodetskikh de6685f3ab wiki: Add missing commas 2024-03-26 08:21:58 +04:00
Ivan Molodetskikh 662e2df0e1 wiki: Clarify auto back and forth like in flake docs 2024-03-26 08:19:18 +04:00
Ivan Molodetskikh 26c4824047 wiki: Input and more Overview 2024-03-26 08:12:55 +04:00
Ivan Molodetskikh 78dbb2308e wiki: Start writing input configuration 2024-03-25 22:51:21 +04:00
Ivan Molodetskikh 1dce99352e wiki: Fix links 2024-03-25 21:56:37 +04:00
Ivan Molodetskikh 0b6d62f65e wiki: Add configuration overview 2024-03-25 21:50:21 +04:00
Ivan Molodetskikh cf54f75113 Move wiki into the main repository 2024-03-25 21:16:03 +04:00
Ivan Molodetskikh 0d90876ad8 CI: Disable checkout progress from nix 2024-03-25 21:13:23 +04:00
Ivan Molodetskikh e5bd1113ba default-config: Make example use screen-capture blocking 2024-03-24 11:42:27 +04:00
Ivan Molodetskikh 6f765db44e default-config: Clarify interactivity in block-out-from "screen-capture" 2024-03-24 11:37:07 +04:00
Ivan Molodetskikh 5f23d344d5 Make screenshot UI render target-aware 2024-03-24 11:25:48 +04:00
Ivan Molodetskikh e43e10f44e Remove unnecessary reference 2024-03-24 11:11:00 +04:00
Ivan Molodetskikh 493c8dc890 Implement block-out-from window rule, fix alpha on window screenshots 2024-03-24 10:22:56 +04:00
Ivan Molodetskikh 8b4a9d68e0 Implement opacity window rule 2024-03-24 08:30:26 +04:00
Ivan Molodetskikh a16a0f0e52 Implement TouchpadScroll binds 2024-03-23 20:30:45 +04:00
Ivan Molodetskikh 6ba195211b Rename WheelTracker to ScrollTracker 2024-03-23 20:17:01 +04:00
Ivan Molodetskikh afaaf36f27 Avoid scroll bind lookup until it is triggered 2024-03-23 19:20:44 +04:00
Ivan Molodetskikh f1b36b0dce Send pending configure after recomputing window rules 2024-03-23 18:57:06 +04:00
Ivan Molodetskikh 6ec65bc0d6 Add is-focused window rule matcher 2024-03-23 16:16:52 +04:00
Ivan Molodetskikh d65446421f Make rules non-pub 2024-03-23 16:04:35 +04:00
Ivan Molodetskikh 24078cfea2 Make need_to_recompute_rules non-pub 2024-03-23 16:02:23 +04:00
Ivan Molodetskikh 5cc2c31a5b Split State::refresh() to get a trace span 2024-03-23 15:45:44 +04:00
Ivan Molodetskikh b7ed2fb82a Add is-active window rule matcher 2024-03-23 15:45:44 +04:00
Ivan Molodetskikh f3f02aca20 Lift output clones from queue_redraw() 2024-03-23 15:45:44 +04:00
Ivan Molodetskikh 021a2a1af7 Don't use an idle for queued redraw tracking
This way we can order the redraw after all the refreshing, where it
should be.
2024-03-23 15:45:44 +04:00
Ivan Molodetskikh 354f0b039a Pass Un/Mapped to window rule resolution 2024-03-23 15:45:44 +04:00
Andreas Stührk d120e0c451 input: Add support for ISO level3 shift modifier
This modifier is typically called "AltGr" on keyboards or "Mod5" in xkb
layouts. Requires a Smithay update.
2024-03-23 15:45:27 +04:00
Ivan Molodetskikh 0f724f2011 Stop hardcoding "us" default layout
XKB has its own way to pick the default.
2024-03-23 10:10:01 +04:00
Ivan Molodetskikh 46131c87a5 default-config: Clarify that wheel binds are affected by natural-scroll 2024-03-23 09:02:50 +04:00
Ivan Molodetskikh c66319314e Fix vertical wheel binds on winit 2024-03-23 09:00:55 +04:00
Ivan Molodetskikh b09dbb80c7 [cfg-breaking] Rename Wheel* to WheelScroll* bindings
Less confusion, and clearer that they are affected by natural-scroll.
2024-03-23 08:49:58 +04:00
Ivan Molodetskikh 54e6a01284 Allow clippy false positive harder 2024-03-22 21:24:11 +04:00
Ivan Molodetskikh 7721e3fc44 Allow clippy false positive 2024-03-22 21:14:03 +04:00
Ivan Molodetskikh 0d2fdb49ef default-config: Add mouse wheel binds 2024-03-22 20:56:20 +04:00
Ivan Molodetskikh b06e51da60 Implement bind cooldown-ms 2024-03-22 20:47:40 +04:00
Ivan Molodetskikh 6c08ba307a input: Make functions return the whole bind 2024-03-22 20:47:35 +04:00
Ivan Molodetskikh 4b2fdd0776 Implement mouse wheel bindings 2024-03-22 13:10:40 +04:00
Ivan Molodetskikh 969519b5d8 input: Generalize bound_action() to Trigger 2024-03-22 11:11:45 +04:00
Ivan Molodetskikh a0c8c39b06 Make binds accept wheel names 2024-03-22 10:36:19 +04:00
Ivan Molodetskikh 977f1487c2 input: Fix discrete axis value on winit 2024-03-22 09:41:10 +04:00
Ivan Molodetskikh fbe021fbdf input: Rename discrete => v120 2024-03-22 09:35:17 +04:00
Ivan Molodetskikh db49deb7fd Implement draw-border-with-background window rule 2024-03-19 18:29:13 +04:00
Ivan Molodetskikh c61361de3c Implement window rule reloading and min/max size rules 2024-03-19 18:29:13 +04:00
Ivan Molodetskikh 3963f537a4 Wrap mapped windows in a Mapped 2024-03-19 18:29:13 +04:00
Ivan Molodetskikh f31e105043 Make window a subdirectory 2024-03-19 18:29:13 +04:00
Ivan Molodetskikh bbb4caeb8c Remove remaining Window-specific functions 2024-03-19 18:29:13 +04:00
Ivan Molodetskikh d421e1fbf8 Move PartialEq from LayoutElement to an associated type 2024-03-19 18:29:13 +04:00
FluxTape 23ac3d7323 Workspace back and forth (#253)
* implement workspace back and forth

* Make our own ID counter instead of SerialCounter, use a newtype

* Rename FocusWorkspaceBackAndForth to FocusWorkspacePrevious

* Add focus-workspace-previous to tests

* Don't special case in switch_workspace_previous

* Minor clean up

* Add switch_workspace_auto_back_and_forth to tests

* Skip animation on switch_workspace_previous

* Preserve previous_workspace_id on workspace movement

* Make Workspace::id private with a getter

Reduce the chance it gets overwritten.

* Add test for workspace ID uniqueness

* Update previous workspace ID upon moving workspace across monitors

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-03-19 07:27:52 -07:00
Ivan Molodetskikh c3327d36da tty: Generalize DRM property helpers 2024-03-19 09:00:00 +04:00
Ivan Molodetskikh e0da101c73 Disable screencast when PipeWire is missing
This can cause a panic.
2024-03-19 08:59:28 +04:00
Ivan Molodetskikh 4740682904 README: Move configuration up 2024-03-18 19:36:18 +04:00
Ivan Molodetskikh df9d721f74 Implement focus-follows-mouse 2024-03-18 19:32:03 +04:00
Ivan Molodetskikh d970abead8 Keep track of output and window in PointerFocus separately 2024-03-18 19:32:03 +04:00
Ivan Molodetskikh 4f6ed9dfc9 Fix lock surface pointer location 2024-03-18 19:32:03 +04:00
Ivan Molodetskikh 84302796dc Take workspace switch gesture into account for visual rect 2024-03-18 19:31:11 +04:00
Ivan Molodetskikh a39e703fc3 Don't warp if currently using tablet
The tablet will override the position anyway.
2024-03-18 19:31:11 +04:00
Ivan Molodetskikh a55db6c6c4 Warp mouse to focus on window closing 2024-03-18 19:31:11 +04:00
Ivan Molodetskikh a011b385d8 Warp mouse to focus on new window appearing 2024-03-18 19:31:11 +04:00
Ivan Molodetskikh 2984722f80 Warp mouse only if layout is focused 2024-03-18 19:31:11 +04:00
Ivan Molodetskikh 118773e17d Track keyboard focus component 2024-03-18 19:31:11 +04:00
FluxTape 741bee461c Implement warp-mouse-to-focus 2024-03-18 19:31:11 +04:00
Ivan Molodetskikh 0c57815fbf Restore gamma on TTY switch back 2024-03-15 22:02:29 +04:00
Ivan Molodetskikh cf89c789c3 README: Link touchpad gestures to showcase video 2024-03-15 09:56:11 -07:00
Ivan Molodetskikh 642c6e7512 Store gamma changes to apply on session resume 2024-03-15 13:29:36 +04:00
Ivan Molodetskikh 6839a118bb Implement gamma adjustment via GAMMA_LUT property 2024-03-15 13:29:36 +04:00
Ivan Molodetskikh 9ae3cad82b gamma-control: Misc. clean ups and fixes 2024-03-15 13:29:36 +04:00
phuhl 89dfaa6cac Adds support for wlr_gamma_control_unstable_v1 protocol 2024-03-15 13:29:36 +04:00
Ivan Molodetskikh f6ffe8b3ab tty: Make binding EGL wl-display optional 2024-03-14 18:08:52 +04:00
la .uetcis cc83ff008d Add clickfinger in touchpad config (#256)
* Add clickfinger in touchpad config

* Change `clickfinger` to `click-method`

* Change `bottom_areas` to `button_areas`

* Change button_areas to button-areas

For consistency.

* Reorder click methods in error message

The most usual one comes first.

* default-config: Move click-method down

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-03-13 21:26:03 -07:00
Ivan Molodetskikh ba4e7481c3 default-config: Clarify how to power on monitors 2024-03-14 08:04:34 +04:00
Ivan Molodetskikh c15bc2a028 tty: Set max bpc to 8 2024-03-13 09:15:18 +04:00
Ivan Molodetskikh bf1cc98886 Update Smithay 2024-03-13 07:17:19 +04:00
Ivan Molodetskikh 5f137b77d3 Reapply "Add wp-viewporter"
This reverts commit 40cec34aa4.

The Chromium issues are now fixed.
2024-03-12 17:22:53 +04:00
Ivan Molodetskikh 128d573e74 Update Smithay (viewporter fixes) 2024-03-12 17:22:52 +04:00
Ivan Molodetskikh ed8a6afe80 Add a 1 Hz fallback frame callback timer
gamescope + Minecraft with NeoForge throws an error upon starting if
there are no frame callbacks, thus making it the first client that has a
problem. Also, apparently, Veloren disconnects from server with VSync
and no frame callbacks.
2024-03-12 10:42:09 +04:00
Ivan Molodetskikh 43aa2f95be Fix new clone_from Clippy lints 2024-03-12 10:42:09 +04:00
Ivan Molodetskikh 5c0a1f4d6f Fix spelling mistake 2024-03-12 10:42:09 +04:00
Ivan Molodetskikh 8c46611c29 Preserve view offset for activate_prev_column_on_removal 2024-03-10 17:59:10 +04:00
Ivan Molodetskikh 40cec34aa4 Revert "Add wp-viewporter"
This reverts commit 348690afb6.

Apparently this breaks input in Chromium: the input region won't resize
together with the window.
2024-03-10 17:59:10 +04:00
Ivan Molodetskikh 1971a41fdd utils/spawning: Pass grandchild PID only on systemd
libc::close_range() is not available on musl, so do this workaround for
now.
2024-03-09 18:37:11 +04:00
Ivan Molodetskikh 4ea90140d4 Fix warning on --no-default-features 2024-03-09 18:36:01 +04:00
Ivan Molodetskikh acd33653b3 README: Update screenshot 2024-03-09 14:45:18 +04:00
Ivan Molodetskikh f7c6516da7 README: Expand package listing 2024-03-09 14:29:20 +04:00
Ivan Molodetskikh b220420fba README: mention just "Touchpad gestures"
We've got both directions now.
2024-03-09 08:29:51 +04:00
Ivan Molodetskikh bbeaba16a0 Bump version to 0.1.3 2024-03-09 08:28:48 +04:00
Ivan Molodetskikh 9d7c39b89a Reposition outputs after potentially changing mode
Currently outputs aren't repositioned again after a mode change, which
can cause overlaps.
2024-03-09 08:23:57 +04:00
Ivan Molodetskikh 03fe864d07 Add xdg-foreign 2024-03-08 17:08:58 +04:00
Ivan Molodetskikh e45dbb8ef6 Pass through subpixel layout 2024-03-08 17:06:46 +04:00
Ivan Molodetskikh 5c4b71a5a4 Update Smithay and dependencies 2024-03-08 17:06:35 +04:00
Ivan Molodetskikh 348690afb6 Add wp-viewporter
Doesn't hurt I guess.
2024-03-08 16:52:54 +04:00
sodiboo ca22e70cc4 Implement wlr-screencopy v1 (#243)
* Implement wlr-screencopy

* Finish the implementation

Lots of changes, mainly to fix transform handling. Turns out, grim
expects transformed buffers and untransforms them by itself using info
from wl_output. This means that render helpers needed to learn how to
actually render transformed buffers.

Also, it meant that y_invert is no longer needed.

Next, moved the rendering to the Screencopy frame handler. Turns out,
copy() is more or less expected to return immediately, whereas
copy_with_damage() is expected to wait until the next VBlank. At least
that's the intent I parse reading the protocol.

Finally, brought the version from 3 down to 1, because
copy_with_damage() will need bigger changes. Grim still works, others
not really, mainly because they bind v3 unnecessarily, even if they
don't use the damage request.

---------

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-03-08 04:10:55 -08:00
Ivan Molodetskikh 1a784e6e66 Remove NOTIFY_FD after reading it 2024-03-06 23:06:39 +04:00
Ivan Molodetskikh 3ee2db71a4 CI: Check dinit feature 2024-03-06 21:01:10 +04:00
Ivan Molodetskikh cedfd4944c Adjust comments 2024-03-06 21:01:00 +04:00
metent 431f070481 Add dinit support (#246)
* Add dinit support

- Add --notify-fd cli flag for ready notifications
- Set dinit activation environment when "dinit" feature flag is enabled

* Make systemd and dinit environment activation additive

* Use NOTIFY_FD env variable instead of --notify-fd cli flag for sending ready notifications

* Format with rustfmt
2024-03-06 08:57:43 -08:00
Ivan Molodetskikh 9cbbffc23c Improve spring comments in default config 2024-03-05 19:06:21 +04:00
Ivan Molodetskikh c6a1398d51 Add fuzzel to generate-rpm requires 2024-03-05 13:40:57 +04:00
Ivan Molodetskikh f9127616b0 Implement rubber banding for the vertical gesture 2024-03-05 13:32:57 +04:00
Ivan Molodetskikh ae89b2e514 Implement spring animations 2024-03-05 13:32:52 +04:00
Ivan Molodetskikh 732f7f6f33 animation: Apply slowdown in realtime 2024-03-05 13:23:06 +04:00
Ivan Molodetskikh 8bebd54c6d tile: Prepare for oscillating animations 2024-03-05 10:33:25 +04:00
Ivan Molodetskikh 1978e5b0b8 monitor: Handle switch idx < 0 and >= len 2024-03-05 08:43:20 +04:00
Ivan Molodetskikh 60b02545f3 Move animation to subfolder 2024-03-04 16:01:57 +04:00
Ivan Molodetskikh 2750b2038b Catch panics from edid-rs
Work around an integer overflow.

See: https://github.com/YaLTeR/niri/issues/239
2024-03-03 19:56:52 +04:00
Ivan Molodetskikh c4145b014a Add proper support for center = always in the horizontal gesture 2024-03-03 12:10:25 +04:00
Ivan Molodetskikh 2e51efd3a3 Remake horizontal gesture to snap with inertia 2024-03-03 09:33:00 +04:00
Ivan Molodetskikh caea05433e Extract WORKSPACE_GESTURE_MOVEMENT constant 2024-03-03 09:25:27 +04:00
Ivan Molodetskikh e4f78c26f0 swipe-tracker: Rename retain_recent to trim_history 2024-03-03 08:04:55 +04:00
Ivan Molodetskikh 1548db56ce Fix vertical gesture constant
400 is for width not height.
2024-03-02 21:18:02 +04:00
Ivan Molodetskikh 5f416abcf9 Change horizontal gesture to focus furthest window 2024-03-02 15:48:54 +04:00
Ivan Molodetskikh 66c1272420 Use unaccelerated delta for vertical gesture
With inertia in place it's ready for this.
2024-03-02 15:41:56 +04:00
Ivan Molodetskikh e0ec6e5b11 Make vertical touchpad swipe inertial
Values and implementation are heavily inspired by AdwSwipeTracker.
2024-03-02 14:33:22 +04:00
Ivan Molodetskikh 93243d7772 Disentangle frame callback sequence from real DRM sequence
It can currently happen that the estimated VBlank timer fires right
before a real VBlank, which can cause some sequence collisions, which
might cause frame callbacks to never be sent. To prevent this, just
track the frame callback sequence fully separately. There isn't really
any harm in this, and if we accidentally increment it more frequently
than necessary then nothing terrible will happen.
2024-03-02 08:20:17 +04:00
sodiboo 24537ec2ba Correctly handle parsing of Binds and DefaultColumnWidth (#234)
* add dev dependencies to flake

* parse only one default-column-width

* require exactly one action per bind, and unique keys for binds

* use proper filename for config errors if possible

* fix duplicate keybinds after invalid action, lose some sanity
2024-03-01 03:50:49 -08:00
Ivan Molodetskikh 88ac16c99a tty: Bump sequence on successful queue_frame()
Before this commit:

- niri queues frame
- successful VBlank happens, sequence is bumped, frame callbacks are
  sent
- niri receives commit, redraws, queues next frame, tries to send frame
  callbacks, but there wasn't a new VBlank yet, so the sequence is old,
  and frame callbacks aren't sent
- frame callbacks are sent only next VBlank
2024-03-01 12:56:55 +04:00
Ivan Molodetskikh 0add457cf0 tty: Avoid zero estimated vblank timer 2024-03-01 08:27:44 +04:00
Ivan Molodetskikh 6e5426ef22 Fix center-column regression
Mistake introduced along with the horizontal gesture.
2024-03-01 08:09:03 +04:00
Ivan Molodetskikh 202406aadf Fix presentation feedback panic with zero presentation time 2024-03-01 07:55:09 +04:00
Ivan Molodetskikh 92d9c7ff4f Add emulate-zero-presentation-time debug flag 2024-03-01 07:54:58 +04:00
Ivan Molodetskikh 28977d1d3f Move workspace gesture into monitor & fix missing workspace cleanup 2024-02-29 09:51:49 +04:00
Ivan Molodetskikh ba10bab010 Implement horizontal touchpad swipe 2024-02-29 09:51:49 +04:00
Ivan Molodetskikh 55038b7c07 Pass prev_idx explicitly to animate_view_offset_to_column() 2024-02-29 08:30:46 +04:00
Ivan Molodetskikh 8018839f5d Extract animate_view_offset_to_column() 2024-02-28 17:23:03 +04:00
Ivan Molodetskikh 077f22edd6 Append _fit to animate_view_offset_to_column() 2024-02-28 17:21:08 +04:00
Ivan Molodetskikh 4f7c3300ef Upgrade dependencies 2024-02-28 13:45:12 +04:00
Ivan Molodetskikh 5628bf7d77 Update Smithay 2024-02-28 13:23:15 +04:00
Christian Meissl 719697179f input: add basic touch support 2024-02-28 13:19:41 +04:00
Christian Meissl 5ac350d51c chore: update smithay 2024-02-28 13:19:41 +04:00
Ivan Molodetskikh 494e98c123 Parse CSS colors in {in,}active-color 2024-02-26 09:14:35 +04:00
Ivan Molodetskikh ec156a8587 Add environment {} config section 2024-02-24 10:08:56 +04:00
Ivan Molodetskikh e278e871c3 Expand ~ in spawn 2024-02-24 09:16:44 +04:00
Ivan Molodetskikh ab9d1aab4e Add open-fullscreen window rule 2024-02-24 08:44:21 +04:00
Ivan Molodetskikh 506dcd99d7 Handle un-/fullscreen after initial configure 2024-02-23 17:47:12 +04:00
Ivan Molodetskikh dfbc024127 Rename surface -> toplevel 2024-02-23 17:40:30 +04:00
Ivan Molodetskikh eb2dce1b53 Fix default width fixed not being honored with borders 2024-02-23 14:40:56 +04:00
Ivan Molodetskikh f5b776a947 Fix unset default width causing a window resize right away 2024-02-23 14:31:35 +04:00
Ivan Molodetskikh 6a587245eb Add open-maximized window rule 2024-02-23 14:24:39 +04:00
Ivan Molodetskikh 2317021a7c Implement explicit unmapped window state tracking 2024-02-23 14:01:32 +04:00
Ivan Molodetskikh af6485cd8c Fix new warnings 2024-02-22 14:04:18 +04:00
Ivan Molodetskikh f32a25eefe Improve shader formatting 2024-02-22 10:21:38 +04:00
Ivan Molodetskikh aefbad0cf7 Simplify gradient border shader 2024-02-22 10:17:06 +04:00
Ivan Molodetskikh b091202d86 visual-tests: Add gradient angle and area tests 2024-02-22 08:54:35 +04:00
Ivan Molodetskikh 48f0f6fb3c Implement gradient borders 2024-02-21 22:15:21 +04:00
Ivan Molodetskikh 340bac0690 Remove unnecessary crop bounds during workspace switch 2024-02-21 21:41:12 +04:00
Ivan Molodetskikh d1b8134337 focus-ring: Store config instead of individual fields 2024-02-21 20:54:24 +04:00
Ivan Molodetskikh 646e3d8995 Accept location in FocusRing
Makes it work more like other elements.
2024-02-21 11:08:48 +04:00
Ivan Molodetskikh d1fe6930a7 Move UI elements into submodule 2024-02-21 10:50:30 +04:00
Ivan Molodetskikh 9e60b344d0 Move watcher to utils 2024-02-21 10:45:03 +04:00
Ivan Molodetskikh 2c01cde9be Move spawn to submodule 2024-02-21 10:42:21 +04:00
Ivan Molodetskikh cb9dc9c0cd Move utils to subfolder 2024-02-21 10:33:09 +04:00
Ivan Molodetskikh 73d2807b4b Fix move_window_to_output losing window instead 2024-02-21 09:39:32 +04:00
Ivan Molodetskikh 7d41f113cb Change non-bug error! to warn!
Be consistent with our usage.
2024-02-21 09:20:34 +04:00
Ivan Molodetskikh 63e5cf8798 Add missing qualified path 2024-02-21 09:12:42 +04:00
Ivan Molodetskikh 9ce19ad7de Use niri_render_elements! for the screenshot UI 2024-02-21 09:12:40 +04:00
Ivan Molodetskikh 751f79dc35 Comment out toggle-debug-tint default bind 2024-02-21 07:58:23 +04:00
Ivan Molodetskikh b8aa0a86e7 Fix debug tint desync for new outputs 2024-02-21 07:58:23 +04:00
Ivan Molodetskikh 82fffdea80 Fix locking with DPMS-inactive monitors
This both enables locking while monitors are powered off (they have no
buffer attached at that point on a TTY, so no sensitive content can
become visible), and fixes the condition below to check even if the
rendering was skipped.
2024-02-21 07:40:50 +04:00
Ivan Molodetskikh 5b3bfd95d9 Upgrade logs about removing env vars to warn!
These are more visible now with the --session flag.
2024-02-21 07:27:49 +04:00
Ivan Molodetskikh 1a15aa704d ci: Check individual features 2024-02-21 07:27:49 +04:00
Ivan Molodetskikh d58a45a96c Add systemd feature flag for systemd-specific things 2024-02-21 07:27:49 +04:00
Ivan Molodetskikh 9f1b4ee299 Set XDG_CURRENT_DESKTOP and XDG_SESSION_TYPE from niri itself 2024-02-21 07:27:49 +04:00
Ivan Molodetskikh f0a5e9c933 Add --session CLI flag instead of detection based on systemd service
Allows running without systemd.
2024-02-21 07:27:49 +04:00
Ivan Molodetskikh c4c07841d7 niri.service: Put into session.slice
Now that we're separating spawned processes, put ourselves in the more
important session.slice.
2024-02-20 12:49:52 +04:00
Ivan Molodetskikh 6ba24e341f utils/spawn: Put processes into systemd scopes
This separates them from the niri scope for the purposes of e.g. the OOM
killer only killing the app and not the compositor.
2024-02-20 12:49:52 +04:00
Ivan Molodetskikh 13b6c74cc3 utils/spawn: Receive grandchild PID 2024-02-20 12:49:52 +04:00
Ivan Molodetskikh d8fb8d5ef0 Update for Smithay MultiGpu shadow copies 2024-02-18 21:12:07 +04:00
Ivan Molodetskikh 2b5eeb6162 Fix fullscreen handling before initial configure 2024-02-18 10:20:34 +04:00
Ivan Molodetskikh 85be5f746c default-config: Clarify how indexed workspace access works 2024-02-17 21:01:10 +04:00
Ivan Molodetskikh dd7362913e Ignore mouse releases for dismissing overlays 2024-02-17 14:07:51 +04:00
Ivan Molodetskikh 62892d6361 Prevent locking while another lock client is already active
Fixes double swaylock from manual + swayidle.
2024-02-17 07:47:06 +04:00
Ivan Molodetskikh 31c13b6a69 default-config: Document enable-color-transformations-capability debug flag 2024-02-17 07:23:43 +04:00
Ivan Molodetskikh baaac2f3c4 Update Smithay 2024-02-16 22:40:37 +04:00
Ivan Molodetskikh 3fdefae45b Bump version to 0.1.2 2024-02-16 18:00:19 +04:00
Ivan Molodetskikh 6345224e95 default-config: Fix spelling mistakes
Ok I added automatic :set spell for KDL now.
2024-02-16 17:40:18 +04:00
Ivan Molodetskikh b3d2096439 Replace set_modified() with manual impl
MSRV moment
2024-02-16 08:46:58 +04:00
Ivan Molodetskikh 94ded2f6a9 CI: Add a MSRV job 2024-02-16 08:33:19 +04:00
Ivan Molodetskikh fa3bc69f94 Add watcher tests 2024-02-15 10:31:53 +04:00
Viktor Pocedulic 363e1d8764 input: enable configuring of trackpoint devices 2024-02-15 10:27:12 +04:00
Ivan Molodetskikh 8e1d4de0dc tty: Filter out interlaced modes
They don't seem to work. wlroots also filters them:
https://gitlab.freedesktop.org/wlroots/wlroots/-/blob/feb54979c0940655e36119c63e18a9ee72cc03b0/backend/drm/drm.c#L1461
2024-02-14 21:14:01 +04:00
Ivan Molodetskikh 72e3fadb9a default-config: Specify example refresh rate with 3 digits
This is the format you need to use.
2024-02-14 19:55:31 +04:00
Ivan Molodetskikh 78cda2e67f tty: Truncate Edid strings to nul
Otherwise they crash in wayland-rs when converting to CString.
2024-02-14 19:49:34 +04:00
Ivan Molodetskikh 924e21f69b Focus output unconditionally after moving window there
Fixes output not getting focus if there was no window to move.
2024-02-14 09:06:13 +04:00
Ivan Molodetskikh befdebfa03 Add the beginnings of window rules 2024-02-14 08:32:14 +04:00
Ivan Molodetskikh 7960a73e9d config: Fix missing layout {} defaulting to 0 gaps 2024-02-13 17:47:11 +04:00
Ivan Molodetskikh 749ee5d627 Do initial configuration right before sending initial configure
Let the toplevel fill in some details about itself.
2024-02-13 17:47:11 +04:00
Ivan Molodetskikh 952dd48115 Deduplicate call to miette hook 2024-02-13 12:16:58 +04:00
Ivan Molodetskikh cbd066ab68 default-config: Document animation properties 2024-02-12 20:46:29 +04:00
Ivan Molodetskikh bccde351fb Update flake.lock 2024-02-12 09:58:04 +04:00
Kiara Grouwstra beaffb1b97 CI: check nix build works 2024-02-12 09:57:34 +04:00
Shawn Wallace 385454378b Implement DRM leasing
Closes #178
2024-02-12 09:48:54 +04:00
Ivan Molodetskikh 18f06a7acd Fix border getting default values for focus ring 2024-02-12 09:34:54 +04:00
Ivan Molodetskikh 6e23073019 Move default_border() into FocusRing 2024-02-12 09:22:22 +04:00
Ivan Molodetskikh a9fcbf81eb Export NIRI_SOCKET to systemd/dbus environment 2024-02-12 08:56:39 +04:00
Ivan Molodetskikh a99f34cba8 tty: Activate monitors on session resume 2024-02-12 08:45:45 +04:00
Ivan Molodetskikh bd2277fa25 tty: Notify idle activity on session resume 2024-02-12 08:42:34 +04:00
Ivan Molodetskikh 67182129ff Add skip-confirmation flag to the quit action 2024-02-12 07:53:48 +04:00
Ivan Molodetskikh d6b116d229 Add missing space 2024-02-12 07:53:48 +04:00
Ivan Molodetskikh c20a843ab2 Add log message when confirming exit dialog 2024-02-12 07:53:48 +04:00
Kiara Grouwstra 1b752fe08f exclude visual tests from nix, closes #181 2024-02-12 00:01:03 +04:00
Ivan Molodetskikh 89f74aae98 freedesktop-screensaver: Filter out non-interesting messages 2024-02-11 23:05:37 +04:00
Ivan Molodetskikh 5e553c2679 Implement org.freedesktop.ScreenSaver Inhibit
xdg-desktop-portal currently has no way of disabling the Inhibit portal
or ever returning an error to the application from it. Thus Flatpak
Firefox will never fall back to its Wayland backend. To remedy this,
let's actually implement the FDO Inhibit interface that the portal can
use.
2024-02-11 22:26:59 +04:00
Ivan Molodetskikh cabf712821 hotkey-overlay: Deduplicate Spawn actions 2024-02-11 09:27:34 +04:00
Ivan Molodetskikh 0931447ec1 Implement error reporting in IPC 2024-02-11 09:19:37 +04:00
Ivan Molodetskikh a388c25795 Update dependencies 2024-02-10 15:01:34 +04:00
Ivan Molodetskikh 5c4d9824a4 Remove logind-zbus dependency
It isn't updated and we don't really need it anyway.
2024-02-10 14:58:22 +04:00
Ivan Molodetskikh ca4ee5ae25 hotkey-overlay: Only show Spawn binds with Mod/Super 2024-02-10 14:37:38 +04:00
Ivan Molodetskikh 93e16a6582 Implement niri msg action 2024-02-10 09:40:32 +04:00
Ivan Molodetskikh 3486fa5536 Remove unused directories workspace dep 2024-02-10 09:34:35 +04:00
Ivan Molodetskikh c022d74c82 Remove extra `` in comment 2024-02-10 09:19:08 +04:00
Ivan Molodetskikh e68641c0a7 Move CLI types to submodule 2024-02-10 08:40:13 +04:00
Ivan Molodetskikh 2a892ef511 input: Fix Clippy warning 2024-02-10 08:38:19 +04:00
Ivan Molodetskikh 90c6721e97 config: Add missing Smithay feature
Fixes build on nightly.
2024-02-10 07:51:53 +04:00
Ivan Molodetskikh e5cd9e9307 default-config: Replace Mod with Super in swaylock bind
Otherwise it conflicts with Mod+L in nested.
2024-02-09 16:23:33 +04:00
Ivan Molodetskikh 573dca10cc input: Fix handling of binds with compositor mod but no explicit Mod 2024-02-09 16:23:05 +04:00
Ivan Molodetskikh 577fba82e5 input: Split bound_action() and add tests 2024-02-09 16:16:18 +04:00
Ivan Molodetskikh b9116c579a Implement idle-notify and idle-inhibit 2024-02-09 15:50:40 +04:00
Ivan Molodetskikh d8dcadc5b2 Clamp animation slowdown to sane values 2024-02-07 20:03:23 +04:00
Ivan Molodetskikh 6424a2738d Make all animations configurable 2024-02-07 17:14:24 +04:00
Ivan Molodetskikh 753a90430a animation: Accept ms as u32
Less boilerplate elsewhere.
2024-02-07 16:32:38 +04:00
Ivan Molodetskikh f9085db564 Implement window open animations 2024-02-07 13:16:54 +04:00
Ivan Molodetskikh 49ce791d13 Add a Tracy span to OffscreenRenderElement::new 2024-02-07 13:16:54 +04:00
Ivan Molodetskikh 4b8e04da04 Activate the new right_of window on its workspace
This way when a dialog opens on a different workspace, the user will see
it right away when they switch to that workspace.
2024-02-07 13:16:54 +04:00
Ivan Molodetskikh 026ad8f377 Add a way to override the element ID for primary output check 2024-02-07 11:30:52 +04:00
Ivan Molodetskikh 0761401650 Add OffscreenRenderElement 2024-02-07 11:30:33 +04:00
Ivan Molodetskikh 3360517f62 Clear before rendering to texture
Otherwise I see artifacts on some GTK dialogs.
2024-02-07 11:18:55 +04:00
Ivan Molodetskikh 9896fd67a0 Open dialogs to the right of their parent, don't steal focus 2024-02-07 10:49:01 +04:00
Ivan Molodetskikh 15ec699fbb visual-tests: Remove "Just" prefix 2024-02-07 09:24:41 +04:00
Ivan Molodetskikh a1cc39a437 visual-tests/tile: Disable focus ring 2024-02-07 09:22:00 +04:00
Ivan Molodetskikh 738d9a2b40 Add blank line 2024-02-06 19:53:31 +04:00
Ivan Molodetskikh 68752db51b layout: Add Column::advance_animations() 2024-02-06 19:52:47 +04:00
Ivan Molodetskikh d4929b8e18 Inline variable 2024-02-06 19:52:10 +04:00
Ivan Molodetskikh 93c547f749 Move focus ring into Tile
For now, will make the open animation better.
2024-02-06 19:49:51 +04:00
Ivan Molodetskikh e2b91c0c1c layout: Fix refresh in tests
Didn't affect anything but still.
2024-02-06 19:09:27 +04:00
Ivan Molodetskikh 322b5cbac7 Add Layout::with_options() 2024-02-06 19:09:15 +04:00
Ivan Molodetskikh 592791611a Change render functions to accept iterators 2024-02-06 17:53:25 +04:00
Ivan Molodetskikh d073d2ab3d Move render functions to render_helpers 2024-02-06 17:53:25 +04:00
Ivan Molodetskikh b2298db5c5 Split render_helpers.rs 2024-02-06 11:25:25 +04:00
Ivan Molodetskikh baa6263cbe Bump libinput to 1.21, add dwtp flag 2024-02-06 09:54:46 +04:00
Ivan Molodetskikh 795da53d53 README: Update Ubuntu dependencies 2024-02-06 09:49:53 +04:00
Ivan Molodetskikh 122afff7d1 Add niri-visual-tests 2024-02-06 09:40:45 +04:00
Ivan Molodetskikh d2a4e6a0cb Update dependencies 2024-02-06 09:40:34 +04:00
Ivan Molodetskikh 8916b18c6b Run Ubuntu CI in a 23.10 container
We will soon need newer dependencies.
2024-02-06 09:40:32 +04:00
Ivan Molodetskikh b0d0fce5f3 Move use into feature-gated function 2024-02-05 17:40:16 +04:00
Ivan Molodetskikh 3dc4a5fdac Fix Clippy warnings 2024-02-05 17:40:16 +04:00
Ivan Molodetskikh 1706a46b2b layout: Mark some things as pub 2024-02-05 17:40:16 +04:00
Ivan Molodetskikh 3789d85588 Add lib.rs, become a mixed lib-bin crate
Will be used for visual tests.
2024-02-05 17:40:16 +04:00
Dennis Ranke 3a23417e98 Add consume-or-expel-window-left/right commands 2024-02-05 14:09:47 +04:00
Ivan Molodetskikh 6bb83757ee Convert everything to niri_render_elements! {} 2024-02-05 14:05:08 +04:00
Ivan Molodetskikh b62a07956a Add niri_render_elements! {}
We will be using this in several other places.
2024-02-05 13:55:09 +04:00
Ivan Molodetskikh 96016790b2 layout: Replace with_tiles_in_render_order() with Iterator 2024-02-05 13:55:09 +04:00
Ivan Molodetskikh bf978fe98d layout/tile: Return Iterator of render elements
Avoid a Vec.
2024-02-05 13:55:09 +04:00
Ivan Molodetskikh 57521c69c3 layout: Add TileRenderElement 2024-02-04 22:52:11 +04:00
Ivan Molodetskikh da826e42aa layout: Add LayoutElementRenderElement
Allows for testing layout rendering without Wayland windows.
2024-02-04 22:31:44 +04:00
Ivan Molodetskikh b824cf90ab layout: Generalize traversal between rendering and input 2024-02-04 22:10:26 +04:00
Ivan Molodetskikh 7a4bb8ba8a layout: Make rendering not Window-specific
Doesn't need to be any more.
2024-02-04 21:23:00 +04:00
Ivan Molodetskikh 72c8f569ac Bump version to 0.1.1 2024-02-03 10:00:06 +04:00
Ivan Molodetskikh 798d9c55df Support fullscreen for new windows 2024-02-03 09:45:26 +04:00
Ivan Molodetskikh 05613eed1e Verify that pending fullscreen matches column 2024-02-03 09:44:34 +04:00
Ivan Molodetskikh b23dd4b800 Respect natural-scroll for workspace switch gesture 2024-02-03 09:00:08 +04:00
Ivan Molodetskikh 1f72089a46 Place new workspace after current when moving
This feels more natural, also makes moving back and forth idempotent in
most cases.
2024-02-03 08:42:56 +04:00
Ivan Molodetskikh fbe9020915 Update dependencies 2024-02-02 17:04:17 +04:00
Ivan Molodetskikh 2036116f16 config: Premultiply alpha in Color when converting to f32
Smithay wants premultiplied alpha.
2024-02-01 18:53:45 +04:00
Ivan Molodetskikh 9afd728ae9 Add error messages to backend initialization 2024-02-01 16:55:46 +04:00
Andreas Stührk e51268a39e Add actions to move the active workspace to another monitor 2024-02-01 12:29:46 +04:00
Ivan Molodetskikh 0a715ce155 default-config: Improve wording for focus-ring/border comment
SSD or server-side decorations is never mentioned elsewhere.
2024-02-01 12:06:13 +04:00
Ivan Molodetskikh 89ac958670 default-config: Document how focus ring and border draw behind
Related: https://github.com/YaLTeR/niri/issues/150
2024-02-01 10:08:15 +04:00
Ivan Molodetskikh 2e50f8dee0 Hardcode winit transform for now 2024-01-31 23:02:38 +04:00
Ivan Molodetskikh 7052f0129e Stop screencasts on size changes 2024-01-31 23:02:38 +04:00
axtloss 962e159db6 Add option to rotate outputs 2024-01-31 23:02:38 +04:00
Ivan Molodetskikh 11bff3a2f1 Update Smithay (rotation fix) 2024-01-31 23:02:38 +04:00
Ivan Molodetskikh 15606304f2 README: Bring AUR link back 2024-01-30 22:36:30 -08:00
Christian Meissl 85eac9d9d0 chore: bump smithay
includes fixes for wrong direct scan-out transform
and damage artifacts on output transform changes.
also includes a fix for a race in popup surface re-use.
2024-01-30 15:30:31 +04:00
Ivan Molodetskikh d3f4583c90 foreign_toplevel: Use OutputHandler to send output_enter on demand 2024-01-30 12:30:57 +04:00
Ivan Molodetskikh fefb1cccd6 foreign_toplevel: Update the focused window last 2024-01-30 12:30:57 +04:00
Ivan Molodetskikh deef52519a foreign_toplevel: Change activated to mean keyboard focus 2024-01-30 12:30:57 +04:00
Ivan Molodetskikh 59ff331597 Implement wlr-foreign-toplevel-management
The parent event isn't sent but whatever.
2024-01-30 12:30:57 +04:00
Christian Meissl b813f99abd tty: reset surface state after changing monitor state
changing the "ACTIVE" property of a surface requires
to re-evaluate the surface state.
2024-01-30 08:03:21 +04:00
Ivan Molodetskikh d9b9cec8b8 README: Remove AUR link for now
It doesn't work properly yet apparently.
2024-01-29 12:29:32 -08:00
Christian Meissl 597ea62d17 input: update keyboard led state 2024-01-28 23:43:08 +04:00
Ivan Molodetskikh 51243a0a50 Show notification about creating a default config 2024-01-28 17:15:47 +04:00
Ivan Molodetskikh 0ebcc3e0d6 Create default config file if missing 2024-01-28 17:15:33 +04:00
Ivan Molodetskikh 64c85d865e winit: Don't remove output on CloseRequested
More winit events can process after CloseRequested, which will cause a
panic if trying to access the now-removed output.
2024-01-28 16:30:29 +04:00
Ivan Molodetskikh 367e4955ea Mark Msg as pub
Seems to break the build on 1.72.0 otherwise.
2024-01-28 09:34:42 +04:00
Ivan Molodetskikh dd967554d1 Bump version to 0.1.0 2024-01-27 14:10:31 +04:00
Ivan Molodetskikh 6d7c220137 Try harder to find an output for the screenshot UI
The mouse might be outside any outputs, let's try to open in that case
anyway.
2024-01-27 14:09:55 +04:00
Ivan Molodetskikh d77aac1afa Fix damage when rendering to texture 2024-01-27 10:50:40 +04:00
Ivan Molodetskikh 837a0a20fb Update README 2024-01-25 08:34:42 +04:00
Ivan Molodetskikh ecdf756b55 Name output render element better 2024-01-25 08:02:33 +04:00
Christian Meissl 73f3c160b2 use pixman for cursor plane rendering 2024-01-25 07:49:51 +04:00
Christian Meissl 5f99eb13ab Remove hack for fixed EGLDisplay issue 2024-01-25 07:49:51 +04:00
Christian Meissl 20326b093c Update smithay 2024-01-25 07:49:51 +04:00
Ivan Molodetskikh 467d92a4b4 github: Add a feature request link to start a discussion 2024-01-23 17:41:35 +04:00
Ivan Molodetskikh 15bb69c0b9 Update issue templates 2024-01-23 05:36:19 -08:00
Ivan Molodetskikh adfbfdffb3 Create a bug report template 2024-01-23 05:34:38 -08:00
Ivan Molodetskikh 087ed260c5 Update Smithay (find_popup_root_surface() panic fix) 2024-01-23 17:12:47 +04:00
Ivan Molodetskikh f5642ab733 Ignore popup grabs when IME keyboard grab is active
Doing this properly will require more refactors, potentially in Smithay.
For now let's just ignore popup grabs to make popups work.
2024-01-23 17:05:08 +04:00
Ivan Molodetskikh ab9706cb30 screencast: Emit MonitorsChanged 2024-01-23 12:02:52 +04:00
Ivan Molodetskikh 05f2a3709b srceencast: Send stream size
Kooha requires this (even though it's optional). Unfortunately, Kooha
also seems to want memfd recording so it doesn't work anyway.
2024-01-23 11:36:11 +04:00
Ivan Molodetskikh 743173ef64 config: Bump precision on the default widths
This seems to actually matter on my 2560x display.
2024-01-22 20:43:33 +04:00
Ivan Molodetskikh cbbb7a26fc Update Smithay, use device changed session resume code
Should fix most cases of monitors failing to light up after a TTY
switch.
2024-01-22 16:13:39 +04:00
sodiboo 18566e3366 Watch for canonical filename, not just mtime 2024-01-22 07:42:45 +04:00
Ivan Molodetskikh df48337d83 tty: Delay output config update until resume
We can't do anything while paused.
2024-01-21 10:25:39 +04:00
Ivan Molodetskikh f5e9b40140 tty: Check changes against pending connectors and mode
If we queued some DRM changes, they will be in pending. Also be more
resilient by removing unwrap.
2024-01-21 10:24:42 +04:00
Ivan Molodetskikh 5cacd03e85 Return error instead of broken screenshot for portal 2024-01-21 10:03:13 +04:00
Ivan Molodetskikh 6945ccde18 Bump version to 0.1.0-beta.1 2024-01-20 09:38:42 +04:00
Ivan Molodetskikh e86e9c6c9a CI: Add a Fedora build 2024-01-20 09:25:50 +04:00
Ivan Molodetskikh dc47de178f Add an option to skip the hotkey overlay at startup 2024-01-20 08:31:05 +04:00
Ivan Molodetskikh 65e864965e Print git version in clap too 2024-01-19 20:46:10 +04:00
Ivan Molodetskikh 55ad36addc layout: Fix crash due to workspace transfer during switch 2024-01-19 20:24:59 +04:00
Ivan Molodetskikh 26c8cbb961 layout: Fix crash due to workspace cleanup during switch 2024-01-19 20:24:18 +04:00
Ivan Molodetskikh 031133c052 README: Add link to important software wiki page 2024-01-19 07:01:56 -08:00
Ivan Molodetskikh a6f821d3fa Update dependencies 2024-01-19 09:41:16 +04:00
Ivan Molodetskikh 475b3df2b5 Don't crash when failing to render a cursor
I only hit this when the renderer was completely busted, but
nevertheless.
2024-01-19 09:13:32 +04:00
Ivan Molodetskikh 1541835f00 Prettify Return => Enter key 2024-01-19 08:35:36 +04:00
Ivan Molodetskikh 4b9cb2f0d3 Add exit confirmation dialog 2024-01-19 08:33:54 +04:00
Ivan Molodetskikh 3461c66d2c Redraw upon starting PW stream
Otherwise it may take a while for the first frame to arrive.
2024-01-18 21:16:36 +04:00
Ivan Molodetskikh 011c91c98a Add an important hotkeys overlay 2024-01-18 20:32:44 +04:00
Ivan Molodetskikh edafa139f6 portal: Name and sort monitors, fix session restore
xdp-gnome restores by a combination of model + make + serial. We
currently can't set those reliably (until libdisplay-info most monitors
will have them unknown) so pass the connector name instead. This will
work as expected in most cases.
2024-01-18 16:31:04 +04:00
Ivan Molodetskikh fa9b3ed106 Add a config parse error notification
We can't rely on a notification daemon being available, especially
during initial niri setup. So, render our own.
2024-01-18 12:44:05 +04:00
Ivan Molodetskikh cc62a403c0 Update Smithay (deadlock fix) 2024-01-18 11:14:39 +04:00
Ivan Molodetskikh 0f85c79548 Watch config path even if it didn't exist at startup 2024-01-18 11:13:36 +04:00
Ivan Molodetskikh 6beef26662 Fix dependency sorting 2024-01-18 11:00:49 +04:00
Ivan Molodetskikh 616055e205 Update README.md 2024-01-17 03:15:05 -08:00
Ivan Molodetskikh 40c85da102 Add an IPC socket and a niri msg outputs subcommand 2024-01-17 10:45:18 +04:00
Ivan Molodetskikh 768b326028 Rename connectors to enabled_outputs 2024-01-17 10:25:23 +04:00
Ivan Molodetskikh f068157f55 Add a calloop futures executor 2024-01-17 10:24:01 +04:00
Ivan Molodetskikh 6703d5ce72 tty: Add Tracy span to on_output_config_changed() 2024-01-17 10:21:40 +04:00
Ivan Molodetskikh 12590f689a Write a comment on xdg-decoration lack of live-reload 2024-01-16 20:43:28 +04:00
Ivan Molodetskikh 4656332d07 Add live-reload to libinput settings 2024-01-16 20:29:37 +04:00
Ivan Molodetskikh 954f711bf3 Extract apply_libinput_settings() 2024-01-16 20:28:37 +04:00
Ivan Molodetskikh c09c964420 default-config: Add example for spawn with bash 2024-01-16 20:08:31 +04:00
Ivan Molodetskikh 1f9abaaa58 Add live-reload for output mode 2024-01-16 18:02:30 +04:00
Ivan Molodetskikh eb4946c3d8 tty: Extract pick_mode() 2024-01-16 18:01:25 +04:00
Ivan Molodetskikh 5f440f7be3 Add live-reload for output on/off 2024-01-16 15:34:00 +04:00
Ivan Molodetskikh 6644cc16ff tty: Remove connector arg from connector_disconnected() 2024-01-16 15:33:37 +04:00
Ivan Molodetskikh 9e667efc4c Close layer surfaces upon output removal
Fixes https://github.com/YaLTeR/niri/issues/23
2024-01-16 13:28:29 +04:00
Ivan Molodetskikh 8a7e4bc3cd Add Tracy span to Config::load and parse 2024-01-16 12:53:40 +04:00
Ivan Molodetskikh 69907f123d Add live-reload of output scales 2024-01-16 11:34:34 +04:00
Ivan Molodetskikh 6ca3b6ddb5 Move output scale setting into niri 2024-01-16 09:46:02 +04:00
Ivan Molodetskikh fc5a080ca5 layout: Fix surface leaving output when consuming into column 2024-01-16 09:46:02 +04:00
Ivan Molodetskikh 83719a49b7 Add live-reload of output positions 2024-01-16 09:46:02 +04:00
Ivan Molodetskikh da4967d43c Reposition all outputs on any change
This way the positioning is independent of the order of plugging in.
2024-01-16 08:43:28 +04:00
Ivan Molodetskikh d958a9679c Change message from debug to trace 2024-01-16 07:38:52 +04:00
Ivan Molodetskikh e4643c6dbe Implement security-context, hide some protocols from it 2024-01-15 16:02:07 +04:00
Ivan Molodetskikh 59763fd0da Hide decoration globals when we need CSD
This gets the current SDL2 with libdecor working.
2024-01-15 16:01:01 +04:00
Ivan Molodetskikh 533659eef8 Update Smithay 2024-01-15 15:59:36 +04:00
Ivan Molodetskikh 81443d8e16 Change default binds to move columns instead of windows 2024-01-15 11:51:04 +04:00
Ivan Molodetskikh fb38ae26c9 Add move-column-to-monitor* binds
As opposed to move-window-to-monitor*
2024-01-15 10:36:59 +04:00
Ivan Molodetskikh cc4acdf24a Add move-column-to-workspace* binds
As opposed to move-window-to-workspace*
2024-01-15 10:31:44 +04:00
Ivan Molodetskikh 2506d43bb9 xdg-decoration: Document SDL2 bug 2024-01-14 09:28:03 +04:00
Ivan Molodetskikh d899bc4712 Revert "Be more insistent on CSD by default"
This reverts commit 43e2cf14d2.

SDL2 until very recently (unreleased version) has had a bug where
changing the decoration mode to client-side during its initial window
creation would keep the window permanently hidden. Breaking all SDL2
apps for years to come is unfortunately not a good solution.
2024-01-14 09:23:15 +04:00
Ivan Molodetskikh 14552d856c xdg-decoration: Always send configure
The protocol wording seems to require it.
2024-01-14 08:57:46 +04:00
Ivan Molodetskikh 632a00fcca Implement popup grabs 2024-01-13 09:00:57 +04:00
Ivan Molodetskikh 80652a0765 Remove is_grabbed check for changing active window
When clicking outside of the popup grab, the click does go through if
the popup is dismissed. This makes the active window change go through
too.
2024-01-13 08:17:53 +04:00
Ivan Molodetskikh a52bf92ae1 Add missing screen redraws on focus changes
The window isn't guaranteed to commit a buffer.
2024-01-13 08:17:53 +04:00
Ivan Molodetskikh 952ff02982 Keep track of keyboard focus manually 2024-01-12 17:14:18 +04:00
Ivan Molodetskikh e1adabed2d Rename update_focus -> update_keyboard_focus 2024-01-12 16:53:00 +04:00
Ivan Molodetskikh b5c4f9ed2a Remove obsolete FIXME comment
It's implemented now.
2024-01-12 14:54:59 +04:00
Ivan Molodetskikh d39f1897c7 Force redraws on window activation
Activating a window does not necessarily make it commit a buffer and
update the screen for us.
2024-01-12 08:48:22 +04:00
Ivan Molodetskikh e46b614c2b Fix clicks activating windows through layer-shell surfaces 2024-01-12 08:45:39 +04:00
Ivan Molodetskikh 78aa08b100 Silence the two type complexity lints
meh
2024-01-11 22:10:12 +04:00
Ivan Molodetskikh d8626fcab0 Fix clippy suggestion 2024-01-11 21:42:00 +04:00
Ivan Molodetskikh f4e04ac910 Mark cause_panic() as #[inline(never)]
Despite compiling with frame pointers, inlining cause_panic() makes the
backtrace omit its frame and even the source location in main...
2024-01-11 18:30:54 +04:00
Bill Sun 236abd9d9d Add Nix Flake (#77)
* Add Nix Flake

Co-authored-by: Bryce Berger <bryce.z.berger@gmail.com>

* Describe nix flake in readme

* Add `niri-config` to build source list

* Add maintainer info

Add comment at top to indicate the Nix Flake file
is community maintained.

* Clarify Nix/NixOS README instructions

* Shorten Nix/NixOS build instructions

Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>

* Move NixOS installation instruction to "Tip" section

---------

Co-authored-by: Bryce Berger <bryce.z.berger@gmail.com>
Co-authored-by: Ivan Molodetskikh <yalterz@gmail.com>
2024-01-10 22:43:46 -08:00
Ivan Molodetskikh b2df3e104f Document debug settings in the default config 2024-01-09 08:18:34 +04:00
Ivan Molodetskikh ec2d339a86 Add panic subcommand to check backtraces 2024-01-09 08:08:38 +04:00
Ivan Molodetskikh 629a2ccb47 layout: Improve Options randomization in tests 2024-01-08 20:57:53 +04:00
Thomas Versteeg fb93038bd8 Add center-focused-column setting 2024-01-08 17:37:18 +04:00
Ivan Molodetskikh 71fef2ad2e Add a few mouse libinput settings 2024-01-08 11:53:34 +04:00
Ivan Molodetskikh c6841f19e9 Add touchpad tap-button-map setting 2024-01-08 10:32:04 +04:00
Ivan Molodetskikh e1971c4af5 Add touchpad dwt setting 2024-01-08 10:24:00 +04:00
Ivan Molodetskikh 07b1d0e98d Add touchpad accel-profile setting 2024-01-08 10:23:53 +04:00
Ivan Molodetskikh ffe25f5cc4 Update Smithay and dependencies 2024-01-07 17:44:08 +04:00
Ivan Molodetskikh 43e2cf14d2 Be more insistent on CSD by default
By default I want CSD so that people don't necessarily have to learn all
of the shortcuts right away, and can at least use the X to close
windows.
2024-01-07 09:41:56 +04:00
Ivan Molodetskikh 2c59131f7f Remove debuginfo from niri-config
Finally, the file sizes are back to sane.
2024-01-07 09:28:50 +04:00
Ivan Molodetskikh 64c41fa2c8 Move config into a separate crate
Get miette and knuffel deps contained within.
2024-01-07 09:28:14 +04:00
Ivan Molodetskikh 4e0aa39113 [cfg-breaking] Move layout settings into their own scope 2024-01-06 13:04:21 +04:00
Ivan Molodetskikh dcb80efc88 Bump version to 0.1.0-alpha.3 2024-01-06 09:30:46 +04:00
5296 changed files with 139660 additions and 10172 deletions
+12
View File
@@ -0,0 +1,12 @@
# LFS configuration for images from the wiki
*.png filter=lfs diff=lfs merge=lfs -text
# Exclude LFS-tracked files from the tarball
/wiki/img/ export-ignore
# exclude .gitattributes itself from the tarball
.gitattributes export-ignore
# tip: can be tested using
# git archive --format=tar.gz --output=source.tar.gz HEAD && \
# tar tfvz source.tar.gz | grep -e '.png' -e '.gitattributes'
+38
View File
@@ -0,0 +1,38 @@
---
name: Bug report
about: Report a bug or a crash
title: ''
labels: bug
assignees: ''
---
<!-- Please describe the issue here at the top, then fill in the system information below. -->
<!-- Attaching your full niri config can help diagnose the problem. -->
<!--
If you have a problem with a specific app, please verify that it is running on Wayland, rather than X11. An easy way is to run xeyes and mouse over the app: xeyes will be able to "see" only X11 windows.
You can also check what process the window PID belongs to:
$ readlink /proc/$(niri msg --json pick-window | jq .pid)/exe
If this points to xwayland-satellite, then it's an X11 window.
Please report issues with X11 apps to xwayland-satellite instead of niri: https://github.com/Supreeeme/xwayland-satellite/issues
-->
### System Information
<!-- Paste the output of `niri -V`, e.g. niri 25.02 (b94a5db) -->
* niri version:
<!-- Write your distribution, e.g. Fedora 40 Silverblue -->
* Distro:
<!-- Write your GPU vendor and model, e.g. AMD RX 6700M -->
* GPU:
<!-- Write your CPU vendor and model, e.g. AMD Ryzen 7 6800H -->
* CPU:
+10
View File
@@ -0,0 +1,10 @@
contact_links:
- name: Feature request
url: https://github.com/YaLTeR/niri/discussions/new?category=ideas
about: Ideas for new features and functionality (start a Discussion)
- name: Ask a question
url: https://github.com/YaLTeR/niri/discussions/new?category=q-a
about: Question about niri (start a Discussion)
- name: Matrix room
url: https://matrix.to/#/#niri:matrix.org
about: Chat about niri with other users
+22
View File
@@ -0,0 +1,22 @@
version: 2
updates:
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "weekly"
groups:
smithay:
patterns:
- "smithay"
- "smithay-drm-extras"
rust-dependencies:
update-types:
- "minor"
- "patch"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
ignore:
- dependency-name: "Andrew-Chen-Wang/github-wiki-action"
+199 -29
View File
@@ -9,6 +9,8 @@ on:
env:
RUN_SLOW_TESTS: 1
DEPS_APT: curl gcc clang libudev-dev libgbm-dev libxkbcommon-dev libegl1-mesa-dev libwayland-dev libinput-dev libdbus-1-dev libsystemd-dev libseat-dev libpipewire-0.3-dev libpango1.0-dev libdisplay-info-dev
DEPS_DNF: cargo gcc clang libudev-devel libgbm-devel libxkbcommon-devel wayland-devel libinput-devel dbus-devel systemd-devel libseat-devel pipewire-devel pango-devel cairo-gobject-devel libdisplay-info-devel
jobs:
build:
@@ -23,7 +25,7 @@ jobs:
release-flag: '--release'
name: test - ${{ matrix.configuration }}
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
@@ -32,41 +34,130 @@ jobs:
- name: Install dependencies
run: |
sudo apt-get install -y software-properties-common
sudo add-apt-repository -y ppa:pipewire-debian/pipewire-upstream
sudo apt-get update -y
sudo apt-get install -y libudev-dev libgbm-dev libxkbcommon-dev libegl1-mesa-dev libwayland-dev libinput-dev libdbus-1-dev libsystemd-dev libseat-dev libpipewire-0.3-dev
sudo apt-get install -y ${{ env.DEPS_APT }}
- name: Install Rust
run: |
rustup set auto-self-update check-only
rustup toolchain install stable --profile minimal
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
key: ${{ matrix.configuration }}
- name: Build (no default features)
run: cargo build ${{ matrix.release-flag }} --no-default-features
- name: Check (no default features)
run: cargo check ${{ matrix.release-flag }} --no-default-features
- name: Build
run: cargo build ${{ matrix.release-flag }}
- name: Check (just dbus)
run: cargo check ${{ matrix.release-flag }} --no-default-features --features dbus
- name: Check (just systemd)
run: cargo check ${{ matrix.release-flag }} --no-default-features --features systemd
- name: Check (just dinit)
run: cargo check ${{ matrix.release-flag }} --no-default-features --features dinit
- name: Check (just xdp-gnome-screencast)
run: cargo check ${{ matrix.release-flag }} --no-default-features --features xdp-gnome-screencast
- name: Check
run: cargo check ${{ matrix.release-flag }}
- name: Build (with profiling)
run: cargo build ${{ matrix.release-flag }} --features profile-with-tracy
- name: Build Tests
run: cargo test --no-run --all ${{ matrix.release-flag }}
- name: Build tests
run: cargo test --no-run --all --exclude niri-visual-tests ${{ matrix.release-flag }}
- name: Test
run: cargo test --all ${{ matrix.release-flag }} -- --nocapture
run: cargo test --all --exclude niri-visual-tests ${{ matrix.release-flag }} -- --nocapture
# Job that runs randomized tests for a longer period of time.
randomized-tests:
strategy:
fail-fast: false
name: randomized tests
runs-on: ubuntu-24.04
env:
RUST_BACKTRACE: 1
PROPTEST_CASES: 200000
PROPTEST_MAX_LOCAL_REJECTS: 200000
PROPTEST_MAX_GLOBAL_REJECTS: 200000
PROPTEST_MAX_SHRINK_ITERS: 200000
steps:
- uses: actions/checkout@v4
with:
show-progress: false
- name: Install dependencies
run: |
sudo apt-get update -y
sudo apt-get install -y ${{ env.DEPS_APT }}
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build tests
run: cargo test --no-run --all --exclude niri-visual-tests --release
- name: Test
run: cargo test --all --exclude niri-visual-tests --release
visual-tests:
strategy:
fail-fast: false
name: visual tests
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
show-progress: false
- name: Install dependencies
run: |
sudo apt-get update -y
sudo apt-get install -y ${{ env.DEPS_APT }} libadwaita-1-dev
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build
run: cargo build --package niri-visual-tests
msrv:
strategy:
fail-fast: false
name: msrv
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
show-progress: false
- name: Install dependencies
run: |
sudo apt-get update -y
sudo apt-get install -y ${{ env.DEPS_APT }} libadwaita-1-dev
- uses: dtolnay/rust-toolchain@1.80.1
- uses: Swatinem/rust-cache@v2
- run: cargo check --all-targets
clippy:
strategy:
fail-fast: false
name: clippy
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
@@ -75,15 +166,12 @@ jobs:
- name: Install dependencies
run: |
sudo apt-get install -y software-properties-common
sudo add-apt-repository -y ppa:pipewire-debian/pipewire-upstream
sudo apt-get update -y
sudo apt-get install -y libudev-dev libgbm-dev libxkbcommon-dev libegl1-mesa-dev libwayland-dev libinput-dev libdbus-1-dev libsystemd-dev libseat-dev libpipewire-0.3-dev
sudo apt-get install -y ${{ env.DEPS_APT }} libadwaita-1-dev
- name: Install Rust
run: |
rustup set auto-self-update check-only
rustup toolchain install stable --profile minimal --component clippy
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- uses: Swatinem/rust-cache@v2
@@ -91,19 +179,101 @@ jobs:
run: cargo clippy --all --all-targets
rustfmt:
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
show-progress: false
- name: Install Rust
run: |
rustup set auto-self-update check-only
rustup toolchain install nightly --profile minimal --component rustfmt
rustup override set nightly
- uses: dtolnay/rust-toolchain@nightly
with:
components: rustfmt
- name: Run rustfmt
run: cargo fmt --all -- --check
fedora:
runs-on: ubuntu-24.04
container: fedora:41
steps:
- uses: actions/checkout@v4
with:
show-progress: false
- name: Install dependencies
run: |
sudo dnf update -y
sudo dnf install -y ${{ env.DEPS_DNF }} libadwaita-devel
- uses: Swatinem/rust-cache@v2
- run: cargo build --all
nix:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
show-progress: false
- name: Check flake inputs
uses: DeterminateSystems/flake-checker-action@v4
continue-on-error: true
- name: Install Nix
uses: DeterminateSystems/nix-installer-action@v3
continue-on-error: true
- run: nix flake check
continue-on-error: true
check-links:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
show-progress: false
- uses: lycheeverse/lychee-action@v2.0.2 # later versions break fragment checks. don't bump until this is fixed: https://github.com/lycheeverse/lychee/issues/1574
with:
args: --offline --include-fragments 'wiki/*.md'
publish-wiki:
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
needs:
- build
- check-links
permissions:
contents: write
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
lfs: true
show-progress: false
- uses: Andrew-Chen-Wang/github-wiki-action@b7e552d7cb0fa7f83e459012ffc6840fd87bcb83
rustdoc:
needs: build
permissions:
contents: write
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
show-progress: false
- uses: dtolnay/rust-toolchain@stable
- name: Generate documentation
run: cargo doc --no-deps -p niri-ipc
- run: cp ./resources/rustdoc-index.html ./target/doc/index.html
- name: Deploy documentation
if: github.ref == 'refs/heads/main'
uses: peaceiris/actions-gh-pages@v4
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./target/doc
force_orphan: true
+63
View File
@@ -0,0 +1,63 @@
name: Prepare release
on:
workflow_dispatch:
inputs:
version:
description: 'Public version'
required: true
concurrency:
group: ${{ github.workflow }}
cancel-in-progress: true
env:
RUN_SLOW_TESTS: 1
jobs:
prepare-release:
runs-on: ubuntu-24.04
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
show-progress: false
- name: Check for unreplaced "Since:" in the wiki
run: |
if grep --recursive 'Since: next release' wiki; then
exit 1
fi
- name: Install dependencies
run: |
sudo apt-get update -y
sudo apt-get install -y curl gcc clang libudev-dev libgbm-dev libxkbcommon-dev libegl1-mesa-dev libwayland-dev libinput-dev libdbus-1-dev libsystemd-dev libseat-dev libpipewire-0.3-dev libpango1.0-dev libdisplay-info-dev libadwaita-1-dev
- uses: dtolnay/rust-toolchain@stable
- name: Create vendored dependencies archive
run: |
mkdir .cargo
cargo vendor --locked > .cargo/config.toml
tar cJf niri-${{ github.event.inputs.version }}-vendored-dependencies.tar.xz vendor/
- name: Build
run: cargo build --all --frozen --release
- name: Build tests
run: cargo test --no-run --all --frozen --release
- name: Test
run: cargo test --all --frozen --release -- --nocapture
- name: Draft release
uses: softprops/action-gh-release@v2
with:
draft: true
tag_name: v${{ github.event.inputs.version }}
files: niri-${{ github.event.inputs.version }}-vendored-dependencies.tar.xz
fail_on_unmatched_files: true
+1
View File
@@ -1 +1,2 @@
/target
/result
Generated
+2399 -1120
View File
File diff suppressed because it is too large Load Diff
+128 -45
View File
@@ -1,48 +1,100 @@
[package]
name = "niri"
version = "0.1.0-alpha.2"
[workspace]
members = [
"niri-config",
"niri-ipc",
"niri-visual-tests",
]
[workspace.package]
version = "25.5.1"
description = "A scrollable-tiling Wayland compositor"
authors = ["Ivan Molodetskikh <yalterz@gmail.com>"]
license = "GPL-3.0-or-later"
edition = "2021"
readme = "README.md"
repository = "https://github.com/YaLTeR/niri"
keywords = ["wayland", "compositor", "tiling", "smithay", "wm"]
rust-version = "1.80.1"
[dependencies]
anyhow = { version = "1.0.79" }
arrayvec = "0.7.4"
async-channel = { version = "2.1.1", optional = true }
async-io = { version = "1.13.0", optional = true }
bitflags = "2.4.1"
clap = { version = "4.4.13", features = ["derive"] }
directories = "5.0.1"
git-version = "0.3.9"
keyframe = { version = "1.1.1", default-features = false }
knuffel = "3.2.0"
libc = "0.2.151"
logind-zbus = { version = "3.1.2", optional = true }
log = { version = "0.4.20", features = ["max_level_trace", "release_max_level_debug"] }
miette = "5.10.0"
notify-rust = { version = "4.10.0", optional = true }
pipewire = { version = "0.7.2", optional = true }
png = "0.17.10"
portable-atomic = { version = "1.6.0", default-features = false, features = ["float"] }
profiling = "1.0.13"
sd-notify = "0.4.1"
serde = { version = "1.0.195", features = ["derive"] }
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
tracing = { version = "0.1.40", features = ["max_level_trace", "release_max_level_debug"] }
tracy-client = { version = "0.16.5", default-features = false }
url = { version = "2.5.0", optional = true }
xcursor = "0.3.5"
zbus = { version = "3.14.1", optional = true }
[workspace.dependencies]
anyhow = "1.0.98"
bitflags = "2.9.1"
clap = { version = "4.5.38", features = ["derive"] }
insta = "1.43.1"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
tracing = { version = "0.1.41", features = ["max_level_trace", "release_max_level_debug"] }
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
tracy-client = { version = "0.18.0", default-features = false }
[dependencies.smithay]
[workspace.dependencies.smithay]
# version = "0.4.1"
git = "https://github.com/Smithay/smithay.git"
# path = "../smithay"
default-features = false
[workspace.dependencies.smithay-drm-extras]
# version = "0.1.0"
git = "https://github.com/Smithay/smithay.git"
# path = "../smithay/smithay-drm-extras"
[package]
name = "niri"
version.workspace = true
description.workspace = true
authors.workspace = true
license.workspace = true
edition.workspace = true
repository.workspace = true
rust-version.workspace = true
readme = "README.md"
keywords = ["wayland", "compositor", "tiling", "smithay", "wm"]
[dependencies]
anyhow.workspace = true
arrayvec = "0.7.6"
async-channel = "2.3.1"
async-io = { version = "2.4.0", optional = true }
atomic = "0.6.0"
bitflags.workspace = true
bytemuck = { version = "1.23.0", features = ["derive"] }
calloop = { version = "0.14.2", features = ["executor", "futures-io"] }
clap = { workspace = true, features = ["string"] }
clap_complete = "4.5.50"
directories = "6.0.0"
drm-ffi = "0.9.0"
fastrand = "2.3.0"
futures-util = { version = "0.3.31", default-features = false, features = ["std", "io"] }
git-version = "0.3.9"
glam = "0.30.3"
input = { version = "0.9.1", features = ["libinput_1_21"] }
keyframe = { version = "1.1.1", default-features = false }
libc = "0.2.172"
libdisplay-info = "0.2.2"
log = { version = "0.4.27", features = ["max_level_trace", "release_max_level_debug"] }
niri-config = { version = "25.5.1", path = "niri-config" }
niri-ipc = { version = "25.5.1", path = "niri-ipc", features = ["clap"] }
ordered-float = "5.0.0"
pango = { version = "0.20.10", features = ["v1_44"] }
pangocairo = "0.20.10"
pipewire = { git = "https://gitlab.freedesktop.org/pipewire/pipewire-rs.git", optional = true, features = ["v0_3_33"] }
png = "0.17.16"
portable-atomic = { version = "1.11.0", default-features = false, features = ["float"] }
profiling = "1.0.16"
sd-notify = "0.4.5"
serde.workspace = true
serde_json.workspace = true
smithay-drm-extras.workspace = true
tracing-subscriber.workspace = true
tracing.workspace = true
tracy-client.workspace = true
url = { version = "2.5.4", optional = true }
wayland-backend = "0.3.10"
wayland-scanner = "0.31.6"
xcursor = "0.3.8"
zbus = { version = "5.7.0", optional = true }
[dependencies.smithay]
workspace = true
features = [
"backend_drm",
"backend_egl",
@@ -53,35 +105,54 @@ features = [
"backend_winit",
"desktop",
"renderer_gl",
"renderer_pixman",
"renderer_multi",
"use_system_lib",
"wayland_frontend",
]
[dependencies.smithay-drm-extras]
git = "https://github.com/Smithay/smithay.git"
# path = "../smithay/smithay-drm-extras"
[dev-dependencies]
proptest = "1.4.0"
proptest-derive = "0.4.0"
approx = "0.5.1"
calloop-wayland-source = "0.4.0"
insta.workspace = true
proptest = "1.6.0"
proptest-derive = { version = "0.5.1", features = ["boxed_union"] }
rayon = "1.10.0"
wayland-client = "0.31.10"
xshell = "0.2.7"
[features]
default = ["dbus", "xdp-gnome-screencast"]
# Enables DBus support (required for xdp-gnome and power button inhibiting).
dbus = ["zbus", "logind-zbus", "async-channel", "async-io", "notify-rust", "url"]
default = ["dbus", "systemd", "xdp-gnome-screencast"]
# Enables D-Bus support (serve various freedesktop and GNOME interfaces, power button handling).
dbus = ["dep:zbus", "dep:async-io", "dep:url"]
# Enables systemd integration (global environment, apps in transient scopes).
systemd = ["dbus"]
# Enables screencasting support through xdg-desktop-portal-gnome.
xdp-gnome-screencast = ["dbus", "pipewire"]
# Enables the Tracy profiler instrumentation.
profile-with-tracy = ["profiling/profile-with-tracy", "tracy-client/default"]
# Enables the on-demand Tracy profiler instrumentation.
profile-with-tracy-ondemand = ["profile-with-tracy", "tracy-client/ondemand", "tracy-client/manual-lifetime"]
# Enables Tracy allocation profiling.
profile-with-tracy-allocations = ["profile-with-tracy"]
# Enables dinit integration (global environment).
dinit = []
[profile.release]
debug = "line-tables-only"
overflow-checks = true
lto = "thin"
[profile.release.package.niri-config]
# knuffel with chomsky generates a metric ton of debuginfo.
debug = false
[profile.dev.package]
insta.opt-level = 3
similar.opt-level = 3
[package.metadata.generate-rpm]
version = "0.1.0~alpha.2"
version = "25.02"
assets = [
{ source = "target/release/niri", dest = "/usr/bin/", mode = "755" },
{ source = "resources/niri-session", dest = "/usr/bin/", mode = "755" },
@@ -92,3 +163,15 @@ assets = [
]
[package.metadata.generate-rpm.requires]
alacritty = "*"
fuzzel = "*"
[package.metadata.deb]
depends = "alacritty, fuzzel"
assets = [
["target/release/niri", "usr/bin/", "755"],
["resources/niri-session", "usr/bin/", "755"],
["resources/niri.desktop", "/usr/share/wayland-sessions/", "644"],
["resources/niri-portals.conf", "/usr/share/xdg-desktop-portal/", "644"],
["resources/niri.service", "/usr/lib/systemd/user/", "644"],
["resources/niri-shutdown.target", "/usr/lib/systemd/user/", "644"],
]
+97 -142
View File
@@ -1,163 +1,118 @@
# niri
<h1 align="center">niri</h1>
<p align="center">A scrollable-tiling Wayland compositor.</p>
<p align="center">
<a href="https://matrix.to/#/#niri:matrix.org"><img alt="Matrix" src="https://img.shields.io/badge/matrix-%23niri-blue?logo=matrix"></a>
<a href="https://github.com/YaLTeR/niri/blob/main/LICENSE"><img alt="GitHub License" src="https://img.shields.io/github/license/YaLTeR/niri"></a>
<a href="https://github.com/YaLTeR/niri/releases"><img alt="GitHub Release" src="https://img.shields.io/github/v/release/YaLTeR/niri?logo=github"></a>
</p>
A scrollable-tiling Wayland compositor.
<p align="center">
<a href="https://github.com/YaLTeR/niri/wiki/Getting-Started">Getting Started</a> | <a href="https://github.com/YaLTeR/niri/wiki/Configuration:-Overview">Configuration</a> | <a href="https://github.com/YaLTeR/niri/discussions/325">Setup&nbsp;Showcase</a>
</p>
![](https://github.com/YaLTeR/niri/assets/1794388/e35fd9e1-105b-4bd5-94c9-207fd6fb3c18)
![niri with a few windows open](https://github.com/user-attachments/assets/535e6530-2f44-4b84-a883-1240a3eee6e9)
## About
Windows are arranged in columns on an infinite strip going to the right.
Opening a new window never causes existing windows to resize.
Every monitor has its own separate window strip.
Windows can never "overflow" onto an adjacent monitor.
Workspaces are dynamic and arranged vertically.
Every monitor has an independent set of workspaces, and there's always one empty workspace present all the way down.
The workspace arrangement is preserved across disconnecting and connecting monitors where it makes sense.
When a monitor disconnects, its workspaces will move to another monitor, but upon reconnection they will move back to the original monitor.
## Features
- Built from the ground up for scrollable tiling
- [Dynamic workspaces](https://github.com/YaLTeR/niri/wiki/Workspaces) like in GNOME
- An [Overview](https://github.com/user-attachments/assets/379a5d1f-acdb-4c11-b36c-e85fd91f0995) that zooms out workspaces and windows
- Built-in screenshot UI
- Monitor and window screencasting through xdg-desktop-portal-gnome
- You can [block out](https://github.com/YaLTeR/niri/wiki/Configuration:-Window-Rules#block-out-from) sensitive windows from screencasts
- [Dynamic cast target](https://github.com/YaLTeR/niri/wiki/Screencasting#dynamic-screencast-target) that can change what it shows on the go
- [Touchpad](https://github.com/YaLTeR/niri/assets/1794388/946a910e-9bec-4cd1-a923-4a9421707515) and [mouse](https://github.com/YaLTeR/niri/assets/1794388/8464e65d-4bf2-44fa-8c8e-5883355bd000) gestures
- Group windows into [tabs](https://github.com/YaLTeR/niri/wiki/Tabs)
- Configurable layout: gaps, borders, struts, window sizes
- [Gradient borders](https://github.com/YaLTeR/niri/wiki/Configuration:-Layout#gradients) with Oklab and Oklch support
- [Animations](https://github.com/YaLTeR/niri/assets/1794388/ce178da2-af9e-4c51-876f-8709c241d95e) with support for [custom shaders](https://github.com/YaLTeR/niri/assets/1794388/27a238d6-0a22-4692-b794-30dc7a626fad)
- Live-reloading config
## Video Demo
https://github.com/YaLTeR/niri/assets/1794388/bce834b0-f205-434e-a027-b373495f9729
## Status
A lot of the essential functionality is implemented, plus some goodies on top.
Feel free to give niri a try.
Have your waybars and fuzzels ready: niri is not a complete desktop environment.
Niri is stable for day-to-day use and does most things expected of a Wayland compositor.
Many people are daily-driving niri, and are happy to help in our [Matrix channel].
https://github.com/YaLTeR/niri/assets/1794388/5d355694-7b06-4f00-8920-8dce54a8721c
Give it a try!
Follow the instructions on the [Getting Started](https://github.com/YaLTeR/niri/wiki/Getting-Started) wiki page.
Have your [waybar]s and [fuzzel]s ready: niri is not a complete desktop environment.
## Idea
Here are some points you may have questions about:
Niri implements scrollable tiling, heavily inspired by [PaperWM].
Windows are arranged in columns on an infinite strip going to the right.
Every column takes up a full monitor worth of height, divided among its windows.
- **Multi-monitor**: yes, a core part of the design from the very start. Mixed DPI works.
- **Fractional scaling**: yes, plus all niri UI stays pixel-perfect.
- **NVIDIA**: seems to work fine.
- **Floating windows**: yes, starting from niri 25.01.
- **Input devices**: niri supports tablets, touchpads, and touchscreens.
You can map the tablet to a specific monitor, or use [OpenTabletDriver].
We have touchpad gestures, but no touchscreen gestures yet.
- **Wlr protocols**: yes, we have most of the important ones like layer-shell, gamma-control, screencopy.
You can check on [wayland.app](https://wayland.app) at the bottom of each protocol's page.
- **Performance**: while I run niri on beefy machines, I try to stay conscious of performance.
I've seen someone use it fine on an Eee PC 900 from 2008, of all things.
- **Xwayland**: no built-in support, but xwayland-satellite is [easy to set up](https://github.com/YaLTeR/niri/wiki/Xwayland#using-xwayland-satellite) and works very well.
- Steam and games, including Proton: work perfectly through xwayland-satellite.
- JetBrains IDEs, Ghidra: work well through xwayland-satellite.
- Discord and other Electron apps: work well through xwayland-satellite.
- Chromium and VSCode: work perfectly natively on Wayland with the right flags.
- X11 apps that want to position windows or bars at specific screen coordinates: won't work well; you can run them in a nested compositor like [labwc](https://github.com/YaLTeR/niri/wiki/Xwayland#using-the-labwc-wayland-compositor) or [rootful Xwayland](https://github.com/YaLTeR/niri/wiki/Xwayland#directly-running-xwayland-in-rootful-mode).
- Display scaling (integer or fractional) keeps X11 apps crisp, but you need the latest xwayland-satellite.
For games, you can run them in [gamescope] at native resolution, even with display scaling.
With multiple monitors, every monitor has its own separate window strip.
Windows can never "overflow" onto an adjacent monitor.
## Inspiration
This is one of the reasons that prompted me to try writing my own compositor.
PaperWM is a solid implementation, but, being a GNOME Shell extension, it has to work around Shell's global window coordinate space to prevent windows from overflowing.
Niri is heavily inspired by [PaperWM] which implements scrollable tiling on top of GNOME Shell.
Niri also has dynamic workspaces which work similar to GNOME Shell.
Since windows go left-to-right horizontally, workspaces are arranged vertically.
Every monitor has an independent set of workspaces, and there's always one empty workspace present all the way down.
One of the reasons that prompted me to try writing my own compositor is being able to properly separate the monitors.
Being a GNOME Shell extension, PaperWM has to work against Shell's global window coordinate space to prevent windows from overflowing.
Niri tries to preserve the workspace arrangement as much as possible upon disconnecting and connecting monitors.
When a monitor disconnects, its workspaces will move to another monitor, but upon reconnection they will move back to the original monitor.
## Tile Scrollably Elsewhere
## Building
Here are some other projects which implement a similar workflow:
> [!TIP]
> For Fedora users, there's a COPR with built and packaged niri: https://copr.fedorainfracloud.org/coprs/yalter/niri/
>
> NixOS users, check out https://github.com/sodiboo/niri-flake
- [PaperWM]: scrollable tiling on top of GNOME Shell.
- [karousel]: scrollable tiling on top of KDE.
- [scroll](https://github.com/dawsers/scroll) and [papersway]: scrollable tiling on top of sway/i3.
- [hyprscrolling] and [hyprslidr]: scrollable tiling on top of Hyprland.
- [PaperWM.spoon]: scrollable tiling on top of macOS.
First, install the dependencies for your distribution.
## Media
- Ubuntu:
[niri: Making a Wayland compositor in Rust](https://youtu.be/Kmz8ODolnDg?list=PLRdS-n5seLRqrmWDQY4KDqtRMfIwU0U3T)
```sh
sudo apt-get install -y software-properties-common
sudo add-apt-repository -y ppa:pipewire-debian/pipewire-upstream
sudo apt-get update -y
sudo apt-get install -y libudev-dev libgbm-dev libxkbcommon-dev libegl1-mesa-dev libwayland-dev libinput-dev libdbus-1-dev libsystemd-dev libseat-dev libpipewire-0.3-dev
```
My talk from the 2024 Moscow RustCon about niri, and how I do randomized property testing and profiling, and measure input latency.
The talk is in Russian, but I prepared full English subtitles that you can find in YouTube's subtitle language selector.
- Fedora:
## Contact
```sh
sudo dnf install gcc libudev-devel libgbm-devel libxkbcommon-devel wayland-devel libinput-devel dbus-devel systemd-devel libseat-devel pipewire-devel clang
```
Next, build niri with `cargo build --release`.
## Installation
The recommended way to install and run niri is as a standalone desktop session.
To do that, put files into the correct directories according to this table.
| File | Destination |
| ---- | ----------- |
| `target/release/niri` | `/usr/bin/` |
| `resources/niri-session` | `/usr/bin/` |
| `resources/niri.desktop` | `/usr/share/wayland-sessions/` |
| `resources/niri-portals.conf` | `/usr/share/xdg-desktop-portal/` |
| `resources/niri.service` | `/usr/lib/systemd/user/` |
| `resources/niri-shutdown.target` | `/usr/lib/systemd/user/` |
Doing this will make niri appear in GDM and, presumably, other display managers.
## Running
`cargo run --release`
Inside an existing desktop session, it will run in a window.
On a TTY, it will run natively.
To exit when running on a TTY, press <kbd>Super</kbd><kbd>Shift</kbd><kbd>E</kbd>.
### Session
If you followed the recommended installation steps above, niri should appear in your display manager.
Starting it from there will run niri as a desktop session.
The niri session will autostart apps through the systemd xdg-autostart target.
You can also autostart systemd services like [mako] by symlinking them into `$HOME/.config/systemd/user/niri.service.wants/`.
A step-by-step process for this is explained [on the wiki](https://github.com/YaLTeR/niri/wiki/Example-systemd-Setup).
Niri also works with some parts of xdg-desktop-portal-gnome.
In particular, it supports file choosers and monitor screencasting (e.g. to [OBS]).
### Xwayland
See [the wiki page](https://github.com/YaLTeR/niri/wiki/Xwayland) to learn how to use Xwayland with niri.
## Default Hotkeys
When running on a TTY, the Mod key is <kbd>Super</kbd>.
When running in a window, the Mod key is <kbd>Alt</kbd>.
The general system is: if a hotkey switches somewhere, then adding <kbd>Ctrl</kbd> will move the focused window or column there.
| Hotkey | Description |
| ------ | ----------- |
| <kbd>Mod</kbd><kbd>T</kbd> | Spawn `alacritty` (terminal) |
| <kbd>Mod</kbd><kbd>D</kbd> | Spawn `fuzzel` (application launcher) |
| <kbd>Mod</kbd><kbd>Alt</kbd><kbd>L</kbd> | Spawn `swaylock` (screen locker) |
| <kbd>Mod</kbd><kbd>Q</kbd> | Close the focused window |
| <kbd>Mod</kbd><kbd>H</kbd> or <kbd>Mod</kbd><kbd>←</kbd> | Focus the column to the left |
| <kbd>Mod</kbd><kbd>L</kbd> or <kbd>Mod</kbd><kbd>→</kbd> | Focus the column to the right |
| <kbd>Mod</kbd><kbd>J</kbd> or <kbd>Mod</kbd><kbd>↓</kbd> | Focus the window below in a column |
| <kbd>Mod</kbd><kbd>K</kbd> or <kbd>Mod</kbd><kbd>↑</kbd> | Focus the window above in a column |
| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>H</kbd> or <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>←</kbd> | Move the focused column to the left |
| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>L</kbd> or <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>→</kbd> | Move the focused column to the right |
| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>J</kbd> or <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>↓</kbd> | Move the focused window below in a column |
| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>K</kbd> or <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>↑</kbd> | Move the focused window above in a column |
| <kbd>Mod</kbd><kbd>Home</kbd> and <kbd>Mod</kbd><kbd>End</kbd> | Focus the first or the last column |
| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>Home</kbd> and <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>End</kbd> | Move the focused column to the very start or to the very end |
| <kbd>Mod</kbd><kbd>Shift</kbd><kbd>H</kbd><kbd>J</kbd><kbd>K</kbd><kbd>L</kbd> or <kbd>Mod</kbd><kbd>Shift</kbd><kbd>←</kbd><kbd>↓</kbd><kbd>↑</kbd><kbd>→</kbd> | Focus the monitor to the side |
| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>H</kbd><kbd>J</kbd><kbd>K</kbd><kbd>L</kbd> or <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>←</kbd><kbd>↓</kbd><kbd>↑</kbd><kbd>→</kbd> | Move the focused window to the monitor to the side |
| <kbd>Mod</kbd><kbd>U</kbd> or <kbd>Mod</kbd><kbd>PageDown</kbd> | Switch to the workspace below |
| <kbd>Mod</kbd><kbd>I</kbd> or <kbd>Mod</kbd><kbd>PageUp</kbd> | Switch to the workspace above |
| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>U</kbd> or <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>PageDown</kbd> | Move the focused window to the workspace below |
| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>I</kbd> or <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>PageUp</kbd> | Move the focused window to the workspace above |
| <kbd>Mod</kbd><kbd>1</kbd><kbd>9</kbd> | Switch to a workspace by index |
| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>1</kbd><kbd>9</kbd> | Move the focused window to a workspace by index |
| <kbd>Mod</kbd><kbd>Shift</kbd><kbd>U</kbd> or <kbd>Mod</kbd><kbd>Shift</kbd><kbd>PageDown</kbd> | Move the focused workspace down |
| <kbd>Mod</kbd><kbd>Shift</kbd><kbd>I</kbd> or <kbd>Mod</kbd><kbd>Shift</kbd><kbd>PageUp</kbd> | Move the focused workspace up |
| <kbd>Mod</kbd><kbd>,</kbd> | Consume the window to the right into the focused column |
| <kbd>Mod</kbd><kbd>.</kbd> | Expel the focused window into its own column |
| <kbd>Mod</kbd><kbd>R</kbd> | Toggle between preset column widths |
| <kbd>Mod</kbd><kbd>F</kbd> | Maximize column |
| <kbd>Mod</kbd><kbd>C</kbd> | Center column within view |
| <kbd>Mod</kbd><kbd>-</kbd> | Decrease column width by 10% |
| <kbd>Mod</kbd><kbd>=</kbd> | Increase column width by 10% |
| <kbd>Mod</kbd><kbd>Shift</kbd><kbd>-</kbd> | Decrease window height by 10% |
| <kbd>Mod</kbd><kbd>Shift</kbd><kbd>=</kbd> | Increase window height by 10% |
| <kbd>Mod</kbd><kbd>Shift</kbd><kbd>F</kbd> | Toggle full-screen on the focused window |
| <kbd>PrtSc</kbd> | Take an area screenshot. Select the area to screenshot with mouse, then press Space to save the screenshot, or Escape to cancel |
| <kbd>Alt</kbd><kbd>PrtSc</kbd> | Take a screenshot of the focused window to clipboard and to `~/Pictures/Screenshots/` |
| <kbd>Ctrl</kbd><kbd>PrtSc</kbd> | Take a screenshot of the focused monitor to clipboard and to `~/Pictures/Screenshots/` |
| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>T</kbd> | Toggle debug tinting of rendered elements |
| <kbd>Mod</kbd><kbd>Shift</kbd><kbd>E</kbd> | Exit niri |
## Configuration
Niri will load configuration from `$XDG_CONFIG_HOME/.config/niri/config.kdl` or `~/.config/niri/config.kdl`.
If this fails, it will load [the default configuration file](resources/default-config.kdl).
Please use the default configuration file as the starting point for your custom configuration.
Niri will live-reload many of the configuration settings, like key binds or gaps, as you change the config file.
Though, some settings are still missing live-reload support.
Notably, output modes and positions will only apply when the output is reconnected.
We have a Matrix chat, feel free to join and ask a question: https://matrix.to/#/#niri:matrix.org
[PaperWM]: https://github.com/paperwm/PaperWM
[mako]: https://github.com/emersion/mako
[OBS]: https://flathub.org/apps/com.obsproject.Studio
[waybar]: https://github.com/Alexays/Waybar
[fuzzel]: https://codeberg.org/dnkl/fuzzel
[karousel]: https://github.com/peterfajdiga/karousel
[papersway]: https://spwhitton.name/tech/code/papersway/
[hyprscrolling]: https://github.com/hyprwm/hyprland-plugins/tree/main/hyprscrolling
[hyprslidr]: https://gitlab.com/magus/hyprslidr
[PaperWM.spoon]: https://github.com/mogenson/PaperWM.spoon
[Matrix channel]: https://matrix.to/#/#niri:matrix.org
[OpenTabletDriver]: https://opentabletdriver.net/
[gamescope]: https://github.com/ValveSoftware/gamescope
+5
View File
@@ -0,0 +1,5 @@
ignore-interior-mutability = [
"smithay::desktop::Window",
"smithay::output::Output",
"wayland_server::backend::ClientId",
]
Generated
+64
View File
@@ -0,0 +1,64 @@
{
"nodes": {
"nix-filter": {
"locked": {
"lastModified": 1731533336,
"narHash": "sha256-oRam5PS1vcrr5UPgALW0eo1m/5/pls27Z/pabHNy2Ms=",
"owner": "numtide",
"repo": "nix-filter",
"rev": "f7653272fd234696ae94229839a99b73c9ab7de0",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "nix-filter",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1742707865,
"narHash": "sha256-RVQQZy38O3Zb8yoRJhuFgWo/iDIDj0hEdRTVfhOtzRk=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "dd613136ee91f67e5dba3f3f41ac99ae89c5406b",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nix-filter": "nix-filter",
"nixpkgs": "nixpkgs",
"rust-overlay": "rust-overlay"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1742697269,
"narHash": "sha256-Lpp0XyAtIl1oGJzNmTiTGLhTkcUjwSkEb0gOiNzYFGM=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "01973c84732f9275c50c5f075dd1f54cc04b3316",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
}
},
"root": "root",
"version": 7
}
+261
View File
@@ -0,0 +1,261 @@
# This flake file is community maintained
{
description = "Niri: A scrollable-tiling Wayland compositor.";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
nix-filter.url = "github:numtide/nix-filter";
# NOTE: This is not necessary for end users
# You can omit it with `inputs.rust-overlay.follows = ""`
rust-overlay = {
url = "github:oxalica/rust-overlay";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs =
{
self,
nixpkgs,
nix-filter,
rust-overlay,
}:
let
niri-package =
{
lib,
cairo,
dbus,
libGL,
libdisplay-info,
libinput,
seatd,
libxkbcommon,
libgbm,
pango,
pipewire,
pkg-config,
rustPlatform,
systemd,
wayland,
installShellFiles,
withDbus ? true,
withSystemd ? true,
withScreencastSupport ? true,
withDinit ? false,
}:
rustPlatform.buildRustPackage {
pname = "niri";
version = self.shortRev or self.dirtyShortRev or "unknown";
src = nix-filter.lib.filter {
root = self;
include = [
"niri-config"
"niri-ipc"
"niri-visual-tests"
"resources"
"src"
./Cargo.lock
./Cargo.toml
];
};
postPatch = ''
patchShebangs resources/niri-session
substituteInPlace resources/niri.service \
--replace-fail '/usr/bin' "$out/bin"
'';
cargoLock = {
# NOTE: This is only used for Git dependencies
allowBuiltinFetchGit = true;
lockFile = ./Cargo.lock;
};
strictDeps = true;
nativeBuildInputs = [
rustPlatform.bindgenHook
pkg-config
installShellFiles
];
buildInputs =
[
cairo
dbus
libGL
libdisplay-info
libinput
seatd
libxkbcommon
libgbm
pango
wayland
]
++ lib.optional (withDbus || withScreencastSupport || withSystemd) dbus
++ lib.optional withScreencastSupport pipewire
# Also includes libudev
++ lib.optional withSystemd systemd;
buildFeatures =
lib.optional withDbus "dbus"
++ lib.optional withDinit "dinit"
++ lib.optional withScreencastSupport "xdp-gnome-screencast"
++ lib.optional withSystemd "systemd";
buildNoDefaultFeatures = true;
# ever since this commit:
# https://github.com/YaLTeR/niri/commit/771ea1e81557ffe7af9cbdbec161601575b64d81
# niri now runs an actual instance of the real compositor (with a mock backend) during tests
# and thus creates a real socket file in the runtime dir.
# this is fine for our build, we just need to make sure it has a directory to write to.
preCheck = ''
export XDG_RUNTIME_DIR="$(mktemp -d)"
'';
postInstall =
''
installShellCompletion --cmd niri \
--bash <($out/bin/niri completions bash) \
--fish <($out/bin/niri completions fish) \
--zsh <($out/bin/niri completions zsh)
install -Dm644 resources/niri.desktop -t $out/share/wayland-sessions
install -Dm644 resources/niri-portals.conf -t $out/share/xdg-desktop-portal
''
+ lib.optionalString withSystemd ''
install -Dm755 resources/niri-session $out/bin/niri-session
install -Dm644 resources/niri{.service,-shutdown.target} -t $out/share/systemd/user
'';
env = {
# Force linking with libEGL and libwayland-client
# so they can be discovered by `dlopen()`
RUSTFLAGS = toString (
map (arg: "-C link-arg=" + arg) [
"-Wl,--push-state,--no-as-needed"
"-lEGL"
"-lwayland-client"
"-Wl,--pop-state"
]
);
};
passthru = {
providedSessions = [ "niri" ];
};
meta = {
description = "Scrollable-tiling Wayland compositor";
homepage = "https://github.com/YaLTeR/niri";
license = lib.licenses.gpl3Only;
mainProgram = "niri";
platforms = lib.platforms.linux;
};
};
inherit (nixpkgs) lib;
# Support all Linux systems that the nixpkgs flake exposes
systems = lib.intersectLists lib.systems.flakeExposed lib.platforms.linux;
forAllSystems = lib.genAttrs systems;
nixpkgsFor = forAllSystems (system: nixpkgs.legacyPackages.${system});
in
{
checks = forAllSystems (system: {
# We use the debug build here to save a bit of time
inherit (self.packages.${system}) niri-debug;
});
devShells = forAllSystems (
system:
let
pkgs = nixpkgsFor.${system};
rust-bin = rust-overlay.lib.mkRustBin { } pkgs;
inherit (self.packages.${system}) niri;
in
{
default = pkgs.mkShell {
packages = [
# We don't use the toolchain from nixpkgs
# because we prefer a nightly toolchain
# and we *require* a nightly rustfmt
(rust-bin.selectLatestNightlyWith (
toolchain:
toolchain.default.override {
extensions = [
# includes already:
# rustc
# cargo
# rust-std
# rust-docs
# rustfmt-preview
# clippy-preview
"rust-analyzer"
"rust-src"
];
}
))
];
nativeBuildInputs = [
pkgs.rustPlatform.bindgenHook
pkgs.pkg-config
pkgs.wrapGAppsHook4 # For `niri-visual-tests`
];
buildInputs = niri.buildInputs ++ [
pkgs.libadwaita # For `niri-visual-tests`
];
env = {
# WARN: Do not overwrite this variable in your shell!
# It is required for `dlopen()` to work on some libraries; see the comment
# in the package expression
#
# This should only be set with `CARGO_BUILD_RUSTFLAGS="$CARGO_BUILD_RUSTFLAGS -C your-flags"`
CARGO_BUILD_RUSTFLAGS = niri.RUSTFLAGS;
};
};
}
);
formatter = forAllSystems (system: nixpkgsFor.${system}.nixfmt-rfc-style);
packages = forAllSystems (
system:
let
niri = nixpkgsFor.${system}.callPackage niri-package { };
in
{
inherit niri;
# NOTE: This is for development purposes only
#
# It is primarily to help with quickly iterating on
# changes made to the above expression - though it is
# also not stripped in order to better debug niri itself
niri-debug = niri.overrideAttrs (
newAttrs: oldAttrs: {
pname = oldAttrs.pname + "-debug";
cargoBuildType = "debug";
cargoCheckType = newAttrs.cargoBuildType;
dontStrip = true;
}
);
default = niri;
}
);
overlays.default = final: _: {
niri = final.callPackage niri-package { };
};
};
}
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "niri-config"
version.workspace = true
description.workspace = true
authors.workspace = true
license.workspace = true
edition.workspace = true
repository.workspace = true
[dependencies]
bitflags.workspace = true
csscolorparser = "0.7.0"
knuffel = "3.2.0"
miette = { version = "5.10.0", features = ["fancy-no-backtrace"] }
niri-ipc = { version = "25.5.1", path = "../niri-ipc" }
regex = "1.11.1"
smithay = { workspace = true, features = ["backend_libinput"] }
tracing.workspace = true
tracy-client.workspace = true
[dev-dependencies]
insta.workspace = true
pretty_assertions = "1.4.1"
+30
View File
@@ -0,0 +1,30 @@
use crate::{BlockOutFrom, CornerRadius, RegexEq, ShadowRule};
#[derive(knuffel::Decode, Debug, Default, Clone, PartialEq)]
pub struct LayerRule {
#[knuffel(children(name = "match"))]
pub matches: Vec<Match>,
#[knuffel(children(name = "exclude"))]
pub excludes: Vec<Match>,
#[knuffel(child, unwrap(argument))]
pub opacity: Option<f32>,
#[knuffel(child, unwrap(argument))]
pub block_out_from: Option<BlockOutFrom>,
#[knuffel(child, default)]
pub shadow: ShadowRule,
#[knuffel(child)]
pub geometry_corner_radius: Option<CornerRadius>,
#[knuffel(child, unwrap(argument))]
pub place_within_backdrop: Option<bool>,
#[knuffel(child, unwrap(argument))]
pub baba_is_float: Option<bool>,
}
#[derive(knuffel::Decode, Debug, Default, Clone, PartialEq)]
pub struct Match {
#[knuffel(property, str)]
pub namespace: Option<RegexEq>,
#[knuffel(property)]
pub at_startup: Option<bool>,
}
File diff suppressed because it is too large Load Diff
+23
View File
@@ -0,0 +1,23 @@
use std::str::FromStr;
use regex::Regex;
/// `Regex` that implements `PartialEq` by its string form.
#[derive(Debug, Clone)]
pub struct RegexEq(pub Regex);
impl PartialEq for RegexEq {
fn eq(&self, other: &Self) -> bool {
self.0.as_str() == other.0.as_str()
}
}
impl Eq for RegexEq {}
impl FromStr for RegexEq {
type Err = <Regex as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Regex::from_str(s).map(Self)
}
}
+111
View File
@@ -0,0 +1,111 @@
use std::fs;
use std::path::PathBuf;
struct KdlCodeBlock {
filename: String,
code: String,
line_number: usize,
must_fail: bool,
}
fn extract_kdl_from_file(file_contents: &str, filename: &str) -> Vec<KdlCodeBlock> {
let mut lines = file_contents
.lines()
.map(|line| {
// Removes the > from callouts that might contain ```kdl```
let line = line.trim();
if line.starts_with('>') {
if line.len() == 1 {
""
} else {
&line[2..]
}
} else {
line
}
})
.enumerate();
let mut kdl_code_blocks = vec![];
while let Some((line_number, line)) = lines.next() {
if !line.starts_with("```kdl") {
continue;
}
let mut snippet = String::new();
for (_, line) in lines
.by_ref()
.take_while(|(_, line)| !line.starts_with("```"))
{
snippet.push_str(line);
snippet.push('\n');
}
kdl_code_blocks.push(KdlCodeBlock {
code: snippet,
line_number,
filename: filename.to_string(),
must_fail: line.contains("must-fail"),
});
}
kdl_code_blocks
}
#[test]
fn wiki_docs_parses() {
let wiki_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../wiki");
let code_blocks = fs::read_dir(wiki_dir)
.unwrap()
.filter_map(|entry| entry.ok())
.filter(|entry| entry.file_type().is_ok_and(|ft| ft.is_file()))
.filter(|file| {
file.path()
.extension()
.map(|ext| ext == "md")
.unwrap_or(false)
})
.flat_map(|file| {
let file_contents = fs::read_to_string(file.path()).unwrap();
let file_path = file.path();
let filename = file_path.to_str().unwrap();
extract_kdl_from_file(&file_contents, filename)
});
let mut errors = vec![];
for KdlCodeBlock {
code,
line_number,
filename,
must_fail,
} in code_blocks
{
if let Err(error) = niri_config::Config::parse(&filename, &code) {
if !must_fail {
errors.push(format!(
"Error parsing wiki KDL code block at {}:{}: {:?}",
filename,
line_number,
miette::Report::new(error)
));
}
} else if must_fail {
errors.push(format!(
"Expected error parsing wiki KDL code block at {}:{}",
filename, line_number
));
}
}
if !errors.is_empty() {
panic!(
"Errors parsing {} wiki KDL code blocks:\n{}",
errors.len(),
errors.join("\n")
);
}
}
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "niri-ipc"
version.workspace = true
authors.workspace = true
license.workspace = true
edition.workspace = true
repository.workspace = true
description = "Types and helpers for interfacing with the niri Wayland compositor."
keywords = ["wayland"]
categories = ["api-bindings", "os"]
readme = "README.md"
[dependencies]
clap = { workspace = true, optional = true }
schemars = { version = "0.8.22", optional = true }
serde.workspace = true
serde_json.workspace = true
[features]
clap = ["dep:clap"]
json-schema = ["dep:schemars"]
+16
View File
@@ -0,0 +1,16 @@
# niri-ipc
Types and helpers for interfacing with the [niri](https://github.com/YaLTeR/niri) Wayland compositor.
## Backwards compatibility
This crate follows the niri version.
It is **not** API-stable in terms of the Rust semver.
In particular, expect new struct fields and enum variants to be added in patch version bumps.
Use an exact version requirement to avoid breaking changes:
```toml
[dependencies]
niri-ipc = "=25.5.1"
```
+1523
View File
File diff suppressed because it is too large Load Diff
+101
View File
@@ -0,0 +1,101 @@
//! Helper for blocking communication over the niri socket.
use std::env;
use std::io::{self, BufRead, BufReader, Write};
use std::net::Shutdown;
use std::os::unix::net::UnixStream;
use std::path::Path;
use crate::{Event, Reply, Request};
/// Name of the environment variable containing the niri IPC socket path.
pub const SOCKET_PATH_ENV: &str = "NIRI_SOCKET";
/// Helper for blocking communication over the niri socket.
///
/// This struct is used to communicate with the niri IPC server. It handles the socket connection
/// and serialization/deserialization of messages.
pub struct Socket {
stream: BufReader<UnixStream>,
}
impl Socket {
/// Connects to the default niri IPC socket.
///
/// This is equivalent to calling [`Self::connect_to`] with the path taken from the
/// [`SOCKET_PATH_ENV`] environment variable.
pub fn connect() -> io::Result<Self> {
let socket_path = env::var_os(SOCKET_PATH_ENV).ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("{SOCKET_PATH_ENV} is not set, are you running this within niri?"),
)
})?;
Self::connect_to(socket_path)
}
/// Connects to the niri IPC socket at the given path.
pub fn connect_to(path: impl AsRef<Path>) -> io::Result<Self> {
let stream = UnixStream::connect(path.as_ref())?;
let stream = BufReader::new(stream);
Ok(Self { stream })
}
/// Sends a request to niri and returns the response.
///
/// Return values:
///
/// * `Ok(Ok(response))`: successful [`Response`](crate::Response) from niri
/// * `Ok(Err(message))`: error message from niri
/// * `Err(error)`: error communicating with niri
pub fn send(&mut self, request: Request) -> io::Result<Reply> {
let mut buf = serde_json::to_string(&request).unwrap();
buf.push('\n');
self.stream.get_mut().write_all(buf.as_bytes())?;
buf.clear();
self.stream.read_line(&mut buf)?;
let reply = serde_json::from_str(&buf)?;
Ok(reply)
}
/// Starts reading event stream [`Event`]s from the socket.
///
/// The returned function will block until the next [`Event`] arrives, then return it.
///
/// Use this only after requesting an [`EventStream`][Request::EventStream].
///
/// # Examples
///
/// ```no_run
/// use niri_ipc::{Request, Response};
/// use niri_ipc::socket::Socket;
///
/// fn main() -> std::io::Result<()> {
/// let mut socket = Socket::connect()?;
///
/// let reply = socket.send(Request::EventStream)?;
/// if matches!(reply, Ok(Response::Handled)) {
/// let mut read_event = socket.read_events();
/// while let Ok(event) = read_event() {
/// println!("Received event: {event:?}");
/// }
/// }
///
/// Ok(())
/// }
/// ```
pub fn read_events(self) -> impl FnMut() -> io::Result<Event> {
let Self { mut stream } = self;
let _ = stream.get_mut().shutdown(Shutdown::Write);
let mut buf = String::new();
move || {
buf.clear();
stream.read_line(&mut buf)?;
let event = serde_json::from_str(&buf)?;
Ok(event)
}
}
}
+239
View File
@@ -0,0 +1,239 @@
//! Helpers for keeping track of the event stream state.
//!
//! 1. Create an [`EventStreamState`] using `Default::default()`, or any individual state part if
//! you only care about part of the state.
//! 2. Connect to the niri socket and request an event stream.
//! 3. Pass every [`Event`] to [`EventStreamStatePart::apply`] on your state.
//! 4. Read the fields of the state as needed.
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use crate::{Event, KeyboardLayouts, Window, Workspace};
/// Part of the state communicated via the event stream.
pub trait EventStreamStatePart {
/// Returns a sequence of events that replicates this state from default initialization.
fn replicate(&self) -> Vec<Event>;
/// Applies the event to this state.
///
/// Returns `None` after applying the event, and `Some(event)` if the event is ignored by this
/// part of the state.
fn apply(&mut self, event: Event) -> Option<Event>;
}
/// The full state communicated over the event stream.
///
/// Different parts of the state are not guaranteed to be consistent across every single event
/// sent by niri. For example, you may receive the first [`Event::WindowOpenedOrChanged`] for a
/// just-opened window *after* an [`Event::WorkspaceActiveWindowChanged`] for that window. Between
/// these two events, the workspace active window id refers to a window that does not yet exist in
/// the windows state part.
#[derive(Debug, Default)]
pub struct EventStreamState {
/// State of workspaces.
pub workspaces: WorkspacesState,
/// State of workspaces.
pub windows: WindowsState,
/// State of the keyboard layouts.
pub keyboard_layouts: KeyboardLayoutsState,
/// State of the overview.
pub overview: OverviewState,
}
/// The workspaces state communicated over the event stream.
#[derive(Debug, Default)]
pub struct WorkspacesState {
/// Map from a workspace id to the workspace.
pub workspaces: HashMap<u64, Workspace>,
}
/// The windows state communicated over the event stream.
#[derive(Debug, Default)]
pub struct WindowsState {
/// Map from a window id to the window.
pub windows: HashMap<u64, Window>,
}
/// The keyboard layout state communicated over the event stream.
#[derive(Debug, Default)]
pub struct KeyboardLayoutsState {
/// Configured keyboard layouts.
pub keyboard_layouts: Option<KeyboardLayouts>,
}
/// The overview state communicated over the event stream.
#[derive(Debug, Default)]
pub struct OverviewState {
/// Whether the overview is currently open.
pub is_open: bool,
}
impl EventStreamStatePart for EventStreamState {
fn replicate(&self) -> Vec<Event> {
let mut events = Vec::new();
events.extend(self.workspaces.replicate());
events.extend(self.windows.replicate());
events.extend(self.keyboard_layouts.replicate());
events.extend(self.overview.replicate());
events
}
fn apply(&mut self, event: Event) -> Option<Event> {
let event = self.workspaces.apply(event)?;
let event = self.windows.apply(event)?;
let event = self.keyboard_layouts.apply(event)?;
let event = self.overview.apply(event)?;
Some(event)
}
}
impl EventStreamStatePart for WorkspacesState {
fn replicate(&self) -> Vec<Event> {
let workspaces = self.workspaces.values().cloned().collect();
vec![Event::WorkspacesChanged { workspaces }]
}
fn apply(&mut self, event: Event) -> Option<Event> {
match event {
Event::WorkspacesChanged { workspaces } => {
self.workspaces = workspaces.into_iter().map(|ws| (ws.id, ws)).collect();
}
Event::WorkspaceUrgencyChanged { id, urgent } => {
for ws in self.workspaces.values_mut() {
if ws.id == id {
ws.is_urgent = urgent;
}
}
}
Event::WorkspaceActivated { id, focused } => {
let ws = self.workspaces.get(&id);
let ws = ws.expect("activated workspace was missing from the map");
let output = ws.output.clone();
for ws in self.workspaces.values_mut() {
let got_activated = ws.id == id;
if ws.output == output {
ws.is_active = got_activated;
}
if focused {
ws.is_focused = got_activated;
}
}
}
Event::WorkspaceActiveWindowChanged {
workspace_id,
active_window_id,
} => {
let ws = self.workspaces.get_mut(&workspace_id);
let ws = ws.expect("changed workspace was missing from the map");
ws.active_window_id = active_window_id;
}
event => return Some(event),
}
None
}
}
impl EventStreamStatePart for WindowsState {
fn replicate(&self) -> Vec<Event> {
let windows = self.windows.values().cloned().collect();
vec![Event::WindowsChanged { windows }]
}
fn apply(&mut self, event: Event) -> Option<Event> {
match event {
Event::WindowsChanged { windows } => {
self.windows = windows.into_iter().map(|win| (win.id, win)).collect();
}
Event::WindowOpenedOrChanged { window } => {
let (id, is_focused) = match self.windows.entry(window.id) {
Entry::Occupied(mut entry) => {
let entry = entry.get_mut();
*entry = window;
(entry.id, entry.is_focused)
}
Entry::Vacant(entry) => {
let entry = entry.insert(window);
(entry.id, entry.is_focused)
}
};
if is_focused {
for win in self.windows.values_mut() {
if win.id != id {
win.is_focused = false;
}
}
}
}
Event::WindowClosed { id } => {
let win = self.windows.remove(&id);
win.expect("closed window was missing from the map");
}
Event::WindowFocusChanged { id } => {
for win in self.windows.values_mut() {
win.is_focused = Some(win.id) == id;
}
}
Event::WindowUrgencyChanged { id, urgent } => {
for win in self.windows.values_mut() {
if win.id == id {
win.is_urgent = urgent;
break;
}
}
}
event => return Some(event),
}
None
}
}
impl EventStreamStatePart for KeyboardLayoutsState {
fn replicate(&self) -> Vec<Event> {
if let Some(keyboard_layouts) = self.keyboard_layouts.clone() {
vec![Event::KeyboardLayoutsChanged { keyboard_layouts }]
} else {
vec![]
}
}
fn apply(&mut self, event: Event) -> Option<Event> {
match event {
Event::KeyboardLayoutsChanged { keyboard_layouts } => {
self.keyboard_layouts = Some(keyboard_layouts);
}
Event::KeyboardLayoutSwitched { idx } => {
let kb = self.keyboard_layouts.as_mut();
let kb = kb.expect("keyboard layouts must be set before a layout can be switched");
kb.current_idx = idx;
}
event => return Some(event),
}
None
}
}
impl EventStreamStatePart for OverviewState {
fn replicate(&self) -> Vec<Event> {
vec![Event::OverviewOpenedOrClosed {
is_open: self.is_open,
}]
}
fn apply(&mut self, event: Event) -> Option<Event> {
match event {
Event::OverviewOpenedOrClosed { is_open } => {
self.is_open = is_open;
}
event => return Some(event),
}
None
}
}
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "niri-visual-tests"
version.workspace = true
description.workspace = true
authors.workspace = true
license.workspace = true
edition.workspace = true
repository.workspace = true
[dependencies]
adw = { version = "0.7.2", package = "libadwaita", features = ["v1_4"] }
anyhow.workspace = true
gtk = { version = "0.9.6", package = "gtk4", features = ["v4_12"] }
niri = { version = "25.5.1", path = ".." }
niri-config = { version = "25.5.1", path = "../niri-config" }
smithay.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
+14
View File
@@ -0,0 +1,14 @@
# niri-visual-tests
> [!NOTE]
>
> This is a development-only app, you shouldn't package it.
This app contains a number of hard-coded test scenarios for visual inspection.
It uses the real niri layout and rendering code, but with mock windows instead of Wayland clients.
The idea is to go through the test scenarios and check that everything *looks* right.
## Running
You will need recent GTK and libadwaita.
Then, `cargo run`.
+3
View File
@@ -0,0 +1,3 @@
.anim-control-bar {
padding: 12px;
}
@@ -0,0 +1,73 @@
use std::f32::consts::{FRAC_PI_2, PI};
use std::time::Duration;
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{Color, CornerRadius, GradientInterpolation};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientAngle {
angle: f32,
prev_time: Duration,
}
impl GradientAngle {
pub fn new(_args: Args) -> Self {
Self {
angle: 0.,
prev_time: Duration::ZERO,
}
}
}
impl TestCase for GradientAngle {
fn are_animations_ongoing(&self) -> bool {
true
}
fn advance_animations(&mut self, current_time: Duration) {
let delta = if self.prev_time.is_zero() {
Duration::ZERO
} else {
current_time.saturating_sub(self.prev_time)
};
self.prev_time = current_time;
self.angle += delta.as_secs_f32() * PI;
if self.angle >= PI * 2. {
self.angle -= PI * 2.
}
}
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 4, size.h / 4);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
GradientInterpolation::default(),
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 1.),
self.angle - FRAC_PI_2,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
@@ -0,0 +1,119 @@
use std::f32::consts::{FRAC_PI_4, PI};
use std::time::Duration;
use niri::layout::focus_ring::FocusRing;
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{Color, CornerRadius, FloatOrInt, GradientInterpolation};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientArea {
progress: f32,
border: FocusRing,
prev_time: Duration,
}
impl GradientArea {
pub fn new(_args: Args) -> Self {
let border = FocusRing::new(niri_config::FocusRing {
off: false,
width: FloatOrInt(1.),
active_color: Color::from_rgba8_unpremul(255, 255, 255, 128),
inactive_color: Color::default(),
urgent_color: Color::default(),
active_gradient: None,
inactive_gradient: None,
urgent_gradient: None,
});
Self {
progress: 0.,
border,
prev_time: Duration::ZERO,
}
}
}
impl TestCase for GradientArea {
fn are_animations_ongoing(&self) -> bool {
true
}
fn advance_animations(&mut self, current_time: Duration) {
let delta = if self.prev_time.is_zero() {
Duration::ZERO
} else {
current_time.saturating_sub(self.prev_time)
};
self.prev_time = current_time;
self.progress += delta.as_secs_f32() * PI;
if self.progress >= PI * 2. {
self.progress -= PI * 2.
}
}
fn render(
&mut self,
renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let mut rv = Vec::new();
let f = (self.progress.sin() + 1.) / 2.;
let (a, b) = (size.w / 4, size.h / 4);
let rect_size = Size::from((size.w - a * 2, size.h - b * 2));
let area = Rectangle::new(Point::from((a, b)), rect_size).to_f64();
let g_size = Size::from((
(size.w as f32 / 8. + size.w as f32 / 8. * 7. * f).round() as i32,
(size.h as f32 / 8. + size.h as f32 / 8. * 7. * f).round() as i32,
));
let g_loc = Point::from(((size.w - g_size.w) / 2, (size.h - g_size.h) / 2)).to_f64();
let g_size = g_size.to_f64();
let mut g_area = Rectangle::new(g_loc, g_size);
g_area.loc -= area.loc;
self.border.update_render_elements(
g_size,
true,
true,
false,
Rectangle::default(),
CornerRadius::default(),
1.,
1.,
);
rv.extend(
self.border
.render(renderer, g_loc)
.map(|elem| Box::new(elem) as _),
);
rv.extend(
[BorderRenderElement::new(
area.size,
g_area,
GradientInterpolation::default(),
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 1.),
FRAC_PI_4,
Rectangle::from_size(rect_size).to_f64(),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _),
);
rv
}
}
@@ -0,0 +1,54 @@
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{
Color, CornerRadius, GradientColorSpace, GradientInterpolation, HueInterpolation,
};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientOklab {
gradient_format: GradientInterpolation,
}
impl GradientOklab {
pub fn new(_args: Args) -> Self {
Self {
gradient_format: GradientInterpolation {
color_space: GradientColorSpace::Oklab,
hue_interpolation: HueInterpolation::Shorter,
},
}
}
}
impl TestCase for GradientOklab {
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 6, size.h / 3);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
self.gradient_format,
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 1.),
0.,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
@@ -0,0 +1,52 @@
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{Color, CornerRadius, GradientColorSpace, GradientInterpolation};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientOklabAlpha {
gradient_format: GradientInterpolation,
}
impl GradientOklabAlpha {
pub fn new(_args: Args) -> Self {
Self {
gradient_format: GradientInterpolation {
color_space: GradientColorSpace::Oklab,
hue_interpolation: Default::default(),
},
}
}
}
impl TestCase for GradientOklabAlpha {
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 6, size.h / 3);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
self.gradient_format,
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 0.),
0.,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
@@ -0,0 +1,54 @@
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{
Color, CornerRadius, GradientColorSpace, GradientInterpolation, HueInterpolation,
};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientOklchAlpha {
gradient_format: GradientInterpolation,
}
impl GradientOklchAlpha {
pub fn new(_args: Args) -> Self {
Self {
gradient_format: GradientInterpolation {
color_space: GradientColorSpace::Oklch,
hue_interpolation: HueInterpolation::Longer,
},
}
}
}
impl TestCase for GradientOklchAlpha {
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 6, size.h / 3);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
self.gradient_format,
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 0.),
0.,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
@@ -0,0 +1,54 @@
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{
Color, CornerRadius, GradientColorSpace, GradientInterpolation, HueInterpolation,
};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientOklchDecreasing {
gradient_format: GradientInterpolation,
}
impl GradientOklchDecreasing {
pub fn new(_args: Args) -> Self {
Self {
gradient_format: GradientInterpolation {
color_space: GradientColorSpace::Oklch,
hue_interpolation: HueInterpolation::Decreasing,
},
}
}
}
impl TestCase for GradientOklchDecreasing {
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 6, size.h / 3);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
self.gradient_format,
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 1.),
0.,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
@@ -0,0 +1,54 @@
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{
Color, CornerRadius, GradientColorSpace, GradientInterpolation, HueInterpolation,
};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientOklchIncreasing {
gradient_format: GradientInterpolation,
}
impl GradientOklchIncreasing {
pub fn new(_args: Args) -> Self {
Self {
gradient_format: GradientInterpolation {
color_space: GradientColorSpace::Oklch,
hue_interpolation: HueInterpolation::Increasing,
},
}
}
}
impl TestCase for GradientOklchIncreasing {
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 6, size.h / 3);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
self.gradient_format,
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 1.),
0.,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
@@ -0,0 +1,54 @@
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{
Color, CornerRadius, GradientColorSpace, GradientInterpolation, HueInterpolation,
};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientOklchLonger {
gradient_format: GradientInterpolation,
}
impl GradientOklchLonger {
pub fn new(_args: Args) -> Self {
Self {
gradient_format: GradientInterpolation {
color_space: GradientColorSpace::Oklch,
hue_interpolation: HueInterpolation::Longer,
},
}
}
}
impl TestCase for GradientOklchLonger {
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 6, size.h / 3);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
self.gradient_format,
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 1.),
0.,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
@@ -0,0 +1,54 @@
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{
Color, CornerRadius, GradientColorSpace, GradientInterpolation, HueInterpolation,
};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientOklchShorter {
gradient_format: GradientInterpolation,
}
impl GradientOklchShorter {
pub fn new(_args: Args) -> Self {
Self {
gradient_format: GradientInterpolation {
color_space: GradientColorSpace::Oklch,
hue_interpolation: HueInterpolation::Shorter,
},
}
}
}
impl TestCase for GradientOklchShorter {
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 6, size.h / 3);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
self.gradient_format,
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 1.),
0.,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
@@ -0,0 +1,54 @@
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{
Color, CornerRadius, GradientColorSpace, GradientInterpolation, HueInterpolation,
};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientSrgb {
gradient_format: GradientInterpolation,
}
impl GradientSrgb {
pub fn new(_args: Args) -> Self {
Self {
gradient_format: GradientInterpolation {
color_space: GradientColorSpace::Srgb,
hue_interpolation: HueInterpolation::Shorter,
},
}
}
}
impl TestCase for GradientSrgb {
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 6, size.h / 3);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
self.gradient_format,
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 1.),
0.,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
@@ -0,0 +1,52 @@
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{Color, CornerRadius, GradientColorSpace, GradientInterpolation};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientSrgbAlpha {
gradient_format: GradientInterpolation,
}
impl GradientSrgbAlpha {
pub fn new(_args: Args) -> Self {
Self {
gradient_format: GradientInterpolation {
color_space: GradientColorSpace::Srgb,
hue_interpolation: Default::default(),
},
}
}
}
impl TestCase for GradientSrgbAlpha {
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 6, size.h / 3);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
self.gradient_format,
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 0.),
0.,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
@@ -0,0 +1,54 @@
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{
Color, CornerRadius, GradientColorSpace, GradientInterpolation, HueInterpolation,
};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientSrgbLinear {
gradient_format: GradientInterpolation,
}
impl GradientSrgbLinear {
pub fn new(_args: Args) -> Self {
Self {
gradient_format: GradientInterpolation {
color_space: GradientColorSpace::SrgbLinear,
hue_interpolation: HueInterpolation::Shorter,
},
}
}
}
impl TestCase for GradientSrgbLinear {
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 6, size.h / 3);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
self.gradient_format,
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 1.),
0.,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
@@ -0,0 +1,52 @@
use niri::render_helpers::border::BorderRenderElement;
use niri_config::{Color, CornerRadius, GradientColorSpace, GradientInterpolation};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
pub struct GradientSrgbLinearAlpha {
gradient_format: GradientInterpolation,
}
impl GradientSrgbLinearAlpha {
pub fn new(_args: Args) -> Self {
Self {
gradient_format: GradientInterpolation {
color_space: GradientColorSpace::SrgbLinear,
hue_interpolation: Default::default(),
},
}
}
}
impl TestCase for GradientSrgbLinearAlpha {
fn render(
&mut self,
_renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let (a, b) = (size.w / 6, size.h / 3);
let size = (size.w - a * 2, size.h - b * 2);
let area = Rectangle::new(Point::from((a, b)), Size::from(size)).to_f64();
[BorderRenderElement::new(
area.size,
Rectangle::from_size(area.size),
self.gradient_format,
Color::new_unpremul(1., 0., 0., 1.),
Color::new_unpremul(0., 1., 0., 0.),
0.,
Rectangle::from_size(area.size),
0.,
CornerRadius::default(),
1.,
1.,
)
.with_location(area.loc)]
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
+275
View File
@@ -0,0 +1,275 @@
use std::collections::HashMap;
use std::time::Duration;
use niri::animation::Clock;
use niri::layout::{ActivateWindow, AddWindowTarget, LayoutElement as _, Options};
use niri::render_helpers::RenderTarget;
use niri_config::{Color, FloatOrInt, OutputName, PresetSize};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::desktop::layer_map_for_output;
use smithay::output::{Mode, Output, PhysicalProperties, Subpixel};
use smithay::utils::{Physical, Size};
use super::{Args, TestCase};
use crate::test_window::TestWindow;
type DynStepFn = Box<dyn FnOnce(&mut Layout)>;
pub struct Layout {
output: Output,
windows: Vec<TestWindow>,
clock: Clock,
layout: niri::layout::Layout<TestWindow>,
start_time: Duration,
steps: HashMap<Duration, DynStepFn>,
}
impl Layout {
pub fn new(args: Args) -> Self {
let Args { size, clock } = args;
let output = Output::new(
String::new(),
PhysicalProperties {
size: Size::from((size.w, size.h)),
subpixel: Subpixel::Unknown,
make: String::new(),
model: String::new(),
},
);
let mode = Some(Mode {
size: size.to_physical(1),
refresh: 60000,
});
output.change_current_state(mode, None, None, None);
output.user_data().insert_if_missing(|| OutputName {
connector: String::new(),
make: None,
model: None,
serial: None,
});
let options = Options {
focus_ring: niri_config::FocusRing {
off: true,
..Default::default()
},
border: niri_config::Border {
off: false,
width: FloatOrInt(4.),
active_color: Color::from_rgba8_unpremul(255, 163, 72, 255),
inactive_color: Color::from_rgba8_unpremul(50, 50, 50, 255),
urgent_color: Color::from_rgba8_unpremul(155, 0, 0, 255),
active_gradient: None,
inactive_gradient: None,
urgent_gradient: None,
},
..Default::default()
};
let mut layout = niri::layout::Layout::with_options(clock.clone(), options);
layout.add_output(output.clone());
let start_time = clock.now_unadjusted();
Self {
output,
windows: Vec::new(),
clock,
layout,
start_time,
steps: HashMap::new(),
}
}
pub fn open_in_between(args: Args) -> Self {
let mut rv = Self::new(args);
rv.add_window(TestWindow::freeform(0), Some(PresetSize::Proportion(0.3)));
rv.add_window(TestWindow::freeform(1), Some(PresetSize::Proportion(0.3)));
rv.layout.activate_window(&0);
rv.add_step(500, |l| {
let win = TestWindow::freeform(2);
l.add_window(win.clone(), Some(PresetSize::Proportion(0.3)));
l.layout.start_open_animation_for_window(win.id());
});
rv
}
pub fn open_multiple_quickly(args: Args) -> Self {
let mut rv = Self::new(args);
for delay in [100, 200, 300] {
rv.add_step(delay, move |l| {
let win = TestWindow::freeform(delay as usize);
l.add_window(win.clone(), Some(PresetSize::Proportion(0.3)));
l.layout.start_open_animation_for_window(win.id());
});
}
rv
}
pub fn open_multiple_quickly_big(args: Args) -> Self {
let mut rv = Self::new(args);
for delay in [100, 200, 300] {
rv.add_step(delay, move |l| {
let win = TestWindow::freeform(delay as usize);
l.add_window(win.clone(), Some(PresetSize::Proportion(0.5)));
l.layout.start_open_animation_for_window(win.id());
});
}
rv
}
pub fn open_to_the_left(args: Args) -> Self {
let mut rv = Self::new(args);
rv.add_window(TestWindow::freeform(0), Some(PresetSize::Proportion(0.3)));
rv.add_window(TestWindow::freeform(1), Some(PresetSize::Proportion(0.3)));
rv.add_step(500, |l| {
let win = TestWindow::freeform(2);
let right_of = l.windows[0].clone();
l.add_window_right_of(&right_of, win.clone(), Some(PresetSize::Proportion(0.3)));
l.layout.start_open_animation_for_window(win.id());
});
rv
}
pub fn open_to_the_left_big(args: Args) -> Self {
let mut rv = Self::new(args);
rv.add_window(TestWindow::freeform(0), Some(PresetSize::Proportion(0.3)));
rv.add_window(TestWindow::freeform(1), Some(PresetSize::Proportion(0.8)));
rv.add_step(500, |l| {
let win = TestWindow::freeform(2);
let right_of = l.windows[0].clone();
l.add_window_right_of(&right_of, win.clone(), Some(PresetSize::Proportion(0.5)));
l.layout.start_open_animation_for_window(win.id());
});
rv
}
fn add_window(&mut self, mut window: TestWindow, width: Option<PresetSize>) {
let ws = self.layout.active_workspace().unwrap();
let min_size = window.min_size();
let max_size = window.max_size();
window.request_size(
ws.new_window_size(width, None, false, window.rules(), (min_size, max_size)),
false,
false,
None,
);
window.communicate();
self.layout.add_window(
window.clone(),
AddWindowTarget::Auto,
width,
None,
false,
false,
ActivateWindow::default(),
);
self.windows.push(window);
}
fn add_window_right_of(
&mut self,
right_of: &TestWindow,
mut window: TestWindow,
width: Option<PresetSize>,
) {
let ws = self.layout.active_workspace().unwrap();
let min_size = window.min_size();
let max_size = window.max_size();
window.request_size(
ws.new_window_size(width, None, false, window.rules(), (min_size, max_size)),
false,
false,
None,
);
window.communicate();
self.layout.add_window(
window.clone(),
AddWindowTarget::NextTo(right_of.id()),
width,
None,
false,
false,
ActivateWindow::default(),
);
self.windows.push(window);
}
fn add_step(&mut self, delay_ms: u64, f: impl FnOnce(&mut Self) + 'static) {
self.steps
.insert(Duration::from_millis(delay_ms), Box::new(f) as _);
}
}
impl TestCase for Layout {
fn resize(&mut self, width: i32, height: i32) {
let mode = Some(Mode {
size: Size::from((width, height)),
refresh: 60000,
});
self.output.change_current_state(mode, None, None, None);
layer_map_for_output(&self.output).arrange();
self.layout.update_output_size(&self.output);
for win in &self.windows {
if win.communicate() {
self.layout.update_window(win.id(), None);
}
}
}
fn are_animations_ongoing(&self) -> bool {
self.layout.are_animations_ongoing(Some(&self.output)) || !self.steps.is_empty()
}
fn advance_animations(&mut self, _current_time: Duration) {
let now_unadjusted = self.clock.now_unadjusted();
let run = self
.steps
.keys()
.copied()
.filter(|delay| self.start_time + *delay <= now_unadjusted)
.collect::<Vec<_>>();
for delay in &run {
let now = self.start_time + *delay;
self.clock.set_unadjusted(now);
self.layout.advance_animations();
let f = self.steps.remove(delay).unwrap();
f(self);
}
self.clock.set_unadjusted(now_unadjusted);
self.layout.advance_animations();
}
fn render(
&mut self,
renderer: &mut GlesRenderer,
_size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
self.layout.update_render_elements(Some(&self.output));
self.layout
.monitor_for_output(&self.output)
.unwrap()
.render_elements(renderer, RenderTarget::Output, true)
.flat_map(|(_, iter)| iter)
.map(|elem| Box::new(elem) as _)
.collect()
}
}
+41
View File
@@ -0,0 +1,41 @@
use std::time::Duration;
use niri::animation::Clock;
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Logical, Physical, Size};
pub mod gradient_angle;
pub mod gradient_area;
pub mod gradient_oklab;
pub mod gradient_oklab_alpha;
pub mod gradient_oklch_alpha;
pub mod gradient_oklch_decreasing;
pub mod gradient_oklch_increasing;
pub mod gradient_oklch_longer;
pub mod gradient_oklch_shorter;
pub mod gradient_srgb;
pub mod gradient_srgb_alpha;
pub mod gradient_srgblinear;
pub mod gradient_srgblinear_alpha;
pub mod layout;
pub mod tile;
pub mod window;
pub struct Args {
pub size: Size<i32, Logical>,
pub clock: Clock,
}
pub trait TestCase {
fn resize(&mut self, _width: i32, _height: i32) {}
fn are_animations_ongoing(&self) -> bool {
false
}
fn advance_animations(&mut self, _current_time: Duration) {}
fn render(
&mut self,
renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>>;
}
+124
View File
@@ -0,0 +1,124 @@
use std::rc::Rc;
use std::time::Duration;
use niri::layout::Options;
use niri::render_helpers::RenderTarget;
use niri_config::{Color, FloatOrInt};
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Rectangle, Size};
use super::{Args, TestCase};
use crate::test_window::TestWindow;
pub struct Tile {
window: TestWindow,
tile: niri::layout::tile::Tile<TestWindow>,
}
impl Tile {
pub fn freeform(args: Args) -> Self {
let window = TestWindow::freeform(0);
Self::with_window(args, window)
}
pub fn fixed_size(args: Args) -> Self {
let window = TestWindow::fixed_size(0);
Self::with_window(args, window)
}
pub fn fixed_size_with_csd_shadow(args: Args) -> Self {
let window = TestWindow::fixed_size(0);
window.set_csd_shadow_width(64);
Self::with_window(args, window)
}
pub fn freeform_open(args: Args) -> Self {
let mut rv = Self::freeform(args);
rv.window.set_color([0.1, 0.1, 0.1, 1.]);
rv.tile.start_open_animation();
rv
}
pub fn fixed_size_open(args: Args) -> Self {
let mut rv = Self::fixed_size(args);
rv.window.set_color([0.1, 0.1, 0.1, 1.]);
rv.tile.start_open_animation();
rv
}
pub fn fixed_size_with_csd_shadow_open(args: Args) -> Self {
let mut rv = Self::fixed_size_with_csd_shadow(args);
rv.window.set_color([0.1, 0.1, 0.1, 1.]);
rv.tile.start_open_animation();
rv
}
pub fn with_window(args: Args, window: TestWindow) -> Self {
let Args { size, clock } = args;
let options = Options {
focus_ring: niri_config::FocusRing {
off: true,
..Default::default()
},
border: niri_config::Border {
off: false,
width: FloatOrInt(32.),
active_color: Color::from_rgba8_unpremul(255, 163, 72, 255),
..Default::default()
},
..Default::default()
};
let mut tile = niri::layout::tile::Tile::new(
window.clone(),
size.to_f64(),
1.,
clock,
Rc::new(options),
);
tile.request_tile_size(size.to_f64(), false, None);
window.communicate();
Self { window, tile }
}
}
impl TestCase for Tile {
fn resize(&mut self, width: i32, height: i32) {
let size = Size::from((width, height)).to_f64();
self.tile
.update_config(size, 1., self.tile.options().clone());
self.tile.request_tile_size(size, false, None);
self.window.communicate();
}
fn are_animations_ongoing(&self) -> bool {
self.tile.are_animations_ongoing()
}
fn advance_animations(&mut self, _current_time: Duration) {
self.tile.advance_animations();
}
fn render(
&mut self,
renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let size = size.to_f64();
let tile_size = self.tile.tile_size().to_physical(1.);
let location = Point::from((size.w - tile_size.w, size.h - tile_size.h)).downscale(2.);
self.tile.update_render_elements(
true,
Rectangle::new(Point::from((-location.x, -location.y)), size.to_logical(1.)),
);
self.tile
.render(renderer, location, true, RenderTarget::Output)
.map(|elem| Box::new(elem) as _)
.collect()
}
}
+67
View File
@@ -0,0 +1,67 @@
use niri::layout::LayoutElement;
use niri::render_helpers::RenderTarget;
use smithay::backend::renderer::element::RenderElement;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::utils::{Physical, Point, Scale, Size};
use super::{Args, TestCase};
use crate::test_window::TestWindow;
pub struct Window {
window: TestWindow,
}
impl Window {
pub fn freeform(args: Args) -> Self {
let mut window = TestWindow::freeform(0);
window.request_size(args.size, false, false, None);
window.communicate();
Self { window }
}
pub fn fixed_size(args: Args) -> Self {
let mut window = TestWindow::fixed_size(0);
window.request_size(args.size, false, false, None);
window.communicate();
Self { window }
}
pub fn fixed_size_with_csd_shadow(args: Args) -> Self {
let mut window = TestWindow::fixed_size(0);
window.set_csd_shadow_width(64);
window.request_size(args.size, false, false, None);
window.communicate();
Self { window }
}
}
impl TestCase for Window {
fn resize(&mut self, width: i32, height: i32) {
self.window
.request_size(Size::from((width, height)), false, false, None);
self.window.communicate();
}
fn render(
&mut self,
renderer: &mut GlesRenderer,
size: Size<i32, Physical>,
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
let win_size = self.window.size().to_physical(1);
let location = Point::from((size.w - win_size.w, size.h - win_size.h))
.to_f64()
.downscale(2.);
self.window
.render(
renderer,
location,
Scale::from(1.),
1.,
RenderTarget::Output,
)
.into_iter()
.map(|elem| Box::new(elem) as _)
.collect()
}
}
+184
View File
@@ -0,0 +1,184 @@
#[macro_use]
extern crate tracing;
use std::env;
use adw::prelude::{AdwApplicationWindowExt, NavigationPageExt};
use cases::Args;
use gtk::prelude::{ApplicationExt, ApplicationExtManual, BoxExt, GtkWindowExt, WidgetExt};
use gtk::{gdk, gio, glib};
use smithay_view::SmithayView;
use tracing_subscriber::EnvFilter;
use crate::cases::gradient_angle::GradientAngle;
use crate::cases::gradient_area::GradientArea;
use crate::cases::gradient_oklab::GradientOklab;
use crate::cases::gradient_oklab_alpha::GradientOklabAlpha;
use crate::cases::gradient_oklch_alpha::GradientOklchAlpha;
use crate::cases::gradient_oklch_decreasing::GradientOklchDecreasing;
use crate::cases::gradient_oklch_increasing::GradientOklchIncreasing;
use crate::cases::gradient_oklch_longer::GradientOklchLonger;
use crate::cases::gradient_oklch_shorter::GradientOklchShorter;
use crate::cases::gradient_srgb::GradientSrgb;
use crate::cases::gradient_srgb_alpha::GradientSrgbAlpha;
use crate::cases::gradient_srgblinear::GradientSrgbLinear;
use crate::cases::gradient_srgblinear_alpha::GradientSrgbLinearAlpha;
use crate::cases::layout::Layout;
use crate::cases::tile::Tile;
use crate::cases::window::Window;
use crate::cases::TestCase;
mod cases;
mod smithay_view;
mod test_window;
fn main() -> glib::ExitCode {
let directives =
env::var("RUST_LOG").unwrap_or_else(|_| "niri-visual-tests=debug,niri=debug".to_owned());
let env_filter = EnvFilter::builder().parse_lossy(directives);
tracing_subscriber::fmt()
.compact()
.with_env_filter(env_filter)
.init();
let app = adw::Application::new(None::<&str>, gio::ApplicationFlags::NON_UNIQUE);
app.connect_startup(on_startup);
app.connect_activate(build_ui);
app.run()
}
fn on_startup(_app: &adw::Application) {
// Load our CSS.
let provider = gtk::CssProvider::new();
provider.load_from_string(include_str!("../resources/style.css"));
if let Some(display) = gdk::Display::default() {
gtk::style_context_add_provider_for_display(
&display,
&provider,
gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
}
}
fn build_ui(app: &adw::Application) {
let stack = gtk::Stack::new();
let anim_adjustment = gtk::Adjustment::new(1., 0., 10., 0.1, 0.5, 0.);
struct S {
stack: gtk::Stack,
anim_adjustment: gtk::Adjustment,
}
impl S {
fn add<T: TestCase + 'static>(&self, make: impl Fn(Args) -> T + 'static, title: &str) {
let view = SmithayView::new(make, &self.anim_adjustment);
self.stack.add_titled(&view, None, title);
}
}
let s = S {
stack: stack.clone(),
anim_adjustment: anim_adjustment.clone(),
};
s.add(Window::freeform, "Freeform Window");
s.add(Window::fixed_size, "Fixed Size Window");
s.add(
Window::fixed_size_with_csd_shadow,
"Fixed Size Window - CSD Shadow",
);
s.add(Tile::freeform, "Freeform Tile");
s.add(Tile::fixed_size, "Fixed Size Tile");
s.add(
Tile::fixed_size_with_csd_shadow,
"Fixed Size Tile - CSD Shadow",
);
s.add(Tile::freeform_open, "Freeform Tile - Open");
s.add(Tile::fixed_size_open, "Fixed Size Tile - Open");
s.add(
Tile::fixed_size_with_csd_shadow_open,
"Fixed Size Tile - CSD Shadow - Open",
);
s.add(Layout::open_in_between, "Layout - Open In-Between");
s.add(
Layout::open_multiple_quickly,
"Layout - Open Multiple Quickly",
);
s.add(
Layout::open_multiple_quickly_big,
"Layout - Open Multiple Quickly - Big",
);
s.add(Layout::open_to_the_left, "Layout - Open To The Left");
s.add(
Layout::open_to_the_left_big,
"Layout - Open To The Left - Big",
);
s.add(GradientAngle::new, "Gradient - Angle");
s.add(GradientArea::new, "Gradient - Area");
s.add(GradientSrgb::new, "Gradient - Srgb");
s.add(GradientSrgbLinear::new, "Gradient - SrgbLinear");
s.add(GradientOklab::new, "Gradient - Oklab");
s.add(GradientOklchShorter::new, "Gradient - Oklch Shorter");
s.add(GradientOklchLonger::new, "Gradient - Oklch Longer");
s.add(GradientOklchIncreasing::new, "Gradient - Oklch Increasing");
s.add(GradientOklchDecreasing::new, "Gradient - Oklch Decreasing");
s.add(GradientSrgbAlpha::new, "Gradient - Srgb Alpha");
s.add(GradientSrgbLinearAlpha::new, "Gradient - SrgbLinear Alpha");
s.add(GradientOklabAlpha::new, "Gradient - Oklab Alpha");
s.add(GradientOklchAlpha::new, "Gradient - Oklch Alpha");
let content_headerbar = adw::HeaderBar::new();
let anim_scale = gtk::Scale::new(gtk::Orientation::Horizontal, Some(&anim_adjustment));
anim_scale.set_hexpand(true);
let anim_control_bar = gtk::Box::new(gtk::Orientation::Horizontal, 6);
anim_control_bar.add_css_class("anim-control-bar");
anim_control_bar.append(&gtk::Label::new(Some("Slowdown")));
anim_control_bar.append(&anim_scale);
let content_view = adw::ToolbarView::new();
content_view.set_top_bar_style(adw::ToolbarStyle::RaisedBorder);
content_view.set_bottom_bar_style(adw::ToolbarStyle::RaisedBorder);
content_view.add_top_bar(&content_headerbar);
content_view.add_bottom_bar(&anim_control_bar);
content_view.set_content(Some(&stack));
let content = adw::NavigationPage::new(
&content_view,
stack
.page(&stack.visible_child().unwrap())
.title()
.as_deref()
.unwrap(),
);
let sidebar_header = adw::HeaderBar::new();
let stack_sidebar = gtk::StackSidebar::new();
stack_sidebar.set_stack(&stack);
let sidebar_view = adw::ToolbarView::new();
sidebar_view.add_top_bar(&sidebar_header);
sidebar_view.set_content(Some(&stack_sidebar));
let sidebar = adw::NavigationPage::new(&sidebar_view, "Tests");
let split_view = adw::NavigationSplitView::new();
split_view.set_content(Some(&content));
split_view.set_sidebar(Some(&sidebar));
stack.connect_visible_child_notify(move |stack| {
content.set_title(
stack
.visible_child()
.and_then(|c| stack.page(&c).title())
.as_deref()
.unwrap_or_default(),
)
});
let window = adw::ApplicationWindow::new(app);
window.set_title(Some("niri visual tests"));
window.set_content(Some(&split_view));
window.present();
}
+291
View File
@@ -0,0 +1,291 @@
use gtk::glib;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use smithay::utils::Size;
use crate::cases::{Args, TestCase};
mod imp {
use std::cell::{Cell, OnceCell, RefCell};
use std::ptr::null;
use std::time::Duration;
use anyhow::{ensure, Context};
use gtk::gdk;
use gtk::prelude::*;
use niri::animation::Clock;
use niri::render_helpers::{resources, shaders};
use smithay::backend::egl::ffi::egl;
use smithay::backend::egl::EGLContext;
use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
use smithay::backend::renderer::{Bind, Color32F, Frame, Offscreen, Renderer};
use smithay::reexports::gbm::Format as Fourcc;
use smithay::utils::{Physical, Rectangle, Scale, Transform};
use super::*;
type DynMakeTestCase = Box<dyn Fn(Args) -> Box<dyn TestCase>>;
struct RendererData {
renderer: GlesRenderer,
dummy_texture: GlesTexture,
}
#[derive(Default)]
pub struct SmithayView {
gl_area: gtk::GLArea,
size: Cell<(i32, i32)>,
renderer: RefCell<Option<Result<RendererData, ()>>>,
pub make_test_case: OnceCell<DynMakeTestCase>,
test_case: RefCell<Option<Box<dyn TestCase>>>,
pub clock: RefCell<Clock>,
}
#[glib::object_subclass]
impl ObjectSubclass for SmithayView {
const NAME: &'static str = "NiriSmithayView";
type Type = super::SmithayView;
type ParentType = gtk::Widget;
fn class_init(klass: &mut Self::Class) {
klass.set_layout_manager_type::<gtk::BinLayout>();
}
}
impl ObjectImpl for SmithayView {
fn constructed(&self) {
let obj = self.obj();
self.parent_constructed();
self.gl_area.set_allowed_apis(gdk::GLAPI::GLES);
self.gl_area.set_parent(&*obj);
self.gl_area.connect_resize({
let imp = self.downgrade();
move |_, width, height| {
if let Some(imp) = imp.upgrade() {
imp.resize(width, height);
}
}
});
self.gl_area.connect_render({
let imp = self.downgrade();
move |_, gl_context| {
if let Some(imp) = imp.upgrade() {
if let Err(err) = imp.render(gl_context) {
warn!("error rendering: {err:?}");
}
}
glib::Propagation::Stop
}
});
obj.add_tick_callback(|obj, _frame_clock| {
let imp = obj.imp();
if let Some(case) = &mut *imp.test_case.borrow_mut() {
if case.are_animations_ongoing() {
imp.gl_area.queue_draw();
}
}
glib::ControlFlow::Continue
});
}
fn dispose(&self) {
self.gl_area.unparent();
}
}
impl WidgetImpl for SmithayView {
fn unmap(&self) {
self.test_case.replace(None);
self.parent_unmap();
}
fn unrealize(&self) {
self.renderer.replace(None);
self.parent_unrealize();
}
}
impl SmithayView {
fn resize(&self, width: i32, height: i32) {
self.size.set((width, height));
if let Some(case) = &mut *self.test_case.borrow_mut() {
case.resize(width, height);
}
}
fn render(&self, _gl_context: &gdk::GLContext) -> anyhow::Result<()> {
// Set up the Smithay renderer.
let mut renderer = self.renderer.borrow_mut();
let renderer = renderer.get_or_insert_with(|| {
unsafe { create_renderer() }
.map_err(|err| warn!("error creating a Smithay renderer: {err:?}"))
});
let Ok(renderer) = renderer else {
return Ok(());
};
let RendererData {
renderer,
dummy_texture,
} = renderer;
let size = self.size.get();
let frame_clock = self.obj().frame_clock().unwrap();
let time = Duration::from_micros(frame_clock.frame_time() as u64);
self.clock.borrow_mut().set_unadjusted(time);
// Create the test case if missing.
let mut case = self.test_case.borrow_mut();
let case = case.get_or_insert_with(|| {
let make = self.make_test_case.get().unwrap();
let args = Args {
size: Size::from(size),
clock: self.clock.borrow().clone(),
};
make(args)
});
case.advance_animations(self.clock.borrow_mut().now());
let rect: Rectangle<i32, Physical> = Rectangle::from_size(Size::from(size));
// Fetch GtkGLArea's framebuffer binding.
let mut framebuffer = 0;
renderer
.with_context(|gl| unsafe {
gl.GetIntegerv(
smithay::backend::renderer::gles::ffi::FRAMEBUFFER_BINDING,
&mut framebuffer,
);
})
.context("error running closure in GL context")?;
ensure!(framebuffer != 0, "error getting the framebuffer");
// This call will already change the framebuffer binding (offscreen elements will bind
// intermediate textures during rendering).
let elements = case.render(renderer, Size::from(size));
// HACK: there's currently no way to "just" render into an externally bound framebuffer
// (like we have in this case). The render() call requires a valid target. So what
// we'll do is use a dummy texture as a target, then swap the framebuffer binding right
// before rendering.
let mut dummy_target = renderer
.bind(dummy_texture)
.context("error binding dummy texture")?;
let mut frame = renderer
.render(&mut dummy_target, rect.size, Transform::Normal)
.context("error creating frame")?;
// Now that render() bound the dummy texture, change the binding underneath it back to
// GtkGLArea's framebuffer, to render there instead.
frame
.with_context(|gl| unsafe {
gl.BindFramebuffer(
smithay::backend::renderer::gles::ffi::FRAMEBUFFER,
framebuffer as u32,
);
})
.context("error running closure in GL context")?;
frame
.clear(Color32F::from([0.3, 0.3, 0.3, 1.]), &[rect])
.context("error clearing")?;
for element in elements.iter().rev() {
let src = element.src();
let dst = element.geometry(Scale::from(1.));
if let Some(mut damage) = rect.intersection(dst) {
damage.loc -= dst.loc;
element
.draw(&mut frame, src, dst, &[damage], &[])
.context("error drawing element")?;
}
}
Ok(())
}
}
unsafe fn create_renderer() -> anyhow::Result<RendererData> {
smithay::backend::egl::ffi::make_sure_egl_is_loaded()
.context("error loading EGL symbols in Smithay")?;
let egl_display = egl::GetCurrentDisplay();
ensure!(egl_display != egl::NO_DISPLAY, "no current EGL display");
let egl_context = egl::GetCurrentContext();
ensure!(egl_context != egl::NO_CONTEXT, "no current EGL context");
// There's no config ID on the EGL context and there's no current EGL surface, but we don't
// really use it anyway so just get some random one.
let mut egl_config_id = null();
let mut num_configs = 0;
let res = egl::GetConfigs(egl_display, &mut egl_config_id, 1, &mut num_configs);
ensure!(res == egl::TRUE, "error choosing EGL config");
ensure!(num_configs != 0, "no EGL config");
let egl_context = EGLContext::from_raw(egl_display, egl_config_id as *const _, egl_context)
.context("error creating EGL context")?;
let mut renderer = GlesRenderer::new(egl_context).context("error creating GlesRenderer")?;
let dummy_texture = renderer
.create_buffer(Fourcc::Abgr8888, Size::from((1, 1)))
.context("error creating dummy texture")?;
resources::init(&mut renderer);
shaders::init(&mut renderer);
Ok(RendererData {
renderer,
dummy_texture,
})
}
}
glib::wrapper! {
pub struct SmithayView(ObjectSubclass<imp::SmithayView>)
@extends gtk::Widget;
}
impl SmithayView {
pub fn new<T: TestCase + 'static>(
make_test_case: impl Fn(Args) -> T + 'static,
anim_adjustment: &gtk::Adjustment,
) -> Self {
let obj: Self = glib::Object::builder().build();
let make = move |args| Box::new(make_test_case(args)) as Box<dyn TestCase>;
let make_test_case = Box::new(make) as _;
let _ = obj.imp().make_test_case.set(make_test_case);
anim_adjustment.connect_value_changed({
let obj = obj.downgrade();
move |adj| {
if let Some(obj) = obj.upgrade() {
let mut clock = obj.imp().clock.borrow_mut();
let instantly = adj.value() == 0.0;
let rate = if instantly {
1.0
} else {
1.0 / adj.value().max(0.001)
};
clock.set_rate(rate);
clock.set_complete_instantly(instantly);
}
}
});
obj
}
}
+279
View File
@@ -0,0 +1,279 @@
use std::cell::RefCell;
use std::cmp::{max, min};
use std::rc::Rc;
use niri::layout::{
ConfigureIntent, InteractiveResizeData, LayoutElement, LayoutElementRenderElement,
LayoutElementRenderSnapshot,
};
use niri::render_helpers::offscreen::OffscreenData;
use niri::render_helpers::renderer::NiriRenderer;
use niri::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
use niri::render_helpers::{RenderTarget, SplitElements};
use niri::utils::transaction::Transaction;
use niri::window::ResolvedWindowRules;
use smithay::backend::renderer::element::Kind;
use smithay::output::{self, Output};
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
use smithay::utils::{Logical, Point, Scale, Serial, Size, Transform};
#[derive(Debug)]
struct TestWindowInner {
size: Size<i32, Logical>,
requested_size: Option<Size<i32, Logical>>,
min_size: Size<i32, Logical>,
max_size: Size<i32, Logical>,
buffer: SolidColorBuffer,
pending_fullscreen: bool,
csd_shadow_width: i32,
csd_shadow_buffer: SolidColorBuffer,
}
#[derive(Debug, Clone)]
pub struct TestWindow {
id: usize,
inner: Rc<RefCell<TestWindowInner>>,
}
impl TestWindow {
pub fn freeform(id: usize) -> Self {
let size = Size::from((100, 200));
let min_size = Size::from((0, 0));
let max_size = Size::from((0, 0));
let buffer = SolidColorBuffer::new(size.to_f64(), [0.15, 0.64, 0.41, 1.]);
Self {
id,
inner: Rc::new(RefCell::new(TestWindowInner {
size,
requested_size: None,
min_size,
max_size,
buffer,
pending_fullscreen: false,
csd_shadow_width: 0,
csd_shadow_buffer: SolidColorBuffer::new((0., 0.), [0., 0., 0., 0.3]),
})),
}
}
pub fn fixed_size(id: usize) -> Self {
let rv = Self::freeform(id);
rv.set_min_size((200, 400).into());
rv.set_max_size((200, 400).into());
rv.set_color([0.88, 0.11, 0.14, 1.]);
rv.communicate();
rv
}
pub fn set_min_size(&self, size: Size<i32, Logical>) {
self.inner.borrow_mut().min_size = size;
}
pub fn set_max_size(&self, size: Size<i32, Logical>) {
self.inner.borrow_mut().max_size = size;
}
pub fn set_color(&self, color: [f32; 4]) {
self.inner.borrow_mut().buffer.set_color(color);
}
pub fn set_csd_shadow_width(&self, width: i32) {
self.inner.borrow_mut().csd_shadow_width = width;
}
pub fn communicate(&self) -> bool {
let mut rv = false;
let mut inner = self.inner.borrow_mut();
let mut new_size = inner.size;
if let Some(size) = inner.requested_size {
assert!(size.w >= 0);
assert!(size.h >= 0);
if size.w != 0 {
new_size.w = size.w;
}
if size.h != 0 {
new_size.h = size.h;
}
}
if inner.max_size.w > 0 {
new_size.w = min(new_size.w, inner.max_size.w);
}
if inner.max_size.h > 0 {
new_size.h = min(new_size.h, inner.max_size.h);
}
if inner.min_size.w > 0 {
new_size.w = max(new_size.w, inner.min_size.w);
}
if inner.min_size.h > 0 {
new_size.h = max(new_size.h, inner.min_size.h);
}
if inner.size != new_size {
inner.size = new_size;
inner.buffer.resize(new_size.to_f64());
rv = true;
}
let mut csd_shadow_size = new_size;
csd_shadow_size.w += inner.csd_shadow_width * 2;
csd_shadow_size.h += inner.csd_shadow_width * 2;
inner.csd_shadow_buffer.resize(csd_shadow_size.to_f64());
rv
}
}
impl LayoutElement for TestWindow {
type Id = usize;
fn id(&self) -> &Self::Id {
&self.id
}
fn size(&self) -> Size<i32, Logical> {
self.inner.borrow().size
}
fn buf_loc(&self) -> Point<i32, Logical> {
(0, 0).into()
}
fn is_in_input_region(&self, _point: Point<f64, Logical>) -> bool {
false
}
fn render<R: NiriRenderer>(
&self,
_renderer: &mut R,
location: Point<f64, Logical>,
_scale: Scale<f64>,
alpha: f32,
_target: RenderTarget,
) -> SplitElements<LayoutElementRenderElement<R>> {
let inner = self.inner.borrow();
SplitElements {
normal: vec![
SolidColorRenderElement::from_buffer(
&inner.buffer,
location,
alpha,
Kind::Unspecified,
)
.into(),
SolidColorRenderElement::from_buffer(
&inner.csd_shadow_buffer,
location
- Point::from((inner.csd_shadow_width, inner.csd_shadow_width)).to_f64(),
alpha,
Kind::Unspecified,
)
.into(),
],
popups: vec![],
}
}
fn request_size(
&mut self,
size: Size<i32, Logical>,
is_fullscreen: bool,
_animate: bool,
_transaction: Option<Transaction>,
) {
self.inner.borrow_mut().requested_size = Some(size);
self.inner.borrow_mut().pending_fullscreen = is_fullscreen;
}
fn min_size(&self) -> Size<i32, Logical> {
self.inner.borrow().min_size
}
fn max_size(&self) -> Size<i32, Logical> {
self.inner.borrow().max_size
}
fn is_wl_surface(&self, _wl_surface: &WlSurface) -> bool {
false
}
fn set_preferred_scale_transform(&self, _scale: output::Scale, _transform: Transform) {}
fn has_ssd(&self) -> bool {
false
}
fn output_enter(&self, _output: &Output) {}
fn output_leave(&self, _output: &Output) {}
fn set_offscreen_data(&self, _data: Option<OffscreenData>) {}
fn set_activated(&mut self, _active: bool) {}
fn set_active_in_column(&mut self, _active: bool) {}
fn set_floating(&mut self, _floating: bool) {}
fn set_bounds(&self, _bounds: Size<i32, Logical>) {}
fn is_ignoring_opacity_window_rule(&self) -> bool {
false
}
fn configure_intent(&self) -> ConfigureIntent {
ConfigureIntent::CanSend
}
fn send_pending_configure(&mut self) {}
fn is_fullscreen(&self) -> bool {
false
}
fn is_pending_fullscreen(&self) -> bool {
self.inner.borrow().pending_fullscreen
}
fn requested_size(&self) -> Option<Size<i32, Logical>> {
self.inner.borrow().requested_size
}
fn is_child_of(&self, _parent: &Self) -> bool {
false
}
fn refresh(&self) {}
fn rules(&self) -> &ResolvedWindowRules {
static EMPTY: ResolvedWindowRules = ResolvedWindowRules::empty();
&EMPTY
}
fn animation_snapshot(&self) -> Option<&LayoutElementRenderSnapshot> {
None
}
fn take_animation_snapshot(&mut self) -> Option<LayoutElementRenderSnapshot> {
None
}
fn set_interactive_resize(&mut self, _data: Option<InteractiveResizeData>) {}
fn cancel_interactive_resize(&mut self) {}
fn on_commit(&mut self, _serial: Serial) {}
fn interactive_resize_data(&self) -> Option<InteractiveResizeData> {
None
}
fn is_urgent(&self) -> bool {
false
}
}
+150
View File
@@ -0,0 +1,150 @@
%bcond_without check
%global cargo_install_lib 0
# We want panic backtraces to work without installing the debuginfo package,
# so we leave the debuginfo in the main binary.
%global debug_package %{nil}
%global __strip /bin/true
# To reduce the file size, do some convincing of rust-srpm-macros
# to leave alone the chosen debug settings from Cargo.toml.
%global rustflags_debuginfo please-remove-me
%global build_rustflags %{shrink:
-Copt-level=%rustflags_opt_level
-Ccodegen-units=%rustflags_codegen_units
-Cstrip=none
%{expr:0%{?_include_frame_pointers} && ("%{_arch}" != "ppc64le" && "%{_arch}" != "s390x" && "%{_arch}" != "i386") ? "-Cforce-frame-pointers=yes" : ""}
-Clink-arg=-Wl,-z,relro
-Clink-arg=-Wl,-z,now
%[0%{?_package_note_status} ? "-Clink-arg=%_package_note_flags" : ""]
--cap-lints=warn
}
# Convince rust-srpm-macros to use Cargo.lock with the Smithay commit.
%global __cargo_common_opts %{?_smp_mflags} -Z avoid-dev-deps --locked
%global version {{{ git_dir_version }}}
Name: niri
Version: %{version}
Release: 1%{?dist}
Summary: Scrollable-tiling Wayland compositor
SourceLicense: GPL-3.0-or-later
# 0BSD OR MIT OR Apache-2.0
# Apache-2.0
# Apache-2.0 OR BSL-1.0
# Apache-2.0 OR MIT
# Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT
# BSD-2-Clause
# BSD-2-Clause OR Apache-2.0 OR MIT
# BSD-3-Clause OR MIT OR Apache-2.0
# GPL-3.0-or-later
# ISC
# MIT
# MIT AND (MIT OR Apache-2.0)
# MIT OR Apache-2.0
# (MIT OR Apache-2.0) AND BSD-3-Clause
# (MIT OR Apache-2.0) AND Unicode-3.0
# MIT OR Apache-2.0 OR Zlib
# MIT OR Zlib OR Apache-2.0
# MPL-2.0
# Unicode-3.0
# Unlicense OR MIT
# Zlib OR Apache-2.0 OR MIT
License: (0BSD OR MIT OR Apache-2.0) AND (Apache-2.0) AND (Apache-2.0 OR BSL-1.0) AND (Apache-2.0 OR MIT) AND (Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT) AND (BSD-2-Clause) AND (BSD-2-Clause OR Apache-2.0 OR MIT) AND (BSD-3-Clause OR MIT OR Apache-2.0) AND (GPL-3.0-or-later) AND (ISC) AND (MIT) AND (MIT AND (MIT OR Apache-2.0)) AND (MIT OR Apache-2.0) AND ((MIT OR Apache-2.0) AND BSD-3-Clause) AND ((MIT OR Apache-2.0) AND Unicode-3.0) AND (MIT OR Apache-2.0 OR Zlib) AND (MIT OR Zlib OR Apache-2.0) AND (MPL-2.0) AND (Unicode-3.0) AND (Unlicense OR MIT) AND (Zlib OR Apache-2.0 OR MIT)
# LICENSE.dependencies contains a full license breakdown
URL: https://github.com/YaLTeR/niri
VCS: {{{ git_dir_vcs }}}
Source: {{{ git_dir_pack }}}
BuildRequires: cargo-rpm-macros >= 26
BuildRequires: pkgconfig(udev)
BuildRequires: pkgconfig(gbm)
BuildRequires: pkgconfig(xkbcommon)
BuildRequires: wayland-devel
BuildRequires: pkgconfig(libinput)
BuildRequires: pkgconfig(dbus-1)
BuildRequires: pkgconfig(systemd)
BuildRequires: pkgconfig(libseat)
BuildRequires: pkgconfig(libdisplay-info)
BuildRequires: pipewire-devel
BuildRequires: pango-devel
BuildRequires: cairo-gobject-devel
# Needed for pipewire-rs
BuildRequires: clang
Requires: mesa-dri-drivers
Requires: mesa-libEGL
# Portal implementations used by niri
Recommends: xdg-desktop-portal-gtk
Recommends: xdg-desktop-portal-gnome
Recommends: gnome-keyring
# Suggested utilities, bound in the default config
Recommends: alacritty
Recommends: fuzzel
Recommends: swaylock
Recommends: waybar
# Suggested utilities
Recommends: swaybg
Recommends: mako
Recommends: swayidle
%description
A scrollable-tiling Wayland compositor.
Windows are arranged in columns on an infinite strip going to the right.
Opening a new window never causes existing windows to resize.
%prep
{{{ git_dir_setup_macro }}}
%cargo_prep -N
# We're doing an online build.
sed -i 's/^offline = true$//' .cargo/config.toml
# Final step in leaving alone our debug settings.
sed -i 's/.*please-remove-me$//' .cargo/config.toml
# Set the commit string.
sed -i 's/\[env\]/[env]\nNIRI_BUILD_COMMIT="%{version}"/' .cargo/config.toml
%build
%cargo_build
%install
%cargo_install
install -Dm755 -t %{buildroot}%{_bindir} ./resources/niri-session
install -Dm644 -t %{buildroot}%{_datadir}/wayland-sessions ./resources/niri.desktop
install -Dm644 -t %{buildroot}%{_datadir}/xdg-desktop-portal ./resources/niri-portals.conf
install -Dm644 -t %{buildroot}%{_userunitdir} ./resources/niri.service
install -Dm644 -t %{buildroot}%{_userunitdir} ./resources/niri-shutdown.target
%if %{with check}
%check
%cargo_test -- --workspace --exclude niri-visual-tests
%endif
%files
%license LICENSE
%doc README.md
%doc resources/default-config.kdl
%doc wiki
%{_bindir}/niri
%{_bindir}/niri-session
%{_datadir}/wayland-sessions/niri.desktop
%dir %{_datadir}/xdg-desktop-portal
%{_datadir}/xdg-desktop-portal/niri-portals.conf
%{_userunitdir}/niri.service
%{_userunitdir}/niri-shutdown.target
%changelog
{{{ git_dir_changelog }}}
+423 -140
View File
@@ -1,6 +1,11 @@
// This config is in the KDL format: https://kdl.dev
// "/-" comments out the following node.
// Check the wiki for a full description of the configuration:
// https://github.com/YaLTeR/niri/wiki/Configuration:-Introduction
// Input device configuration.
// Find the full list of options on the wiki:
// https://github.com/YaLTeR/niri/wiki/Configuration:-Input
input {
keyboard {
xkb {
@@ -12,145 +17,253 @@ input {
// options "grp:win_space_toggle,compose:ralt,ctrl:nocaps"
}
// You can set the keyboard repeat parameters. The defaults match wlroots and sway.
// Delay is in milliseconds before the repeat starts. Rate is in characters per second.
// repeat-delay 600
// repeat-rate 25
// Niri can remember the keyboard layout globally (the default) or per-window.
// - "global" - layout change is global for all windows.
// - "window" - layout is tracked for each window individually.
// track-layout "global"
// Enable numlock on startup, omitting this setting disables it.
numlock
}
// Next sections include libinput settings.
// Omitting settings disables them, or leaves them at their default values.
touchpad {
// off
tap
// dwt
// dwtp
// drag false
// drag-lock
natural-scroll
// accel-speed 0.2
// accel-profile "flat"
// scroll-method "two-finger"
// disabled-on-external-mouse
}
tablet {
// Set the name of the output (see below) which the tablet will map to.
// If this is unset or the output doesn't exist, the tablet maps to one of the
// existing outputs.
map-to-output "eDP-1"
mouse {
// off
// natural-scroll
// accel-speed 0.2
// accel-profile "flat"
// scroll-method "no-scroll"
}
// By default, niri will take over the power button to make it sleep
// instead of power off.
// Uncomment this if you would like to configure the power button elsewhere
// (i.e. logind.conf).
// disable-power-key-handling
trackpoint {
// off
// natural-scroll
// accel-speed 0.2
// accel-profile "flat"
// scroll-method "on-button-down"
// scroll-button 273
// middle-emulation
}
// Uncomment this to make the mouse warp to the center of newly focused windows.
// warp-mouse-to-focus
// Focus windows and outputs automatically when moving the mouse into them.
// Setting max-scroll-amount="0%" makes it work only on windows already fully on screen.
// focus-follows-mouse max-scroll-amount="0%"
}
// You can configure outputs by their name, which you can find with wayland-info(1).
// You can configure outputs by their name, which you can find
// by running `niri msg outputs` while inside a niri instance.
// The built-in laptop monitor is usually called "eDP-1".
// Remember to uncommend the node by removing "/-"!
// Find more information on the wiki:
// https://github.com/YaLTeR/niri/wiki/Configuration:-Outputs
// Remember to uncomment the node by removing "/-"!
/-output "eDP-1" {
// Uncomment this line to disable this output.
// off
// Scale is a floating-point number, but at the moment only integer values work.
scale 2.0
// Resolution and, optionally, refresh rate of the output.
// The format is "<width>x<height>" or "<width>x<height>@<refresh rate>".
// If the refresh rate is omitted, niri will pick the highest refresh rate
// for the resolution.
// If the mode is omitted altogether or is invalid, niri will pick one automatically.
// All valid modes are listed in niri's debug output when an output is connected.
mode "1920x1080@144"
// Run `niri msg outputs` while inside a niri instance to list all outputs and their modes.
mode "1920x1080@120.030"
// You can use integer or fractional scale, for example use 1.5 for 150% scale.
scale 2
// Transform allows to rotate the output counter-clockwise, valid values are:
// normal, 90, 180, 270, flipped, flipped-90, flipped-180 and flipped-270.
transform "normal"
// Position of the output in the global coordinate space.
// This affects directional monitor actions like "focus-monitor-left", and cursor movement.
// The cursor can only move between directly adjacent outputs.
// Output scale has to be taken into account for positioning:
// Output scale and rotation has to be taken into account for positioning:
// outputs are sized in logical, or scaled, pixels.
// For example, a 3840×2160 output with scale 2.0 will have a logical size of 1920×1080,
// so to put another output directly adjacent to it on the right, set its x to 1920.
// It the position is unset or results in an overlap, the output is instead placed
// If the position is unset or results in an overlap, the output is instead placed
// automatically.
position x=1280 y=0
}
// Settings that influence how windows are positioned and sized.
// Find more information on the wiki:
// https://github.com/YaLTeR/niri/wiki/Configuration:-Layout
layout {
// Set gaps around windows in logical pixels.
gaps 16
// When to center a column when changing focus, options are:
// - "never", default behavior, focusing an off-screen column will keep at the left
// or right edge of the screen.
// - "always", the focused column will always be centered.
// - "on-overflow", focusing a column will center it if it doesn't fit
// together with the previously focused column.
center-focused-column "never"
// You can customize the widths that "switch-preset-column-width" (Mod+R) toggles between.
preset-column-widths {
// Proportion sets the width as a fraction of the output width, taking gaps into account.
// For example, you can perfectly fit four windows sized "proportion 0.25" on an output.
// The default preset widths are 1/3, 1/2 and 2/3 of the output.
proportion 0.33333
proportion 0.5
proportion 0.66667
// Fixed sets the width in logical pixels exactly.
// fixed 1920
}
// You can also customize the heights that "switch-preset-window-height" (Mod+Shift+R) toggles between.
// preset-window-heights { }
// You can change the default width of the new windows.
default-column-width { proportion 0.5; }
// If you leave the brackets empty, the windows themselves will decide their initial width.
// default-column-width {}
// By default focus ring and border are rendered as a solid background rectangle
// behind windows. That is, they will show up through semitransparent windows.
// This is because windows using client-side decorations can have an arbitrary shape.
//
// If you don't like that, you should uncomment `prefer-no-csd` below.
// Niri will draw focus ring and border *around* windows that agree to omit their
// client-side decorations.
//
// Alternatively, you can override it with a window rule called
// `draw-border-with-background`.
// You can change how the focus ring looks.
focus-ring {
// Uncomment this line to disable the focus ring.
// off
// How many logical pixels the ring extends out from the windows.
width 4
// Colors can be set in a variety of ways:
// - CSS named colors: "red"
// - RGB hex: "#rgb", "#rgba", "#rrggbb", "#rrggbbaa"
// - CSS-like notation: "rgb(255, 127, 0)", rgba(), hsl() and a few others.
// Color of the ring on the active monitor.
active-color "#7fc8ff"
// Color of the ring on inactive monitors.
inactive-color "#505050"
// You can also use gradients. They take precedence over solid colors.
// Gradients are rendered the same as CSS linear-gradient(angle, from, to).
// The angle is the same as in linear-gradient, and is optional,
// defaulting to 180 (top-to-bottom gradient).
// You can use any CSS linear-gradient tool on the web to set these up.
// Changing the color space is also supported, check the wiki for more info.
//
// active-gradient from="#80c8ff" to="#bbddff" angle=45
// You can also color the gradient relative to the entire view
// of the workspace, rather than relative to just the window itself.
// To do that, set relative-to="workspace-view".
//
// inactive-gradient from="#505050" to="#808080" angle=45 relative-to="workspace-view"
}
// You can also add a border. It's similar to the focus ring, but always visible.
border {
// The settings are the same as for the focus ring.
// If you enable the border, you probably want to disable the focus ring.
off
width 4
active-color "#ffc87f"
inactive-color "#505050"
// Color of the border around windows that request your attention.
urgent-color "#9b0000"
// active-gradient from="#ffbb66" to="#ffc880" angle=45 relative-to="workspace-view"
// inactive-gradient from="#505050" to="#808080" angle=45 relative-to="workspace-view"
}
// You can enable drop shadows for windows.
shadow {
// Uncomment the next line to enable shadows.
// on
// By default, the shadow draws only around its window, and not behind it.
// Uncomment this setting to make the shadow draw behind its window.
//
// Note that niri has no way of knowing about the CSD window corner
// radius. It has to assume that windows have square corners, leading to
// shadow artifacts inside the CSD rounded corners. This setting fixes
// those artifacts.
//
// However, instead you may want to set prefer-no-csd and/or
// geometry-corner-radius. Then, niri will know the corner radius and
// draw the shadow correctly, without having to draw it behind the
// window. These will also remove client-side shadows if the window
// draws any.
//
// draw-behind-window true
// You can change how shadows look. The values below are in logical
// pixels and match the CSS box-shadow properties.
// Softness controls the shadow blur radius.
softness 30
// Spread expands the shadow.
spread 5
// Offset moves the shadow relative to the window.
offset x=0 y=5
// You can also change the shadow color and opacity.
color "#0007"
}
// Struts shrink the area occupied by windows, similarly to layer-shell panels.
// You can think of them as a kind of outer gaps. They are set in logical pixels.
// Left and right struts will cause the next window to the side to always be visible.
// Top and bottom struts will simply add outer gaps in addition to the area occupied by
// layer-shell panels and regular gaps.
struts {
// left 64
// right 64
// top 64
// bottom 64
}
}
// Add lines like this to spawn processes at startup.
// Note that running niri as a session supports xdg-desktop-autostart,
// which may be more convenient to use.
// spawn-at-startup "alacritty" "-e" "fish"
// See the binds section below for more spawn examples.
// You can change how the focus ring looks.
focus-ring {
// Uncomment this line to disable the focus ring.
// off
// How many logical pixels the ring extends out from the windows.
width 4
// Color of the ring on the active monitor: red, green, blue, alpha.
active-color 127 200 255 255
// Color of the ring on inactive monitors: red, green, blue, alpha.
inactive-color 80 80 80 255
}
// You can also add a border. It's similar to the focus ring, but always visible.
border {
// The settings are the same as for the focus ring.
// If you enable the border, you probably want to disable the focus ring.
off
width 4
active-color 255 200 127 255
inactive-color 80 80 80 255
}
cursor {
// Change the theme and size of the cursor as well as set the
// `XCURSOR_THEME` and `XCURSOR_SIZE` env variables.
// xcursor-theme "default"
// xcursor-size 24
}
// This line starts waybar, a commonly used bar for Wayland compositors.
spawn-at-startup "waybar"
// Uncomment this line to ask the clients to omit their client-side decorations if possible.
// If the client will specifically ask for CSD, the request will be honored.
// Additionally, clients will be informed that they are tiled, removing some rounded corners.
// Additionally, clients will be informed that they are tiled, removing some client-side rounded corners.
// This option will also fix border/focus ring drawing behind some semitransparent windows.
// After enabling or disabling this, you need to restart the apps for this to take effect.
// prefer-no-csd
// You can customize the widths that "switch-preset-column-width" (Mod+R) toggles between.
preset-column-widths {
// Proportion sets the width as a fraction of the output width, taking gaps into account.
// For example, you can perfectly fit four windows sized "proportion 0.25" on an output.
// The default preset widths are 1/3, 1/2 and 2/3 of the output.
proportion 0.333
proportion 0.5
proportion 0.667
// Fixed sets the width in logical pixels exactly.
// fixed 1920
}
// You can change the default width of the new windows.
default-column-width { proportion 0.5; }
// If you leave the brackets empty, the windows themselves will decide their initial width.
// default-column-width {}
// Set gaps around windows in logical pixels.
gaps 16
// Struts shrink the area occupied by windows, similarly to layer-shell panels.
// You can think of them as a kind of outer gaps. They are set in logical pixels.
// Left and right struts will cause the next window to the side to always be visible.
// Top and bottom struts will simply add outer gaps in addition to the area occupied by
// layer-shell panels and regular gaps.
struts {
// left 64
// right 64
// top 64
// bottom 64
}
// You can change the path where screenshots are saved.
// A ~ at the front will be expanded to the home directory.
// The path is formatted with strftime(3) to give you the screenshot date and time.
@@ -159,6 +272,59 @@ screenshot-path "~/Pictures/Screenshots/Screenshot from %Y-%m-%d %H-%M-%S.png"
// You can also set this to null to disable saving screenshots to disk.
// screenshot-path null
// Animation settings.
// The wiki explains how to configure individual animations:
// https://github.com/YaLTeR/niri/wiki/Configuration:-Animations
animations {
// Uncomment to turn off all animations.
// off
// Slow down all animations by this factor. Values below 1 speed them up instead.
// slowdown 3.0
}
// Window rules let you adjust behavior for individual windows.
// Find more information on the wiki:
// https://github.com/YaLTeR/niri/wiki/Configuration:-Window-Rules
// Work around WezTerm's initial configure bug
// by setting an empty default-column-width.
window-rule {
// This regular expression is intentionally made as specific as possible,
// since this is the default config, and we want no false positives.
// You can get away with just app-id="wezterm" if you want.
match app-id=r#"^org\.wezfurlong\.wezterm$"#
default-column-width {}
}
// Open the Firefox picture-in-picture player as floating by default.
window-rule {
// This app-id regular expression will work for both:
// - host Firefox (app-id is "firefox")
// - Flatpak Firefox (app-id is "org.mozilla.firefox")
match app-id=r#"firefox$"# title="^Picture-in-Picture$"
open-floating true
}
// Example: block out two password managers from screen capture.
// (This example rule is commented out with a "/-" in front.)
/-window-rule {
match app-id=r#"^org\.keepassxc\.KeePassXC$"#
match app-id=r#"^org\.gnome\.World\.Secrets$"#
block-out-from "screen-capture"
// Use this instead if you want them visible on third-party screenshot tools.
// block-out-from "screencast"
}
// Example: enable rounded corners for all windows.
// (This example rule is commented out with a "/-" in front.)
/-window-rule {
geometry-corner-radius 12
clip-to-geometry true
}
binds {
// Keys consist of modifiers separated by + signs, followed by an XKB key name
// in the end. To find an XKB name for a particular key, you may use a program
@@ -166,35 +332,54 @@ binds {
//
// "Mod" is a special modifier equal to Super when running on a TTY, and to Alt
// when running as a winit window.
//
// Most actions that you can bind here can also be invoked programmatically with
// `niri msg action do-something`.
// Mod-Shift-/, which is usually the same as Mod-?,
// shows a list of important hotkeys.
Mod+Shift+Slash { show-hotkey-overlay; }
// Suggested binds for running programs: terminal, app launcher, screen locker.
Mod+T { spawn "alacritty"; }
Mod+D { spawn "fuzzel"; }
Mod+Alt+L { spawn "swaylock"; }
Mod+T hotkey-overlay-title="Open a Terminal: alacritty" { spawn "alacritty"; }
Mod+D hotkey-overlay-title="Run an Application: fuzzel" { spawn "fuzzel"; }
Super+Alt+L hotkey-overlay-title="Lock the Screen: swaylock" { spawn "swaylock"; }
// You can also use a shell. Do this if you need pipes, multiple commands, etc.
// Note: the entire command goes as a single argument in the end.
// Mod+T { spawn "bash" "-c" "notify-send hello && exec alacritty"; }
// Example volume keys mappings for PipeWire & WirePlumber.
XF86AudioRaiseVolume { spawn "wpctl" "set-volume" "@DEFAULT_AUDIO_SINK@" "0.1+"; }
XF86AudioLowerVolume { spawn "wpctl" "set-volume" "@DEFAULT_AUDIO_SINK@" "0.1-"; }
// The allow-when-locked=true property makes them work even when the session is locked.
XF86AudioRaiseVolume allow-when-locked=true { spawn "wpctl" "set-volume" "@DEFAULT_AUDIO_SINK@" "0.1+"; }
XF86AudioLowerVolume allow-when-locked=true { spawn "wpctl" "set-volume" "@DEFAULT_AUDIO_SINK@" "0.1-"; }
XF86AudioMute allow-when-locked=true { spawn "wpctl" "set-mute" "@DEFAULT_AUDIO_SINK@" "toggle"; }
XF86AudioMicMute allow-when-locked=true { spawn "wpctl" "set-mute" "@DEFAULT_AUDIO_SOURCE@" "toggle"; }
// Open/close the Overview: a zoomed-out view of workspaces and windows.
// You can also move the mouse into the top-left hot corner,
// or do a four-finger swipe up on a touchpad.
Mod+O repeat=false { toggle-overview; }
Mod+Q { close-window; }
Mod+H { focus-column-left; }
Mod+J { focus-window-down; }
Mod+K { focus-window-up; }
Mod+L { focus-column-right; }
Mod+Left { focus-column-left; }
Mod+Down { focus-window-down; }
Mod+Up { focus-window-up; }
Mod+Right { focus-column-right; }
Mod+H { focus-column-left; }
Mod+J { focus-window-down; }
Mod+K { focus-window-up; }
Mod+L { focus-column-right; }
Mod+Ctrl+H { move-column-left; }
Mod+Ctrl+J { move-window-down; }
Mod+Ctrl+K { move-window-up; }
Mod+Ctrl+L { move-column-right; }
Mod+Ctrl+Left { move-column-left; }
Mod+Ctrl+Down { move-window-down; }
Mod+Ctrl+Up { move-window-up; }
Mod+Ctrl+Right { move-column-right; }
Mod+Ctrl+H { move-column-left; }
Mod+Ctrl+J { move-window-down; }
Mod+Ctrl+K { move-window-up; }
Mod+Ctrl+L { move-column-right; }
// Alternative commands that move across workspaces when reaching
// the first or last window in a column.
@@ -208,38 +393,90 @@ binds {
Mod+Ctrl+Home { move-column-to-first; }
Mod+Ctrl+End { move-column-to-last; }
Mod+Shift+H { focus-monitor-left; }
Mod+Shift+J { focus-monitor-down; }
Mod+Shift+K { focus-monitor-up; }
Mod+Shift+L { focus-monitor-right; }
Mod+Shift+Left { focus-monitor-left; }
Mod+Shift+Down { focus-monitor-down; }
Mod+Shift+Up { focus-monitor-up; }
Mod+Shift+Right { focus-monitor-right; }
Mod+Shift+H { focus-monitor-left; }
Mod+Shift+J { focus-monitor-down; }
Mod+Shift+K { focus-monitor-up; }
Mod+Shift+L { focus-monitor-right; }
Mod+Shift+Ctrl+H { move-window-to-monitor-left; }
Mod+Shift+Ctrl+J { move-window-to-monitor-down; }
Mod+Shift+Ctrl+K { move-window-to-monitor-up; }
Mod+Shift+Ctrl+L { move-window-to-monitor-right; }
Mod+Shift+Ctrl+Left { move-window-to-monitor-left; }
Mod+Shift+Ctrl+Down { move-window-to-monitor-down; }
Mod+Shift+Ctrl+Up { move-window-to-monitor-up; }
Mod+Shift+Ctrl+Right { move-window-to-monitor-right; }
Mod+Shift+Ctrl+Left { move-column-to-monitor-left; }
Mod+Shift+Ctrl+Down { move-column-to-monitor-down; }
Mod+Shift+Ctrl+Up { move-column-to-monitor-up; }
Mod+Shift+Ctrl+Right { move-column-to-monitor-right; }
Mod+Shift+Ctrl+H { move-column-to-monitor-left; }
Mod+Shift+Ctrl+J { move-column-to-monitor-down; }
Mod+Shift+Ctrl+K { move-column-to-monitor-up; }
Mod+Shift+Ctrl+L { move-column-to-monitor-right; }
// Alternatively, there are commands to move just a single window:
// Mod+Shift+Ctrl+Left { move-window-to-monitor-left; }
// ...
// And you can also move a whole workspace to another monitor:
// Mod+Shift+Ctrl+Left { move-workspace-to-monitor-left; }
// ...
Mod+U { focus-workspace-down; }
Mod+I { focus-workspace-up; }
Mod+Page_Down { focus-workspace-down; }
Mod+Page_Up { focus-workspace-up; }
Mod+Ctrl+U { move-window-to-workspace-down; }
Mod+Ctrl+I { move-window-to-workspace-up; }
Mod+Ctrl+Page_Down { move-window-to-workspace-down; }
Mod+Ctrl+Page_Up { move-window-to-workspace-up; }
Mod+U { focus-workspace-down; }
Mod+I { focus-workspace-up; }
Mod+Ctrl+Page_Down { move-column-to-workspace-down; }
Mod+Ctrl+Page_Up { move-column-to-workspace-up; }
Mod+Ctrl+U { move-column-to-workspace-down; }
Mod+Ctrl+I { move-column-to-workspace-up; }
// Alternatively, there are commands to move just a single window:
// Mod+Ctrl+Page_Down { move-window-to-workspace-down; }
// ...
Mod+Shift+U { move-workspace-down; }
Mod+Shift+I { move-workspace-up; }
Mod+Shift+Page_Down { move-workspace-down; }
Mod+Shift+Page_Up { move-workspace-up; }
Mod+Shift+U { move-workspace-down; }
Mod+Shift+I { move-workspace-up; }
// You can bind mouse wheel scroll ticks using the following syntax.
// These binds will change direction based on the natural-scroll setting.
//
// To avoid scrolling through workspaces really fast, you can use
// the cooldown-ms property. The bind will be rate-limited to this value.
// You can set a cooldown on any bind, but it's most useful for the wheel.
Mod+WheelScrollDown cooldown-ms=150 { focus-workspace-down; }
Mod+WheelScrollUp cooldown-ms=150 { focus-workspace-up; }
Mod+Ctrl+WheelScrollDown cooldown-ms=150 { move-column-to-workspace-down; }
Mod+Ctrl+WheelScrollUp cooldown-ms=150 { move-column-to-workspace-up; }
Mod+WheelScrollRight { focus-column-right; }
Mod+WheelScrollLeft { focus-column-left; }
Mod+Ctrl+WheelScrollRight { move-column-right; }
Mod+Ctrl+WheelScrollLeft { move-column-left; }
// Usually scrolling up and down with Shift in applications results in
// horizontal scrolling; these binds replicate that.
Mod+Shift+WheelScrollDown { focus-column-right; }
Mod+Shift+WheelScrollUp { focus-column-left; }
Mod+Ctrl+Shift+WheelScrollDown { move-column-right; }
Mod+Ctrl+Shift+WheelScrollUp { move-column-left; }
// Similarly, you can bind touchpad scroll "ticks".
// Touchpad scrolling is continuous, so for these binds it is split into
// discrete intervals.
// These binds are also affected by touchpad's natural-scroll, so these
// example binds are "inverted", since we have natural-scroll enabled for
// touchpads by default.
// Mod+TouchpadScrollDown { spawn "wpctl" "set-volume" "@DEFAULT_AUDIO_SINK@" "0.02+"; }
// Mod+TouchpadScrollUp { spawn "wpctl" "set-volume" "@DEFAULT_AUDIO_SINK@" "0.02-"; }
// You can refer to workspaces by index. However, keep in mind that
// niri is a dynamic workspace system, so these commands are kind of
// "best effort". Trying to refer to a workspace index bigger than
// the current workspace count will instead refer to the bottommost
// (empty) workspace.
//
// For example, with 2 workspaces + 1 empty, indices 3, 4, 5 and so on
// will all refer to the 3rd workspace.
Mod+1 { focus-workspace 1; }
Mod+2 { focus-workspace 2; }
Mod+3 { focus-workspace 3; }
@@ -249,24 +486,48 @@ binds {
Mod+7 { focus-workspace 7; }
Mod+8 { focus-workspace 8; }
Mod+9 { focus-workspace 9; }
Mod+Ctrl+1 { move-window-to-workspace 1; }
Mod+Ctrl+2 { move-window-to-workspace 2; }
Mod+Ctrl+3 { move-window-to-workspace 3; }
Mod+Ctrl+4 { move-window-to-workspace 4; }
Mod+Ctrl+5 { move-window-to-workspace 5; }
Mod+Ctrl+6 { move-window-to-workspace 6; }
Mod+Ctrl+7 { move-window-to-workspace 7; }
Mod+Ctrl+8 { move-window-to-workspace 8; }
Mod+Ctrl+9 { move-window-to-workspace 9; }
Mod+Ctrl+1 { move-column-to-workspace 1; }
Mod+Ctrl+2 { move-column-to-workspace 2; }
Mod+Ctrl+3 { move-column-to-workspace 3; }
Mod+Ctrl+4 { move-column-to-workspace 4; }
Mod+Ctrl+5 { move-column-to-workspace 5; }
Mod+Ctrl+6 { move-column-to-workspace 6; }
Mod+Ctrl+7 { move-column-to-workspace 7; }
Mod+Ctrl+8 { move-column-to-workspace 8; }
Mod+Ctrl+9 { move-column-to-workspace 9; }
// Alternatively, there are commands to move just a single window:
// Mod+Ctrl+1 { move-window-to-workspace 1; }
// Switches focus between the current and the previous workspace.
// Mod+Tab { focus-workspace-previous; }
// The following binds move the focused window in and out of a column.
// If the window is alone, they will consume it into the nearby column to the side.
// If the window is already in a column, they will expel it out.
Mod+BracketLeft { consume-or-expel-window-left; }
Mod+BracketRight { consume-or-expel-window-right; }
// Consume one window from the right to the bottom of the focused column.
Mod+Comma { consume-window-into-column; }
// Expel the bottom window from the focused column to the right.
Mod+Period { expel-window-from-column; }
Mod+R { switch-preset-column-width; }
Mod+Shift+R { switch-preset-window-height; }
Mod+Ctrl+R { reset-window-height; }
Mod+F { maximize-column; }
Mod+Shift+F { fullscreen-window; }
// Expand the focused column to space not taken up by other fully visible columns.
// Makes the column "fill the rest of the space".
Mod+Ctrl+F { expand-column-to-available-width; }
Mod+C { center-column; }
// Center all fully visible columns on screen.
Mod+Ctrl+C { center-visible-columns; }
// Finer width adjustments.
// This command can also:
// * set width in pixels: "1000"
@@ -282,6 +543,15 @@ binds {
Mod+Shift+Minus { set-window-height "-10%"; }
Mod+Shift+Equal { set-window-height "+10%"; }
// Move the focused window between the floating and the tiling layout.
Mod+V { toggle-window-floating; }
Mod+Shift+V { switch-focus-between-floating-and-tiling; }
// Toggle tabbed column display mode.
// Windows in this column will appear as vertical tabs,
// rather than stacked on top of each other.
Mod+W { toggle-column-tabbed-display; }
// Actions to switch layouts.
// Note: if you uncomment these, make sure you do NOT have
// a matching layout switch hotkey configured in xkb options above.
@@ -294,8 +564,21 @@ binds {
Ctrl+Print { screenshot-screen; }
Alt+Print { screenshot-window; }
Mod+Shift+E { quit; }
Mod+Shift+P { power-off-monitors; }
// Applications such as remote-desktop clients and software KVM switches may
// request that niri stops processing the keyboard shortcuts defined here
// so they may, for example, forward the key presses as-is to a remote machine.
// It's a good idea to bind an escape hatch to toggle the inhibitor,
// so a buggy application can't hold your session hostage.
//
// The allow-inhibiting=false property can be applied to other binds as well,
// which ensures niri always processes them, even when an inhibitor is active.
Mod+Escape allow-inhibiting=false { toggle-keyboard-shortcuts-inhibit; }
Mod+Shift+Ctrl+T { toggle-debug-tint; }
// The quit action will show a confirmation dialog to avoid accidental exits.
Mod+Shift+E { quit; }
Ctrl+Alt+Delete { quit; }
// Powers off the monitors. To turn them back on, do any input like
// moving the mouse or pressing any other key.
Mod+Shift+P { power-off-monitors; }
}
+8
View File
@@ -0,0 +1,8 @@
type = process
command = niri --session
restart = false
working-dir = $HOME
depends-on = dbus
after = niri-shutdown
chain-to = niri-shutdown
options: always-chain
+3
View File
@@ -0,0 +1,3 @@
type = scripted
command = dinitctl -u setenv WAYLAND_DISPLAY= XDG_SESSION_TYPE= XDG_CURRENT_DESKTOP= NIRI_SOCKET=
restart = false
+18
View File
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="mutter_x11_interop">
<description summary="X11 interoperability helper">
This protocol is intended to be used by the portal backend to map Wayland
dialogs as modal dialogs on top of X11 windows.
</description>
<interface name="mutter_x11_interop" version="1">
<description summary="X11 interoperability helper"/>
<request name="destroy" type="destructor"/>
<request name="set_x11_parent">
<arg name="surface" type="object" interface="wl_surface"/>
<arg name="xwindow" type="uint"/>
</request>
</interface>
</protocol>
+2
View File
@@ -1,3 +1,5 @@
[preferred]
default=gnome;gtk;
org.freedesktop.impl.portal.Access=gtk;
org.freedesktop.impl.portal.Notification=gtk;
org.freedesktop.impl.portal.Secret=gnome-keyring;
+47 -33
View File
@@ -11,37 +11,51 @@ if [ -n "$SHELL" ] &&
fi
fi
# Make sure there's no already running session.
if systemctl --user -q is-active niri.service; then
echo 'A niri session is already running.'
exit 1
# Try to detect the service manager that is being used
if hash systemctl >/dev/null 2>&1; then
# Make sure there's no already running session.
if systemctl --user -q is-active niri.service; then
echo 'A niri session is already running.'
exit 1
fi
# Reset failed state of all user units.
systemctl --user reset-failed
# Import the login manager environment.
systemctl --user import-environment
# DBus activation environment is independent from systemd. While most of
# dbus-activated services are already using `SystemdService` directive, some
# still don't and thus we should set the dbus environment with a separate
# command.
if hash dbus-update-activation-environment 2>/dev/null; then
dbus-update-activation-environment --all
fi
# Start niri and wait for it to terminate.
systemctl --user --wait start niri.service
# Force stop of graphical-session.target.
systemctl --user start --job-mode=replace-irreversibly niri-shutdown.target
# Unset environment that we've set.
systemctl --user unset-environment WAYLAND_DISPLAY XDG_SESSION_TYPE XDG_CURRENT_DESKTOP NIRI_SOCKET
elif hash dinitctl >/dev/null 2>&1; then
# Check that the user dinit daemon is running
if ! pgrep -u "$(id -u)" dinit >/dev/null 2>&1; then
echo "dinit user daemon is not running."
exit 1
fi
# Make sure there's no already running session.
if dinitctl --user is-started niri >/dev/null 2>&1; then
echo 'A niri session is already running.'
exit 1
fi
# Start niri
dinitctl --user start niri
else
echo "No systemd or dinit detected, please use niri --session instead."
fi
# Reset failed state of all user units.
systemctl --user reset-failed
# Set the current desktop for xdg-desktop-portal.
export XDG_CURRENT_DESKTOP=niri
# Ensure the session type is set to Wayland for xdg-autostart apps.
export XDG_SESSION_TYPE=wayland
# Import the login manager environment.
systemctl --user import-environment
# DBus activation environment is independent from systemd. While most of
# dbus-activated services are already using `SystemdService` directive, some
# still don't and thus we should set the dbus environment with a separate
# command.
if hash dbus-update-activation-environment 2>/dev/null; then
dbus-update-activation-environment --all
fi
# Start niri and wait for it to terminate.
systemctl --user --wait start niri.service
# Force stop of grahical-session.target.
systemctl --user start --job-mode=replace-irreversibly niri-shutdown.target
# Unset environment that we've set.
systemctl --user unset-environment WAYLAND_DISPLAY XDG_SESSION_TYPE XDG_CURRENT_DESKTOP
+2 -1
View File
@@ -9,5 +9,6 @@ Wants=xdg-desktop-autostart.target
Before=xdg-desktop-autostart.target
[Service]
Slice=session.slice
Type=notify
ExecStart=/usr/bin/niri
ExecStart=/usr/bin/niri --session
+6
View File
@@ -0,0 +1,6 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=refresh content=0;url=niri_ipc/index.html />
</head>
</html>
-53
View File
@@ -1,53 +0,0 @@
use std::time::Duration;
use keyframe::functions::EaseOutCubic;
use keyframe::EasingFunction;
use portable_atomic::{AtomicF64, Ordering};
use crate::utils::get_monotonic_time;
pub static ANIMATION_SLOWDOWN: AtomicF64 = AtomicF64::new(1.);
#[derive(Debug)]
pub struct Animation {
from: f64,
to: f64,
duration: Duration,
start_time: Duration,
current_time: Duration,
}
impl Animation {
pub fn new(from: f64, to: f64, over: Duration) -> Self {
// FIXME: ideally we shouldn't use current time here because animations started within the
// same frame cycle should have the same start time to be synchronized.
let now = get_monotonic_time();
Self {
from,
to,
duration: over.mul_f64(ANIMATION_SLOWDOWN.load(Ordering::Relaxed)),
start_time: now,
current_time: now,
}
}
pub fn set_current_time(&mut self, time: Duration) {
self.current_time = time;
}
pub fn is_done(&self) -> bool {
self.current_time >= self.start_time + self.duration
}
pub fn value(&self) -> f64 {
let passed = (self.current_time - self.start_time).as_secs_f64();
let total = self.duration.as_secs_f64();
let x = (passed / total).clamp(0., 1.);
EaseOutCubic.y(x) * (self.to - self.from) + self.from
}
pub fn to(&self) -> f64 {
self.to
}
}
+202
View File
@@ -0,0 +1,202 @@
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;
use crate::utils::get_monotonic_time;
/// Shareable lazy clock that can change rate.
///
/// The clock will fetch the time once and then retain it until explicitly cleared with
/// [`Clock::clear`].
#[derive(Debug, Default, Clone)]
pub struct Clock {
inner: Rc<RefCell<AdjustableClock>>,
}
#[derive(Debug, Default)]
struct LazyClock {
time: Option<Duration>,
}
/// Clock that can adjust its rate.
#[derive(Debug)]
struct AdjustableClock {
inner: LazyClock,
current_time: Duration,
last_seen_time: Duration,
rate: f64,
complete_instantly: bool,
}
impl Clock {
/// Creates a new clock with the given time.
pub fn with_time(time: Duration) -> Self {
let clock = AdjustableClock::new(LazyClock::with_time(time));
Self {
inner: Rc::new(RefCell::new(clock)),
}
}
/// Returns the current time.
pub fn now(&self) -> Duration {
self.inner.borrow_mut().now()
}
/// Returns the underlying time not adjusted for rate change.
pub fn now_unadjusted(&self) -> Duration {
self.inner.borrow_mut().inner.now()
}
/// Sets the unadjusted clock time.
pub fn set_unadjusted(&mut self, time: Duration) {
self.inner.borrow_mut().inner.set(time);
}
/// Clears the stored time so it's re-fetched again next.
pub fn clear(&mut self) {
self.inner.borrow_mut().inner.clear();
}
/// Gets the clock rate.
pub fn rate(&self) -> f64 {
self.inner.borrow().rate()
}
/// Sets the clock rate.
pub fn set_rate(&mut self, rate: f64) {
self.inner.borrow_mut().set_rate(rate);
}
/// Returns whether animations should complete instantly.
pub fn should_complete_instantly(&self) -> bool {
self.inner.borrow().should_complete_instantly()
}
/// Sets whether animations should complete instantly.
pub fn set_complete_instantly(&mut self, value: bool) {
self.inner.borrow_mut().set_complete_instantly(value);
}
}
impl PartialEq for Clock {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.inner, &other.inner)
}
}
impl Eq for Clock {}
impl LazyClock {
pub fn with_time(time: Duration) -> Self {
Self { time: Some(time) }
}
pub fn clear(&mut self) {
self.time = None;
}
pub fn set(&mut self, time: Duration) {
self.time = Some(time);
}
pub fn now(&mut self) -> Duration {
*self.time.get_or_insert_with(get_monotonic_time)
}
}
impl AdjustableClock {
pub fn new(mut inner: LazyClock) -> Self {
let time = inner.now();
Self {
inner,
current_time: time,
last_seen_time: time,
rate: 1.,
complete_instantly: false,
}
}
pub fn rate(&self) -> f64 {
self.rate
}
pub fn set_rate(&mut self, rate: f64) {
self.rate = rate.clamp(0., 1000.);
}
pub fn should_complete_instantly(&self) -> bool {
self.complete_instantly
}
pub fn set_complete_instantly(&mut self, value: bool) {
self.complete_instantly = value;
}
pub fn now(&mut self) -> Duration {
let time = self.inner.now();
if self.last_seen_time == time {
return self.current_time;
}
if self.last_seen_time < time {
let delta = time - self.last_seen_time;
let delta = delta.mul_f64(self.rate);
self.current_time = self.current_time.saturating_add(delta);
} else {
let delta = self.last_seen_time - time;
let delta = delta.mul_f64(self.rate);
self.current_time = self.current_time.saturating_sub(delta);
}
self.last_seen_time = time;
self.current_time
}
}
impl Default for AdjustableClock {
fn default() -> Self {
Self::new(LazyClock::default())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn frozen_clock() {
let mut clock = Clock::with_time(Duration::ZERO);
assert_eq!(clock.now(), Duration::ZERO);
clock.set_unadjusted(Duration::from_millis(100));
assert_eq!(clock.now(), Duration::from_millis(100));
clock.set_unadjusted(Duration::from_millis(200));
assert_eq!(clock.now(), Duration::from_millis(200));
}
#[test]
fn rate_change() {
let mut clock = Clock::with_time(Duration::ZERO);
clock.set_rate(0.5);
clock.set_unadjusted(Duration::from_millis(100));
assert_eq!(clock.now_unadjusted(), Duration::from_millis(100));
assert_eq!(clock.now(), Duration::from_millis(50));
clock.set_unadjusted(Duration::from_millis(200));
assert_eq!(clock.now_unadjusted(), Duration::from_millis(200));
assert_eq!(clock.now(), Duration::from_millis(100));
clock.set_unadjusted(Duration::from_millis(150));
assert_eq!(clock.now_unadjusted(), Duration::from_millis(150));
assert_eq!(clock.now(), Duration::from_millis(75));
clock.set_rate(2.0);
clock.set_unadjusted(Duration::from_millis(250));
assert_eq!(clock.now_unadjusted(), Duration::from_millis(250));
assert_eq!(clock.now(), Duration::from_millis(275));
}
}
+358
View File
@@ -0,0 +1,358 @@
use std::time::Duration;
use keyframe::functions::{EaseOutCubic, EaseOutQuad};
use keyframe::EasingFunction;
mod spring;
pub use spring::{Spring, SpringParams};
mod clock;
pub use clock::Clock;
#[derive(Debug, Clone)]
pub struct Animation {
from: f64,
to: f64,
initial_velocity: f64,
is_off: bool,
duration: Duration,
/// Time until the animation first reaches `to`.
///
/// Best effort; not always exactly precise.
clamped_duration: Duration,
start_time: Duration,
clock: Clock,
kind: Kind,
}
#[derive(Debug, Clone, Copy)]
enum Kind {
Easing {
curve: Curve,
},
Spring(Spring),
Deceleration {
initial_velocity: f64,
deceleration_rate: f64,
},
}
#[derive(Debug, Clone, Copy)]
pub enum Curve {
Linear,
EaseOutQuad,
EaseOutCubic,
EaseOutExpo,
}
impl Animation {
pub fn new(
clock: Clock,
from: f64,
to: f64,
initial_velocity: f64,
config: niri_config::Animation,
) -> Self {
// Scale the velocity by rate to keep the touchpad gestures feeling right.
let initial_velocity = initial_velocity / clock.rate().max(0.001);
let mut rv = Self::ease(clock, from, to, initial_velocity, 0, Curve::EaseOutCubic);
if config.off {
rv.is_off = true;
return rv;
}
rv.replace_config(config);
rv
}
pub fn replace_config(&mut self, config: niri_config::Animation) {
self.is_off = config.off;
if config.off {
self.duration = Duration::ZERO;
self.clamped_duration = Duration::ZERO;
return;
}
let start_time = self.start_time;
match config.kind {
niri_config::AnimationKind::Spring(p) => {
let params = SpringParams::new(p.damping_ratio, f64::from(p.stiffness), p.epsilon);
let spring = Spring {
from: self.from,
to: self.to,
initial_velocity: self.initial_velocity,
params,
};
*self = Self::spring(self.clock.clone(), spring);
}
niri_config::AnimationKind::Easing(p) => {
*self = Self::ease(
self.clock.clone(),
self.from,
self.to,
self.initial_velocity,
u64::from(p.duration_ms),
Curve::from(p.curve),
);
}
}
self.start_time = start_time;
}
/// Restarts the animation using the previous config.
pub fn restarted(&self, from: f64, to: f64, initial_velocity: f64) -> Self {
if self.is_off {
return self.clone();
}
// Scale the velocity by rate to keep the touchpad gestures feeling right.
let initial_velocity = initial_velocity / self.clock.rate().max(0.001);
match self.kind {
Kind::Easing { curve } => Self::ease(
self.clock.clone(),
from,
to,
initial_velocity,
self.duration.as_millis() as u64,
curve,
),
Kind::Spring(spring) => {
let spring = Spring {
from,
to,
initial_velocity: self.initial_velocity,
params: spring.params,
};
Self::spring(self.clock.clone(), spring)
}
Kind::Deceleration {
initial_velocity,
deceleration_rate,
} => {
let threshold = 0.001; // FIXME
Self::decelerate(
self.clock.clone(),
from,
initial_velocity,
deceleration_rate,
threshold,
)
}
}
}
pub fn ease(
clock: Clock,
from: f64,
to: f64,
initial_velocity: f64,
duration_ms: u64,
curve: Curve,
) -> Self {
let duration = Duration::from_millis(duration_ms);
let kind = Kind::Easing { curve };
Self {
from,
to,
initial_velocity,
is_off: false,
duration,
// Our current curves never overshoot.
clamped_duration: duration,
start_time: clock.now(),
clock,
kind,
}
}
pub fn spring(clock: Clock, spring: Spring) -> Self {
let _span = tracy_client::span!("Animation::spring");
let duration = spring.duration();
let clamped_duration = spring.clamped_duration().unwrap_or(duration);
let kind = Kind::Spring(spring);
Self {
from: spring.from,
to: spring.to,
initial_velocity: spring.initial_velocity,
is_off: false,
duration,
clamped_duration,
start_time: clock.now(),
clock,
kind,
}
}
pub fn decelerate(
clock: Clock,
from: f64,
initial_velocity: f64,
deceleration_rate: f64,
threshold: f64,
) -> Self {
let duration_s = if initial_velocity == 0. {
0.
} else {
let coeff = 1000. * deceleration_rate.ln();
(-coeff * threshold / initial_velocity.abs()).ln() / coeff
};
let duration = Duration::from_secs_f64(duration_s);
let to = from - initial_velocity / (1000. * deceleration_rate.ln());
let kind = Kind::Deceleration {
initial_velocity,
deceleration_rate,
};
Self {
from,
to,
initial_velocity,
is_off: false,
duration,
clamped_duration: duration,
start_time: clock.now(),
clock,
kind,
}
}
pub fn is_done(&self) -> bool {
if self.clock.should_complete_instantly() {
return true;
}
self.clock.now() >= self.start_time + self.duration
}
pub fn is_clamped_done(&self) -> bool {
if self.clock.should_complete_instantly() {
return true;
}
self.clock.now() >= self.start_time + self.clamped_duration
}
pub fn value_at(&self, at: Duration) -> f64 {
if at <= self.start_time {
// Return from when at == start_time so that when the animations are off, the behavior
// within a single event loop cycle (i.e. no time had passed since the start of an
// animation) matches the behavior when the animations are on.
return self.from;
} else if self.start_time + self.duration <= at {
return self.to;
}
if self.clock.should_complete_instantly() {
return self.to;
}
let passed = at.saturating_sub(self.start_time);
match self.kind {
Kind::Easing { curve } => {
let passed = passed.as_secs_f64();
let total = self.duration.as_secs_f64();
let x = (passed / total).clamp(0., 1.);
curve.y(x) * (self.to - self.from) + self.from
}
Kind::Spring(spring) => {
let value = spring.value_at(passed);
// Protect against numerical instability.
let range = (self.to - self.from) * 10.;
let a = self.from - range;
let b = self.to + range;
if self.from <= self.to {
value.clamp(a, b)
} else {
value.clamp(b, a)
}
}
Kind::Deceleration {
initial_velocity,
deceleration_rate,
} => {
let passed = passed.as_secs_f64();
let coeff = 1000. * deceleration_rate.ln();
self.from + (deceleration_rate.powf(1000. * passed) - 1.) / coeff * initial_velocity
}
}
}
pub fn value(&self) -> f64 {
self.value_at(self.clock.now())
}
/// Returns a value that stops at the target value after first reaching it.
///
/// Best effort; not always exactly precise.
pub fn clamped_value(&self) -> f64 {
if self.is_clamped_done() {
return self.to;
}
self.value()
}
pub fn to(&self) -> f64 {
self.to
}
pub fn from(&self) -> f64 {
self.from
}
pub fn start_time(&self) -> Duration {
self.start_time
}
pub fn end_time(&self) -> Duration {
self.start_time + self.duration
}
pub fn duration(&self) -> Duration {
self.duration
}
pub fn offset(&mut self, offset: f64) {
self.from += offset;
self.to += offset;
if let Kind::Spring(spring) = &mut self.kind {
spring.from += offset;
spring.to += offset;
}
}
}
impl Curve {
pub fn y(self, x: f64) -> f64 {
match self {
Curve::Linear => x,
Curve::EaseOutQuad => EaseOutQuad.y(x),
Curve::EaseOutCubic => EaseOutCubic.y(x),
Curve::EaseOutExpo => 1. - 2f64.powf(-10. * x),
}
}
}
impl From<niri_config::AnimationCurve> for Curve {
fn from(value: niri_config::AnimationCurve) -> Self {
match value {
niri_config::AnimationCurve::Linear => Curve::Linear,
niri_config::AnimationCurve::EaseOutQuad => Curve::EaseOutQuad,
niri_config::AnimationCurve::EaseOutCubic => Curve::EaseOutCubic,
niri_config::AnimationCurve::EaseOutExpo => Curve::EaseOutExpo,
}
}
}
+209
View File
@@ -0,0 +1,209 @@
use std::time::Duration;
#[derive(Debug, Clone, Copy)]
pub struct SpringParams {
pub damping: f64,
pub mass: f64,
pub stiffness: f64,
pub epsilon: f64,
}
#[derive(Debug, Clone, Copy)]
pub struct Spring {
pub from: f64,
pub to: f64,
pub initial_velocity: f64,
pub params: SpringParams,
}
impl SpringParams {
pub fn new(damping_ratio: f64, stiffness: f64, epsilon: f64) -> Self {
let damping_ratio = damping_ratio.max(0.);
let stiffness = stiffness.max(0.);
let epsilon = epsilon.max(0.);
let mass = 1.;
let critical_damping = 2. * (mass * stiffness).sqrt();
let damping = damping_ratio * critical_damping;
Self {
damping,
mass,
stiffness,
epsilon,
}
}
}
impl Spring {
pub fn value_at(&self, t: Duration) -> f64 {
self.oscillate(t.as_secs_f64())
}
// Based on libadwaita (LGPL-2.1-or-later):
// https://gitlab.gnome.org/GNOME/libadwaita/-/blob/1.4.4/src/adw-spring-animation.c,
// which itself is based on (MIT):
// https://github.com/robb/RBBAnimation/blob/master/RBBAnimation/RBBSpringAnimation.m
/// Computes and returns the duration until the spring is at rest.
pub fn duration(&self) -> Duration {
const DELTA: f64 = 0.001;
let beta = self.params.damping / (2. * self.params.mass);
if beta.abs() <= f64::EPSILON || beta < 0. {
return Duration::MAX;
}
if (self.to - self.from).abs() <= f64::EPSILON {
return Duration::ZERO;
}
let omega0 = (self.params.stiffness / self.params.mass).sqrt();
// As first ansatz for the overdamped solution,
// and general estimation for the oscillating ones
// we take the value of the envelope when it's < epsilon.
let mut x0 = -self.params.epsilon.ln() / beta;
// f64::EPSILON is too small for this specific comparison, so we use
// f32::EPSILON even though it's doubles.
if (beta - omega0).abs() <= f64::from(f32::EPSILON) || beta < omega0 {
return Duration::from_secs_f64(x0);
}
// Since the overdamped solution decays way slower than the envelope
// we need to use the value of the oscillation itself.
// Newton's root finding method is a good candidate in this particular case:
// https://en.wikipedia.org/wiki/Newton%27s_method
let mut y0 = self.oscillate(x0);
let m = (self.oscillate(x0 + DELTA) - y0) / DELTA;
let mut x1 = (self.to - y0 + m * x0) / m;
let mut y1 = self.oscillate(x1);
let mut i = 0;
while (self.to - y1).abs() > self.params.epsilon {
if i > 1000 {
return Duration::ZERO;
}
x0 = x1;
y0 = y1;
let m = (self.oscillate(x0 + DELTA) - y0) / DELTA;
x1 = (self.to - y0 + m * x0) / m;
y1 = self.oscillate(x1);
// Overdamped springs have some numerical stability issues...
if !y1.is_finite() {
return Duration::from_secs_f64(x0);
}
i += 1;
}
Duration::from_secs_f64(x1)
}
/// Computes and returns the duration until the spring reaches its target position.
pub fn clamped_duration(&self) -> Option<Duration> {
let beta = self.params.damping / (2. * self.params.mass);
if beta.abs() <= f64::EPSILON || beta < 0. {
return Some(Duration::MAX);
}
if (self.to - self.from).abs() <= f64::EPSILON {
return Some(Duration::ZERO);
}
// The first frame is not that important and we avoid finding the trivial 0 for in-place
// animations.
let mut i = 1u16;
let mut y = self.oscillate(f64::from(i) / 1000.);
while (self.to - self.from > f64::EPSILON && self.to - y > self.params.epsilon)
|| (self.from - self.to > f64::EPSILON && y - self.to > self.params.epsilon)
{
if i > 3000 {
return None;
}
i += 1;
y = self.oscillate(f64::from(i) / 1000.);
}
Some(Duration::from_millis(u64::from(i)))
}
/// Returns the spring position at a given time in seconds.
fn oscillate(&self, t: f64) -> f64 {
let b = self.params.damping;
let m = self.params.mass;
let k = self.params.stiffness;
let v0 = self.initial_velocity;
let beta = b / (2. * m);
let omega0 = (k / m).sqrt();
let x0 = self.from - self.to;
let envelope = (-beta * t).exp();
// Solutions of the form C1*e^(lambda1*x) + C2*e^(lambda2*x)
// for the differential equation m*ẍ+b*ẋ+kx = 0
// f64::EPSILON is too small for this specific comparison, so we use
// f32::EPSILON even though it's doubles.
if (beta - omega0).abs() <= f64::from(f32::EPSILON) {
// Critically damped.
self.to + envelope * (x0 + (beta * x0 + v0) * t)
} else if beta < omega0 {
// Underdamped.
let omega1 = ((omega0 * omega0) - (beta * beta)).sqrt();
self.to
+ envelope
* (x0 * (omega1 * t).cos() + ((beta * x0 + v0) / omega1) * (omega1 * t).sin())
} else {
// Overdamped.
let omega2 = ((beta * beta) - (omega0 * omega0)).sqrt();
self.to
+ envelope
* (x0 * (omega2 * t).cosh() + ((beta * x0 + v0) / omega2) * (omega2 * t).sinh())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn overdamped_spring_equal_from_to_nan() {
let spring = Spring {
from: 0.,
to: 0.,
initial_velocity: 0.,
params: SpringParams::new(1.15, 850., 0.0001),
};
let _ = spring.duration();
let _ = spring.clamped_duration();
let _ = spring.value_at(Duration::ZERO);
}
#[test]
fn overdamped_spring_duration_panic() {
let spring = Spring {
from: 0.,
to: 1.,
initial_velocity: 0.,
params: SpringParams::new(6., 1200., 0.0001),
};
let _ = spring.duration();
let _ = spring.clamped_duration();
let _ = spring.value_at(Duration::ZERO);
}
}
+140
View File
@@ -0,0 +1,140 @@
//! Headless backend for tests.
//!
//! This can eventually grow into a more complete backend if needed, but for now it's missing some
//! crucial parts like rendering.
use std::mem;
use std::sync::{Arc, Mutex};
use niri_config::OutputName;
use smithay::backend::allocator::dmabuf::Dmabuf;
use smithay::backend::renderer::element::RenderElementStates;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::output::{Mode, Output, PhysicalProperties, Subpixel};
use smithay::reexports::wayland_protocols::wp::presentation_time::server::wp_presentation_feedback;
use smithay::utils::Size;
use smithay::wayland::presentation::Refresh;
use super::{IpcOutputMap, OutputId, RenderResult};
use crate::niri::{Niri, RedrawState};
use crate::utils::{get_monotonic_time, logical_output};
pub struct Headless {
ipc_outputs: Arc<Mutex<IpcOutputMap>>,
}
impl Headless {
pub fn new() -> Self {
Self {
ipc_outputs: Default::default(),
}
}
pub fn init(&mut self, _niri: &mut Niri) {}
pub fn add_output(&mut self, niri: &mut Niri, n: u8, size: (u16, u16)) {
let connector = format!("headless-{n}");
let make = "niri".to_string();
let model = "headless".to_string();
let serial = n.to_string();
let output = Output::new(
connector.clone(),
PhysicalProperties {
size: (0, 0).into(),
subpixel: Subpixel::Unknown,
make: make.clone(),
model: model.clone(),
},
);
let mode = Mode {
size: Size::from((i32::from(size.0), i32::from(size.1))),
refresh: 60_000,
};
output.change_current_state(Some(mode), None, None, None);
output.set_preferred(mode);
output.user_data().insert_if_missing(|| OutputName {
connector,
make: Some(make),
model: Some(model),
serial: Some(serial),
});
let physical_properties = output.physical_properties();
self.ipc_outputs.lock().unwrap().insert(
OutputId::next(),
niri_ipc::Output {
name: output.name(),
make: physical_properties.make,
model: physical_properties.model,
serial: None,
physical_size: None,
modes: vec![niri_ipc::Mode {
width: size.0,
height: size.1,
refresh_rate: 60_000,
is_preferred: true,
}],
current_mode: Some(0),
vrr_supported: false,
vrr_enabled: false,
logical: Some(logical_output(&output)),
},
);
niri.add_output(output, None, false);
}
pub fn seat_name(&self) -> String {
"headless".to_owned()
}
pub fn with_primary_renderer<T>(
&mut self,
_f: impl FnOnce(&mut GlesRenderer) -> T,
) -> Option<T> {
None
}
pub fn render(&mut self, niri: &mut Niri, output: &Output) -> RenderResult {
let states = RenderElementStates::default();
let mut presentation_feedbacks = niri.take_presentation_feedbacks(output, &states);
presentation_feedbacks.presented::<_, smithay::utils::Monotonic>(
get_monotonic_time(),
Refresh::Unknown,
0,
wp_presentation_feedback::Kind::empty(),
);
let output_state = niri.output_state.get_mut(output).unwrap();
match mem::replace(&mut output_state.redraw_state, RedrawState::Idle) {
RedrawState::Idle => unreachable!(),
RedrawState::Queued => (),
RedrawState::WaitingForVBlank { .. } => unreachable!(),
RedrawState::WaitingForEstimatedVBlank(_) => unreachable!(),
RedrawState::WaitingForEstimatedVBlankAndQueued(_) => unreachable!(),
}
output_state.frame_callback_sequence = output_state.frame_callback_sequence.wrapping_add(1);
// FIXME: request redraw on unfinished animations remain
RenderResult::Submitted
}
pub fn import_dmabuf(&mut self, _dmabuf: &Dmabuf) -> bool {
unimplemented!()
}
pub fn ipc_outputs(&self) -> Arc<Mutex<IpcOutputMap>> {
self.ipc_outputs.clone()
}
}
impl Default for Headless {
fn default() -> Self {
Self::new()
}
}
+83 -11
View File
@@ -2,13 +2,14 @@ use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use niri_config::{Config, ModKey};
use smithay::backend::allocator::dmabuf::Dmabuf;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::output::Output;
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
use crate::input::CompositorMod;
use crate::Niri;
use crate::niri::Niri;
use crate::utils::id::IdCounter;
pub mod tty;
pub use tty::Tty;
@@ -16,9 +17,14 @@ pub use tty::Tty;
pub mod winit;
pub use winit::Winit;
pub mod headless;
pub use headless::Headless;
#[allow(clippy::large_enum_variant)]
pub enum Backend {
Tty(Tty),
Winit(Winit),
Headless(Headless),
}
#[derive(PartialEq, Eq)]
@@ -31,11 +37,29 @@ pub enum RenderResult {
Skipped,
}
pub type IpcOutputMap = HashMap<OutputId, niri_ipc::Output>;
static OUTPUT_ID_COUNTER: IdCounter = IdCounter::new();
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OutputId(u64);
impl OutputId {
fn next() -> OutputId {
OutputId(OUTPUT_ID_COUNTER.next())
}
pub fn get(self) -> u64 {
self.0
}
}
impl Backend {
pub fn init(&mut self, niri: &mut Niri) {
match self {
Backend::Tty(tty) => tty.init(niri),
Backend::Winit(winit) => winit.init(niri),
Backend::Headless(headless) => headless.init(niri),
}
}
@@ -43,6 +67,7 @@ impl Backend {
match self {
Backend::Tty(tty) => tty.seat_name(),
Backend::Winit(winit) => winit.seat_name(),
Backend::Headless(headless) => headless.seat_name(),
}
}
@@ -53,6 +78,7 @@ impl Backend {
match self {
Backend::Tty(tty) => tty.with_primary_renderer(f),
Backend::Winit(winit) => winit.with_primary_renderer(f),
Backend::Headless(headless) => headless.with_primary_renderer(f),
}
}
@@ -65,13 +91,20 @@ impl Backend {
match self {
Backend::Tty(tty) => tty.render(niri, output, target_presentation_time),
Backend::Winit(winit) => winit.render(niri, output),
Backend::Headless(headless) => headless.render(niri, output),
}
}
pub fn mod_key(&self) -> CompositorMod {
pub fn mod_key(&self, config: &Config) -> ModKey {
match self {
Backend::Tty(_) => CompositorMod::Super,
Backend::Winit(_) => CompositorMod::Alt,
Backend::Winit(_) => config.input.mod_key_nested.unwrap_or({
if let Some(ModKey::Alt) = config.input.mod_key {
ModKey::Super
} else {
ModKey::Alt
}
}),
Backend::Tty(_) | Backend::Headless(_) => config.input.mod_key.unwrap_or(ModKey::Super),
}
}
@@ -79,6 +112,7 @@ impl Backend {
match self {
Backend::Tty(tty) => tty.change_vt(vt),
Backend::Winit(_) => (),
Backend::Headless(_) => (),
}
}
@@ -86,6 +120,7 @@ impl Backend {
match self {
Backend::Tty(tty) => tty.suspend(),
Backend::Winit(_) => (),
Backend::Headless(_) => (),
}
}
@@ -93,13 +128,15 @@ impl Backend {
match self {
Backend::Tty(tty) => tty.toggle_debug_tint(),
Backend::Winit(winit) => winit.toggle_debug_tint(),
Backend::Headless(_) => (),
}
}
pub fn import_dmabuf(&mut self, dmabuf: &Dmabuf) -> Result<(), ()> {
pub fn import_dmabuf(&mut self, dmabuf: &Dmabuf) -> bool {
match self {
Backend::Tty(tty) => tty.import_dmabuf(dmabuf),
Backend::Winit(winit) => winit.import_dmabuf(dmabuf),
Backend::Headless(headless) => headless.import_dmabuf(dmabuf),
}
}
@@ -107,14 +144,15 @@ impl Backend {
match self {
Backend::Tty(tty) => tty.early_import(surface),
Backend::Winit(_) => (),
Backend::Headless(_) => (),
}
}
#[cfg_attr(not(feature = "dbus"), allow(unused))]
pub fn connectors(&self) -> Arc<Mutex<HashMap<String, Output>>> {
pub fn ipc_outputs(&self) -> Arc<Mutex<IpcOutputMap>> {
match self {
Backend::Tty(tty) => tty.connectors(),
Backend::Winit(winit) => winit.connectors(),
Backend::Tty(tty) => tty.ipc_outputs(),
Backend::Winit(winit) => winit.ipc_outputs(),
Backend::Headless(headless) => headless.ipc_outputs(),
}
}
@@ -126,13 +164,39 @@ impl Backend {
match self {
Backend::Tty(tty) => tty.primary_gbm_device(),
Backend::Winit(_) => None,
Backend::Headless(_) => None,
}
}
pub fn set_monitors_active(&self, active: bool) {
pub fn set_monitors_active(&mut self, active: bool) {
match self {
Backend::Tty(tty) => tty.set_monitors_active(active),
Backend::Winit(_) => (),
Backend::Headless(_) => (),
}
}
pub fn set_output_on_demand_vrr(&mut self, niri: &mut Niri, output: &Output, enable_vrr: bool) {
match self {
Backend::Tty(tty) => tty.set_output_on_demand_vrr(niri, output, enable_vrr),
Backend::Winit(_) => (),
Backend::Headless(_) => (),
}
}
pub fn on_output_config_changed(&mut self, niri: &mut Niri) {
match self {
Backend::Tty(tty) => tty.on_output_config_changed(niri),
Backend::Winit(_) => (),
Backend::Headless(_) => (),
}
}
pub fn tty_checked(&mut self) -> Option<&mut Tty> {
if let Self::Tty(v) = self {
Some(v)
} else {
None
}
}
@@ -151,4 +215,12 @@ impl Backend {
panic!("backend is not Winit")
}
}
pub fn headless(&mut self) -> &mut Headless {
if let Self::Headless(v) = self {
v
} else {
panic!("backend is not Headless")
}
}
}
+1554 -409
View File
File diff suppressed because it is too large Load Diff
+121 -66
View File
@@ -3,49 +3,44 @@ use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use niri_config::{Config, OutputName};
use smithay::backend::allocator::dmabuf::Dmabuf;
use smithay::backend::renderer::damage::OutputDamageTracker;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::backend::renderer::{DebugFlags, ImportDma, ImportEgl, Renderer};
use smithay::backend::winit::{self, WinitEvent, WinitGraphicsBackend};
use smithay::output::{Mode, Output, PhysicalProperties, Scale, Subpixel};
use smithay::output::{Mode, Output, PhysicalProperties, Subpixel};
use smithay::reexports::calloop::LoopHandle;
use smithay::reexports::wayland_protocols::wp::presentation_time::server::wp_presentation_feedback;
use smithay::reexports::winit::dpi::LogicalSize;
use smithay::reexports::winit::window::WindowBuilder;
use smithay::utils::Transform;
use smithay::reexports::winit::window::Window;
use smithay::wayland::presentation::Refresh;
use super::RenderResult;
use crate::config::Config;
use crate::niri::{RedrawState, State};
use crate::utils::get_monotonic_time;
use crate::Niri;
use super::{IpcOutputMap, OutputId, RenderResult};
use crate::niri::{Niri, RedrawState, State};
use crate::render_helpers::debug::draw_damage;
use crate::render_helpers::{resources, shaders, RenderTarget};
use crate::utils::{get_monotonic_time, logical_output};
pub struct Winit {
config: Rc<RefCell<Config>>,
output: Output,
backend: WinitGraphicsBackend<GlesRenderer>,
damage_tracker: OutputDamageTracker,
connectors: Arc<Mutex<HashMap<String, Output>>>,
ipc_outputs: Arc<Mutex<IpcOutputMap>>,
}
impl Winit {
pub fn new(config: Rc<RefCell<Config>>, event_loop: LoopHandle<State>) -> Self {
let builder = WindowBuilder::new()
pub fn new(
config: Rc<RefCell<Config>>,
event_loop: LoopHandle<State>,
) -> Result<Self, winit::Error> {
let builder = Window::default_attributes()
.with_inner_size(LogicalSize::new(1280.0, 800.0))
// .with_resizable(false)
.with_title("niri");
let (backend, winit) = winit::init_from_builder(builder).unwrap();
let output_config = config
.borrow()
.outputs
.iter()
.find(|o| o.name == "winit")
.cloned()
.unwrap_or_default();
let (backend, winit) = winit::init_from_attributes(builder)?;
let output = Output::new(
"winit".to_string(),
@@ -61,18 +56,36 @@ impl Winit {
size: backend.window_size(),
refresh: 60_000,
};
let scale = output_config.scale.clamp(1., 10.).ceil() as i32;
output.change_current_state(
Some(mode),
Some(Transform::Flipped180),
Some(Scale::Integer(scale)),
None,
);
output.change_current_state(Some(mode), None, None, None);
output.set_preferred(mode);
let connectors = Arc::new(Mutex::new(HashMap::from([(
"winit".to_owned(),
output.clone(),
output.user_data().insert_if_missing(|| OutputName {
connector: "winit".to_string(),
make: Some("Smithay".to_string()),
model: Some("Winit".to_string()),
serial: None,
});
let physical_properties = output.physical_properties();
let ipc_outputs = Arc::new(Mutex::new(HashMap::from([(
OutputId::next(),
niri_ipc::Output {
name: output.name(),
make: physical_properties.make,
model: physical_properties.model,
serial: None,
physical_size: None,
modes: vec![niri_ipc::Mode {
width: backend.window_size().w.clamp(0, u16::MAX as i32) as u16,
height: backend.window_size().h.clamp(0, u16::MAX as i32) as u16,
refresh_rate: 60_000,
is_preferred: true,
}],
current_mode: Some(0),
vrr_supported: false,
vrr_enabled: false,
logical: Some(logical_output(&output)),
},
)])));
let damage_tracker = OutputDamageTracker::from_output(&output);
@@ -90,39 +103,62 @@ impl Winit {
None,
None,
);
state.niri.output_resized(winit.output.clone());
{
let mut ipc_outputs = winit.ipc_outputs.lock().unwrap();
let output = ipc_outputs.values_mut().next().unwrap();
let mode = &mut output.modes[0];
mode.width = size.w.clamp(0, u16::MAX as i32) as u16;
mode.height = size.h.clamp(0, u16::MAX as i32) as u16;
if let Some(logical) = output.logical.as_mut() {
logical.width = size.w as u32;
logical.height = size.h as u32;
}
state.niri.ipc_outputs_changed = true;
}
state.niri.output_resized(&winit.output);
}
WinitEvent::Input(event) => state.process_input_event(event),
WinitEvent::Focus(_) => (),
WinitEvent::Redraw => state
.niri
.queue_redraw(state.backend.winit().output.clone()),
WinitEvent::CloseRequested => {
state.niri.stop_signal.stop();
state.niri.remove_output(&state.backend.winit().output);
}
WinitEvent::Redraw => state.niri.queue_redraw(&state.backend.winit().output),
WinitEvent::CloseRequested => state.niri.stop_signal.stop(),
})
.unwrap();
Self {
Ok(Self {
config,
output,
backend,
damage_tracker,
connectors,
}
ipc_outputs,
})
}
pub fn init(&mut self, niri: &mut Niri) {
if let Err(err) = self
.backend
.renderer()
.bind_wl_display(&niri.display_handle)
{
let renderer = self.backend.renderer();
if let Err(err) = renderer.bind_wl_display(&niri.display_handle) {
warn!("error binding renderer wl_display: {err}");
}
niri.add_output(self.output.clone(), None);
resources::init(renderer);
shaders::init(renderer);
let config = self.config.borrow();
if let Some(src) = config.animations.window_resize.custom_shader.as_deref() {
shaders::set_custom_resize_program(renderer, Some(src));
}
if let Some(src) = config.animations.window_close.custom_shader.as_deref() {
shaders::set_custom_close_program(renderer, Some(src));
}
if let Some(src) = config.animations.window_open.custom_shader.as_deref() {
shaders::set_custom_open_program(renderer, Some(src));
}
drop(config);
niri.update_shaders();
niri.add_output(self.output.clone(), None, false);
}
pub fn seat_name(&self) -> String {
@@ -140,15 +176,30 @@ impl Winit {
let _span = tracy_client::span!("Winit::render");
// Render the elements.
let elements = niri.render::<GlesRenderer>(self.backend.renderer(), output, true);
let mut elements = niri.render::<GlesRenderer>(
self.backend.renderer(),
output,
true,
RenderTarget::Output,
);
// Visualize the damage, if enabled.
if niri.debug_draw_damage {
let output_state = niri.output_state.get_mut(output).unwrap();
draw_damage(&mut output_state.debug_damage_tracker, &mut elements);
}
// Hand them over to winit.
self.backend.bind().unwrap();
let age = self.backend.buffer_age().unwrap();
let res = self
.damage_tracker
.render_output(self.backend.renderer(), age, &elements, [0.; 4])
.unwrap();
let res = {
let (renderer, mut framebuffer) = self.backend.bind().unwrap();
// FIXME: currently impossible to call due to a mutable borrow.
//
// let age = self.backend.buffer_age().unwrap();
let age = 0;
self.damage_tracker
.render_output(renderer, &mut framebuffer, age, &elements, [0.; 4])
.unwrap()
};
niri.update_primary_scanout_output(output, &res.states);
@@ -161,17 +212,17 @@ impl Winit {
.wait_for_frame_completion_before_queueing
{
let _span = tracy_client::span!("wait for completion");
res.sync.wait();
if let Err(err) = res.sync.wait() {
warn!("error waiting for frame completion: {err:?}");
}
}
self.backend.submit(Some(&damage)).unwrap();
self.backend.submit(Some(damage)).unwrap();
let mut presentation_feedbacks = niri.take_presentation_feedbacks(output, &res.states);
let mode = output.current_mode().unwrap();
let refresh = Duration::from_secs_f64(1_000f64 / mode.refresh as f64);
presentation_feedbacks.presented::<_, smithay::utils::Monotonic>(
get_monotonic_time(),
refresh,
Refresh::Unknown,
0,
wp_presentation_feedback::Kind::empty(),
);
@@ -184,12 +235,16 @@ impl Winit {
let output_state = niri.output_state.get_mut(output).unwrap();
match mem::replace(&mut output_state.redraw_state, RedrawState::Idle) {
RedrawState::Idle => unreachable!(),
RedrawState::Queued(_) => (),
RedrawState::Queued => (),
RedrawState::WaitingForVBlank { .. } => unreachable!(),
RedrawState::WaitingForEstimatedVBlank(_) => unreachable!(),
RedrawState::WaitingForEstimatedVBlankAndQueued(_) => unreachable!(),
}
output_state.frame_callback_sequence = output_state.frame_callback_sequence.wrapping_add(1);
// FIXME: this should wait until a frame callback from the host compositor, but it redraws
// right away instead.
if output_state.unfinished_animations_remain {
self.backend.window().request_redraw();
}
@@ -202,17 +257,17 @@ impl Winit {
renderer.set_debug_flags(renderer.debug_flags() ^ DebugFlags::TINT);
}
pub fn import_dmabuf(&mut self, dmabuf: &Dmabuf) -> Result<(), ()> {
pub fn import_dmabuf(&mut self, dmabuf: &Dmabuf) -> bool {
match self.backend.renderer().import_dmabuf(dmabuf, None) {
Ok(_texture) => Ok(()),
Ok(_texture) => true,
Err(err) => {
debug!("error importing dmabuf: {err:?}");
Err(())
false
}
}
}
pub fn connectors(&self) -> Arc<Mutex<HashMap<String, Output>>> {
self.connectors.clone()
pub fn ipc_outputs(&self) -> Arc<Mutex<IpcOutputMap>> {
self.ipc_outputs.clone()
}
}
+110
View File
@@ -0,0 +1,110 @@
use std::ffi::OsString;
use std::path::PathBuf;
use clap::{Parser, Subcommand};
use clap_complete::Shell;
use niri_ipc::{Action, OutputAction};
use crate::utils::version;
#[derive(Parser)]
#[command(author, version = version(), about, long_about = None)]
#[command(args_conflicts_with_subcommands = true)]
#[command(subcommand_value_name = "SUBCOMMAND")]
#[command(subcommand_help_heading = "Subcommands")]
pub struct Cli {
/// Path to config file (default: `$XDG_CONFIG_HOME/niri/config.kdl`).
///
/// This can also be set with the `NIRI_CONFIG` environment variable. If both are set, the
/// command line argument takes precedence.
#[arg(short, long)]
pub config: Option<PathBuf>,
/// Import environment globally to systemd and D-Bus, run D-Bus services.
///
/// Set this flag in a systemd service started by your display manager, or when running
/// manually as your main compositor instance. Do not set when running as a nested window, or
/// on a TTY as your non-main compositor instance, to avoid messing up the global environment.
#[arg(long)]
pub session: bool,
/// Command to run upon compositor startup.
#[arg(last = true)]
pub command: Vec<OsString>,
#[command(subcommand)]
pub subcommand: Option<Sub>,
}
#[derive(Subcommand)]
pub enum Sub {
/// Communicate with the running niri instance.
Msg {
#[command(subcommand)]
msg: Msg,
/// Format output as JSON.
#[arg(short, long)]
json: bool,
},
/// Validate the config file.
Validate {
/// Path to config file (default: `$XDG_CONFIG_HOME/niri/config.kdl`).
///
/// This can also be set with the `NIRI_CONFIG` environment variable. If both are set, the
/// command line argument takes precedence.
#[arg(short, long)]
config: Option<PathBuf>,
},
/// Cause a panic to check if the backtraces are good.
Panic,
/// Generate shell completions.
Completions { shell: Shell },
}
#[derive(Subcommand)]
pub enum Msg {
/// List connected outputs.
Outputs,
/// List workspaces.
Workspaces,
/// List open windows.
Windows,
/// List open layer-shell surfaces.
Layers,
/// Get the configured keyboard layouts.
KeyboardLayouts,
/// Print information about the focused output.
FocusedOutput,
/// Print information about the focused window.
FocusedWindow,
/// Pick a window with the mouse and print information about it.
PickWindow,
/// Pick a color from the screen with the mouse.
PickColor,
/// Perform an action.
Action {
#[command(subcommand)]
action: Action,
},
/// Change output configuration temporarily.
///
/// The configuration is changed temporarily and not saved into the config file. If the output
/// configuration subsequently changes in the config file, these temporary changes will be
/// forgotten.
Output {
/// Output name.
///
/// Run `niri msg outputs` to see the output names.
#[arg()]
output: String,
/// Configuration to apply.
#[command(subcommand)]
action: OutputAction,
},
/// Start continuously receiving events from the compositor.
EventStream,
/// Print the version of the running niri instance.
Version,
/// Request an error from the running niri instance.
RequestError,
/// Print the overview state.
OverviewState,
}
-866
View File
@@ -1,866 +0,0 @@
use std::path::PathBuf;
use std::str::FromStr;
use bitflags::bitflags;
use directories::ProjectDirs;
use miette::{miette, Context, IntoDiagnostic};
use smithay::input::keyboard::keysyms::KEY_NoSymbol;
use smithay::input::keyboard::xkb::{keysym_from_name, KEYSYM_CASE_INSENSITIVE};
use smithay::input::keyboard::{Keysym, XkbConfig};
#[derive(knuffel::Decode, Debug, PartialEq)]
pub struct Config {
#[knuffel(child, default)]
pub input: Input,
#[knuffel(children(name = "output"))]
pub outputs: Vec<Output>,
#[knuffel(children(name = "spawn-at-startup"))]
pub spawn_at_startup: Vec<SpawnAtStartup>,
#[knuffel(child, default)]
pub focus_ring: FocusRing,
#[knuffel(child, default = default_border())]
pub border: FocusRing,
#[knuffel(child, default)]
pub prefer_no_csd: bool,
#[knuffel(child, default)]
pub cursor: Cursor,
#[knuffel(child, unwrap(children), default)]
pub preset_column_widths: Vec<PresetWidth>,
#[knuffel(child)]
pub default_column_width: Option<DefaultColumnWidth>,
#[knuffel(child, unwrap(argument), default = 16)]
pub gaps: u16,
#[knuffel(child, default)]
pub struts: Struts,
#[knuffel(
child,
unwrap(argument),
default = Some(String::from(
"~/Pictures/Screenshots/Screenshot from %Y-%m-%d %H-%M-%S.png"
)))
]
pub screenshot_path: Option<String>,
#[knuffel(child, default)]
pub binds: Binds,
#[knuffel(child, default)]
pub debug: DebugConfig,
}
// FIXME: Add other devices.
#[derive(knuffel::Decode, Debug, Default, PartialEq)]
pub struct Input {
#[knuffel(child, default)]
pub keyboard: Keyboard,
#[knuffel(child, default)]
pub touchpad: Touchpad,
#[knuffel(child, default)]
pub tablet: Tablet,
#[knuffel(child)]
pub disable_power_key_handling: bool,
}
#[derive(knuffel::Decode, Debug, Default, PartialEq, Eq)]
pub struct Keyboard {
#[knuffel(child, default)]
pub xkb: Xkb,
// The defaults were chosen to match wlroots and sway.
#[knuffel(child, unwrap(argument), default = 600)]
pub repeat_delay: u16,
#[knuffel(child, unwrap(argument), default = 25)]
pub repeat_rate: u8,
#[knuffel(child, unwrap(argument), default)]
pub track_layout: TrackLayout,
}
#[derive(knuffel::Decode, Debug, Default, PartialEq, Eq, Clone)]
pub struct Xkb {
#[knuffel(child, unwrap(argument), default)]
pub rules: String,
#[knuffel(child, unwrap(argument), default)]
pub model: String,
#[knuffel(child, unwrap(argument))]
pub layout: Option<String>,
#[knuffel(child, unwrap(argument), default)]
pub variant: String,
#[knuffel(child, unwrap(argument))]
pub options: Option<String>,
}
impl Xkb {
pub fn to_xkb_config(&self) -> XkbConfig {
XkbConfig {
rules: &self.rules,
model: &self.model,
layout: self.layout.as_deref().unwrap_or("us"),
variant: &self.variant,
options: self.options.clone(),
}
}
}
#[derive(knuffel::DecodeScalar, Debug, Default, PartialEq, Eq)]
pub enum TrackLayout {
/// The layout change is global.
#[default]
Global,
/// The layout change is window local.
Window,
}
// FIXME: Add the rest of the settings.
#[derive(knuffel::Decode, Debug, Default, PartialEq)]
pub struct Touchpad {
#[knuffel(child)]
pub tap: bool,
#[knuffel(child)]
pub natural_scroll: bool,
#[knuffel(child, unwrap(argument), default)]
pub accel_speed: f64,
}
#[derive(knuffel::Decode, Debug, Default, PartialEq)]
pub struct Tablet {
#[knuffel(child, unwrap(argument))]
pub map_to_output: Option<String>,
}
#[derive(knuffel::Decode, Debug, Clone, PartialEq)]
pub struct Output {
#[knuffel(child)]
pub off: bool,
#[knuffel(argument)]
pub name: String,
#[knuffel(child, unwrap(argument), default = 1.)]
pub scale: f64,
#[knuffel(child)]
pub position: Option<Position>,
#[knuffel(child, unwrap(argument, str))]
pub mode: Option<Mode>,
}
impl Default for Output {
fn default() -> Self {
Self {
off: false,
name: String::new(),
scale: 1.,
position: None,
mode: None,
}
}
}
#[derive(knuffel::Decode, Debug, Clone, PartialEq, Eq)]
pub struct Position {
#[knuffel(property)]
pub x: i32,
#[knuffel(property)]
pub y: i32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Mode {
pub width: u16,
pub height: u16,
pub refresh: Option<f64>,
}
#[derive(knuffel::Decode, Debug, Clone, PartialEq, Eq)]
pub struct SpawnAtStartup {
#[knuffel(arguments)]
pub command: Vec<String>,
}
#[derive(knuffel::Decode, Debug, Clone, Copy, PartialEq)]
pub struct FocusRing {
#[knuffel(child)]
pub off: bool,
#[knuffel(child, unwrap(argument), default = 4)]
pub width: u16,
#[knuffel(child, default = Color::new(127, 200, 255, 255))]
pub active_color: Color,
#[knuffel(child, default = Color::new(80, 80, 80, 255))]
pub inactive_color: Color,
}
impl Default for FocusRing {
fn default() -> Self {
Self {
off: false,
width: 4,
active_color: Color::new(127, 200, 255, 255),
inactive_color: Color::new(80, 80, 80, 255),
}
}
}
pub const fn default_border() -> FocusRing {
FocusRing {
off: true,
width: 4,
active_color: Color::new(255, 200, 127, 255),
inactive_color: Color::new(80, 80, 80, 255),
}
}
#[derive(knuffel::Decode, Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Color {
#[knuffel(argument)]
pub r: u8,
#[knuffel(argument)]
pub g: u8,
#[knuffel(argument)]
pub b: u8,
#[knuffel(argument)]
pub a: u8,
}
impl Color {
pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
Self { r, g, b, a }
}
}
impl From<Color> for [f32; 4] {
fn from(c: Color) -> Self {
[c.r, c.g, c.b, c.a].map(|x| x as f32 / 255.)
}
}
#[derive(knuffel::Decode, Debug, PartialEq)]
pub struct Cursor {
#[knuffel(child, unwrap(argument), default = String::from("default"))]
pub xcursor_theme: String,
#[knuffel(child, unwrap(argument), default = 24)]
pub xcursor_size: u8,
}
impl Default for Cursor {
fn default() -> Self {
Self {
xcursor_theme: String::from("default"),
xcursor_size: 24,
}
}
}
#[derive(knuffel::Decode, Debug, Clone, Copy, PartialEq)]
pub enum PresetWidth {
Proportion(#[knuffel(argument)] f64),
Fixed(#[knuffel(argument)] i32),
}
#[derive(knuffel::Decode, Debug, Clone, PartialEq)]
pub struct DefaultColumnWidth(#[knuffel(children)] pub Vec<PresetWidth>);
#[derive(knuffel::Decode, Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Struts {
#[knuffel(child, unwrap(argument), default)]
pub left: u16,
#[knuffel(child, unwrap(argument), default)]
pub right: u16,
#[knuffel(child, unwrap(argument), default)]
pub top: u16,
#[knuffel(child, unwrap(argument), default)]
pub bottom: u16,
}
#[derive(knuffel::Decode, Debug, Default, PartialEq)]
pub struct Binds(#[knuffel(children)] pub Vec<Bind>);
#[derive(knuffel::Decode, Debug, PartialEq)]
pub struct Bind {
#[knuffel(node_name)]
pub key: Key,
#[knuffel(children)]
pub actions: Vec<Action>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Key {
pub keysym: Keysym,
pub modifiers: Modifiers,
}
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Modifiers : u8 {
const CTRL = 1;
const SHIFT = 2;
const ALT = 4;
const SUPER = 8;
const COMPOSITOR = 16;
}
}
#[derive(knuffel::Decode, Debug, Clone, PartialEq)]
pub enum Action {
Quit,
#[knuffel(skip)]
ChangeVt(i32),
Suspend,
PowerOffMonitors,
ToggleDebugTint,
Spawn(#[knuffel(arguments)] Vec<String>),
#[knuffel(skip)]
ConfirmScreenshot,
#[knuffel(skip)]
CancelScreenshot,
Screenshot,
ScreenshotScreen,
ScreenshotWindow,
CloseWindow,
FullscreenWindow,
FocusColumnLeft,
FocusColumnRight,
FocusColumnFirst,
FocusColumnLast,
FocusWindowDown,
FocusWindowUp,
FocusWindowOrWorkspaceDown,
FocusWindowOrWorkspaceUp,
MoveColumnLeft,
MoveColumnRight,
MoveColumnToFirst,
MoveColumnToLast,
MoveWindowDown,
MoveWindowUp,
MoveWindowDownOrToWorkspaceDown,
MoveWindowUpOrToWorkspaceUp,
ConsumeWindowIntoColumn,
ExpelWindowFromColumn,
CenterColumn,
FocusWorkspaceDown,
FocusWorkspaceUp,
FocusWorkspace(#[knuffel(argument)] u8),
MoveWindowToWorkspaceDown,
MoveWindowToWorkspaceUp,
MoveWindowToWorkspace(#[knuffel(argument)] u8),
MoveWorkspaceDown,
MoveWorkspaceUp,
FocusMonitorLeft,
FocusMonitorRight,
FocusMonitorDown,
FocusMonitorUp,
MoveWindowToMonitorLeft,
MoveWindowToMonitorRight,
MoveWindowToMonitorDown,
MoveWindowToMonitorUp,
SetWindowHeight(#[knuffel(argument, str)] SizeChange),
SwitchPresetColumnWidth,
MaximizeColumn,
SetColumnWidth(#[knuffel(argument, str)] SizeChange),
SwitchLayout(#[knuffel(argument)] LayoutAction),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SizeChange {
SetFixed(i32),
SetProportion(f64),
AdjustFixed(i32),
AdjustProportion(f64),
}
#[derive(knuffel::DecodeScalar, Debug, Clone, Copy, PartialEq)]
pub enum LayoutAction {
Next,
Prev,
}
#[derive(knuffel::Decode, Debug, PartialEq)]
pub struct DebugConfig {
#[knuffel(child, unwrap(argument), default = 1.)]
pub animation_slowdown: f64,
#[knuffel(child)]
pub dbus_interfaces_in_non_session_instances: bool,
#[knuffel(child)]
pub wait_for_frame_completion_before_queueing: bool,
#[knuffel(child)]
pub enable_color_transformations_capability: bool,
#[knuffel(child)]
pub enable_overlay_planes: bool,
#[knuffel(child)]
pub disable_cursor_plane: bool,
#[knuffel(child, unwrap(argument))]
pub render_drm_device: Option<PathBuf>,
}
impl Default for DebugConfig {
fn default() -> Self {
Self {
animation_slowdown: 1.,
dbus_interfaces_in_non_session_instances: false,
wait_for_frame_completion_before_queueing: false,
enable_color_transformations_capability: false,
enable_overlay_planes: false,
disable_cursor_plane: false,
render_drm_device: None,
}
}
}
impl Config {
pub fn load(path: Option<PathBuf>) -> miette::Result<(Self, PathBuf)> {
let path = if let Some(path) = path {
path
} else {
let mut path = ProjectDirs::from("", "", "niri")
.ok_or_else(|| miette!("error retrieving home directory"))?
.config_dir()
.to_owned();
path.push("config.kdl");
path
};
let contents = std::fs::read_to_string(&path)
.into_diagnostic()
.with_context(|| format!("error reading {path:?}"))?;
let config = Self::parse("config.kdl", &contents).context("error parsing")?;
debug!("loaded config from {path:?}");
Ok((config, path))
}
pub fn parse(filename: &str, text: &str) -> Result<Self, knuffel::Error> {
knuffel::parse(filename, text)
}
}
impl Default for Config {
fn default() -> Self {
Config::parse(
"default-config.kdl",
include_str!("../resources/default-config.kdl"),
)
.unwrap()
}
}
impl FromStr for Mode {
type Err = miette::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let Some((width, rest)) = s.split_once('x') else {
return Err(miette!("no 'x' separator found"));
};
let (height, refresh) = match rest.split_once('@') {
Some((height, refresh)) => (height, Some(refresh)),
None => (rest, None),
};
let width = width
.parse()
.into_diagnostic()
.context("error parsing width")?;
let height = height
.parse()
.into_diagnostic()
.context("error parsing height")?;
let refresh = refresh
.map(str::parse)
.transpose()
.into_diagnostic()
.context("error parsing refresh rate")?;
Ok(Self {
width,
height,
refresh,
})
}
}
impl FromStr for Key {
type Err = miette::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut modifiers = Modifiers::empty();
let mut split = s.split('+');
let key = split.next_back().unwrap();
for part in split {
let part = part.trim();
if part.eq_ignore_ascii_case("mod") {
modifiers |= Modifiers::COMPOSITOR
} else if part.eq_ignore_ascii_case("ctrl") || part.eq_ignore_ascii_case("control") {
modifiers |= Modifiers::CTRL;
} else if part.eq_ignore_ascii_case("shift") {
modifiers |= Modifiers::SHIFT;
} else if part.eq_ignore_ascii_case("alt") {
modifiers |= Modifiers::ALT;
} else if part.eq_ignore_ascii_case("super") || part.eq_ignore_ascii_case("win") {
modifiers |= Modifiers::SUPER;
} else {
return Err(miette!("invalid modifier: {part}"));
}
}
let keysym = keysym_from_name(key, KEYSYM_CASE_INSENSITIVE);
if keysym.raw() == KEY_NoSymbol {
return Err(miette!("invalid key: {key}"));
}
Ok(Key { keysym, modifiers })
}
}
impl FromStr for SizeChange {
type Err = miette::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.split_once('%') {
Some((value, empty)) => {
if !empty.is_empty() {
return Err(miette!("trailing characters after '%' are not allowed"));
}
match value.bytes().next() {
Some(b'-' | b'+') => {
let value = value
.parse()
.into_diagnostic()
.context("error parsing value")?;
Ok(Self::AdjustProportion(value))
}
Some(_) => {
let value = value
.parse()
.into_diagnostic()
.context("error parsing value")?;
Ok(Self::SetProportion(value))
}
None => Err(miette!("value is missing")),
}
}
None => {
let value = s;
match value.bytes().next() {
Some(b'-' | b'+') => {
let value = value
.parse()
.into_diagnostic()
.context("error parsing value")?;
Ok(Self::AdjustFixed(value))
}
Some(_) => {
let value = value
.parse()
.into_diagnostic()
.context("error parsing value")?;
Ok(Self::SetFixed(value))
}
None => Err(miette!("value is missing")),
}
}
}
}
}
#[cfg(test)]
mod tests {
use miette::NarratableReportHandler;
use super::*;
#[track_caller]
fn check(text: &str, expected: Config) {
let _ = miette::set_hook(Box::new(|_| Box::new(NarratableReportHandler::new())));
let parsed = Config::parse("test.kdl", text)
.map_err(miette::Report::new)
.unwrap();
assert_eq!(parsed, expected);
}
#[test]
fn parse() {
check(
r#"
input {
keyboard {
repeat-delay 600
repeat-rate 25
track-layout "window"
xkb {
layout "us,ru"
options "grp:win_space_toggle"
}
}
touchpad {
tap
accel-speed 0.2
}
tablet {
map-to-output "eDP-1"
}
disable-power-key-handling
}
output "eDP-1" {
scale 2.0
position x=10 y=20
mode "1920x1080@144"
}
spawn-at-startup "alacritty" "-e" "fish"
focus-ring {
width 5
active-color 0 100 200 255
inactive-color 255 200 100 0
}
border {
width 3
active-color 0 100 200 255
inactive-color 255 200 100 0
}
prefer-no-csd
cursor {
xcursor-theme "breeze_cursors"
xcursor-size 16
}
preset-column-widths {
proportion 0.25
proportion 0.5
fixed 960
fixed 1280
}
default-column-width { proportion 0.25; }
gaps 8
struts {
left 1
right 2
top 3
}
screenshot-path "~/Screenshots/screenshot.png"
binds {
Mod+T { spawn "alacritty"; }
Mod+Q { close-window; }
Mod+Shift+H { focus-monitor-left; }
Mod+Ctrl+Shift+L { move-window-to-monitor-right; }
Mod+Comma { consume-window-into-column; }
Mod+1 { focus-workspace 1;}
}
debug {
animation-slowdown 2.0
render-drm-device "/dev/dri/renderD129"
}
"#,
Config {
input: Input {
keyboard: Keyboard {
xkb: Xkb {
layout: Some("us,ru".to_owned()),
options: Some("grp:win_space_toggle".to_owned()),
..Default::default()
},
repeat_delay: 600,
repeat_rate: 25,
track_layout: TrackLayout::Window,
},
touchpad: Touchpad {
tap: true,
natural_scroll: false,
accel_speed: 0.2,
},
tablet: Tablet {
map_to_output: Some("eDP-1".to_owned()),
},
disable_power_key_handling: true,
},
outputs: vec![Output {
off: false,
name: "eDP-1".to_owned(),
scale: 2.,
position: Some(Position { x: 10, y: 20 }),
mode: Some(Mode {
width: 1920,
height: 1080,
refresh: Some(144.),
}),
}],
spawn_at_startup: vec![SpawnAtStartup {
command: vec!["alacritty".to_owned(), "-e".to_owned(), "fish".to_owned()],
}],
focus_ring: FocusRing {
off: false,
width: 5,
active_color: Color {
r: 0,
g: 100,
b: 200,
a: 255,
},
inactive_color: Color {
r: 255,
g: 200,
b: 100,
a: 0,
},
},
border: FocusRing {
off: false,
width: 3,
active_color: Color {
r: 0,
g: 100,
b: 200,
a: 255,
},
inactive_color: Color {
r: 255,
g: 200,
b: 100,
a: 0,
},
},
prefer_no_csd: true,
cursor: Cursor {
xcursor_theme: String::from("breeze_cursors"),
xcursor_size: 16,
},
preset_column_widths: vec![
PresetWidth::Proportion(0.25),
PresetWidth::Proportion(0.5),
PresetWidth::Fixed(960),
PresetWidth::Fixed(1280),
],
default_column_width: Some(DefaultColumnWidth(vec![PresetWidth::Proportion(0.25)])),
gaps: 8,
struts: Struts {
left: 1,
right: 2,
top: 3,
bottom: 0,
},
screenshot_path: Some(String::from("~/Screenshots/screenshot.png")),
binds: Binds(vec![
Bind {
key: Key {
keysym: Keysym::t,
modifiers: Modifiers::COMPOSITOR,
},
actions: vec![Action::Spawn(vec!["alacritty".to_owned()])],
},
Bind {
key: Key {
keysym: Keysym::q,
modifiers: Modifiers::COMPOSITOR,
},
actions: vec![Action::CloseWindow],
},
Bind {
key: Key {
keysym: Keysym::h,
modifiers: Modifiers::COMPOSITOR | Modifiers::SHIFT,
},
actions: vec![Action::FocusMonitorLeft],
},
Bind {
key: Key {
keysym: Keysym::l,
modifiers: Modifiers::COMPOSITOR | Modifiers::SHIFT | Modifiers::CTRL,
},
actions: vec![Action::MoveWindowToMonitorRight],
},
Bind {
key: Key {
keysym: Keysym::comma,
modifiers: Modifiers::COMPOSITOR,
},
actions: vec![Action::ConsumeWindowIntoColumn],
},
Bind {
key: Key {
keysym: Keysym::_1,
modifiers: Modifiers::COMPOSITOR,
},
actions: vec![Action::FocusWorkspace(1)],
},
]),
debug: DebugConfig {
animation_slowdown: 2.,
render_drm_device: Some(PathBuf::from("/dev/dri/renderD129")),
..Default::default()
},
},
);
}
#[test]
fn can_create_default_config() {
let _ = Config::default();
}
#[test]
fn parse_mode() {
assert_eq!(
"2560x1600@165.004".parse::<Mode>().unwrap(),
Mode {
width: 2560,
height: 1600,
refresh: Some(165.004),
},
);
assert_eq!(
"1920x1080".parse::<Mode>().unwrap(),
Mode {
width: 1920,
height: 1080,
refresh: None,
},
);
assert!("1920".parse::<Mode>().is_err());
assert!("1920x".parse::<Mode>().is_err());
assert!("1920x1080@".parse::<Mode>().is_err());
assert!("1920x1080@60Hz".parse::<Mode>().is_err());
}
#[test]
fn parse_size_change() {
assert_eq!(
"10".parse::<SizeChange>().unwrap(),
SizeChange::SetFixed(10),
);
assert_eq!(
"+10".parse::<SizeChange>().unwrap(),
SizeChange::AdjustFixed(10),
);
assert_eq!(
"-10".parse::<SizeChange>().unwrap(),
SizeChange::AdjustFixed(-10),
);
assert_eq!(
"10%".parse::<SizeChange>().unwrap(),
SizeChange::SetProportion(10.),
);
assert_eq!(
"+10%".parse::<SizeChange>().unwrap(),
SizeChange::AdjustProportion(10.),
);
assert_eq!(
"-10%".parse::<SizeChange>().unwrap(),
SizeChange::AdjustProportion(-10.),
);
assert!("-".parse::<SizeChange>().is_err());
assert!("10% ".parse::<SizeChange>().is_err());
}
}
+23 -28
View File
@@ -4,13 +4,11 @@ use std::env;
use std::fs::File;
use std::io::Read;
use std::rc::Rc;
use std::sync::Mutex;
use anyhow::{anyhow, Context};
use smithay::backend::allocator::Fourcc;
use smithay::backend::renderer::element::texture::TextureBuffer;
use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
use smithay::input::pointer::{CursorIcon, CursorImageAttributes, CursorImageStatus};
use smithay::backend::renderer::element::memory::MemoryRenderBuffer;
use smithay::input::pointer::{CursorIcon, CursorImageStatus, CursorImageSurfaceData};
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
use smithay::utils::{IsAlive, Logical, Physical, Point, Transform};
use smithay::wayland::compositor::with_states;
@@ -68,7 +66,7 @@ impl CursorManager {
let hotspot = with_states(&surface, |states| {
states
.data_map
.get::<Mutex<CursorImageAttributes>>()
.get::<CursorImageSurfaceData>()
.unwrap()
.lock()
.unwrap()
@@ -77,21 +75,24 @@ impl CursorManager {
RenderCursor::Surface { hotspot, surface }
}
CursorImageStatus::Named(icon) => self
.get_cursor_with_name(icon, scale)
.map(|cursor| RenderCursor::Named {
icon,
scale,
cursor,
})
.unwrap_or_else(|| RenderCursor::Named {
icon: Default::default(),
scale,
cursor: self.get_default_cursor(scale),
}),
CursorImageStatus::Named(icon) => self.get_render_cursor_named(icon, scale),
}
}
fn get_render_cursor_named(&self, icon: CursorIcon, scale: i32) -> RenderCursor {
self.get_cursor_with_name(icon, scale)
.map(|cursor| RenderCursor::Named {
icon,
scale,
cursor,
})
.unwrap_or_else(|| RenderCursor::Named {
icon: Default::default(),
scale,
cursor: self.get_default_cursor(scale),
})
}
pub fn is_current_cursor_animated(&self, scale: i32) -> bool {
match &self.current_cursor {
CursorImageStatus::Hidden => false,
@@ -143,7 +144,7 @@ impl CursorManager {
.unwrap()
}
/// Currenly used cursor_image as a cursor provider.
/// Currently used cursor_image as a cursor provider.
pub fn cursor_image(&self) -> &CursorImageStatus {
&self.current_cursor
}
@@ -224,7 +225,7 @@ pub enum RenderCursor {
},
}
type TextureCache = HashMap<(CursorIcon, i32), Vec<TextureBuffer<GlesTexture>>>;
type TextureCache = HashMap<(CursorIcon, i32), Vec<MemoryRenderBuffer>>;
#[derive(Default)]
pub struct CursorTextureCache {
@@ -238,12 +239,11 @@ impl CursorTextureCache {
pub fn get(
&self,
renderer: &mut GlesRenderer,
icon: CursorIcon,
scale: i32,
cursor: &XCursor,
idx: usize,
) -> TextureBuffer<GlesTexture> {
) -> MemoryRenderBuffer {
self.cache
.borrow_mut()
.entry((icon, scale))
@@ -252,19 +252,14 @@ impl CursorTextureCache {
.frames()
.iter()
.map(|frame| {
let _span = tracy_client::span!("create TextureBuffer");
TextureBuffer::from_memory(
renderer,
MemoryRenderBuffer::from_slice(
&frame.pixels_rgba,
Fourcc::Abgr8888,
Fourcc::Argb8888,
(frame.width as i32, frame.height as i32),
false,
scale,
Transform::Normal,
None,
)
.unwrap()
})
.collect()
})[idx]
+167
View File
@@ -0,0 +1,167 @@
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use anyhow::Context;
use futures_util::StreamExt;
use zbus::fdo::{self, RequestNameFlags};
use zbus::message::Header;
use zbus::names::{OwnedUniqueName, UniqueName};
use zbus::zvariant::NoneValue;
use zbus::{interface, Task};
use super::Start;
pub struct ScreenSaver {
is_inhibited: Arc<AtomicBool>,
is_broken: Arc<AtomicBool>,
inhibitors: Arc<Mutex<HashMap<u32, OwnedUniqueName>>>,
counter: u32,
monitor_task: Arc<OnceLock<Task<()>>>,
}
#[interface(name = "org.freedesktop.ScreenSaver")]
impl ScreenSaver {
async fn inhibit(
&mut self,
#[zbus(header)] hdr: Header<'_>,
application_name: &str,
reason_for_inhibit: &str,
) -> fdo::Result<u32> {
trace!(
"fdo inhibit, app: `{application_name}`, reason: `{reason_for_inhibit}`, owner: {:?}",
hdr.sender()
);
let Some(name) = hdr.sender() else {
return Err(fdo::Error::Failed(String::from("no sender")));
};
let name = OwnedUniqueName::from(name.to_owned());
let mut inhibitors = self.inhibitors.lock().unwrap();
let mut cookie = None;
for _ in 0..3 {
// Start from 1 because some clients don't like 0.
self.counter = self.counter.wrapping_add(1);
if self.counter == 0 {
self.counter += 1;
}
if let Entry::Vacant(entry) = inhibitors.entry(self.counter) {
entry.insert(name);
self.is_inhibited.store(true, Ordering::SeqCst);
cookie = Some(self.counter);
break;
}
}
cookie.ok_or_else(|| fdo::Error::Failed(String::from("no available cookie")))
}
async fn un_inhibit(&mut self, cookie: u32) -> fdo::Result<()> {
trace!("fdo uninhibit, cookie: {cookie}");
let mut inhibitors = self.inhibitors.lock().unwrap();
if inhibitors.remove(&cookie).is_some() {
if inhibitors.is_empty() {
self.is_inhibited.store(false, Ordering::SeqCst);
}
Ok(())
} else {
Err(fdo::Error::Failed(String::from("invalid cookie")))
}
}
}
impl ScreenSaver {
pub fn new(is_inhibited: Arc<AtomicBool>) -> Self {
Self {
is_inhibited,
is_broken: Arc::new(AtomicBool::new(false)),
inhibitors: Arc::new(Mutex::new(HashMap::new())),
counter: 0,
monitor_task: Arc::new(OnceLock::new()),
}
}
}
async fn monitor_disappeared_clients(
conn: &zbus::Connection,
is_inhibited: Arc<AtomicBool>,
inhibitors: Arc<Mutex<HashMap<u32, OwnedUniqueName>>>,
) -> anyhow::Result<()> {
let proxy = fdo::DBusProxy::new(conn)
.await
.context("error creating a DBusProxy")?;
let mut stream = proxy
.receive_name_owner_changed_with_args(&[(2, UniqueName::null_value())])
.await
.context("error creating a NameOwnerChanged stream")?;
while let Some(signal) = stream.next().await {
let args = signal
.args()
.context("error retrieving NameOwnerChanged args")?;
let Some(name) = &**args.old_owner() else {
continue;
};
if args.new_owner().is_none() {
trace!("fdo ScreenSaver client disappeared: {name}");
let mut inhibitors = inhibitors.lock().unwrap();
inhibitors.retain(|_, owner| owner != name);
is_inhibited.store(!inhibitors.is_empty(), Ordering::SeqCst);
} else {
error!("non-null new_owner should've been filtered out");
}
}
Ok(())
}
impl Start for ScreenSaver {
fn start(self) -> anyhow::Result<zbus::blocking::Connection> {
let is_inhibited = self.is_inhibited.clone();
let is_broken = self.is_broken.clone();
let inhibitors = self.inhibitors.clone();
let monitor_task = self.monitor_task.clone();
let conn = zbus::blocking::Connection::session()?;
let flags = RequestNameFlags::AllowReplacement
| RequestNameFlags::ReplaceExisting
| RequestNameFlags::DoNotQueue;
conn.object_server()
.at("/org/freedesktop/ScreenSaver", self)?;
conn.request_name_with_flags("org.freedesktop.ScreenSaver", flags)?;
let async_conn = conn.inner();
let future = {
let conn = async_conn.clone();
async move {
if let Err(err) =
monitor_disappeared_clients(&conn, is_inhibited.clone(), inhibitors.clone())
.await
{
warn!("error monitoring org.freedesktop.ScreenSaver clients: {err:?}");
is_broken.store(true, Ordering::SeqCst);
is_inhibited.store(false, Ordering::SeqCst);
inhibitors.lock().unwrap().clear();
}
}
};
let task = async_conn
.executor()
.spawn(future, "monitor disappearing clients");
monitor_task.set(task).unwrap();
Ok(conn)
}
}
+82
View File
@@ -0,0 +1,82 @@
use std::collections::HashMap;
use zbus::fdo::{self, RequestNameFlags};
use zbus::interface;
use zbus::object_server::SignalEmitter;
use zbus::zvariant::{SerializeDict, Type, Value};
use super::Start;
pub struct Introspect {
to_niri: calloop::channel::Sender<IntrospectToNiri>,
from_niri: async_channel::Receiver<NiriToIntrospect>,
}
pub enum IntrospectToNiri {
GetWindows,
}
pub enum NiriToIntrospect {
Windows(HashMap<u64, WindowProperties>),
}
#[derive(Debug, SerializeDict, Type, Value)]
#[zvariant(signature = "dict")]
pub struct WindowProperties {
/// Window title.
pub title: String,
/// Window app ID.
///
/// This is actually the name of the .desktop file, and Shell does internal tracking to match
/// Wayland app IDs to desktop files. We don't do that yet, which is the reason why
/// xdg-desktop-portal-gnome's window list is missing icons.
#[zvariant(rename = "app-id")]
pub app_id: String,
}
#[interface(name = "org.gnome.Shell.Introspect")]
impl Introspect {
async fn get_windows(&self) -> fdo::Result<HashMap<u64, WindowProperties>> {
if let Err(err) = self.to_niri.send(IntrospectToNiri::GetWindows) {
warn!("error sending message to niri: {err:?}");
return Err(fdo::Error::Failed("internal error".to_owned()));
}
match self.from_niri.recv().await {
Ok(NiriToIntrospect::Windows(windows)) => Ok(windows),
Err(err) => {
warn!("error receiving message from niri: {err:?}");
Err(fdo::Error::Failed("internal error".to_owned()))
}
}
}
// FIXME: call this upon window changes, once more of the infrastructure is there (will be
// needed for the event stream IPC anyway).
#[zbus(signal)]
pub async fn windows_changed(ctxt: &SignalEmitter<'_>) -> zbus::Result<()>;
}
impl Introspect {
pub fn new(
to_niri: calloop::channel::Sender<IntrospectToNiri>,
from_niri: async_channel::Receiver<NiriToIntrospect>,
) -> Self {
Self { to_niri, from_niri }
}
}
impl Start for Introspect {
fn start(self) -> anyhow::Result<zbus::blocking::Connection> {
let conn = zbus::blocking::Connection::session()?;
let flags = RequestNameFlags::AllowReplacement
| RequestNameFlags::ReplaceExisting
| RequestNameFlags::DoNotQueue;
conn.object_server()
.at("/org/gnome/Shell/Introspect", self)?;
conn.request_name_with_flags("org.gnome.Shell.Introspect", flags)?;
Ok(conn)
}
}
+34 -3
View File
@@ -1,8 +1,10 @@
use std::collections::HashMap;
use std::path::PathBuf;
use smithay::reexports::calloop;
use zbus::dbus_interface;
use niri_ipc::PickedColor;
use zbus::fdo::{self, RequestNameFlags};
use zbus::zvariant::OwnedValue;
use zbus::{interface, zvariant};
use super::Start;
@@ -13,13 +15,14 @@ pub struct Screenshot {
pub enum ScreenshotToNiri {
TakeScreenshot { include_cursor: bool },
PickColor(async_channel::Sender<Option<PickedColor>>),
}
pub enum NiriToScreenshot {
ScreenshotResult(Option<PathBuf>),
}
#[dbus_interface(name = "org.gnome.Shell.Screenshot")]
#[interface(name = "org.gnome.Shell.Screenshot")]
impl Screenshot {
async fn screenshot(
&self,
@@ -48,6 +51,34 @@ impl Screenshot {
Ok((true, filename))
}
async fn pick_color(&self) -> fdo::Result<HashMap<String, OwnedValue>> {
let (tx, rx) = async_channel::bounded(1);
if let Err(err) = self.to_niri.send(ScreenshotToNiri::PickColor(tx)) {
warn!("error sending pick color message to niri: {err:?}");
return Err(fdo::Error::Failed("internal error".to_owned()));
}
let color = match rx.recv().await {
Ok(Some(color)) => color,
Ok(None) => {
return Err(fdo::Error::Failed("no color picked".to_owned()));
}
Err(err) => {
warn!("error receiving message from niri: {err:?}");
return Err(fdo::Error::Failed("internal error".to_owned()));
}
};
let mut result = HashMap::new();
let [r, g, b] = color.rgb;
result.insert(
"color".to_string(),
zvariant::OwnedValue::try_from(zvariant::Value::from((r, g, b))).unwrap(),
);
Ok(result)
}
}
impl Screenshot {
+54 -9
View File
@@ -1,9 +1,10 @@
use smithay::reexports::calloop;
use zbus::blocking::Connection;
use zbus::Interface;
use zbus::object_server::Interface;
use crate::niri::State;
pub mod freedesktop_screensaver;
pub mod gnome_shell_introspect;
pub mod gnome_shell_screenshot;
pub mod mutter_display_config;
pub mod mutter_service_channel;
@@ -13,6 +14,8 @@ pub mod mutter_screen_cast;
#[cfg(feature = "xdp-gnome-screencast")]
use mutter_screen_cast::ScreenCast;
use self::freedesktop_screensaver::ScreenSaver;
use self::gnome_shell_introspect::Introspect;
use self::mutter_display_config::DisplayConfig;
use self::mutter_service_channel::ServiceChannel;
@@ -24,7 +27,9 @@ trait Start: Interface {
pub struct DBusServers {
pub conn_service_channel: Option<Connection>,
pub conn_display_config: Option<Connection>,
pub conn_screen_saver: Option<Connection>,
pub conn_screen_shot: Option<Connection>,
pub conn_introspect: Option<Connection>,
#[cfg(feature = "xdp-gnome-screencast")]
pub conn_screen_cast: Option<Connection>,
}
@@ -40,14 +45,44 @@ impl DBusServers {
let mut dbus = Self::default();
if is_session_instance {
let service_channel = ServiceChannel::new(niri.display_handle.clone());
let (to_niri, from_service_channel) = calloop::channel::channel();
let service_channel = ServiceChannel::new(to_niri);
niri.event_loop
.insert_source(from_service_channel, move |event, _, state| match event {
calloop::channel::Event::Msg(new_client) => {
state.niri.insert_client(new_client);
}
calloop::channel::Event::Closed => (),
})
.unwrap();
dbus.conn_service_channel = try_start(service_channel);
}
if is_session_instance || config.debug.dbus_interfaces_in_non_session_instances {
let display_config = DisplayConfig::new(backend.connectors());
let (to_niri, from_display_config) = calloop::channel::channel();
let display_config = DisplayConfig::new(to_niri, backend.ipc_outputs());
niri.event_loop
.insert_source(from_display_config, move |event, _, state| match event {
calloop::channel::Event::Msg(new_conf) => {
for (name, conf) in new_conf {
state.modify_output_config(&name, move |output| {
if let Some(new_output) = conf {
*output = new_output;
} else {
output.off = true;
}
});
}
state.reload_output_config();
}
calloop::channel::Event::Closed => (),
})
.unwrap();
dbus.conn_display_config = try_start(display_config);
let screen_saver = ScreenSaver::new(niri.is_fdo_idle_inhibited.clone());
dbus.conn_screen_saver = try_start(screen_saver);
let (to_niri, from_screenshot) = calloop::channel::channel();
let (to_screenshot, from_niri) = async_channel::unbounded();
niri.event_loop
@@ -61,21 +96,31 @@ impl DBusServers {
let screenshot = gnome_shell_screenshot::Screenshot::new(to_niri, from_niri);
dbus.conn_screen_shot = try_start(screenshot);
let (to_niri, from_introspect) = calloop::channel::channel();
let (to_introspect, from_niri) = async_channel::unbounded();
niri.event_loop
.insert_source(from_introspect, move |event, _, state| match event {
calloop::channel::Event::Msg(msg) => {
state.on_introspect_msg(&to_introspect, msg)
}
calloop::channel::Event::Closed => (),
})
.unwrap();
let introspect = Introspect::new(to_niri, from_niri);
dbus.conn_introspect = try_start(introspect);
#[cfg(feature = "xdp-gnome-screencast")]
{
let (to_niri, from_screen_cast) = calloop::channel::channel();
niri.event_loop
.insert_source(from_screen_cast, {
let to_niri = to_niri.clone();
move |event, _, state| match event {
calloop::channel::Event::Msg(msg) => {
state.on_screen_cast_msg(&to_niri, msg)
}
calloop::channel::Event::Msg(msg) => state.on_screen_cast_msg(msg),
calloop::channel::Event::Closed => (),
}
})
.unwrap();
let screen_cast = ScreenCast::new(backend.connectors(), to_niri);
let screen_cast = ScreenCast::new(backend.ipc_outputs(), to_niri);
dbus.conn_screen_cast = try_start(screen_cast);
}
}
+281 -33
View File
@@ -1,16 +1,22 @@
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use serde::Serialize;
use smithay::output::Output;
use serde::{Deserialize, Serialize};
use smithay::utils::Size;
use zbus::fdo::RequestNameFlags;
use zbus::zvariant::{OwnedValue, Type};
use zbus::{dbus_interface, fdo};
use zbus::object_server::SignalEmitter;
use zbus::zvariant::{self, OwnedValue, Type};
use zbus::{fdo, interface};
use super::Start;
use crate::backend::IpcOutputMap;
use crate::utils::is_laptop_panel;
use crate::utils::scale::supported_scales;
pub struct DisplayConfig {
connectors: Arc<Mutex<HashMap<String, Output>>>,
to_niri: calloop::channel::Sender<HashMap<String, Option<niri_config::Output>>>,
ipc_outputs: Arc<Mutex<IpcOutputMap>>,
}
#[derive(Serialize, Type)]
@@ -42,7 +48,18 @@ pub struct LogicalMonitor {
properties: HashMap<String, OwnedValue>,
}
#[dbus_interface(name = "org.gnome.Mutter.DisplayConfig")]
// ApplyMonitorsConfig
#[derive(Deserialize, Type)]
pub struct LogicalMonitorConfiguration {
x: i32,
y: i32,
scale: f64,
transform: u32,
_is_primary: bool,
monitors: Vec<(String, String, HashMap<String, OwnedValue>)>,
}
#[interface(name = "org.gnome.Mutter.DisplayConfig")]
impl DisplayConfig {
async fn get_current_state(
&self,
@@ -53,40 +70,226 @@ impl DisplayConfig {
HashMap<String, OwnedValue>,
)> {
// Construct the DBus response.
let monitors: Vec<Monitor> = self
.connectors
.lock()
.unwrap()
.keys()
.map(|c| Monitor {
names: (c.clone(), String::new(), String::new(), String::new()),
modes: vec![],
properties: HashMap::new(),
})
.collect();
let mut monitors = Vec::new();
let mut logical_monitors = Vec::new();
let logical_monitors = monitors
.iter()
.map(|m| LogicalMonitor {
x: 0,
y: 0,
scale: 1.,
transform: 0,
is_primary: false,
monitors: vec![m.names.clone()],
properties: HashMap::new(),
})
.collect();
for output in self.ipc_outputs.lock().unwrap().values() {
// Loosely matches the check in Mutter.
let c = &output.name;
let is_laptop_panel = is_laptop_panel(c);
let display_name = make_display_name(output, is_laptop_panel);
Ok((0, monitors, logical_monitors, HashMap::new()))
let mut properties = HashMap::new();
properties.insert(
String::from("display-name"),
OwnedValue::from(zvariant::Str::from(display_name)),
);
properties.insert(
String::from("is-builtin"),
OwnedValue::from(is_laptop_panel),
);
let mut modes: Vec<Mode> = output
.modes
.iter()
.map(|m| {
let niri_ipc::Mode {
width,
height,
refresh_rate,
is_preferred,
} = *m;
let width = i32::from(width);
let height = i32::from(height);
let refresh_rate = refresh_rate as f64 / 1000.;
Mode {
id: format!("{width}x{height}@{refresh_rate:.3}"),
width,
height,
refresh_rate,
preferred_scale: 1.,
supported_scales: supported_scales(Size::from((width, height))).collect(),
properties: HashMap::from([(
String::from("is-preferred"),
OwnedValue::from(is_preferred),
)]),
}
})
.collect();
if let Some(mode) = output.current_mode {
modes[mode]
.properties
.insert(String::from("is-current"), OwnedValue::from(true));
}
let connector = c.clone();
let model = output.model.clone();
let make = output.make.clone();
// Serial is used for session restore, so fall back to the connector name if it's
// not available.
let serial = output.serial.as_ref().unwrap_or(&connector).clone();
let names = (connector, make, model, serial);
if let Some(logical) = output.logical.as_ref() {
let transform = match logical.transform {
niri_ipc::Transform::Normal => 0,
niri_ipc::Transform::_90 => 1,
niri_ipc::Transform::_180 => 2,
niri_ipc::Transform::_270 => 3,
niri_ipc::Transform::Flipped => 4,
niri_ipc::Transform::Flipped90 => 5,
niri_ipc::Transform::Flipped180 => 6,
niri_ipc::Transform::Flipped270 => 7,
};
logical_monitors.push(LogicalMonitor {
x: logical.x,
y: logical.y,
scale: logical.scale,
transform,
is_primary: false,
monitors: vec![names.clone()],
properties: HashMap::new(),
});
}
monitors.push(Monitor {
names,
modes,
properties,
});
}
// Sort by connector.
monitors.sort_unstable_by(|a, b| a.names.0.cmp(&b.names.0));
logical_monitors.sort_unstable_by(|a, b| a.monitors[0].0.cmp(&b.monitors[0].0));
let properties = HashMap::from([(String::from("layout-mode"), OwnedValue::from(1u32))]);
Ok((0, monitors, logical_monitors, properties))
}
// FIXME: monitors-changed signal.
async fn apply_monitors_config(
&self,
_serial: u32,
method: u32,
logical_monitor_configs: Vec<LogicalMonitorConfiguration>,
_properties: HashMap<String, OwnedValue>,
) -> fdo::Result<()> {
let current_conf = self.ipc_outputs.lock().unwrap();
let mut new_conf = HashMap::new();
for requested_config in logical_monitor_configs {
if requested_config.monitors.len() > 1 {
return Err(zbus::fdo::Error::Failed(
"Mirroring is not yet supported".to_owned(),
));
}
for (connector, mode, _props) in requested_config.monitors {
if !current_conf.values().any(|o| o.name == connector) {
return Err(zbus::fdo::Error::Failed(format!(
"Connector '{}' not found",
connector
)));
}
new_conf.insert(
connector.clone(),
Some(niri_config::Output {
off: false,
name: connector,
scale: Some(niri_config::FloatOrInt(requested_config.scale)),
transform: match requested_config.transform {
0 => niri_ipc::Transform::Normal,
1 => niri_ipc::Transform::_90,
2 => niri_ipc::Transform::_180,
3 => niri_ipc::Transform::_270,
4 => niri_ipc::Transform::Flipped,
5 => niri_ipc::Transform::Flipped90,
6 => niri_ipc::Transform::Flipped180,
7 => niri_ipc::Transform::Flipped270,
x => {
return Err(zbus::fdo::Error::Failed(format!(
"Unknown transform {}",
x
)))
}
},
position: Some(niri_config::Position {
x: requested_config.x,
y: requested_config.y,
}),
mode: Some(niri_ipc::ConfiguredMode::from_str(&mode).map_err(|e| {
zbus::fdo::Error::Failed(format!(
"Could not parse mode '{}': {}",
mode, e
))
})?),
// FIXME: VRR
..Default::default()
}),
);
}
}
if new_conf.is_empty() {
return Err(zbus::fdo::Error::Failed(
"At least one output must be enabled".to_owned(),
));
}
for output in current_conf.values() {
if !new_conf.contains_key(&output.name) {
new_conf.insert(output.name.clone(), None);
}
}
if method == 0 {
// 0 means "verify", so don't actually apply here
return Ok(());
}
if let Err(err) = self.to_niri.send(new_conf) {
warn!("error sending message to niri: {err:?}");
return Err(fdo::Error::Failed("internal error".to_owned()));
}
Ok(())
}
#[zbus(signal)]
pub async fn monitors_changed(ctxt: &SignalEmitter<'_>) -> zbus::Result<()>;
#[zbus(property)]
fn power_save_mode(&self) -> i32 {
-1
}
#[zbus(property)]
fn set_power_save_mode(&self, _mode: i32) -> zbus::Result<()> {
Err(zbus::Error::Unsupported)
}
#[zbus(property)]
fn panel_orientation_managed(&self) -> bool {
false
}
#[zbus(property)]
fn apply_monitors_config_allowed(&self) -> bool {
true
}
#[zbus(property)]
fn night_light_supported(&self) -> bool {
false
}
}
impl DisplayConfig {
pub fn new(connectors: Arc<Mutex<HashMap<String, Output>>>) -> Self {
Self { connectors }
pub fn new(
to_niri: calloop::channel::Sender<HashMap<String, Option<niri_config::Output>>>,
ipc_outputs: Arc<Mutex<IpcOutputMap>>,
) -> Self {
Self {
to_niri,
ipc_outputs,
}
}
}
@@ -104,3 +307,48 @@ impl Start for DisplayConfig {
Ok(conn)
}
}
// Adapted from Mutter.
fn make_display_name(output: &niri_ipc::Output, is_laptop_panel: bool) -> String {
if is_laptop_panel {
return String::from("Built-in display");
}
let make = &output.make;
let model = &output.model;
if let Some(diagonal) = output.physical_size.map(|(width_mm, height_mm)| {
let diagonal = f64::hypot(f64::from(width_mm), f64::from(height_mm)) / 25.4;
format_diagonal(diagonal)
}) {
format!("{make} {diagonal}")
} else if model != "Unknown" {
format!("{make} {model}")
} else {
make.clone()
}
}
fn format_diagonal(diagonal_inches: f64) -> String {
let known = [12.1, 13.3, 15.6];
if let Some(d) = known.iter().find(|d| (*d - diagonal_inches).abs() < 0.1) {
format!("{d:.1}")
} else {
format!("{}", diagonal_inches.round() as u32)
}
}
#[cfg(test)]
mod tests {
use insta::assert_snapshot;
use super::*;
#[test]
fn test_format_diagonal() {
assert_snapshot!(format_diagonal(12.11), @"12.1″");
assert_snapshot!(format_diagonal(13.28), @"13.3″");
assert_snapshot!(format_diagonal(15.6), @"15.6″");
assert_snapshot!(format_diagonal(23.2), @"23″");
assert_snapshot!(format_diagonal(24.8), @"25″");
}
}
+172 -38
View File
@@ -4,27 +4,30 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use serde::Deserialize;
use smithay::output::Output;
use smithay::reexports::calloop;
use zbus::fdo::RequestNameFlags;
use zbus::zvariant::{DeserializeDict, OwnedObjectPath, Type, Value};
use zbus::{dbus_interface, fdo, InterfaceRef, ObjectServer, SignalContext};
use zbus::object_server::{InterfaceRef, SignalEmitter};
use zbus::zvariant::{DeserializeDict, OwnedObjectPath, SerializeDict, Type, Value};
use zbus::{fdo, interface, ObjectServer};
use super::Start;
use crate::backend::IpcOutputMap;
#[derive(Clone)]
pub struct ScreenCast {
connectors: Arc<Mutex<HashMap<String, Output>>>,
ipc_outputs: Arc<Mutex<IpcOutputMap>>,
to_niri: calloop::channel::Sender<ScreenCastToNiri>,
#[allow(clippy::type_complexity)]
sessions: Arc<Mutex<Vec<(Session, InterfaceRef<Session>)>>>,
}
#[derive(Clone)]
pub struct Session {
id: usize,
connectors: Arc<Mutex<HashMap<String, Output>>>,
ipc_outputs: Arc<Mutex<IpcOutputMap>>,
to_niri: calloop::channel::Sender<ScreenCastToNiri>,
#[allow(clippy::type_complexity)]
streams: Arc<Mutex<Vec<(Stream, InterfaceRef<Stream>)>>>,
stopped: Arc<AtomicBool>,
}
#[derive(Debug, Default, Deserialize, Type, Clone, Copy)]
@@ -44,27 +47,65 @@ struct RecordMonitorProperties {
_is_recording: Option<bool>,
}
#[derive(Debug, DeserializeDict, Type)]
#[zvariant(signature = "dict")]
struct RecordWindowProperties {
#[zvariant(rename = "window-id")]
window_id: u64,
#[zvariant(rename = "cursor-mode")]
cursor_mode: Option<CursorMode>,
#[zvariant(rename = "is-recording")]
_is_recording: Option<bool>,
}
static STREAM_ID: AtomicUsize = AtomicUsize::new(0);
#[derive(Clone)]
pub struct Stream {
output: Output,
id: usize,
session_id: usize,
target: StreamTarget,
cursor_mode: CursorMode,
was_started: Arc<AtomicBool>,
to_niri: calloop::channel::Sender<ScreenCastToNiri>,
}
#[derive(Clone)]
enum StreamTarget {
// FIXME: update on scale changes and whatnot.
Output(niri_ipc::Output),
Window { id: u64 },
}
#[derive(Debug, Clone)]
pub enum StreamTargetId {
Output { name: String },
Window { id: u64 },
}
#[derive(Debug, SerializeDict, Type, Value)]
#[zvariant(signature = "dict")]
struct StreamParameters {
/// Position of the stream in logical coordinates.
position: (i32, i32),
/// Size of the stream in logical coordinates.
size: (i32, i32),
}
pub enum ScreenCastToNiri {
StartCast {
session_id: usize,
output: Output,
stream_id: usize,
target: StreamTargetId,
cursor_mode: CursorMode,
signal_ctx: SignalContext<'static>,
signal_ctx: SignalEmitter<'static>,
},
StopCast {
session_id: usize,
},
}
#[dbus_interface(name = "org.gnome.Mutter.ScreenCast")]
#[interface(name = "org.gnome.Mutter.ScreenCast")]
impl ScreenCast {
async fn create_session(
&self,
@@ -82,7 +123,7 @@ impl ScreenCast {
let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{}", session_id);
let path = OwnedObjectPath::try_from(path).unwrap();
let session = Session::new(session_id, self.connectors.clone(), self.to_niri.clone());
let session = Session::new(session_id, self.ipc_outputs.clone(), self.to_niri.clone());
match server.at(&path, session.clone()).await {
Ok(true) => {
let iface = server.interface(&path).await.unwrap();
@@ -99,29 +140,34 @@ impl ScreenCast {
Ok(path)
}
#[dbus_interface(property)]
#[zbus(property)]
async fn version(&self) -> i32 {
4
}
}
#[dbus_interface(name = "org.gnome.Mutter.ScreenCast.Session")]
#[interface(name = "org.gnome.Mutter.ScreenCast.Session")]
impl Session {
async fn start(&self) {
debug!("start");
for (stream, iface) in &*self.streams.lock().unwrap() {
stream.start(self.id, iface.signal_context().clone());
stream.start(iface.signal_emitter().clone());
}
}
pub async fn stop(
&self,
#[zbus(object_server)] server: &ObjectServer,
#[zbus(signal_context)] ctxt: SignalContext<'_>,
#[zbus(signal_context)] ctxt: SignalEmitter<'_>,
) {
debug!("stop");
if self.stopped.swap(true, Ordering::SeqCst) {
// Already stopped.
return;
}
Session::closed(&ctxt).await.unwrap();
if let Err(err) = self.to_niri.send(ScreenCastToNiri::StopCast {
@@ -133,7 +179,7 @@ impl Session {
let streams = mem::take(&mut *self.streams.lock().unwrap());
for (_, iface) in streams.iter() {
server
.remove::<Stream, _>(iface.signal_context().path())
.remove::<Stream, _>(iface.signal_emitter().path())
.await
.unwrap();
}
@@ -149,20 +195,32 @@ impl Session {
) -> fdo::Result<OwnedObjectPath> {
debug!(connector, ?properties, "record_monitor");
let Some(output) = self.connectors.lock().unwrap().get(connector).cloned() else {
let output = {
let ipc_outputs = self.ipc_outputs.lock().unwrap();
ipc_outputs.values().find(|o| o.name == connector).cloned()
};
let Some(output) = output else {
return Err(fdo::Error::Failed("no such monitor".to_owned()));
};
static NUMBER: AtomicUsize = AtomicUsize::new(0);
let path = format!(
"/org/gnome/Mutter/ScreenCast/Stream/u{}",
NUMBER.fetch_add(1, Ordering::SeqCst)
);
if output.logical.is_none() {
return Err(fdo::Error::Failed("monitor is disabled".to_owned()));
}
let stream_id = STREAM_ID.fetch_add(1, Ordering::SeqCst);
let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{stream_id}");
let path = OwnedObjectPath::try_from(path).unwrap();
let cursor_mode = properties.cursor_mode.unwrap_or_default();
let stream = Stream::new(output, cursor_mode, self.to_niri.clone());
let target = StreamTarget::Output(output);
let stream = Stream::new(
stream_id,
self.id,
target,
cursor_mode,
self.to_niri.clone(),
);
match server.at(&path, stream.clone()).await {
Ok(true) => {
let iface = server.interface(&path).await.unwrap();
@@ -179,24 +237,83 @@ impl Session {
Ok(path)
}
#[dbus_interface(signal)]
async fn closed(ctxt: &SignalContext<'_>) -> zbus::Result<()>;
async fn record_window(
&mut self,
#[zbus(object_server)] server: &ObjectServer,
properties: RecordWindowProperties,
) -> fdo::Result<OwnedObjectPath> {
debug!(?properties, "record_window");
let stream_id = STREAM_ID.fetch_add(1, Ordering::SeqCst);
let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{stream_id}");
let path = OwnedObjectPath::try_from(path).unwrap();
let cursor_mode = properties.cursor_mode.unwrap_or_default();
let target = StreamTarget::Window {
id: properties.window_id,
};
let stream = Stream::new(
stream_id,
self.id,
target,
cursor_mode,
self.to_niri.clone(),
);
match server.at(&path, stream.clone()).await {
Ok(true) => {
let iface = server.interface(&path).await.unwrap();
self.streams.lock().unwrap().push((stream, iface));
}
Ok(false) => return Err(fdo::Error::Failed("stream path already exists".to_owned())),
Err(err) => {
return Err(fdo::Error::Failed(format!(
"error creating stream object: {err:?}"
)))
}
}
Ok(path)
}
#[zbus(signal)]
async fn closed(ctxt: &SignalEmitter<'_>) -> zbus::Result<()>;
}
#[dbus_interface(name = "org.gnome.Mutter.ScreenCast.Stream")]
#[interface(name = "org.gnome.Mutter.ScreenCast.Stream")]
impl Stream {
#[dbus_interface(signal)]
pub async fn pipe_wire_stream_added(ctxt: &SignalContext<'_>, node_id: u32)
#[zbus(signal)]
pub async fn pipe_wire_stream_added(ctxt: &SignalEmitter<'_>, node_id: u32)
-> zbus::Result<()>;
#[zbus(property)]
async fn parameters(&self) -> StreamParameters {
match &self.target {
StreamTarget::Output(output) => {
let logical = output.logical.as_ref().unwrap();
StreamParameters {
position: (logical.x, logical.y),
size: (logical.width as i32, logical.height as i32),
}
}
StreamTarget::Window { .. } => {
// Does any consumer need this?
StreamParameters {
position: (0, 0),
size: (1, 1),
}
}
}
}
}
impl ScreenCast {
pub fn new(
connectors: Arc<Mutex<HashMap<String, Output>>>,
ipc_outputs: Arc<Mutex<IpcOutputMap>>,
to_niri: calloop::channel::Sender<ScreenCastToNiri>,
) -> Self {
Self {
connectors,
ipc_outputs,
to_niri,
sessions: Arc::new(Mutex::new(vec![])),
}
@@ -221,14 +338,15 @@ impl Start for ScreenCast {
impl Session {
pub fn new(
id: usize,
connectors: Arc<Mutex<HashMap<String, Output>>>,
ipc_outputs: Arc<Mutex<IpcOutputMap>>,
to_niri: calloop::channel::Sender<ScreenCastToNiri>,
) -> Self {
Self {
id,
connectors,
ipc_outputs,
streams: Arc::new(Mutex::new(vec![])),
to_niri,
stopped: Arc::new(AtomicBool::new(false)),
}
}
}
@@ -242,27 +360,32 @@ impl Drop for Session {
}
impl Stream {
pub fn new(
output: Output,
fn new(
id: usize,
session_id: usize,
target: StreamTarget,
cursor_mode: CursorMode,
to_niri: calloop::channel::Sender<ScreenCastToNiri>,
) -> Self {
Self {
output,
id,
session_id,
target,
cursor_mode,
was_started: Arc::new(AtomicBool::new(false)),
to_niri,
}
}
fn start(&self, session_id: usize, ctxt: SignalContext<'static>) {
fn start(&self, ctxt: SignalEmitter<'static>) {
if self.was_started.load(Ordering::SeqCst) {
return;
}
let msg = ScreenCastToNiri::StartCast {
session_id,
output: self.output.clone(),
session_id: self.session_id,
stream_id: self.id,
target: self.target.make_id(),
cursor_mode: self.cursor_mode,
signal_ctx: ctxt,
};
@@ -272,3 +395,14 @@ impl Stream {
}
}
}
impl StreamTarget {
fn make_id(&self) -> StreamTargetId {
match self {
StreamTarget::Output(output) => StreamTargetId::Output {
name: output.name.clone(),
},
StreamTarget::Window { id } => StreamTargetId::Window { id: *id },
}
}
}
+21 -16
View File
@@ -1,46 +1,51 @@
use std::os::fd::{FromRawFd, IntoRawFd};
use std::os::unix::net::UnixStream;
use std::sync::Arc;
use smithay::reexports::wayland_server::DisplayHandle;
use zbus::dbus_interface;
use zbus::{fdo, interface, zvariant};
use super::Start;
use crate::niri::ClientState;
use crate::niri::NewClient;
pub struct ServiceChannel {
display: DisplayHandle,
to_niri: calloop::channel::Sender<NewClient>,
}
#[dbus_interface(name = "org.gnome.Mutter.ServiceChannel")]
#[interface(name = "org.gnome.Mutter.ServiceChannel")]
impl ServiceChannel {
async fn open_wayland_service_connection(
&mut self,
service_client_type: u32,
) -> zbus::fdo::Result<zbus::zvariant::OwnedFd> {
) -> fdo::Result<zvariant::OwnedFd> {
if service_client_type != 1 {
return Err(zbus::fdo::Error::InvalidArgs(
return Err(fdo::Error::InvalidArgs(
"Invalid service client type".to_owned(),
));
}
let (sock1, sock2) = UnixStream::pair().unwrap();
self.display
.insert_client(sock2, Arc::new(ClientState::default()))
.unwrap();
Ok(unsafe { zbus::zvariant::OwnedFd::from_raw_fd(sock1.into_raw_fd()) })
let client = NewClient {
client: sock2,
restricted: false,
// FIXME: maybe you can get the PID from D-Bus somehow?
credentials_unknown: true,
};
if let Err(err) = self.to_niri.send(client) {
warn!("error sending message to niri: {err:?}");
return Err(fdo::Error::Failed("internal error".to_owned()));
}
Ok(zvariant::OwnedFd::from(std::os::fd::OwnedFd::from(sock1)))
}
}
impl ServiceChannel {
pub fn new(display: DisplayHandle) -> Self {
Self { display }
pub fn new(to_niri: calloop::channel::Sender<NewClient>) -> Self {
Self { to_niri }
}
}
impl Start for ServiceChannel {
fn start(self) -> anyhow::Result<zbus::blocking::Connection> {
let conn = zbus::blocking::ConnectionBuilder::session()?
let conn = zbus::blocking::connection::Builder::session()?
.name("org.gnome.Mutter.ServiceChannel")?
.serve_at("/org/gnome/Mutter/ServiceChannel", self)?
.build()?;
+24 -2
View File
@@ -7,10 +7,11 @@ use crate::utils::get_monotonic_time;
pub struct FrameClock {
last_presentation_time: Option<Duration>,
refresh_interval_ns: Option<NonZeroU64>,
vrr: bool,
}
impl FrameClock {
pub fn new(refresh_interval: Option<Duration>) -> Self {
pub fn new(refresh_interval: Option<Duration>, vrr: bool) -> Self {
let refresh_interval_ns = if let Some(interval) = &refresh_interval {
assert_eq!(interval.as_secs(), 0);
Some(NonZeroU64::new(interval.subsec_nanos().into()).unwrap())
@@ -21,6 +22,7 @@ impl FrameClock {
Self {
last_presentation_time: None,
refresh_interval_ns,
vrr,
}
}
@@ -29,6 +31,19 @@ impl FrameClock {
.map(|r| Duration::from_nanos(r.get()))
}
pub fn set_vrr(&mut self, vrr: bool) {
if self.vrr == vrr {
return;
}
self.vrr = vrr;
self.last_presentation_time = None;
}
pub fn vrr(&self) -> bool {
self.vrr
}
pub fn presented(&mut self, presentation_time: Duration) {
if presentation_time.is_zero() {
// Not interested in these.
@@ -71,6 +86,13 @@ impl FrameClock {
let since_last_ns =
since_last.as_secs() * 1_000_000_000 + u64::from(since_last.subsec_nanos());
let to_next_ns = (since_last_ns / refresh_interval_ns + 1) * refresh_interval_ns;
last_presentation_time + Duration::from_nanos(to_next_ns)
// If VRR is enabled and more than one frame passed since last presentation, assume that we
// can present immediately.
if self.vrr && to_next_ns > refresh_interval_ns {
now
} else {
last_presentation_time + Duration::from_nanos(to_next_ns)
}
}
}
+384 -75
View File
@@ -1,24 +1,30 @@
use std::collections::hash_map::Entry;
use smithay::backend::renderer::utils::{on_commit_buffer_handler, with_renderer_surface_state};
use smithay::input::pointer::CursorImageStatus;
use niri_ipc::PositionChange;
use smithay::backend::renderer::utils::on_commit_buffer_handler;
use smithay::input::pointer::{CursorImageStatus, CursorImageSurfaceData};
use smithay::reexports::calloop::Interest;
use smithay::reexports::wayland_server::protocol::wl_buffer;
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
use smithay::reexports::wayland_server::{Client, Resource};
use smithay::wayland::buffer::BufferHandler;
use smithay::wayland::compositor::{
add_blocker, add_pre_commit_hook, get_parent, is_sync_subsurface, send_surface_state,
add_blocker, add_pre_commit_hook, get_parent, is_sync_subsurface, remove_pre_commit_hook,
with_states, BufferAssignment, CompositorClientState, CompositorHandler, CompositorState,
SurfaceAttributes,
};
use smithay::wayland::dmabuf::get_dmabuf;
use smithay::wayland::shell::xdg::XdgToplevelSurfaceData;
use smithay::wayland::shm::{ShmHandler, ShmState};
use smithay::{delegate_compositor, delegate_shm};
use super::xdg_shell;
use crate::niri::{ClientState, State};
use crate::utils::clone2;
use super::xdg_shell::add_mapped_toplevel_pre_commit_hook;
use crate::handlers::XDG_ACTIVATION_TOKEN_TIMEOUT;
use crate::layout::{ActivateWindow, AddWindowTarget};
use crate::niri::{CastTarget, ClientState, LockState, State};
use crate::utils::transaction::Transaction;
use crate::utils::{is_mapped, send_scale_transform};
use crate::window::{InitialConfigureState, Mapped, ResolvedWindowRules, Unmapped};
impl CompositorHandler for State {
fn compositor_state(&mut self) -> &mut CompositorState {
@@ -36,50 +42,21 @@ impl CompositorHandler for State {
}
if let Some(output) = self.niri.output_for_root(&root) {
let scale = output.current_scale().integer_scale();
let scale = output.current_scale();
let transform = output.current_transform();
with_states(surface, |data| {
send_surface_state(surface, data, scale, transform);
send_scale_transform(surface, data, scale, transform);
});
}
}
fn new_surface(&mut self, surface: &WlSurface) {
add_pre_commit_hook::<Self, _>(surface, move |state, _dh, surface| {
let maybe_dmabuf = with_states(surface, |surface_data| {
surface_data
.cached_state
.pending::<SurfaceAttributes>()
.buffer
.as_ref()
.and_then(|assignment| match assignment {
BufferAssignment::NewBuffer(buffer) => get_dmabuf(buffer).ok(),
_ => None,
})
});
if let Some(dmabuf) = maybe_dmabuf {
if let Ok((blocker, source)) = dmabuf.generate_blocker(Interest::READ) {
let client = surface.client().unwrap();
let res = state
.niri
.event_loop
.insert_source(source, move |_, _, state| {
let display_handle = state.niri.display_handle.clone();
state
.client_compositor_state(&client)
.blocker_cleared(state, &display_handle);
Ok(())
});
if res.is_ok() {
add_blocker(surface, blocker);
}
}
}
})
self.add_default_dmabuf_pre_commit_hook(surface);
}
fn commit(&mut self, surface: &WlSurface) {
let _span = tracy_client::span!("CompositorHandler::commit");
trace!(surface = ?surface.id(), "commit");
on_commit_buffer_handler::<Self>(surface);
self.backend.early_import(surface);
@@ -93,55 +70,250 @@ impl CompositorHandler for State {
root_surface = parent;
}
// Update the cached root surface.
self.niri
.root_surface
.insert(surface.clone(), root_surface.clone());
if surface == &root_surface {
// This is a root surface commit. It might have mapped a previously-unmapped toplevel.
if let Entry::Occupied(entry) = self.niri.unmapped_windows.entry(surface.clone()) {
let is_mapped =
with_renderer_surface_state(surface, |state| state.buffer().is_some());
if is_mapped {
if is_mapped(surface) {
// The toplevel got mapped.
let window = entry.remove();
let Unmapped {
window,
state,
activation_token_data,
} = entry.remove();
window.on_commit();
if let Some(output) = self.niri.layout.add_window(window, None, false).cloned()
{
self.niri.queue_redraw(output);
let toplevel = window.toplevel().expect("no X11 support");
let (rules, width, height, is_full_width, output, workspace_id) =
if let InitialConfigureState::Configured {
rules,
width,
height,
floating_width: _,
floating_height: _,
is_full_width,
output,
workspace_name,
} = state
{
// Check that the output is still connected.
let output =
output.filter(|o| self.niri.layout.monitor_for_output(o).is_some());
// Check that the workspace still exists.
let workspace_id = workspace_name
.as_deref()
.and_then(|n| self.niri.layout.find_workspace_by_name(n))
.map(|(_, ws)| ws.id());
(rules, width, height, is_full_width, output, workspace_id)
} else {
error!("window map must happen after initial configure");
(ResolvedWindowRules::empty(), None, None, false, None, None)
};
// The GTK about dialog sets min/max size after the initial configure but
// before mapping, so we need to compute open_floating at the last possible
// moment, that is here.
let is_floating = rules.compute_open_floating(toplevel);
// Figure out if we should activate the window.
let activate = rules.open_focused.map(|focus| {
if focus {
ActivateWindow::Yes
} else {
ActivateWindow::No
}
});
let activate = activate.unwrap_or_else(|| {
// Check the token timestamp again in case the window took a while between
// requesting activation and mapping.
let token = activation_token_data.filter(|token| {
token.timestamp.elapsed() < XDG_ACTIVATION_TOKEN_TIMEOUT
});
if token.is_some() {
ActivateWindow::Yes
} else {
let config = self.niri.config.borrow();
if config.debug.strict_new_window_focus_policy {
ActivateWindow::No
} else {
ActivateWindow::Smart
}
}
});
let parent = toplevel
.parent()
.and_then(|parent| self.niri.layout.find_window_and_output(&parent))
// Only consider the parent if we configured the window for the same
// output.
//
// Normally when we're following the parent, the configured output will be
// None. If the configured output is set, that means it was set explicitly
// by a window rule or a fullscreen request.
.filter(|(_, parent_output)| {
parent_output.is_none()
|| output.is_none()
|| output.as_ref() == *parent_output
})
.map(|(mapped, _)| mapped.window.clone());
// The mapped pre-commit hook deals with dma-bufs on its own.
self.remove_default_dmabuf_pre_commit_hook(toplevel.wl_surface());
let hook = add_mapped_toplevel_pre_commit_hook(toplevel);
let mapped = Mapped::new(window, rules, hook);
let window = mapped.window.clone();
let target = if let Some(p) = &parent {
// Open dialogs next to their parent window.
AddWindowTarget::NextTo(p)
} else if let Some(id) = workspace_id {
AddWindowTarget::Workspace(id)
} else if let Some(output) = &output {
AddWindowTarget::Output(output)
} else {
AddWindowTarget::Auto
};
let output = self.niri.layout.add_window(
mapped,
target,
width,
height,
is_full_width,
is_floating,
activate,
);
if let Some(output) = output.cloned() {
self.niri.layout.start_open_animation_for_window(&window);
let new_focus = self.niri.layout.focus().map(|m| &m.window);
if new_focus == Some(&window) {
// We activated the newly opened window.
self.maybe_warp_cursor_to_focus();
self.niri.layer_shell_on_demand_focus = None;
}
self.niri.queue_redraw(&output);
}
return;
}
// The toplevel remains unmapped.
let window = entry.get();
xdg_shell::send_initial_configure_if_needed(window.toplevel());
let unmapped = entry.get();
if unmapped.needs_initial_configure() {
let toplevel = unmapped.window.toplevel().expect("no x11 support").clone();
self.queue_initial_configure(toplevel);
}
return;
}
// This is a commit of a previously-mapped root or a non-toplevel root.
if let Some(win_out) = self.niri.layout.find_window_and_output(surface) {
let (window, output) = clone2(win_out);
if let Some((mapped, output)) = self.niri.layout.find_window_and_output(surface) {
let window = mapped.window.clone();
let output = output.cloned();
let id = mapped.id();
// This is a commit of a previously-mapped toplevel.
let is_mapped = is_mapped(surface);
// Must start the close animation before window.on_commit().
let transaction = Transaction::new();
if !is_mapped {
let blocker = transaction.blocker();
self.backend.with_primary_renderer(|renderer| {
self.niri
.layout
.start_close_animation_for_window(renderer, &window, blocker);
});
}
window.on_commit();
// This is a commit of a previously-mapped toplevel.
let is_mapped =
with_renderer_surface_state(surface, |state| state.buffer().is_some());
if !is_mapped {
// The toplevel got unmapped.
self.niri.layout.remove_window(&window);
self.niri.unmapped_windows.insert(surface.clone(), window);
self.niri.queue_redraw(output);
//
// Test client: wleird-unmap.
let active_window = self.niri.layout.focus().map(|m| &m.window);
let was_active = active_window == Some(&window);
self.niri
.stop_casts_for_target(CastTarget::Window { id: id.get() });
self.niri.layout.remove_window(&window, transaction.clone());
self.add_default_dmabuf_pre_commit_hook(surface);
// If this is the only instance, then this transaction will complete
// immediately, so no need to set the timer.
if !transaction.is_last() {
transaction.register_deadline_timer(&self.niri.event_loop);
}
if was_active {
self.maybe_warp_cursor_to_focus();
}
// Newly-unmapped toplevels must perform the initial commit-configure sequence
// afresh.
let unmapped = Unmapped::new(window);
self.niri.unmapped_windows.insert(surface.clone(), unmapped);
if let Some(output) = output {
self.niri.queue_redraw(&output);
}
return;
}
let (serial, buffer_delta) = with_states(surface, |states| {
let buffer_delta = states
.cached_state
.get::<SurfaceAttributes>()
.current()
.buffer_delta
.take();
let role = states
.data_map
.get::<XdgToplevelSurfaceData>()
.unwrap()
.lock()
.unwrap();
(role.configure_serial, buffer_delta)
});
if serial.is_none() {
error!("commit on a mapped surface without a configured serial");
}
// The toplevel remains mapped.
self.niri.layout.update_window(&window);
self.niri.layout.update_window(&window, serial);
// Move the toplevel according to the attach offset.
if let Some(delta) = buffer_delta {
if delta.x != 0 || delta.y != 0 {
let (x, y) = delta.to_f64().into();
self.niri.layout.move_floating_window(
Some(&window),
PositionChange::AdjustFixed(x),
PositionChange::AdjustFixed(y),
false,
);
}
}
// Popup placement depends on window size which might have changed.
self.update_reactive_popups(&window, &output);
self.update_reactive_popups(&window);
self.niri.queue_redraw(output);
if let Some(output) = output {
self.niri.queue_redraw(&output);
}
return;
}
@@ -150,10 +322,14 @@ impl CompositorHandler for State {
// This is a commit of a non-root or a non-toplevel root.
let root_window_output = self.niri.layout.find_window_and_output(&root_surface);
if let Some((window, output)) = root_window_output.map(clone2) {
if let Some((mapped, output)) = root_window_output {
let window = mapped.window.clone();
let output = output.cloned();
window.on_commit();
self.niri.layout.update_window(&window);
self.niri.queue_redraw(output);
self.niri.layout.update_window(&window, None);
if let Some(output) = output {
self.niri.queue_redraw(&output);
}
return;
}
@@ -161,37 +337,116 @@ impl CompositorHandler for State {
self.popups_handle_commit(surface);
if let Some(popup) = self.niri.popups.find_popup(surface) {
if let Some(output) = self.output_for_popup(&popup) {
self.niri.queue_redraw(output.clone());
self.niri.queue_redraw(&output.clone());
}
return;
}
// This might be a layer-shell surface.
self.layer_shell_handle_commit(surface);
if self.layer_shell_handle_commit(surface) {
return;
}
// This might be a cursor surface.
if matches!(&self.niri.cursor_manager.cursor_image(), CursorImageStatus::Surface(s) if s == surface)
{
if matches!(
&self.niri.cursor_manager.cursor_image(),
CursorImageStatus::Surface(s) if s == &root_surface
) {
// In case the cursor surface has been committed handle the role specific
// buffer offset by applying the offset on the cursor image hotspot
if surface == &root_surface {
with_states(surface, |states| {
let cursor_image_attributes = states.data_map.get::<CursorImageSurfaceData>();
if let Some(mut cursor_image_attributes) =
cursor_image_attributes.map(|attrs| attrs.lock().unwrap())
{
let buffer_delta = states
.cached_state
.get::<SurfaceAttributes>()
.current()
.buffer_delta
.take();
if let Some(buffer_delta) = buffer_delta {
cursor_image_attributes.hotspot -= buffer_delta;
}
}
});
}
// FIXME: granular redraws for cursors.
self.niri.queue_redraw_all();
return;
}
// This might be a DnD icon surface.
if self.niri.dnd_icon.as_ref() == Some(surface) {
if matches!(&self.niri.dnd_icon, Some(icon) if icon.surface == root_surface) {
let dnd_icon = self.niri.dnd_icon.as_mut().unwrap();
// In case the dnd surface has been committed handle the role specific
// buffer offset by applying the offset on the dnd icon offset
if surface == &dnd_icon.surface {
with_states(&dnd_icon.surface, |states| {
let buffer_delta = states
.cached_state
.get::<SurfaceAttributes>()
.current()
.buffer_delta
.take()
.unwrap_or_default();
dnd_icon.offset += buffer_delta;
});
}
// FIXME: granular redraws for cursors.
self.niri.queue_redraw_all();
return;
}
// This might be a lock surface.
if self.niri.is_locked() {
for (output, state) in &self.niri.output_state {
if let Some(lock_surface) = &state.lock_surface {
if lock_surface.wl_surface() == surface {
self.niri.queue_redraw(output.clone());
break;
for (output, state) in &self.niri.output_state {
if let Some(lock_surface) = &state.lock_surface {
if lock_surface.wl_surface() == &root_surface {
if matches!(self.niri.lock_state, LockState::WaitingForSurfaces { .. }) {
self.niri.maybe_continue_to_locking();
} else {
self.niri.queue_redraw(&output.clone());
}
return;
}
}
}
// This message can trigger for lock surfaces that had a commit right after we unlocked
// the session, but that's ok, we don't need to handle them.
trace!("commit on an unrecognized surface: {surface:?}, root: {root_surface:?}");
}
fn destroyed(&mut self, surface: &WlSurface) {
// Clients may destroy their subsurfaces before the main surface. Ensure we have a snapshot
// when that happens, so that the closing animation includes all these subsurfaces.
//
// Test client: alacritty with CSD <= 0.13 (it was fixed in winit afterwards:
// https://github.com/rust-windowing/winit/pull/3625).
//
// This is still not perfect, as this function is called already after the (first)
// subsurface is destroyed; in the case of alacritty, this is the top CSD shadow. But, it
// gets most of the job done.
if let Some(root) = self.niri.root_surface.get(surface) {
if let Some((mapped, _)) = self.niri.layout.find_window_and_output(root) {
let window = mapped.window.clone();
self.backend.with_primary_renderer(|renderer| {
self.niri.layout.store_unmap_snapshot(renderer, &window);
});
}
}
self.niri
.root_surface
.retain(|k, v| k != surface && v != surface);
self.niri.dmabuf_pre_commit_hook.remove(surface);
}
}
@@ -207,3 +462,57 @@ impl ShmHandler for State {
delegate_compositor!(State);
delegate_shm!(State);
impl State {
pub fn add_default_dmabuf_pre_commit_hook(&mut self, surface: &WlSurface) {
let hook = add_pre_commit_hook::<Self, _>(surface, move |state, _dh, surface| {
let maybe_dmabuf = with_states(surface, |surface_data| {
surface_data
.cached_state
.get::<SurfaceAttributes>()
.pending()
.buffer
.as_ref()
.and_then(|assignment| match assignment {
BufferAssignment::NewBuffer(buffer) => get_dmabuf(buffer).cloned().ok(),
_ => None,
})
});
if let Some(dmabuf) = maybe_dmabuf {
if let Ok((blocker, source)) = dmabuf.generate_blocker(Interest::READ) {
if let Some(client) = surface.client() {
let res =
state
.niri
.event_loop
.insert_source(source, move |_, _, state| {
let display_handle = state.niri.display_handle.clone();
state
.client_compositor_state(&client)
.blocker_cleared(state, &display_handle);
Ok(())
});
if res.is_ok() {
add_blocker(surface, blocker);
trace!("added default dmabuf blocker");
}
}
}
}
});
let s = surface.clone();
if let Some(prev) = self.niri.dmabuf_pre_commit_hook.insert(s, hook) {
error!("tried to add dmabuf pre-commit hook when there was already one");
remove_pre_commit_hook(surface, prev);
}
}
pub fn remove_default_dmabuf_pre_commit_hook(&mut self, surface: &WlSurface) {
if let Some(hook) = self.niri.dmabuf_pre_commit_hook.remove(surface) {
remove_pre_commit_hook(surface, hook);
} else {
error!("tried to remove dmabuf pre-commit hook but there was none");
}
}
}
+143 -39
View File
@@ -1,16 +1,18 @@
use smithay::delegate_layer_shell;
use smithay::desktop::{layer_map_for_output, LayerSurface, WindowSurfaceType};
use smithay::desktop::{layer_map_for_output, LayerSurface, PopupKind, WindowSurfaceType};
use smithay::output::Output;
use smithay::reexports::wayland_server::protocol::wl_output::WlOutput;
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
use smithay::wayland::compositor::{send_surface_state, with_states};
use smithay::wayland::compositor::{get_parent, with_states};
use smithay::wayland::shell::wlr_layer::{
Layer, LayerSurface as WlrLayerSurface, LayerSurfaceData, WlrLayerShellHandler,
self, Layer, LayerSurface as WlrLayerSurface, LayerSurfaceData, WlrLayerShellHandler,
WlrLayerShellState,
};
use smithay::wayland::shell::xdg::PopupSurface;
use crate::layer::{MappedLayer, ResolvedLayerRules};
use crate::niri::State;
use crate::utils::{is_mapped, output_size, send_scale_transform};
impl WlrLayerShellHandler for State {
fn shell_state(&mut self) -> &mut WlrLayerShellState {
@@ -24,17 +26,30 @@ impl WlrLayerShellHandler for State {
_layer: Layer,
namespace: String,
) {
let output = wl_output
.as_ref()
.and_then(Output::from_resource)
.or_else(|| self.niri.layout.active_output().cloned())
.unwrap();
let output = if let Some(wl_output) = &wl_output {
Output::from_resource(wl_output)
} else {
self.niri.layout.active_output().cloned()
};
let Some(output) = output else {
warn!("no output for new layer surface, closing");
surface.send_close();
return;
};
let wl_surface = surface.wl_surface().clone();
let is_new = self.niri.unmapped_layer_surfaces.insert(wl_surface);
assert!(is_new);
let mut map = layer_map_for_output(&output);
map.map_layer(&LayerSurface::new(surface, namespace))
.unwrap();
}
fn layer_destroyed(&mut self, surface: WlrLayerSurface) {
let wl_surface = surface.wl_surface();
self.niri.unmapped_layer_surfaces.remove(wl_surface);
let output = if let Some((output, mut map, layer)) =
self.niri.layout.outputs().find_map(|o| {
let map = layer_map_for_output(o);
@@ -45,68 +60,157 @@ impl WlrLayerShellHandler for State {
layer.map(|layer| (o.clone(), map, layer))
}) {
map.unmap_layer(&layer);
self.niri.mapped_layer_surfaces.remove(&layer);
Some(output)
} else {
None
};
if let Some(output) = output {
self.niri.output_resized(output);
self.niri.output_resized(&output);
}
}
fn new_popup(&mut self, _parent: WlrLayerSurface, popup: PopupSurface) {
self.unconstrain_popup(&popup);
self.unconstrain_popup(&PopupKind::Xdg(popup));
}
}
delegate_layer_shell!(State);
impl State {
pub fn layer_shell_handle_commit(&mut self, surface: &WlSurface) {
let Some(output) = self
pub fn layer_shell_handle_commit(&mut self, surface: &WlSurface) -> bool {
let mut root_surface = surface.clone();
while let Some(parent) = get_parent(&root_surface) {
root_surface = parent;
}
let output = self
.niri
.layout
.outputs()
.find(|o| {
let map = layer_map_for_output(o);
map.layer_for_surface(surface, WindowSurfaceType::TOPLEVEL)
map.layer_for_surface(&root_surface, WindowSurfaceType::TOPLEVEL)
.is_some()
})
.cloned()
else {
return;
.cloned();
let Some(output) = output else {
return false;
};
let initial_configure_sent = with_states(surface, |states| {
states
.data_map
.get::<LayerSurfaceData>()
.unwrap()
.lock()
.unwrap()
.initial_configure_sent
});
if surface == &root_surface {
let initial_configure_sent = with_states(surface, |states| {
states
.data_map
.get::<LayerSurfaceData>()
.unwrap()
.lock()
.unwrap()
.initial_configure_sent
});
let mut map = layer_map_for_output(&output);
let mut map = layer_map_for_output(&output);
// Arrange the layers before sending the initial configure to respect any size the
// client may have sent.
map.arrange();
// arrange the layers before sending the initial configure
// to respect any size the client may have sent
map.arrange();
// send the initial configure if relevant
if !initial_configure_sent {
let layer = map
.layer_for_surface(surface, WindowSurfaceType::TOPLEVEL)
.unwrap();
let scale = output.current_scale().integer_scale();
let transform = output.current_transform();
with_states(surface, |data| {
send_surface_state(surface, data, scale, transform);
});
if initial_configure_sent {
if is_mapped(surface) {
let was_unmapped = self.niri.unmapped_layer_surfaces.remove(surface);
layer.layer_surface().send_configure();
// Resolve rules for newly mapped layer surfaces.
if was_unmapped {
let config = self.niri.config.borrow();
let rules = &config.layer_rules;
let rules =
ResolvedLayerRules::compute(rules, layer, self.niri.is_at_startup);
let output_size = output_size(&output);
let scale = output.current_scale().fractional_scale();
let mapped = MappedLayer::new(
layer.clone(),
rules,
output_size,
scale,
self.niri.clock.clone(),
&config,
);
let prev = self
.niri
.mapped_layer_surfaces
.insert(layer.clone(), mapped);
if prev.is_some() {
error!("MappedLayer was present for an unmapped surface");
}
}
// Give focus to newly mapped on-demand surfaces. Some launchers like
// lxqt-runner rely on this behavior. While this behavior doesn't make much
// sense for other clients like panels, the consensus seems to be that it's not
// a big deal since panels generally only open once at the start of the
// session.
//
// Note that:
// 1) Exclusive layer surfaces already get focus automatically in
// update_keyboard_focus().
// 2) Same-layer exclusive layer surfaces are already preferred to on-demand
// surfaces in update_keyboard_focus(), so we don't need to check for that
// here.
//
// https://github.com/YaLTeR/niri/issues/641
let on_demand = layer.cached_state().keyboard_interactivity
== wlr_layer::KeyboardInteractivity::OnDemand;
if was_unmapped && on_demand {
// I guess it'd make sense to check that no higher-layer on-demand surface
// has focus, but Smithay's Layer doesn't implement Ord so this would be a
// little annoying.
self.niri.layer_shell_on_demand_focus = Some(layer.clone());
}
} else {
let was_mapped = self.niri.mapped_layer_surfaces.remove(layer).is_some();
self.niri.unmapped_layer_surfaces.insert(surface.clone());
// After layer surface unmaps it has to perform the initial commit-configure
// sequence again. This is a workaround until Smithay properly resets
// initial_configure_sent upon the surface unmapping itself as it does for
// toplevels.
if was_mapped {
with_states(surface, |states| {
let mut data = states
.data_map
.get::<LayerSurfaceData>()
.unwrap()
.lock()
.unwrap();
data.initial_configure_sent = false;
});
}
}
} else {
let scale = output.current_scale();
let transform = output.current_transform();
with_states(surface, |data| {
send_scale_transform(surface, data, scale, transform);
});
layer.layer_surface().send_configure();
}
drop(map);
// This will call queue_redraw() inside.
self.niri.output_resized(&output);
} else {
// This is an unsync layer-shell subsurface.
self.niri.queue_redraw(&output);
}
drop(map);
self.niri.output_resized(output);
true
}
}
+586 -37
View File
@@ -7,47 +7,101 @@ use std::io::Write;
use std::os::fd::OwnedFd;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use smithay::backend::allocator::dmabuf::Dmabuf;
use smithay::backend::drm::DrmNode;
use smithay::backend::input::{InputEvent, TabletToolDescriptor};
use smithay::desktop::{PopupKind, PopupManager};
use smithay::input::pointer::{CursorIcon, CursorImageStatus, PointerHandle};
use smithay::input::{Seat, SeatHandler, SeatState};
use smithay::input::pointer::{
CursorIcon, CursorImageStatus, CursorImageSurfaceData, PointerHandle,
};
use smithay::input::{keyboard, Seat, SeatHandler, SeatState};
use smithay::output::Output;
use smithay::reexports::rustix::fs::{fcntl_setfl, OFlags};
use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
use smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1;
use smithay::reexports::wayland_server::protocol::wl_data_source::WlDataSource;
use smithay::reexports::wayland_server::protocol::wl_output::WlOutput;
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
use smithay::reexports::wayland_server::Resource;
use smithay::utils::{Logical, Rectangle, Size};
use smithay::wayland::compositor::{send_surface_state, with_states};
use smithay::utils::{Logical, Point, Rectangle, Size};
use smithay::wayland::compositor::{get_parent, with_states};
use smithay::wayland::dmabuf::{DmabufGlobal, DmabufHandler, DmabufState, ImportNotifier};
use smithay::wayland::drm_lease::{
DrmLease, DrmLeaseBuilder, DrmLeaseHandler, DrmLeaseRequest, DrmLeaseState, LeaseRejected,
};
use smithay::wayland::fractional_scale::FractionalScaleHandler;
use smithay::wayland::idle_inhibit::IdleInhibitHandler;
use smithay::wayland::idle_notify::{IdleNotifierHandler, IdleNotifierState};
use smithay::wayland::input_method::{InputMethodHandler, PopupSurface};
use smithay::wayland::pointer_constraints::PointerConstraintsHandler;
use smithay::wayland::keyboard_shortcuts_inhibit::{
KeyboardShortcutsInhibitHandler, KeyboardShortcutsInhibitState, KeyboardShortcutsInhibitor,
};
use smithay::wayland::output::OutputHandler;
use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraintsHandler};
use smithay::wayland::security_context::{
SecurityContext, SecurityContextHandler, SecurityContextListenerSource,
};
use smithay::wayland::selection::data_device::{
set_data_device_focus, ClientDndGrabHandler, DataDeviceHandler, DataDeviceState,
ServerDndGrabHandler,
};
use smithay::wayland::selection::ext_data_control::{
DataControlHandler as ExtDataControlHandler, DataControlState as ExtDataControlState,
};
use smithay::wayland::selection::primary_selection::{
set_primary_focus, PrimarySelectionHandler, PrimarySelectionState,
};
use smithay::wayland::selection::wlr_data_control::{DataControlHandler, DataControlState};
use smithay::wayland::selection::wlr_data_control::{
DataControlHandler as WlrDataControlHandler, DataControlState as WlrDataControlState,
};
use smithay::wayland::selection::{SelectionHandler, SelectionTarget};
use smithay::wayland::session_lock::{
LockSurface, SessionLockHandler, SessionLockManagerState, SessionLocker,
};
use smithay::wayland::tablet_manager::TabletSeatHandler;
use smithay::wayland::xdg_activation::{
XdgActivationHandler, XdgActivationState, XdgActivationToken, XdgActivationTokenData,
};
use smithay::{
delegate_cursor_shape, delegate_data_control, delegate_data_device, delegate_dmabuf,
delegate_input_method_manager, delegate_output, delegate_pointer_constraints,
delegate_drm_lease, delegate_ext_data_control, delegate_fractional_scale,
delegate_idle_inhibit, delegate_idle_notify, delegate_input_method_manager,
delegate_keyboard_shortcuts_inhibit, delegate_output, delegate_pointer_constraints,
delegate_pointer_gestures, delegate_presentation, delegate_primary_selection,
delegate_relative_pointer, delegate_seat, delegate_session_lock, delegate_tablet_manager,
delegate_text_input_manager, delegate_virtual_keyboard_manager,
delegate_relative_pointer, delegate_seat, delegate_security_context, delegate_session_lock,
delegate_single_pixel_buffer, delegate_tablet_manager, delegate_text_input_manager,
delegate_viewporter, delegate_virtual_keyboard_manager, delegate_xdg_activation,
};
use crate::niri::State;
use crate::utils::output_size;
pub use crate::handlers::xdg_shell::KdeDecorationsModeState;
use crate::layout::ActivateWindow;
use crate::niri::{DndIcon, NewClient, State};
use crate::protocols::foreign_toplevel::{
self, ForeignToplevelHandler, ForeignToplevelManagerState,
};
use crate::protocols::gamma_control::{GammaControlHandler, GammaControlManagerState};
use crate::protocols::mutter_x11_interop::MutterX11InteropHandler;
use crate::protocols::output_management::{OutputManagementHandler, OutputManagementManagerState};
use crate::protocols::screencopy::{Screencopy, ScreencopyHandler, ScreencopyManagerState};
use crate::protocols::virtual_pointer::{
VirtualPointerAxisEvent, VirtualPointerButtonEvent, VirtualPointerHandler,
VirtualPointerInputBackend, VirtualPointerManagerState, VirtualPointerMotionAbsoluteEvent,
VirtualPointerMotionEvent,
};
use crate::utils::{output_size, send_scale_transform, with_toplevel_role};
use crate::{
delegate_foreign_toplevel, delegate_gamma_control, delegate_mutter_x11_interop,
delegate_output_management, delegate_screencopy, delegate_virtual_pointer,
};
pub const XDG_ACTIVATION_TOKEN_TIMEOUT: Duration = Duration::from_secs(10);
impl SeatHandler for State {
type KeyboardFocus = WlSurface;
type PointerFocus = WlSurface;
type TouchFocus = WlSurface;
fn seat_state(&mut self) -> &mut SeatState<State> {
&mut self.niri.seat_state
@@ -70,54 +124,162 @@ impl SeatHandler for State {
set_data_device_focus(dh, seat, client.clone());
set_primary_focus(dh, seat, client);
}
fn led_state_changed(&mut self, _seat: &Seat<Self>, led_state: keyboard::LedState) {
let keyboards = self
.niri
.devices
.iter()
.filter(|device| device.has_capability(input::DeviceCapability::Keyboard))
.cloned();
for mut keyboard in keyboards {
keyboard.led_update(led_state.into());
}
}
}
delegate_seat!(State);
delegate_cursor_shape!(State);
delegate_tablet_manager!(State);
delegate_pointer_gestures!(State);
delegate_relative_pointer!(State);
delegate_text_input_manager!(State);
impl TabletSeatHandler for State {
fn tablet_tool_image(&mut self, _tool: &TabletToolDescriptor, image: CursorImageStatus) {
// FIXME: tablet tools should have their own cursors.
self.niri.cursor_manager.set_cursor_image(image);
// FIXME: granular.
self.niri.queue_redraw_all();
}
}
delegate_tablet_manager!(State);
impl PointerConstraintsHandler for State {
fn new_constraint(&mut self, _surface: &WlSurface, pointer: &PointerHandle<Self>) {
self.niri.maybe_activate_pointer_constraint(
pointer.current_location(),
&self.niri.pointer_focus,
);
fn new_constraint(&mut self, _surface: &WlSurface, _pointer: &PointerHandle<Self>) {
// Pointer constraints track pointer focus internally, so make sure it's up to date before
// activating a new one.
self.refresh_pointer_contents();
self.niri.maybe_activate_pointer_constraint();
}
fn cursor_position_hint(
&mut self,
surface: &WlSurface,
pointer: &PointerHandle<Self>,
location: Point<f64, Logical>,
) {
let is_constraint_active = with_pointer_constraint(surface, pointer, |constraint| {
constraint.is_some_and(|c| c.is_active())
});
if !is_constraint_active {
return;
}
// Note: this is surface under pointer, not pointer focus. So if you start, say, a
// middle-drag in Blender, then touchpad-swipe the window away, the surface under pointer
// will change, even though the real pointer focus remains on the Blender surface due to
// the click grab.
//
// Ideally we would just use the constraint surface, but we need its origin. So this is
// more of a hack because pointer contents has the surface origin available.
//
// FIXME: use the constraint surface somehow, don't use pointer contents.
let Some((ref surface_under_pointer, origin)) = self.niri.pointer_contents.surface else {
return;
};
if surface_under_pointer != surface {
return;
}
let mut root = surface.clone();
while let Some(parent) = get_parent(&root) {
root = parent;
}
let target = self
.niri
.output_for_root(&root)
.and_then(|output| self.niri.global_space.output_geometry(output))
.map_or(origin + location, |mut output_geometry| {
// i32 sizes are exclusive, but f64 sizes are inclusive.
output_geometry.size -= (1, 1).into();
(origin + location).constrain(output_geometry.to_f64())
});
pointer.set_location(target);
// Redraw to update the cursor position if it's visible.
if self.niri.pointer_visibility.is_visible() {
// FIXME: redraw only outputs overlapping the cursor.
self.niri.queue_redraw_all();
}
}
}
delegate_pointer_constraints!(State);
impl InputMethodHandler for State {
fn new_popup(&mut self, surface: PopupSurface) {
let popup = PopupKind::from(surface.clone());
let popup = PopupKind::InputMethod(surface);
if let Some(output) = self.output_for_popup(&popup) {
let scale = output.current_scale().integer_scale();
let scale = output.current_scale();
let transform = output.current_transform();
let wl_surface = surface.wl_surface();
let wl_surface = popup.wl_surface();
with_states(wl_surface, |data| {
send_surface_state(wl_surface, data, scale, transform);
send_scale_transform(wl_surface, data, scale, transform);
});
}
self.unconstrain_popup(&popup);
if let Err(err) = self.niri.popups.track_popup(popup) {
warn!("error tracking ime popup {err:?}");
}
}
fn popup_repositioned(&mut self, surface: PopupSurface) {
let popup = PopupKind::InputMethod(surface);
self.unconstrain_popup(&popup);
}
fn dismiss_popup(&mut self, surface: PopupSurface) {
if let Some(parent) = surface.get_parent().map(|parent| parent.surface.clone()) {
let _ = PopupManager::dismiss_popup(&parent, &PopupKind::from(surface));
}
}
fn parent_geometry(&self, parent: &WlSurface) -> Rectangle<i32, Logical> {
self.niri
.layout
.find_window_and_output(parent)
.map(|(window, _)| window.geometry())
.map(|(mapped, _)| mapped.window.geometry())
.unwrap_or_default()
}
}
impl KeyboardShortcutsInhibitHandler for State {
fn keyboard_shortcuts_inhibit_state(&mut self) -> &mut KeyboardShortcutsInhibitState {
&mut self.niri.keyboard_shortcuts_inhibit_state
}
fn new_inhibitor(&mut self, inhibitor: KeyboardShortcutsInhibitor) {
// FIXME: show a confirmation dialog with a "remember for this application" kind of toggle.
inhibitor.activate();
self.niri
.keyboard_shortcuts_inhibiting_surfaces
.insert(inhibitor.wl_surface().clone(), inhibitor);
}
fn inhibitor_destroyed(&mut self, inhibitor: KeyboardShortcutsInhibitor) {
self.niri
.keyboard_shortcuts_inhibiting_surfaces
.remove(&inhibitor.wl_surface().clone());
}
}
delegate_input_method_manager!(State);
delegate_keyboard_shortcuts_inhibit!(State);
delegate_virtual_keyboard_manager!(State);
impl SelectionHandler for State {
@@ -135,6 +297,10 @@ impl SelectionHandler for State {
let buf = user_data.clone();
thread::spawn(move || {
// Clear O_NONBLOCK, otherwise File::write_all() will stop halfway.
if let Err(err) = fcntl_setfl(&fd, OFlags::empty()) {
warn!("error clearing flags on selection target fd: {err:?}");
}
if let Err(err) = File::from(fd).write_all(&buf) {
warn!("error writing selection: {err:?}");
}
@@ -155,12 +321,63 @@ impl ClientDndGrabHandler for State {
icon: Option<WlSurface>,
_seat: Seat<Self>,
) {
self.niri.dnd_icon = icon;
let offset = if let CursorImageStatus::Surface(ref surface) =
self.niri.cursor_manager.cursor_image()
{
with_states(surface, |states| {
let hotspot = states
.data_map
.get::<CursorImageSurfaceData>()
.unwrap()
.lock()
.unwrap()
.hotspot;
Point::from((-hotspot.x, -hotspot.y))
})
} else {
(0, 0).into()
};
self.niri.dnd_icon = icon.map(|surface| DndIcon { surface, offset });
// FIXME: more granular
self.niri.queue_redraw_all();
}
fn dropped(&mut self, _seat: Seat<Self>) {
fn dropped(&mut self, target: Option<WlSurface>, validated: bool, _seat: Seat<Self>) {
trace!("client dropped, target: {target:?}, validated: {validated}");
// End DnD before activating a specific window below so that it takes precedence.
self.niri.layout.dnd_end();
// Activate the target output, since that's how Firefox drag-tab-into-new-window works for
// example. On successful drop, additionally activate the target window.
let mut activate_output = true;
if let Some(target) = validated.then_some(target).flatten() {
let root = self.niri.find_root_shell_surface(&target);
if let Some((mapped, _)) = self.niri.layout.find_window_and_output(&root) {
let window = mapped.window.clone();
self.niri.layout.activate_window(&window);
self.niri.layer_shell_on_demand_focus = None;
activate_output = false;
}
}
if activate_output {
// Find the output from cursor coordinates.
//
// FIXME: uhhh, we can't actually properly tell if the DnD comes from pointer or touch,
// and if it comes from touch, then what the coordinates are. Need to pass more
// parameters from Smithay I guess.
//
// Assume that hidden pointer means touch DnD.
if self.niri.pointer_visibility.is_visible() {
// We can't even get the current pointer location because it's locked (we're deep
// in the grab call stack here). So use the last known one.
if let Some(output) = &self.niri.pointer_contents.output {
self.niri.layout.focus_output(output);
}
}
}
self.niri.dnd_icon = None;
// FIXME: more granular
self.niri.queue_redraw_all();
@@ -178,14 +395,27 @@ impl PrimarySelectionHandler for State {
}
delegate_primary_selection!(State);
impl DataControlHandler for State {
fn data_control_state(&self) -> &DataControlState {
&self.niri.data_control_state
impl WlrDataControlHandler for State {
fn data_control_state(&self) -> &WlrDataControlState {
&self.niri.wlr_data_control_state
}
}
delegate_data_control!(State);
impl ExtDataControlHandler for State {
fn data_control_state(&self) -> &ExtDataControlState {
&self.niri.ext_data_control_state
}
}
delegate_ext_data_control!(State);
impl OutputHandler for State {
fn output_bound(&mut self, output: Output, wl_output: WlOutput) {
foreign_toplevel::on_output_bound(self, &output, &wl_output);
}
}
delegate_output!(State);
delegate_presentation!(State);
@@ -201,13 +431,10 @@ impl DmabufHandler for State {
dmabuf: Dmabuf,
notifier: ImportNotifier,
) {
match self.backend.import_dmabuf(&dmabuf) {
Ok(_) => {
let _ = notifier.successful::<State>();
}
Err(_) => {
notifier.failed();
}
if self.backend.import_dmabuf(&dmabuf) {
let _ = notifier.successful::<State>();
} else {
notifier.failed();
}
}
}
@@ -224,11 +451,13 @@ impl SessionLockHandler for State {
fn unlock(&mut self) {
self.niri.unlock();
self.niri.activate_monitors(&mut self.backend);
self.niri.notify_activity();
}
fn new_surface(&mut self, surface: LockSurface, output: WlOutput) {
let Some(output) = Output::from_resource(&output) else {
error!("no Output matching WlOutput");
warn!("no Output matching WlOutput");
return;
};
@@ -243,11 +472,331 @@ pub fn configure_lock_surface(surface: &LockSurface, output: &Output) {
let size = output_size(output);
states.size = Some(Size::from((size.w as u32, size.h as u32)));
});
let scale = output.current_scale().integer_scale();
let scale = output.current_scale();
let transform = output.current_transform();
let wl_surface = surface.wl_surface();
with_states(wl_surface, |data| {
send_surface_state(wl_surface, data, scale, transform);
send_scale_transform(wl_surface, data, scale, transform);
});
surface.send_configure();
}
impl SecurityContextHandler for State {
fn context_created(&mut self, source: SecurityContextListenerSource, context: SecurityContext) {
self.niri
.event_loop
.insert_source(source, move |client, _, state| {
trace!("inserting a new restricted client, context={context:?}");
state.niri.insert_client(NewClient {
client,
restricted: true,
credentials_unknown: false,
});
})
.unwrap();
}
}
delegate_security_context!(State);
impl IdleNotifierHandler for State {
fn idle_notifier_state(&mut self) -> &mut IdleNotifierState<Self> {
&mut self.niri.idle_notifier_state
}
}
delegate_idle_notify!(State);
impl IdleInhibitHandler for State {
fn inhibit(&mut self, surface: WlSurface) {
self.niri.idle_inhibiting_surfaces.insert(surface);
}
fn uninhibit(&mut self, surface: WlSurface) {
self.niri.idle_inhibiting_surfaces.remove(&surface);
}
}
delegate_idle_inhibit!(State);
impl ForeignToplevelHandler for State {
fn foreign_toplevel_manager_state(&mut self) -> &mut ForeignToplevelManagerState {
&mut self.niri.foreign_toplevel_state
}
fn activate(&mut self, wl_surface: WlSurface) {
if let Some((mapped, _)) = self.niri.layout.find_window_and_output(&wl_surface) {
let window = mapped.window.clone();
self.niri.layout.activate_window(&window);
self.niri.layer_shell_on_demand_focus = None;
self.niri.queue_redraw_all();
}
}
fn close(&mut self, wl_surface: WlSurface) {
if let Some((mapped, _)) = self.niri.layout.find_window_and_output(&wl_surface) {
mapped.toplevel().send_close();
}
}
fn set_fullscreen(&mut self, wl_surface: WlSurface, wl_output: Option<WlOutput>) {
if let Some((mapped, current_output)) = self.niri.layout.find_window_and_output(&wl_surface)
{
let has_fullscreen_cap = with_toplevel_role(mapped.toplevel(), |role| {
role.current
.capabilities
.contains(xdg_toplevel::WmCapabilities::Fullscreen)
});
if !has_fullscreen_cap {
return;
}
let window = mapped.window.clone();
if let Some(requested_output) = wl_output.as_ref().and_then(Output::from_resource) {
if Some(&requested_output) != current_output {
self.niri.layout.move_to_output(
Some(&window),
&requested_output,
None,
ActivateWindow::Smart,
);
}
}
self.niri.layout.set_fullscreen(&window, true);
}
}
fn unset_fullscreen(&mut self, wl_surface: WlSurface) {
if let Some((mapped, _)) = self.niri.layout.find_window_and_output(&wl_surface) {
let window = mapped.window.clone();
self.niri.layout.set_fullscreen(&window, false);
}
}
}
delegate_foreign_toplevel!(State);
impl ScreencopyHandler for State {
fn frame(&mut self, manager: &ZwlrScreencopyManagerV1, screencopy: Screencopy) {
// If with_damage then push it onto the queue for redraw of the output,
// otherwise render it immediately.
if screencopy.with_damage() {
let Some(queue) = self.niri.screencopy_state.get_queue_mut(manager) else {
trace!("screencopy manager destroyed already");
return;
};
queue.push(screencopy);
} else {
self.backend.with_primary_renderer(|renderer| {
if let Err(err) = self
.niri
.render_for_screencopy_without_damage(renderer, manager, screencopy)
{
warn!("error rendering for screencopy: {err:?}");
}
});
}
}
fn screencopy_state(&mut self) -> &mut ScreencopyManagerState {
&mut self.niri.screencopy_state
}
}
delegate_screencopy!(State);
impl VirtualPointerHandler for State {
fn virtual_pointer_manager_state(&mut self) -> &mut VirtualPointerManagerState {
&mut self.niri.virtual_pointer_state
}
fn on_virtual_pointer_motion(&mut self, event: VirtualPointerMotionEvent) {
self.process_input_event(InputEvent::<VirtualPointerInputBackend>::PointerMotion { event });
}
fn on_virtual_pointer_motion_absolute(&mut self, event: VirtualPointerMotionAbsoluteEvent) {
self.process_input_event(
InputEvent::<VirtualPointerInputBackend>::PointerMotionAbsolute { event },
);
}
fn on_virtual_pointer_button(&mut self, event: VirtualPointerButtonEvent) {
self.process_input_event(InputEvent::<VirtualPointerInputBackend>::PointerButton { event });
}
fn on_virtual_pointer_axis(&mut self, event: VirtualPointerAxisEvent) {
self.process_input_event(InputEvent::<VirtualPointerInputBackend>::PointerAxis { event });
}
}
delegate_virtual_pointer!(State);
impl DrmLeaseHandler for State {
fn drm_lease_state(&mut self, node: DrmNode) -> &mut DrmLeaseState {
self.backend
.tty()
.get_device_from_node(node)
.unwrap()
.drm_lease_state
.as_mut()
.unwrap()
}
fn lease_request(
&mut self,
node: DrmNode,
request: DrmLeaseRequest,
) -> Result<DrmLeaseBuilder, LeaseRejected> {
debug!(
"Received lease request for {} connectors",
request.connectors.len()
);
self.backend
.tty()
.get_device_from_node(node)
.unwrap()
.lease_request(request)
}
fn new_active_lease(&mut self, node: DrmNode, lease: DrmLease) {
debug!("Lease success");
self.backend
.tty()
.get_device_from_node(node)
.unwrap()
.new_lease(lease);
}
fn lease_destroyed(&mut self, node: DrmNode, lease_id: u32) {
debug!("Destroyed lease");
self.backend
.tty()
.get_device_from_node(node)
.unwrap()
.remove_lease(lease_id);
}
}
delegate_drm_lease!(State);
delegate_viewporter!(State);
impl GammaControlHandler for State {
fn gamma_control_manager_state(&mut self) -> &mut GammaControlManagerState {
&mut self.niri.gamma_control_manager_state
}
fn get_gamma_size(&mut self, output: &Output) -> Option<u32> {
match self.backend.tty().get_gamma_size(output) {
Ok(0) => None, // Setting gamma is not supported.
Ok(size) => Some(size),
Err(err) => {
warn!(
"error getting gamma size for output {}: {err:?}",
output.name()
);
None
}
}
}
fn set_gamma(&mut self, output: &Output, ramp: Option<Vec<u16>>) -> Option<()> {
match self.backend.tty().set_gamma(output, ramp) {
Ok(()) => Some(()),
Err(err) => {
warn!("error setting gamma for output {}: {err:?}", output.name());
None
}
}
}
}
delegate_gamma_control!(State);
struct UrgentOnlyMarker;
impl XdgActivationHandler for State {
fn activation_state(&mut self) -> &mut XdgActivationState {
&mut self.niri.activation_state
}
fn token_created(&mut self, _token: XdgActivationToken, data: XdgActivationTokenData) -> bool {
// Tokens without a serial are urgency-only. This is not specified, but it seems to be the
// common client behavior.
//
// See also: https://gitlab.freedesktop.org/wayland/wayland-protocols/-/issues/150
let Some((serial, seat)) = data.serial else {
data.user_data.insert_if_missing(|| UrgentOnlyMarker);
return true;
};
let Some(seat) = Seat::<State>::from_resource(&seat) else {
return false;
};
// Widely-used clients such as Discord and Telegram make new tokens (with invalid serials)
// upon clicking on their tray icon or on their notification. This debug flag makes that
// work.
//
// Clicking on a notification sends clients a perfectly valid activation token from the
// notification daemon, but alas they ignore it. Maybe in the future the clients are fixed,
// and we can remove this debug flag.
let config = self.niri.config.borrow();
if config.debug.honor_xdg_activation_with_invalid_serial {
return true;
}
// Check the serial against both a keyboard and a pointer, since layer-shell surfaces
// with no keyboard interactivity won't have any keyboard focus.
let kb_last_enter = seat.get_keyboard().unwrap().last_enter();
if kb_last_enter.is_some_and(|last_enter| serial.is_no_older_than(&last_enter)) {
return true;
}
let pointer_last_enter = seat.get_pointer().unwrap().last_enter();
if pointer_last_enter.is_some_and(|last_enter| serial.is_no_older_than(&last_enter)) {
return true;
}
false
}
fn request_activation(
&mut self,
token: XdgActivationToken,
token_data: XdgActivationTokenData,
surface: WlSurface,
) {
if token_data.timestamp.elapsed() < XDG_ACTIVATION_TOKEN_TIMEOUT {
if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(&surface) {
let window = mapped.window.clone();
if token_data.user_data.get::<UrgentOnlyMarker>().is_some() {
mapped.set_urgent(true);
self.niri.queue_redraw_all();
} else {
self.niri.layout.activate_window(&window);
self.niri.layer_shell_on_demand_focus = None;
self.niri.queue_redraw_all();
}
} else if let Some(unmapped) = self.niri.unmapped_windows.get_mut(&surface) {
unmapped.activation_token_data = Some(token_data);
}
}
self.niri.activation_state.remove_token(&token);
}
}
delegate_xdg_activation!(State);
impl FractionalScaleHandler for State {}
delegate_fractional_scale!(State);
impl OutputManagementHandler for State {
fn output_management_state(&mut self) -> &mut OutputManagementManagerState {
&mut self.niri.output_management_state
}
fn apply_output_config(&mut self, config: niri_config::Outputs) {
self.niri.config.borrow_mut().outputs = config;
self.reload_output_config();
}
}
delegate_output_management!(State);
impl MutterX11InteropHandler for State {}
delegate_mutter_x11_interop!(State);
delegate_single_pixel_buffer!(State);
+1098 -172
View File
File diff suppressed because it is too large Load Diff
-1465
View File
File diff suppressed because it is too large Load Diff
+51
View File
@@ -0,0 +1,51 @@
use ::input as libinput;
use smithay::backend::input;
use smithay::backend::winit::WinitVirtualDevice;
use smithay::output::Output;
use crate::niri::State;
use crate::protocols::virtual_pointer::VirtualPointer;
pub trait NiriInputBackend: input::InputBackend<Device = Self::NiriDevice> {
type NiriDevice: NiriInputDevice;
}
impl<T: input::InputBackend> NiriInputBackend for T
where
Self::Device: NiriInputDevice,
{
type NiriDevice = Self::Device;
}
pub trait NiriInputDevice: input::Device {
// FIXME: this should maybe be per-event, not per-device,
// but it's not clear that this matters in practice?
// it might be more obvious once we implement it for libinput
fn output(&self, state: &State) -> Option<Output>;
}
impl NiriInputDevice for libinput::Device {
fn output(&self, _state: &State) -> Option<Output> {
// FIXME: Allow specifying the output per-device?
None
}
}
impl NiriInputDevice for WinitVirtualDevice {
fn output(&self, _state: &State) -> Option<Output> {
// FIXME: we should be returning the single output that the winit backend creates,
// but for now, that will cause issues because the output is normally upside down,
// so we apply Transform::Flipped180 to it and that would also cause
// the cursor position to be flipped, which is not what we want.
//
// instead, we just return None and rely on the fact that it has only one output.
// doing so causes the cursor to be placed in *global* output coordinates,
// which are not flipped, and happen to be what we want.
None
}
}
impl NiriInputDevice for VirtualPointer {
fn output(&self, _: &State) -> Option<Output> {
self.output().cloned()
}
}
+4816
View File
File diff suppressed because it is too large Load Diff
+240
View File
@@ -0,0 +1,240 @@
use smithay::backend::input::ButtonState;
use smithay::desktop::Window;
use smithay::input::pointer::{
AxisFrame, ButtonEvent, CursorIcon, CursorImageStatus, GestureHoldBeginEvent,
GestureHoldEndEvent, GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent,
GestureSwipeBeginEvent, GestureSwipeEndEvent, GestureSwipeUpdateEvent,
GrabStartData as PointerGrabStartData, MotionEvent, PointerGrab, PointerInnerHandle,
RelativeMotionEvent,
};
use smithay::input::SeatHandler;
use smithay::utils::{IsAlive, Logical, Point};
use crate::niri::State;
pub struct MoveGrab {
start_data: PointerGrabStartData<State>,
last_location: Point<f64, Logical>,
window: Window,
gesture: GestureState,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GestureState {
Recognizing,
Move,
}
impl MoveGrab {
pub fn new(
start_data: PointerGrabStartData<State>,
window: Window,
use_threshold: bool,
) -> Self {
let gesture = if use_threshold {
GestureState::Recognizing
} else {
GestureState::Move
};
Self {
last_location: start_data.location,
start_data,
window,
gesture,
}
}
fn on_ungrab(&mut self, state: &mut State) {
state.niri.layout.interactive_move_end(&self.window);
// FIXME: only redraw the window output.
state.niri.queue_redraw_all();
state
.niri
.cursor_manager
.set_cursor_image(CursorImageStatus::default_named());
}
}
impl PointerGrab<State> for MoveGrab {
fn motion(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
event: &MotionEvent,
) {
// While the grab is active, no client has pointer focus.
handle.motion(data, None, event);
if self.window.alive() {
if let Some((output, pos_within_output)) = data.niri.output_under(event.location) {
let output = output.clone();
let event_delta = event.location - self.last_location;
self.last_location = event.location;
if self.gesture == GestureState::Recognizing {
let c = event.location - self.start_data.location;
// Check if the gesture moved far enough to decide.
if c.x * c.x + c.y * c.y >= 8. * 8. {
self.gesture = GestureState::Move;
data.niri
.cursor_manager
.set_cursor_image(CursorImageStatus::Named(CursorIcon::Move));
}
}
if self.gesture != GestureState::Move {
return;
}
let ongoing = data.niri.layout.interactive_move_update(
&self.window,
event_delta,
output,
pos_within_output,
);
if ongoing {
// FIXME: only redraw the previous and the new output.
data.niri.queue_redraw_all();
return;
}
} else {
return;
}
}
// The move is no longer ongoing.
handle.unset_grab(self, data, event.serial, event.time, true);
}
fn relative_motion(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
event: &RelativeMotionEvent,
) {
// While the grab is active, no client has pointer focus.
handle.relative_motion(data, None, event);
}
fn button(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &ButtonEvent,
) {
handle.button(data, event);
// When moving with the left button, right toggles floating, and vice versa.
let toggle_floating_button = if self.start_data.button == 0x110 {
0x111
} else {
0x110
};
if event.button == toggle_floating_button && event.state == ButtonState::Pressed {
data.niri.layout.toggle_window_floating(Some(&self.window));
}
if !handle.current_pressed().contains(&self.start_data.button) {
// The button that initiated the grab was released.
handle.unset_grab(self, data, event.serial, event.time, true);
}
}
fn axis(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
details: AxisFrame,
) {
handle.axis(data, details);
}
fn frame(&mut self, data: &mut State, handle: &mut PointerInnerHandle<'_, State>) {
handle.frame(data);
}
fn gesture_swipe_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeBeginEvent,
) {
handle.gesture_swipe_begin(data, event);
}
fn gesture_swipe_update(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeUpdateEvent,
) {
handle.gesture_swipe_update(data, event);
}
fn gesture_swipe_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeEndEvent,
) {
handle.gesture_swipe_end(data, event);
}
fn gesture_pinch_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchBeginEvent,
) {
handle.gesture_pinch_begin(data, event);
}
fn gesture_pinch_update(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchUpdateEvent,
) {
handle.gesture_pinch_update(data, event);
}
fn gesture_pinch_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchEndEvent,
) {
handle.gesture_pinch_end(data, event);
}
fn gesture_hold_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureHoldBeginEvent,
) {
handle.gesture_hold_begin(data, event);
}
fn gesture_hold_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureHoldEndEvent,
) {
handle.gesture_hold_end(data, event);
}
fn start_data(&self) -> &PointerGrabStartData<State> {
&self.start_data
}
fn unset(&mut self, data: &mut State) {
self.on_ungrab(data);
}
}
+227
View File
@@ -0,0 +1,227 @@
use niri_ipc::PickedColor;
use smithay::backend::allocator::Fourcc;
use smithay::backend::input::ButtonState;
use smithay::backend::renderer::element::utils::{Relocate, RelocateRenderElement};
use smithay::input::pointer::{
AxisFrame, ButtonEvent, CursorImageStatus, GestureHoldBeginEvent, GestureHoldEndEvent,
GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent,
GestureSwipeEndEvent, GestureSwipeUpdateEvent, GrabStartData as PointerGrabStartData,
MotionEvent, PointerGrab, PointerInnerHandle, RelativeMotionEvent,
};
use smithay::input::SeatHandler;
use smithay::utils::{Logical, Physical, Point, Scale, Size, Transform};
use crate::niri::State;
use crate::render_helpers::{render_to_vec, RenderTarget};
pub struct PickColorGrab {
start_data: PointerGrabStartData<State>,
}
impl PickColorGrab {
pub fn new(start_data: PointerGrabStartData<State>) -> Self {
Self { start_data }
}
fn on_ungrab(&mut self, state: &mut State) {
if let Some(tx) = state.niri.pick_color.take() {
let _ = tx.send_blocking(None);
}
state
.niri
.cursor_manager
.set_cursor_image(CursorImageStatus::default_named());
state.niri.queue_redraw_all();
}
fn pick_color_at_point(location: Point<f64, Logical>, data: &mut State) -> Option<PickedColor> {
let (output, pos_within_output) = data.niri.output_under(location)?;
let output = output.clone();
data.backend
.with_primary_renderer(|renderer| {
data.niri.update_render_elements(Some(&output));
let scale = Scale::from(output.current_scale().fractional_scale());
// FIXME: perhaps replace floor with round once we figure out the pointer behavior
// at the bottom/right edges of the monitors.
let pos = pos_within_output.to_physical_precise_floor(scale);
let size = Size::<i32, Physical>::from((1, 1));
let elements = data.niri.render(
renderer,
&output,
false,
// This is an interactive operation so we can render without blocking out.
RenderTarget::Output,
);
let pixels = match render_to_vec(
renderer,
size,
scale,
Transform::Normal,
Fourcc::Abgr8888,
elements.iter().rev().map(|elem| {
let offset = pos.upscale(-1);
RelocateRenderElement::from_element(elem, offset, Relocate::Relative)
}),
) {
Ok(pixels) => pixels,
Err(_) => return None,
};
if pixels.len() == 4 {
let rgb = [
f64::from(pixels[0]) / 255.0,
f64::from(pixels[1]) / 255.0,
f64::from(pixels[2]) / 255.0,
];
Some(PickedColor { rgb })
} else {
error!(
"unexpected pixel data length: {} (expected 4)",
pixels.len()
);
None
}
})
.flatten()
}
}
impl PointerGrab<State> for PickColorGrab {
fn motion(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
event: &MotionEvent,
) {
handle.motion(data, None, event);
}
fn relative_motion(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
event: &RelativeMotionEvent,
) {
handle.relative_motion(data, None, event);
}
fn button(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &ButtonEvent,
) {
if event.state != ButtonState::Pressed {
return;
}
// We're handling this press, don't send the release to the window.
data.niri.suppressed_buttons.insert(event.button);
if let Some(tx) = data.niri.pick_color.take() {
let color = Self::pick_color_at_point(handle.current_location(), data);
let _ = tx.send_blocking(color);
}
handle.unset_grab(self, data, event.serial, event.time, true);
}
fn axis(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
details: AxisFrame,
) {
handle.axis(data, details);
}
fn frame(&mut self, data: &mut State, handle: &mut PointerInnerHandle<'_, State>) {
handle.frame(data);
}
fn gesture_swipe_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeBeginEvent,
) {
handle.gesture_swipe_begin(data, event);
}
fn gesture_swipe_update(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeUpdateEvent,
) {
handle.gesture_swipe_update(data, event);
}
fn gesture_swipe_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeEndEvent,
) {
handle.gesture_swipe_end(data, event);
}
fn gesture_pinch_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchBeginEvent,
) {
handle.gesture_pinch_begin(data, event);
}
fn gesture_pinch_update(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchUpdateEvent,
) {
handle.gesture_pinch_update(data, event);
}
fn gesture_pinch_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchEndEvent,
) {
handle.gesture_pinch_end(data, event);
}
fn gesture_hold_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureHoldBeginEvent,
) {
handle.gesture_hold_begin(data, event);
}
fn gesture_hold_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureHoldEndEvent,
) {
handle.gesture_hold_end(data, event);
}
fn start_data(&self) -> &PointerGrabStartData<State> {
&self.start_data
}
fn unset(&mut self, data: &mut State) {
self.on_ungrab(data);
}
}
+173
View File
@@ -0,0 +1,173 @@
use smithay::backend::input::ButtonState;
use smithay::input::pointer::{
AxisFrame, ButtonEvent, CursorImageStatus, GestureHoldBeginEvent, GestureHoldEndEvent,
GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent,
GestureSwipeEndEvent, GestureSwipeUpdateEvent, GrabStartData as PointerGrabStartData,
MotionEvent, PointerGrab, PointerInnerHandle, RelativeMotionEvent,
};
use smithay::input::SeatHandler;
use smithay::utils::{Logical, Point};
use crate::niri::State;
use crate::window::Mapped;
pub struct PickWindowGrab {
start_data: PointerGrabStartData<State>,
}
impl PickWindowGrab {
pub fn new(start_data: PointerGrabStartData<State>) -> Self {
Self { start_data }
}
fn on_ungrab(&mut self, state: &mut State) {
if let Some(tx) = state.niri.pick_window.take() {
let _ = tx.send_blocking(None);
}
state
.niri
.cursor_manager
.set_cursor_image(CursorImageStatus::default_named());
// Redraw to update the cursor.
state.niri.queue_redraw_all();
}
}
impl PointerGrab<State> for PickWindowGrab {
fn motion(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
event: &MotionEvent,
) {
handle.motion(data, None, event);
}
fn relative_motion(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
event: &RelativeMotionEvent,
) {
handle.relative_motion(data, None, event);
}
fn button(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &ButtonEvent,
) {
if event.state != ButtonState::Pressed {
return;
}
// We're handling this press, don't send the release to the window.
data.niri.suppressed_buttons.insert(event.button);
if let Some(tx) = data.niri.pick_window.take() {
let _ = tx.send_blocking(
data.niri
.window_under(handle.current_location())
.map(Mapped::id),
);
}
handle.unset_grab(self, data, event.serial, event.time, true);
}
fn axis(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
details: AxisFrame,
) {
handle.axis(data, details);
}
fn frame(&mut self, data: &mut State, handle: &mut PointerInnerHandle<'_, State>) {
handle.frame(data);
}
fn gesture_swipe_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeBeginEvent,
) {
handle.gesture_swipe_begin(data, event);
}
fn gesture_swipe_update(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeUpdateEvent,
) {
handle.gesture_swipe_update(data, event);
}
fn gesture_swipe_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeEndEvent,
) {
handle.gesture_swipe_end(data, event);
}
fn gesture_pinch_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchBeginEvent,
) {
handle.gesture_pinch_begin(data, event);
}
fn gesture_pinch_update(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchUpdateEvent,
) {
handle.gesture_pinch_update(data, event);
}
fn gesture_pinch_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchEndEvent,
) {
handle.gesture_pinch_end(data, event);
}
fn gesture_hold_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureHoldBeginEvent,
) {
handle.gesture_hold_begin(data, event);
}
fn gesture_hold_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureHoldEndEvent,
) {
handle.gesture_hold_end(data, event);
}
fn start_data(&self) -> &PointerGrabStartData<State> {
&self.start_data
}
fn unset(&mut self, data: &mut State) {
self.on_ungrab(data);
}
}
+175
View File
@@ -0,0 +1,175 @@
use smithay::desktop::Window;
use smithay::input::pointer::{
AxisFrame, ButtonEvent, CursorImageStatus, GestureHoldBeginEvent, GestureHoldEndEvent,
GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent,
GestureSwipeEndEvent, GestureSwipeUpdateEvent, GrabStartData as PointerGrabStartData,
MotionEvent, PointerGrab, PointerInnerHandle, RelativeMotionEvent,
};
use smithay::input::SeatHandler;
use smithay::utils::{IsAlive, Logical, Point};
use crate::niri::State;
pub struct ResizeGrab {
start_data: PointerGrabStartData<State>,
window: Window,
}
impl ResizeGrab {
pub fn new(start_data: PointerGrabStartData<State>, window: Window) -> Self {
Self { start_data, window }
}
fn on_ungrab(&mut self, state: &mut State) {
state.niri.layout.interactive_resize_end(&self.window);
state
.niri
.cursor_manager
.set_cursor_image(CursorImageStatus::default_named());
}
}
impl PointerGrab<State> for ResizeGrab {
fn motion(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
event: &MotionEvent,
) {
// While the grab is active, no client has pointer focus.
handle.motion(data, None, event);
if self.window.alive() {
let delta = event.location - self.start_data.location;
let ongoing = data
.niri
.layout
.interactive_resize_update(&self.window, delta);
if ongoing {
return;
}
}
// The resize is no longer ongoing.
handle.unset_grab(self, data, event.serial, event.time, true);
}
fn relative_motion(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
event: &RelativeMotionEvent,
) {
// While the grab is active, no client has pointer focus.
handle.relative_motion(data, None, event);
}
fn button(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &ButtonEvent,
) {
handle.button(data, event);
if handle.current_pressed().is_empty() {
// No more buttons are pressed, release the grab.
handle.unset_grab(self, data, event.serial, event.time, true);
}
}
fn axis(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
details: AxisFrame,
) {
handle.axis(data, details);
}
fn frame(&mut self, data: &mut State, handle: &mut PointerInnerHandle<'_, State>) {
handle.frame(data);
}
fn gesture_swipe_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeBeginEvent,
) {
handle.gesture_swipe_begin(data, event);
}
fn gesture_swipe_update(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeUpdateEvent,
) {
handle.gesture_swipe_update(data, event);
}
fn gesture_swipe_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeEndEvent,
) {
handle.gesture_swipe_end(data, event);
}
fn gesture_pinch_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchBeginEvent,
) {
handle.gesture_pinch_begin(data, event);
}
fn gesture_pinch_update(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchUpdateEvent,
) {
handle.gesture_pinch_update(data, event);
}
fn gesture_pinch_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchEndEvent,
) {
handle.gesture_pinch_end(data, event);
}
fn gesture_hold_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureHoldBeginEvent,
) {
handle.gesture_hold_begin(data, event);
}
fn gesture_hold_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureHoldEndEvent,
) {
handle.gesture_hold_end(data, event);
}
fn start_data(&self) -> &PointerGrabStartData<State> {
&self.start_data
}
fn unset(&mut self, data: &mut State) {
self.on_ungrab(data);
}
}
+69
View File
@@ -0,0 +1,69 @@
//! Swipe gesture from scroll events.
//!
//! Tracks when to begin, update, and end a swipe gesture from pointer axis events, also whether
//! the gesture is vertical or horizontal. Necessary because libinput only provides touchpad swipe
//! gesture events for 3+ fingers.
#[derive(Debug)]
pub struct ScrollSwipeGesture {
ongoing: bool,
vertical: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
BeginUpdate,
Update,
End,
}
impl ScrollSwipeGesture {
pub const fn new() -> Self {
Self {
ongoing: false,
vertical: false,
}
}
pub fn update(&mut self, dx: f64, dy: f64) -> Action {
if dx == 0. && dy == 0. {
self.ongoing = false;
Action::End
} else if !self.ongoing {
self.ongoing = true;
self.vertical = dy != 0.;
Action::BeginUpdate
} else {
Action::Update
}
}
pub fn reset(&mut self) -> bool {
if self.ongoing {
self.ongoing = false;
true
} else {
false
}
}
pub fn is_vertical(&self) -> bool {
self.vertical
}
}
impl Default for ScrollSwipeGesture {
fn default() -> Self {
Self::new()
}
}
impl Action {
pub fn begin(self) -> bool {
self == Action::BeginUpdate
}
pub fn end(self) -> bool {
self == Action::End
}
}
+40
View File
@@ -0,0 +1,40 @@
pub struct ScrollTracker {
tick: f64,
last: f64,
acc: f64,
}
impl ScrollTracker {
#[allow(clippy::new_without_default)]
pub fn new(tick: i8) -> Self {
Self {
tick: f64::from(tick),
last: 0.,
acc: 0.,
}
}
pub fn accumulate(&mut self, amount: f64) -> i8 {
let changed_direction = (self.last > 0. && amount < 0.) || (self.last < 0. && amount > 0.);
if changed_direction {
self.acc = 0.
}
self.last = amount;
self.acc += amount;
let mut ticks = 0;
if self.acc.abs() >= self.tick {
let clamped = self.acc.clamp(-127. * self.tick, 127. * self.tick);
ticks = (clamped as i16 / self.tick as i16) as i8;
self.acc %= self.tick;
}
ticks
}
pub fn reset(&mut self) {
self.last = 0.;
self.acc = 0.;
}
}
+250
View File
@@ -0,0 +1,250 @@
use std::time::Duration;
use smithay::input::pointer::{
AxisFrame, ButtonEvent, CursorImageStatus, GestureHoldBeginEvent, GestureHoldEndEvent,
GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent,
GestureSwipeEndEvent, GestureSwipeUpdateEvent, GrabStartData as PointerGrabStartData,
MotionEvent, PointerGrab, PointerInnerHandle, RelativeMotionEvent,
};
use smithay::input::SeatHandler;
use smithay::output::Output;
use smithay::utils::{Logical, Point};
use crate::layout::workspace::WorkspaceId;
use crate::niri::State;
pub struct SpatialMovementGrab {
start_data: PointerGrabStartData<State>,
last_location: Point<f64, Logical>,
output: Output,
workspace_id: WorkspaceId,
gesture: GestureState,
}
#[derive(Debug, Clone, Copy)]
enum GestureState {
Recognizing,
ViewOffset,
WorkspaceSwitch,
}
impl SpatialMovementGrab {
pub fn new(
start_data: PointerGrabStartData<State>,
output: Output,
workspace_id: WorkspaceId,
is_view_offset: bool,
) -> Self {
let gesture = if is_view_offset {
GestureState::ViewOffset
} else {
GestureState::Recognizing
};
Self {
last_location: start_data.location,
start_data,
output,
workspace_id,
gesture,
}
}
fn on_ungrab(&mut self, state: &mut State) {
let layout = &mut state.niri.layout;
let res = match self.gesture {
GestureState::Recognizing => None,
GestureState::ViewOffset => layout.view_offset_gesture_end(Some(false)),
GestureState::WorkspaceSwitch => layout.workspace_switch_gesture_end(Some(false)),
};
if let Some(output) = res {
state.niri.queue_redraw(&output);
}
state
.niri
.cursor_manager
.set_cursor_image(CursorImageStatus::default_named());
}
}
impl PointerGrab<State> for SpatialMovementGrab {
fn motion(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
event: &MotionEvent,
) {
// While the grab is active, no client has pointer focus.
handle.motion(data, None, event);
let timestamp = Duration::from_millis(u64::from(event.time));
let delta = event.location - self.last_location;
self.last_location = event.location;
let layout = &mut data.niri.layout;
let res = match self.gesture {
GestureState::Recognizing => {
let c = event.location - self.start_data.location;
// Check if the gesture moved far enough to decide. Threshold copied from GTK 4.
if c.x * c.x + c.y * c.y >= 8. * 8. {
if c.x.abs() > c.y.abs() {
self.gesture = GestureState::ViewOffset;
if let Some((ws_idx, ws)) = layout.find_workspace_by_id(self.workspace_id) {
if ws.current_output() == Some(&self.output) {
layout.view_offset_gesture_begin(&self.output, Some(ws_idx), false);
layout.view_offset_gesture_update(-c.x, timestamp, false)
} else {
None
}
} else {
None
}
} else {
self.gesture = GestureState::WorkspaceSwitch;
layout.workspace_switch_gesture_begin(&self.output, false);
layout.workspace_switch_gesture_update(-c.y, timestamp, false)
}
} else {
Some(None)
}
}
GestureState::ViewOffset => {
layout.view_offset_gesture_update(-delta.x, timestamp, false)
}
GestureState::WorkspaceSwitch => {
layout.workspace_switch_gesture_update(-delta.y, timestamp, false)
}
};
if let Some(output) = res {
if let Some(output) = output {
data.niri.queue_redraw(&output);
}
} else {
// The move is no longer ongoing.
handle.unset_grab(self, data, event.serial, event.time, true);
}
}
fn relative_motion(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
event: &RelativeMotionEvent,
) {
// While the grab is active, no client has pointer focus.
handle.relative_motion(data, None, event);
}
fn button(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &ButtonEvent,
) {
handle.button(data, event);
if handle.current_pressed().is_empty() {
// No more buttons are pressed, release the grab.
handle.unset_grab(self, data, event.serial, event.time, true);
}
}
fn axis(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
details: AxisFrame,
) {
handle.axis(data, details);
}
fn frame(&mut self, data: &mut State, handle: &mut PointerInnerHandle<'_, State>) {
handle.frame(data);
}
fn gesture_swipe_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeBeginEvent,
) {
handle.gesture_swipe_begin(data, event);
}
fn gesture_swipe_update(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeUpdateEvent,
) {
handle.gesture_swipe_update(data, event);
}
fn gesture_swipe_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureSwipeEndEvent,
) {
handle.gesture_swipe_end(data, event);
}
fn gesture_pinch_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchBeginEvent,
) {
handle.gesture_pinch_begin(data, event);
}
fn gesture_pinch_update(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchUpdateEvent,
) {
handle.gesture_pinch_update(data, event);
}
fn gesture_pinch_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GesturePinchEndEvent,
) {
handle.gesture_pinch_end(data, event);
}
fn gesture_hold_begin(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureHoldBeginEvent,
) {
handle.gesture_hold_begin(data, event);
}
fn gesture_hold_end(
&mut self,
data: &mut State,
handle: &mut PointerInnerHandle<'_, State>,
event: &GestureHoldEndEvent,
) {
handle.gesture_hold_end(data, event);
}
fn start_data(&self) -> &PointerGrabStartData<State> {
&self.start_data
}
fn unset(&mut self, data: &mut State) {
self.on_ungrab(data);
}
}
+87
View File
@@ -0,0 +1,87 @@
use std::collections::VecDeque;
use std::time::Duration;
const HISTORY_LIMIT: Duration = Duration::from_millis(150);
const DECELERATION_TOUCHPAD: f64 = 0.997;
#[derive(Debug)]
pub struct SwipeTracker {
history: VecDeque<Event>,
pos: f64,
}
#[derive(Debug, Clone, Copy)]
struct Event {
delta: f64,
timestamp: Duration,
}
impl SwipeTracker {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
history: VecDeque::new(),
pos: 0.,
}
}
/// Pushes a new reading into the tracker.
pub fn push(&mut self, delta: f64, timestamp: Duration) {
// For the events that we care about, timestamps should always increase
// monotonically.
if let Some(last) = self.history.back() {
if timestamp < last.timestamp {
trace!(
"ignoring event with timestamp {timestamp:?} earlier than last {:?}",
last.timestamp
);
return;
}
}
self.history.push_back(Event { delta, timestamp });
self.pos += delta;
self.trim_history();
}
/// Returns the current gesture position.
pub fn pos(&self) -> f64 {
self.pos
}
/// Computes the current gesture velocity.
pub fn velocity(&self) -> f64 {
let (Some(first), Some(last)) = (self.history.front(), self.history.back()) else {
return 0.;
};
let total_time = (last.timestamp - first.timestamp).as_secs_f64();
if total_time == 0. {
return 0.;
}
let total_delta = self.history.iter().map(|event| event.delta).sum::<f64>();
total_delta / total_time
}
/// Computes the gesture end position after decelerating to a halt.
pub fn projected_end_pos(&self) -> f64 {
let vel = self.velocity();
self.pos - vel / (1000. * DECELERATION_TOUCHPAD.ln())
}
fn trim_history(&mut self) {
let Some(&Event { timestamp, .. }) = self.history.back() else {
return;
};
while let Some(first) = self.history.front() {
if timestamp <= first.timestamp + HISTORY_LIMIT {
break;
}
let _ = self.history.pop_front();
}
}
}
+136
View File
@@ -0,0 +1,136 @@
use smithay::desktop::Window;
use smithay::input::touch::{
DownEvent, GrabStartData as TouchGrabStartData, MotionEvent, OrientationEvent, ShapeEvent,
TouchGrab, TouchInnerHandle, UpEvent,
};
use smithay::input::SeatHandler;
use smithay::utils::{IsAlive, Logical, Point, Serial};
use crate::niri::State;
pub struct TouchMoveGrab {
start_data: TouchGrabStartData<State>,
last_location: Point<f64, Logical>,
window: Window,
}
impl TouchMoveGrab {
pub fn new(start_data: TouchGrabStartData<State>, window: Window) -> Self {
Self {
last_location: start_data.location,
start_data,
window,
}
}
fn on_ungrab(&mut self, state: &mut State) {
state.niri.layout.interactive_move_end(&self.window);
// FIXME: only redraw the window output.
state.niri.queue_redraw_all();
}
}
impl TouchGrab<State> for TouchMoveGrab {
fn down(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::TouchFocus, Point<f64, Logical>)>,
event: &DownEvent,
seq: Serial,
) {
handle.down(data, None, event, seq);
}
fn up(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
event: &UpEvent,
seq: Serial,
) {
handle.up(data, event, seq);
if event.slot != self.start_data.slot {
return;
}
handle.unset_grab(self, data);
}
fn motion(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::TouchFocus, Point<f64, Logical>)>,
event: &MotionEvent,
seq: Serial,
) {
handle.motion(data, None, event, seq);
if event.slot != self.start_data.slot {
return;
}
if self.window.alive() {
if let Some((output, pos_within_output)) = data.niri.output_under(event.location) {
let output = output.clone();
let event_delta = event.location - self.last_location;
self.last_location = event.location;
let ongoing = data.niri.layout.interactive_move_update(
&self.window,
event_delta,
output,
pos_within_output,
);
if ongoing {
// FIXME: only redraw the previous and the new output.
data.niri.queue_redraw_all();
return;
}
} else {
return;
}
}
// The move is no longer ongoing.
handle.unset_grab(self, data);
}
fn frame(&mut self, data: &mut State, handle: &mut TouchInnerHandle<'_, State>, seq: Serial) {
handle.frame(data, seq);
}
fn cancel(&mut self, data: &mut State, handle: &mut TouchInnerHandle<'_, State>, seq: Serial) {
handle.cancel(data, seq);
handle.unset_grab(self, data);
}
fn shape(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
event: &ShapeEvent,
seq: Serial,
) {
handle.shape(data, event, seq);
}
fn orientation(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
event: &OrientationEvent,
seq: Serial,
) {
handle.orientation(data, event, seq);
}
fn start_data(&self) -> &TouchGrabStartData<State> {
&self.start_data
}
fn unset(&mut self, data: &mut State) {
self.on_ungrab(data);
}
}
+274
View File
@@ -0,0 +1,274 @@
use std::time::Duration;
use smithay::desktop::Window;
use smithay::input::touch::{
DownEvent, GrabStartData as TouchGrabStartData, MotionEvent, OrientationEvent, ShapeEvent,
TouchGrab, TouchInnerHandle, UpEvent,
};
use smithay::input::SeatHandler;
use smithay::output::Output;
use smithay::utils::{IsAlive, Logical, Point, Serial};
use crate::layout::workspace::{Workspace, WorkspaceId};
use crate::niri::State;
use crate::window::Mapped;
// When the touch is stationary for this much time, it becomes an interactive move.
const INTERACTIVE_MOVE_THRESHOLD: Duration = Duration::from_millis(500);
pub struct TouchOverviewGrab {
start_data: TouchGrabStartData<State>,
start_timestamp: Duration,
last_location: Point<f64, Logical>,
output: Output,
start_pos_within_output: Point<f64, Logical>,
workspace_id: Option<WorkspaceId>,
workspace_matched_narrow: bool,
window: Option<Window>,
gesture: GestureState,
}
#[derive(Debug, Clone, Copy)]
enum GestureState {
Recognizing,
ViewOffset,
WorkspaceSwitch,
InteractiveMove,
}
impl TouchOverviewGrab {
pub fn new(
start_data: TouchGrabStartData<State>,
start_timestamp: Duration,
output: Output,
start_pos_within_output: Point<f64, Logical>,
workspace_id: Option<WorkspaceId>,
workspace_matched_narrow: bool,
window: Option<Window>,
) -> Self {
Self {
last_location: start_data.location,
start_timestamp,
start_data,
output,
start_pos_within_output,
workspace_id,
workspace_matched_narrow,
window,
gesture: GestureState::Recognizing,
}
}
fn on_ungrab(&mut self, state: &mut State) {
let layout = &mut state.niri.layout;
match self.gesture {
GestureState::Recognizing => {
// Tap to activate.
layout.focus_output(&self.output);
// Activate the workspace if necessary.
if self.window.is_some() || self.workspace_matched_narrow {
// When activating a window, we want to activate the window's current
// workspace. Otherwise, find the workspace that we tapped on.
let ws_matches = |ws: &Workspace<Mapped>| {
if let Some(window) = &self.window {
ws.has_window(window)
} else if let Some(ws_id) = self.workspace_id {
ws.id() == ws_id
} else {
false
}
};
let ws_idx = if let Some((Some(mon), ws_idx, _)) =
layout.workspaces().find(|(_, _, ws)| ws_matches(ws))
{
// The workspace could've moved to a different output in the meantime.
(*mon.output() == self.output).then_some(ws_idx)
} else {
None
};
if let Some(ws_idx) = ws_idx {
layout.toggle_overview_to_workspace(ws_idx);
}
}
if let Some(window) = self.window.as_ref() {
layout.activate_window(window);
}
}
GestureState::ViewOffset => {
layout.view_offset_gesture_end(Some(false));
}
GestureState::WorkspaceSwitch => {
layout.workspace_switch_gesture_end(Some(false));
}
GestureState::InteractiveMove => {
layout.interactive_move_end(self.window.as_ref().unwrap());
}
};
state.niri.queue_redraw_all();
}
}
impl TouchGrab<State> for TouchOverviewGrab {
fn down(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::TouchFocus, Point<f64, Logical>)>,
event: &DownEvent,
seq: Serial,
) {
handle.down(data, None, event, seq);
}
fn up(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
event: &UpEvent,
seq: Serial,
) {
handle.up(data, event, seq);
if event.slot != self.start_data.slot {
return;
}
handle.unset_grab(self, data);
}
fn motion(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::TouchFocus, Point<f64, Logical>)>,
event: &MotionEvent,
seq: Serial,
) {
handle.motion(data, None, event, seq);
if event.slot != self.start_data.slot {
return;
}
let timestamp = Duration::from_millis(u64::from(event.time));
let layout = &mut data.niri.layout;
// Check if we should become interactive move.
if matches!(self.gesture, GestureState::Recognizing) {
if let Some(window) = self.window.as_ref().filter(|win| win.alive()) {
let passed = timestamp.saturating_sub(self.start_timestamp);
if INTERACTIVE_MOVE_THRESHOLD <= passed
&& layout.interactive_move_begin(
window.clone(),
&self.output,
self.start_pos_within_output,
)
{
self.gesture = GestureState::InteractiveMove;
}
}
}
// Check if we should become a spatial scroll.
if matches!(self.gesture, GestureState::Recognizing) {
let c = event.location - self.start_data.location;
// Check if the gesture moved far enough to decide. Threshold copied from libadwaita.
if c.x * c.x + c.y * c.y >= 16. * 16. {
if let Some(ws_id) = self.workspace_id.filter(|_| c.x.abs() > c.y.abs()) {
if let Some((ws_idx, ws)) = layout.find_workspace_by_id(ws_id) {
if ws.current_output() == Some(&self.output) {
layout.view_offset_gesture_begin(&self.output, Some(ws_idx), false);
self.gesture = GestureState::ViewOffset;
}
}
}
if matches!(self.gesture, GestureState::Recognizing) {
layout.workspace_switch_gesture_begin(&self.output, false);
self.gesture = GestureState::WorkspaceSwitch;
}
}
}
// Do nothing if still recognizing.
if matches!(self.gesture, GestureState::Recognizing) {
return;
}
let delta = event.location - self.last_location;
self.last_location = event.location;
let ongoing = match self.gesture {
GestureState::Recognizing => unreachable!(),
GestureState::ViewOffset => layout
.view_offset_gesture_update(-delta.x, timestamp, false)
.is_some(),
GestureState::WorkspaceSwitch => layout
.workspace_switch_gesture_update(-delta.y, timestamp, false)
.is_some(),
GestureState::InteractiveMove => {
let window = self.window.as_ref().unwrap();
if let Some((output, pos_within_output)) = data.niri.output_under(event.location) {
let output = output.clone();
data.niri.layout.interactive_move_update(
window,
delta,
output,
pos_within_output,
)
} else {
false
}
}
};
if ongoing {
data.niri.queue_redraw_all();
} else {
handle.unset_grab(self, data);
}
}
fn frame(&mut self, data: &mut State, handle: &mut TouchInnerHandle<'_, State>, seq: Serial) {
handle.frame(data, seq);
}
fn cancel(&mut self, data: &mut State, handle: &mut TouchInnerHandle<'_, State>, seq: Serial) {
handle.cancel(data, seq);
handle.unset_grab(self, data);
}
fn shape(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
event: &ShapeEvent,
seq: Serial,
) {
handle.shape(data, event, seq);
}
fn orientation(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
event: &OrientationEvent,
seq: Serial,
) {
handle.orientation(data, event, seq);
}
fn start_data(&self) -> &TouchGrabStartData<State> {
&self.start_data
}
fn unset(&mut self, data: &mut State) {
self.on_ungrab(data);
}
}
+119
View File
@@ -0,0 +1,119 @@
use smithay::desktop::Window;
use smithay::input::touch::{
DownEvent, GrabStartData as TouchGrabStartData, MotionEvent, OrientationEvent, ShapeEvent,
TouchGrab, TouchInnerHandle, UpEvent,
};
use smithay::input::SeatHandler;
use smithay::utils::{IsAlive, Logical, Point, Serial};
use crate::niri::State;
pub struct TouchResizeGrab {
start_data: TouchGrabStartData<State>,
window: Window,
}
impl TouchResizeGrab {
pub fn new(start_data: TouchGrabStartData<State>, window: Window) -> Self {
Self { start_data, window }
}
fn on_ungrab(&mut self, state: &mut State) {
state.niri.layout.interactive_resize_end(&self.window);
}
}
impl TouchGrab<State> for TouchResizeGrab {
fn down(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::TouchFocus, Point<f64, Logical>)>,
event: &DownEvent,
seq: Serial,
) {
handle.down(data, None, event, seq);
}
fn up(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
event: &UpEvent,
seq: Serial,
) {
handle.up(data, event, seq);
if event.slot != self.start_data.slot {
return;
}
handle.unset_grab(self, data);
}
fn motion(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
_focus: Option<(<State as SeatHandler>::TouchFocus, Point<f64, Logical>)>,
event: &MotionEvent,
seq: Serial,
) {
handle.motion(data, None, event, seq);
if event.slot != self.start_data.slot {
return;
}
if self.window.alive() {
let delta = event.location - self.start_data.location;
let ongoing = data
.niri
.layout
.interactive_resize_update(&self.window, delta);
if ongoing {
return;
}
}
// The resize is no longer ongoing.
handle.unset_grab(self, data);
}
fn frame(&mut self, data: &mut State, handle: &mut TouchInnerHandle<'_, State>, seq: Serial) {
handle.frame(data, seq);
}
fn cancel(&mut self, data: &mut State, handle: &mut TouchInnerHandle<'_, State>, seq: Serial) {
handle.cancel(data, seq);
handle.unset_grab(self, data);
}
fn shape(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
event: &ShapeEvent,
seq: Serial,
) {
handle.shape(data, event, seq);
}
fn orientation(
&mut self,
data: &mut State,
handle: &mut TouchInnerHandle<'_, State>,
event: &OrientationEvent,
seq: Serial,
) {
handle.orientation(data, event, seq);
}
fn start_data(&self) -> &TouchGrabStartData<State> {
&self.start_data
}
fn unset(&mut self, data: &mut State) {
self.on_ungrab(data);
}
}
+615
View File
@@ -0,0 +1,615 @@
use std::io::ErrorKind;
use std::iter::Peekable;
use std::slice;
use anyhow::{anyhow, bail, Context};
use niri_config::OutputName;
use niri_ipc::socket::Socket;
use niri_ipc::{
Event, KeyboardLayouts, LogicalOutput, Mode, Output, OutputConfigChanged, Overview, Request,
Response, Transform, Window,
};
use serde_json::json;
use crate::cli::Msg;
use crate::utils::version;
pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
let request = match &msg {
Msg::Version => Request::Version,
Msg::Outputs => Request::Outputs,
Msg::FocusedWindow => Request::FocusedWindow,
Msg::FocusedOutput => Request::FocusedOutput,
Msg::PickWindow => Request::PickWindow,
Msg::PickColor => Request::PickColor,
Msg::Action { action } => Request::Action(action.clone()),
Msg::Output { output, action } => Request::Output {
output: output.clone(),
action: action.clone(),
},
Msg::Workspaces => Request::Workspaces,
Msg::Windows => Request::Windows,
Msg::Layers => Request::Layers,
Msg::KeyboardLayouts => Request::KeyboardLayouts,
Msg::EventStream => Request::EventStream,
Msg::RequestError => Request::ReturnError,
Msg::OverviewState => Request::OverviewState,
};
let mut socket = Socket::connect().context("error connecting to the niri socket")?;
let result = socket.send(request);
// For errors that can be caused by a version mismatch between the running niri instance and
// the niri msg CLI, we will try to fetch and compare the versions.
let check_compositor_version = match &result {
Err(err) => {
// Response JSON parsing errors.
matches!(
err.kind(),
ErrorKind::InvalidData | ErrorKind::UnexpectedEof
)
}
// Error returned from niri.
Ok(Err(_)) => true,
_ => false,
};
let compositor_version = if check_compositor_version && !matches!(msg, Msg::Version) {
// Reconnect to support older niri versions with one request per connection.
Socket::connect()
.and_then(|mut socket| socket.send(Request::Version))
.ok()
} else {
None
};
// Default SIGPIPE so that our prints don't panic on stdout closing.
unsafe {
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
}
// Check for CLI-server version mismatch to add helpful context.
match compositor_version {
Some(Ok(Response::Version(compositor_version))) => {
let cli_version = version();
if cli_version != compositor_version {
eprintln!("Running niri compositor has a different version from the niri CLI:");
eprintln!("Compositor version: {compositor_version}");
eprintln!("CLI version: {cli_version}");
eprintln!("Did you forget to restart niri after an update?");
eprintln!();
}
}
Some(_) => {
eprintln!("Unable to get the running niri compositor version.");
eprintln!("Did you forget to restart niri after an update?");
eprintln!();
}
None => {
// Communication error, or the original request was already a version request, or the
// original request had succeeded. Don't add irrelevant context.
}
}
let reply = result.context("error communicating with niri")?;
let response = reply.map_err(|err_msg| anyhow!(err_msg).context("niri returned an error"))?;
match msg {
Msg::RequestError => {
bail!("unexpected response: expected an error, got {response:?}");
}
Msg::Version => {
let Response::Version(compositor_version) = response else {
bail!("unexpected response: expected Version, got {response:?}");
};
let cli_version = version();
if json {
println!(
"{}",
json!({
"compositor": compositor_version,
"cli": cli_version,
})
);
return Ok(());
}
if cli_version != compositor_version {
eprintln!("Running niri compositor has a different version from the niri CLI.");
eprintln!("Did you forget to restart niri after an update?");
eprintln!();
}
println!("Compositor version: {compositor_version}");
println!("CLI version: {cli_version}");
}
Msg::Outputs => {
let Response::Outputs(outputs) = response else {
bail!("unexpected response: expected Outputs, got {response:?}");
};
if json {
let output =
serde_json::to_string(&outputs).context("error formatting response")?;
println!("{output}");
return Ok(());
}
let mut outputs = outputs
.into_values()
.map(|out| (OutputName::from_ipc_output(&out), out))
.collect::<Vec<_>>();
outputs.sort_unstable_by(|a, b| a.0.compare(&b.0));
for (_name, output) in outputs.into_iter() {
print_output(output)?;
println!();
}
}
Msg::FocusedWindow => {
let Response::FocusedWindow(window) = response else {
bail!("unexpected response: expected FocusedWindow, got {response:?}");
};
if json {
let window = serde_json::to_string(&window).context("error formatting response")?;
println!("{window}");
return Ok(());
}
if let Some(window) = window {
print_window(&window);
} else {
println!("No window is focused.");
}
}
Msg::Windows => {
let Response::Windows(mut windows) = response else {
bail!("unexpected response: expected Windows, got {response:?}");
};
if json {
let windows =
serde_json::to_string(&windows).context("error formatting response")?;
println!("{windows}");
return Ok(());
}
windows.sort_unstable_by(|a, b| a.id.cmp(&b.id));
for window in windows {
print_window(&window);
println!();
}
}
Msg::Layers => {
let Response::Layers(mut layers) = response else {
bail!("unexpected response: expected Layers, got {response:?}");
};
if json {
let layers = serde_json::to_string(&layers).context("error formatting response")?;
println!("{layers}");
return Ok(());
}
layers.sort_by(|a, b| {
Ord::cmp(&a.output, &b.output)
.then_with(|| Ord::cmp(&a.layer, &b.layer))
.then_with(|| Ord::cmp(&a.namespace, &b.namespace))
});
let mut iter = layers.iter().peekable();
let print = |surface: &niri_ipc::LayerSurface| {
println!(" Surface:");
println!(" Namespace: \"{}\"", &surface.namespace);
let interactivity = match surface.keyboard_interactivity {
niri_ipc::LayerSurfaceKeyboardInteractivity::None => "none",
niri_ipc::LayerSurfaceKeyboardInteractivity::Exclusive => "exclusive",
niri_ipc::LayerSurfaceKeyboardInteractivity::OnDemand => "on-demand",
};
println!(" Keyboard interactivity: {interactivity}");
};
let print_layer = |iter: &mut Peekable<slice::Iter<niri_ipc::LayerSurface>>,
output: &str,
layer| {
let mut empty = true;
while let Some(surface) = iter.next_if(|s| s.output == output && s.layer == layer) {
empty = false;
println!();
print(surface);
}
if empty {
println!(" (empty)\n");
} else {
println!();
}
};
while let Some(surface) = iter.peek() {
let output = &surface.output;
println!("Output \"{output}\":");
print!(" Background layer:");
print_layer(&mut iter, output, niri_ipc::Layer::Background);
print!(" Bottom layer:");
print_layer(&mut iter, output, niri_ipc::Layer::Bottom);
print!(" Top layer:");
print_layer(&mut iter, output, niri_ipc::Layer::Top);
print!(" Overlay layer:");
print_layer(&mut iter, output, niri_ipc::Layer::Overlay);
}
}
Msg::FocusedOutput => {
let Response::FocusedOutput(output) = response else {
bail!("unexpected response: expected FocusedOutput, got {response:?}");
};
if json {
let output = serde_json::to_string(&output).context("error formatting response")?;
println!("{output}");
return Ok(());
}
if let Some(output) = output {
print_output(output)?;
} else {
println!("No output is focused.");
}
}
Msg::PickWindow => {
let Response::PickedWindow(window) = response else {
bail!("unexpected response: expected PickedWindow, got {response:?}");
};
if json {
let window = serde_json::to_string(&window).context("error formatting response")?;
println!("{window}");
return Ok(());
}
if let Some(window) = window {
print_window(&window);
} else {
println!("No window selected.");
}
}
Msg::PickColor => {
let Response::PickedColor(color) = response else {
bail!("unexpected response: expected PickedColor, got {response:?}");
};
if json {
let color = serde_json::to_string(&color).context("error formatting response")?;
println!("{color}");
return Ok(());
}
if let Some(color) = color {
let [r, g, b] = color.rgb.map(|v| (v.clamp(0., 1.) * 255.).round() as u8);
println!("Picked color: rgb({r}, {g}, {b})",);
println!("Hex: #{:02x}{:02x}{:02x}", r, g, b);
} else {
println!("No color was picked.");
}
}
Msg::Action { .. } => {
let Response::Handled = response else {
bail!("unexpected response: expected Handled, got {response:?}");
};
}
Msg::Output { output, .. } => {
let Response::OutputConfigChanged(response) = response else {
bail!("unexpected response: expected OutputConfigChanged, got {response:?}");
};
if json {
let response =
serde_json::to_string(&response).context("error formatting response")?;
println!("{response}");
return Ok(());
}
if response == OutputConfigChanged::OutputWasMissing {
println!("Output \"{output}\" is not connected.");
println!("The change will apply when it is connected.");
}
}
Msg::Workspaces => {
let Response::Workspaces(mut response) = response else {
bail!("unexpected response: expected Workspaces, got {response:?}");
};
if json {
let response =
serde_json::to_string(&response).context("error formatting response")?;
println!("{response}");
return Ok(());
}
if response.is_empty() {
println!("No workspaces.");
return Ok(());
}
response.sort_by_key(|ws| ws.idx);
response.sort_by(|a, b| a.output.cmp(&b.output));
let mut current_output = if let Some(output) = response[0].output.as_deref() {
println!("Output \"{output}\":");
Some(output)
} else {
println!("No output:");
None
};
for ws in &response {
if ws.output.as_deref() != current_output {
let output = ws.output.as_deref().context(
"invalid response: workspace with no output \
following a workspace with an output",
)?;
current_output = Some(output);
println!("\nOutput \"{output}\":");
}
let is_active = if ws.is_active { " * " } else { " " };
let idx = ws.idx;
let name = if let Some(name) = ws.name.as_deref() {
format!(" \"{name}\"")
} else {
String::new()
};
println!("{is_active}{idx}{name}");
}
}
Msg::KeyboardLayouts => {
let Response::KeyboardLayouts(response) = response else {
bail!("unexpected response: expected KeyboardLayouts, got {response:?}");
};
if json {
let response =
serde_json::to_string(&response).context("error formatting response")?;
println!("{response}");
return Ok(());
}
let KeyboardLayouts { names, current_idx } = response;
let current_idx = usize::from(current_idx);
println!("Keyboard layouts:");
for (idx, name) in names.iter().enumerate() {
let is_active = if idx == current_idx { " * " } else { " " };
println!("{is_active}{idx} {name}");
}
}
Msg::EventStream => {
let Response::Handled = response else {
bail!("unexpected response: expected Handled, got {response:?}");
};
if !json {
println!("Started reading events.");
}
let mut read_event = socket.read_events();
loop {
let event = read_event().context("error reading event from niri")?;
if json {
let event = serde_json::to_string(&event).context("error formatting event")?;
println!("{event}");
continue;
}
match event {
Event::WorkspacesChanged { workspaces } => {
println!("Workspaces changed: {workspaces:?}");
}
Event::WorkspaceUrgencyChanged { id, urgent } => {
println!("Workspace {id}: urgency changed to {urgent}");
}
Event::WorkspaceActivated { id, focused } => {
let word = if focused { "focused" } else { "activated" };
println!("Workspace {word}: {id}");
}
Event::WorkspaceActiveWindowChanged {
workspace_id,
active_window_id,
} => {
println!(
"Workspace {workspace_id}: \
active window changed to {active_window_id:?}"
);
}
Event::WindowsChanged { windows } => {
println!("Windows changed: {windows:?}");
}
Event::WindowOpenedOrChanged { window } => {
println!("Window opened or changed: {window:?}");
}
Event::WindowClosed { id } => {
println!("Window closed: {id}");
}
Event::WindowFocusChanged { id } => {
println!("Window focus changed: {id:?}");
}
Event::WindowUrgencyChanged { id, urgent } => {
println!("Window {id}: urgency changed to {urgent}");
}
Event::KeyboardLayoutsChanged { keyboard_layouts } => {
println!("Keyboard layouts changed: {keyboard_layouts:?}");
}
Event::KeyboardLayoutSwitched { idx } => {
println!("Keyboard layout switched: {idx}");
}
Event::OverviewOpenedOrClosed { is_open: opened } => {
println!("Overview toggled: {opened}");
}
}
}
}
Msg::OverviewState => {
let Response::OverviewState(response) = response else {
bail!("unexpected response: expected Overview, got {response:?}");
};
if json {
let response =
serde_json::to_string(&response).context("error formatting response")?;
println!("{response}");
return Ok(());
}
let Overview { is_open } = response;
if is_open {
println!("Overview is open.");
} else {
println!("Overview is closed.");
}
}
}
Ok(())
}
fn print_output(output: Output) -> anyhow::Result<()> {
let Output {
name,
make,
model,
serial,
physical_size,
modes,
current_mode,
vrr_supported,
vrr_enabled,
logical,
} = output;
let serial = serial.as_deref().unwrap_or("Unknown");
println!(r#"Output "{make} {model} {serial}" ({name})"#);
if let Some(current) = current_mode {
let mode = *modes
.get(current)
.context("invalid response: current mode does not exist")?;
let Mode {
width,
height,
refresh_rate,
is_preferred,
} = mode;
let refresh = refresh_rate as f64 / 1000.;
let preferred = if is_preferred { " (preferred)" } else { "" };
println!(" Current mode: {width}x{height} @ {refresh:.3} Hz{preferred}");
} else {
println!(" Disabled");
}
if vrr_supported {
let enabled = if vrr_enabled { "enabled" } else { "disabled" };
println!(" Variable refresh rate: supported, {enabled}");
} else {
println!(" Variable refresh rate: not supported");
}
if let Some((width, height)) = physical_size {
println!(" Physical size: {width}x{height} mm");
} else {
println!(" Physical size: unknown");
}
if let Some(logical) = logical {
let LogicalOutput {
x,
y,
width,
height,
scale,
transform,
} = logical;
println!(" Logical position: {x}, {y}");
println!(" Logical size: {width}x{height}");
println!(" Scale: {scale}");
let transform = match transform {
Transform::Normal => "normal",
Transform::_90 => "90° counter-clockwise",
Transform::_180 => "180°",
Transform::_270 => "270° counter-clockwise",
Transform::Flipped => "flipped horizontally",
Transform::Flipped90 => "90° counter-clockwise, flipped horizontally",
Transform::Flipped180 => "flipped vertically",
Transform::Flipped270 => "270° counter-clockwise, flipped horizontally",
};
println!(" Transform: {transform}");
}
println!(" Available modes:");
for (idx, mode) in modes.into_iter().enumerate() {
let Mode {
width,
height,
refresh_rate,
is_preferred,
} = mode;
let refresh = refresh_rate as f64 / 1000.;
let is_current = Some(idx) == current_mode;
let qualifier = match (is_current, is_preferred) {
(true, true) => " (current, preferred)",
(true, false) => " (current)",
(false, true) => " (preferred)",
(false, false) => "",
};
println!(" {width}x{height}@{refresh:.3}{qualifier}");
}
Ok(())
}
fn print_window(window: &Window) {
let focused = if window.is_focused { " (focused)" } else { "" };
let urgent = if window.is_urgent { " (urgent)" } else { "" };
println!("Window ID {}:{focused}{urgent}", window.id);
if let Some(title) = &window.title {
println!(" Title: \"{title}\"");
} else {
println!(" Title: (unset)");
}
if let Some(app_id) = &window.app_id {
println!(" App ID: \"{app_id}\"");
} else {
println!(" App ID: (unset)");
}
println!(
" Is floating: {}",
if window.is_floating { "yes" } else { "no" }
);
if let Some(pid) = window.pid {
println!(" PID: {pid}");
} else {
println!(" PID: (unknown)");
}
if let Some(workspace_id) = window.workspace_id {
println!(" Workspace ID: {workspace_id}");
} else {
println!(" Workspace ID: (none)");
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod client;
pub mod server;
+742
View File
@@ -0,0 +1,742 @@
use std::cell::RefCell;
use std::collections::HashSet;
use std::ffi::OsStr;
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::{env, io, process};
use anyhow::Context;
use async_channel::{Receiver, Sender, TrySendError};
use calloop::futures::Scheduler;
use calloop::io::Async;
use directories::BaseDirs;
use futures_util::io::{AsyncReadExt, BufReader};
use futures_util::{select_biased, AsyncBufReadExt, AsyncWrite, AsyncWriteExt, FutureExt as _};
use niri_config::OutputName;
use niri_ipc::state::{EventStreamState, EventStreamStatePart as _};
use niri_ipc::{
Event, KeyboardLayouts, OutputConfigChanged, Overview, Reply, Request, Response, Workspace,
};
use smithay::desktop::layer_map_for_output;
use smithay::input::pointer::{
CursorIcon, CursorImageStatus, Focus, GrabStartData as PointerGrabStartData,
};
use smithay::reexports::calloop::generic::Generic;
use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
use smithay::reexports::rustix::fs::unlink;
use smithay::utils::SERIAL_COUNTER;
use smithay::wayland::shell::wlr_layer::{KeyboardInteractivity, Layer};
use crate::backend::IpcOutputMap;
use crate::input::pick_window_grab::PickWindowGrab;
use crate::layout::workspace::WorkspaceId;
use crate::niri::State;
use crate::utils::{version, with_toplevel_role};
use crate::window::Mapped;
// If an event stream client fails to read events fast enough that we accumulate more than this
// number in our buffer, we drop that event stream client.
const EVENT_STREAM_BUFFER_SIZE: usize = 64;
pub struct IpcServer {
/// Path to the IPC socket.
///
/// This is `None` when creating `IpcServer` without a socket.
pub socket_path: Option<PathBuf>,
event_streams: Rc<RefCell<Vec<EventStreamSender>>>,
event_stream_state: Rc<RefCell<EventStreamState>>,
}
struct ClientCtx {
event_loop: LoopHandle<'static, State>,
scheduler: Scheduler<()>,
ipc_outputs: Arc<Mutex<IpcOutputMap>>,
event_streams: Rc<RefCell<Vec<EventStreamSender>>>,
event_stream_state: Rc<RefCell<EventStreamState>>,
}
struct EventStreamClient {
events: Receiver<Event>,
disconnect: Receiver<()>,
write: Box<dyn AsyncWrite + Unpin>,
}
struct EventStreamSender {
events: Sender<Event>,
disconnect: Sender<()>,
}
impl IpcServer {
pub fn start(
event_loop: &LoopHandle<'static, State>,
wayland_socket_name: Option<&OsStr>,
) -> anyhow::Result<Self> {
let _span = tracy_client::span!("Ipc::start");
let socket_path = if let Some(wayland_socket_name) = wayland_socket_name {
let wayland_socket_name = wayland_socket_name.to_string_lossy();
let socket_name = format!("niri.{wayland_socket_name}.{}.sock", process::id());
let mut socket_path = socket_dir();
socket_path.push(socket_name);
let listener = UnixListener::bind(&socket_path).context("error binding socket")?;
listener
.set_nonblocking(true)
.context("error setting socket to non-blocking")?;
let source = Generic::new(listener, Interest::READ, Mode::Level);
event_loop
.insert_source(source, |_, socket, state| {
match socket.accept() {
Ok((stream, _)) => on_new_ipc_client(state, stream),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => (),
Err(e) => return Err(e),
}
Ok(PostAction::Continue)
})
.unwrap();
Some(socket_path)
} else {
None
};
Ok(Self {
socket_path,
event_streams: Rc::new(RefCell::new(Vec::new())),
event_stream_state: Rc::new(RefCell::new(EventStreamState::default())),
})
}
fn send_event(&self, event: Event) {
let mut streams = self.event_streams.borrow_mut();
let mut to_remove = Vec::new();
for (idx, stream) in streams.iter_mut().enumerate() {
match stream.events.try_send(event.clone()) {
Ok(()) => (),
Err(TrySendError::Closed(_)) => to_remove.push(idx),
Err(TrySendError::Full(_)) => {
warn!(
"disconnecting IPC event stream client \
because it is reading events too slowly"
);
to_remove.push(idx);
}
}
}
for idx in to_remove.into_iter().rev() {
let stream = streams.swap_remove(idx);
let _ = stream.disconnect.send_blocking(());
}
}
}
impl Drop for IpcServer {
fn drop(&mut self) {
if let Some(socket_path) = &self.socket_path {
let _ = unlink(socket_path);
}
}
}
fn socket_dir() -> PathBuf {
BaseDirs::new()
.as_ref()
.and_then(|x| x.runtime_dir())
.map(|x| x.to_owned())
.unwrap_or_else(env::temp_dir)
}
fn on_new_ipc_client(state: &mut State, stream: UnixStream) {
let _span = tracy_client::span!("on_new_ipc_client");
trace!("new IPC client connected");
let stream = match state.niri.event_loop.adapt_io(stream) {
Ok(stream) => stream,
Err(err) => {
warn!("error making IPC stream async: {err:?}");
return;
}
};
let ipc_server = state.niri.ipc_server.as_ref().unwrap();
let ctx = ClientCtx {
event_loop: state.niri.event_loop.clone(),
scheduler: state.niri.scheduler.clone(),
ipc_outputs: state.backend.ipc_outputs(),
event_streams: ipc_server.event_streams.clone(),
event_stream_state: ipc_server.event_stream_state.clone(),
};
let future = async move {
if let Err(err) = handle_client(ctx, stream).await {
warn!("error handling IPC client: {err:?}");
}
};
if let Err(err) = state.niri.scheduler.schedule(future) {
warn!("error scheduling IPC stream future: {err:?}");
}
}
async fn handle_client(ctx: ClientCtx, stream: Async<'static, UnixStream>) -> anyhow::Result<()> {
let (read, mut write) = stream.split();
let mut read = BufReader::new(read);
loop {
// Don't keep buf around to avoid clients wasting RAM by filling it with bogus data.
let mut buf = Vec::new();
let res = read.read_until(b'\n', &mut buf).await;
match res {
Ok(0) => return Ok(()),
Ok(_) => (),
// Normal client disconnection.
Err(err) if err.kind() == io::ErrorKind::BrokenPipe => return Ok(()),
Err(err) => {
return Err(err).context("error reading request");
}
}
let request = serde_json::from_slice(&buf)
.context("error parsing request")
.map_err(|err| err.to_string());
let requested_error = matches!(request, Ok(Request::ReturnError));
let requested_event_stream = matches!(request, Ok(Request::EventStream));
let reply = match request {
Ok(request) => process(&ctx, request).await,
Err(err) => Err(err),
};
if let Err(err) = &reply {
if !requested_error {
warn!("error processing IPC request: {err:?}");
}
}
buf.clear();
serde_json::to_writer(&mut buf, &reply).context("error formatting reply")?;
buf.push(b'\n');
write.write_all(&buf).await.context("error writing reply")?;
if requested_event_stream {
let (events_tx, events_rx) = async_channel::bounded(EVENT_STREAM_BUFFER_SIZE);
let (disconnect_tx, disconnect_rx) = async_channel::bounded(1);
// Spawn a task for the client.
let client = EventStreamClient {
events: events_rx,
disconnect: disconnect_rx,
write: Box::new(write) as _,
};
let future = async move {
if let Err(err) = handle_event_stream_client(client).await {
warn!("error handling IPC event stream client: {err:?}");
}
};
if let Err(err) = ctx.scheduler.schedule(future) {
warn!("error scheduling IPC event stream future: {err:?}");
}
// Send the initial state.
{
let state = ctx.event_stream_state.borrow();
for event in state.replicate() {
events_tx
.try_send(event)
.expect("initial event burst had more events than buffer size");
}
}
// Add it to the list.
{
let mut streams = ctx.event_streams.borrow_mut();
let sender = EventStreamSender {
events: events_tx,
disconnect: disconnect_tx,
};
streams.push(sender);
}
return Ok(());
}
}
}
async fn process(ctx: &ClientCtx, request: Request) -> Reply {
let response = match request {
Request::ReturnError => return Err(String::from("example compositor error")),
Request::Version => Response::Version(version()),
Request::Outputs => {
let ipc_outputs = ctx.ipc_outputs.lock().unwrap().clone();
let outputs = ipc_outputs.values().cloned().map(|o| (o.name.clone(), o));
Response::Outputs(outputs.collect())
}
Request::Workspaces => {
let state = ctx.event_stream_state.borrow();
let workspaces = state.workspaces.workspaces.values().cloned().collect();
Response::Workspaces(workspaces)
}
Request::Windows => {
let state = ctx.event_stream_state.borrow();
let windows = state.windows.windows.values().cloned().collect();
Response::Windows(windows)
}
Request::Layers => {
let (tx, rx) = async_channel::bounded(1);
ctx.event_loop.insert_idle(move |state| {
let mut layers = Vec::new();
for output in state.niri.global_space.outputs() {
let name = output.name();
for surface in layer_map_for_output(output).layers() {
let layer = match surface.layer() {
Layer::Background => niri_ipc::Layer::Background,
Layer::Bottom => niri_ipc::Layer::Bottom,
Layer::Top => niri_ipc::Layer::Top,
Layer::Overlay => niri_ipc::Layer::Overlay,
};
let keyboard_interactivity =
match surface.cached_state().keyboard_interactivity {
KeyboardInteractivity::None => {
niri_ipc::LayerSurfaceKeyboardInteractivity::None
}
KeyboardInteractivity::Exclusive => {
niri_ipc::LayerSurfaceKeyboardInteractivity::Exclusive
}
KeyboardInteractivity::OnDemand => {
niri_ipc::LayerSurfaceKeyboardInteractivity::OnDemand
}
};
layers.push(niri_ipc::LayerSurface {
namespace: surface.namespace().to_owned(),
output: name.clone(),
layer,
keyboard_interactivity,
});
}
}
let _ = tx.send_blocking(layers);
});
let result = rx.recv().await;
let layers = result.map_err(|_| String::from("error getting layers info"))?;
Response::Layers(layers)
}
Request::KeyboardLayouts => {
let state = ctx.event_stream_state.borrow();
let layout = state.keyboard_layouts.keyboard_layouts.clone();
let layout = layout.expect("keyboard layouts should be set at startup");
Response::KeyboardLayouts(layout)
}
Request::FocusedWindow => {
let state = ctx.event_stream_state.borrow();
let windows = &state.windows.windows;
let window = windows.values().find(|win| win.is_focused).cloned();
Response::FocusedWindow(window)
}
Request::PickWindow => {
let (tx, rx) = async_channel::bounded(1);
ctx.event_loop.insert_idle(move |state| {
let pointer = state.niri.seat.get_pointer().unwrap();
let start_data = PointerGrabStartData {
focus: None,
button: 0,
location: pointer.current_location(),
};
let grab = PickWindowGrab::new(start_data);
// The `WindowPickGrab` ungrab handler will cancel the previous ongoing pick, if
// any.
pointer.set_grab(state, grab, SERIAL_COUNTER.next_serial(), Focus::Clear);
state.niri.pick_window = Some(tx);
state
.niri
.cursor_manager
.set_cursor_image(CursorImageStatus::Named(CursorIcon::Crosshair));
// Redraw to update the cursor.
state.niri.queue_redraw_all();
});
let result = rx.recv().await;
let id = result.map_err(|_| String::from("error getting picked window info"))?;
let window = id.and_then(|id| {
let state = ctx.event_stream_state.borrow();
state.windows.windows.get(&id.get()).cloned()
});
Response::PickedWindow(window)
}
Request::PickColor => {
let (tx, rx) = async_channel::bounded(1);
ctx.event_loop.insert_idle(move |state| {
state.handle_pick_color(tx);
});
let result = rx.recv().await;
let color = result.map_err(|_| String::from("error getting picked color"))?;
Response::PickedColor(color)
}
Request::Action(action) => {
let (tx, rx) = async_channel::bounded(1);
let action = niri_config::Action::from(action);
ctx.event_loop.insert_idle(move |state| {
// Make sure some logic like workspace clean-up has a chance to run before doing
// actions.
state.niri.advance_animations();
state.do_action(action, false);
let _ = tx.send_blocking(());
});
// Wait until the action has been processed before returning. This is important for a
// few actions, for instance for DoScreenTransition this wait ensures that the screen
// contents were sampled into the texture.
let _ = rx.recv().await;
Response::Handled
}
Request::Output { output, action } => {
let ipc_outputs = ctx.ipc_outputs.lock().unwrap();
let found = ipc_outputs
.values()
.any(|o| OutputName::from_ipc_output(o).matches(&output));
let response = if found {
OutputConfigChanged::Applied
} else {
OutputConfigChanged::OutputWasMissing
};
drop(ipc_outputs);
ctx.event_loop.insert_idle(move |state| {
state.apply_transient_output_config(&output, action);
});
Response::OutputConfigChanged(response)
}
Request::FocusedOutput => {
let (tx, rx) = async_channel::bounded(1);
ctx.event_loop.insert_idle(move |state| {
let active_output = state
.niri
.layout
.active_output()
.map(|output| output.name());
let output = active_output.and_then(|active_output| {
state
.backend
.ipc_outputs()
.lock()
.unwrap()
.values()
.find(|o| o.name == active_output)
.cloned()
});
let _ = tx.send_blocking(output);
});
let result = rx.recv().await;
let output = result.map_err(|_| String::from("error getting active output info"))?;
Response::FocusedOutput(output)
}
Request::EventStream => Response::Handled,
Request::OverviewState => {
let state = ctx.event_stream_state.borrow();
let is_open = state.overview.is_open;
Response::OverviewState(Overview { is_open })
}
};
Ok(response)
}
async fn handle_event_stream_client(client: EventStreamClient) -> anyhow::Result<()> {
let EventStreamClient {
events,
disconnect,
mut write,
} = client;
while let Ok(event) = events.recv().await {
let mut buf = serde_json::to_vec(&event).context("error formatting event")?;
buf.push(b'\n');
let res = select_biased! {
_ = disconnect.recv().fuse() => return Ok(()),
res = write.write_all(&buf).fuse() => res,
};
match res {
Ok(()) => (),
// Normal client disconnection.
Err(err) if err.kind() == io::ErrorKind::BrokenPipe => return Ok(()),
res @ Err(_) => res.context("error writing event")?,
}
}
Ok(())
}
fn make_ipc_window(mapped: &Mapped, workspace_id: Option<WorkspaceId>) -> niri_ipc::Window {
with_toplevel_role(mapped.toplevel(), |role| niri_ipc::Window {
id: mapped.id().get(),
title: role.title.clone(),
app_id: role.app_id.clone(),
pid: mapped.credentials().map(|c| c.pid),
workspace_id: workspace_id.map(|id| id.get()),
is_focused: mapped.is_focused(),
is_floating: mapped.is_floating(),
is_urgent: mapped.is_urgent(),
})
}
impl State {
pub fn ipc_keyboard_layouts_changed(&mut self) {
let keyboard = self.niri.seat.get_keyboard().unwrap();
let keyboard_layouts = keyboard.with_xkb_state(self, |context| {
let xkb = context.xkb().lock().unwrap();
let layouts = xkb.layouts();
KeyboardLayouts {
names: layouts
.map(|layout| xkb.layout_name(layout).to_owned())
.collect(),
current_idx: xkb.active_layout().0 as u8,
}
});
let Some(server) = &self.niri.ipc_server else {
return;
};
let mut state = server.event_stream_state.borrow_mut();
let state = &mut state.keyboard_layouts;
let event = Event::KeyboardLayoutsChanged { keyboard_layouts };
state.apply(event.clone());
server.send_event(event);
}
pub fn ipc_refresh_keyboard_layout_index(&mut self) {
let keyboard = self.niri.seat.get_keyboard().unwrap();
let idx = keyboard.with_xkb_state(self, |context| {
let xkb = context.xkb().lock().unwrap();
xkb.active_layout().0 as u8
});
let Some(server) = &self.niri.ipc_server else {
return;
};
let mut state = server.event_stream_state.borrow_mut();
let state = &mut state.keyboard_layouts;
if state.keyboard_layouts.as_ref().unwrap().current_idx == idx {
return;
}
let event = Event::KeyboardLayoutSwitched { idx };
state.apply(event.clone());
server.send_event(event);
}
pub fn ipc_refresh_layout(&mut self) {
self.ipc_refresh_workspaces();
self.ipc_refresh_windows();
self.ipc_refresh_overview();
}
fn ipc_refresh_workspaces(&mut self) {
let Some(server) = &self.niri.ipc_server else {
return;
};
let _span = tracy_client::span!("State::ipc_refresh_workspaces");
let mut state = server.event_stream_state.borrow_mut();
let state = &mut state.workspaces;
let mut events = Vec::new();
let layout = &self.niri.layout;
let focused_ws_id = layout.active_workspace().map(|ws| ws.id().get());
// Check for workspace changes.
let mut seen = HashSet::new();
let mut need_workspaces_changed = false;
for (mon, ws_idx, ws) in layout.workspaces() {
let id = ws.id().get();
seen.insert(id);
let Some(ipc_ws) = state.workspaces.get(&id) else {
// A new workspace was added.
need_workspaces_changed = true;
break;
};
// Check for any changes that we can't signal as individual events.
let output_name = mon.map(|mon| mon.output_name());
if ipc_ws.idx != u8::try_from(ws_idx + 1).unwrap_or(u8::MAX)
|| ipc_ws.name.as_ref() != ws.name()
|| ipc_ws.output.as_ref() != output_name
{
need_workspaces_changed = true;
break;
}
let active_window_id = ws.active_window().map(|win| win.id().get());
if ipc_ws.active_window_id != active_window_id {
events.push(Event::WorkspaceActiveWindowChanged {
workspace_id: id,
active_window_id,
});
}
// Check if this workspace urgent state changed.
let urgent = ws.is_urgent();
if urgent != ipc_ws.is_urgent {
events.push(Event::WorkspaceUrgencyChanged { id, urgent });
}
// Check if this workspace became focused.
let is_focused = Some(id) == focused_ws_id;
if is_focused && !ipc_ws.is_focused {
events.push(Event::WorkspaceActivated { id, focused: true });
continue;
}
// Check if this workspace became active.
let is_active = mon.is_some_and(|mon| mon.active_workspace_idx() == ws_idx);
if is_active && !ipc_ws.is_active {
events.push(Event::WorkspaceActivated { id, focused: false });
}
}
// Check if any workspaces were removed.
if !need_workspaces_changed && state.workspaces.keys().any(|id| !seen.contains(id)) {
need_workspaces_changed = true;
}
if need_workspaces_changed {
events.clear();
let workspaces = layout
.workspaces()
.map(|(mon, ws_idx, ws)| {
let id = ws.id().get();
Workspace {
id,
idx: u8::try_from(ws_idx + 1).unwrap_or(u8::MAX),
name: ws.name().cloned(),
output: mon.map(|mon| mon.output_name().clone()),
is_urgent: ws.is_urgent(),
is_active: mon.is_some_and(|mon| mon.active_workspace_idx() == ws_idx),
is_focused: Some(id) == focused_ws_id,
active_window_id: ws.active_window().map(|win| win.id().get()),
}
})
.collect();
events.push(Event::WorkspacesChanged { workspaces });
}
for event in events {
state.apply(event.clone());
server.send_event(event);
}
}
fn ipc_refresh_windows(&mut self) {
let Some(server) = &self.niri.ipc_server else {
return;
};
let _span = tracy_client::span!("State::ipc_refresh_windows");
let mut state = server.event_stream_state.borrow_mut();
let state = &mut state.windows;
let mut events = Vec::new();
let layout = &self.niri.layout;
// Check for window changes.
let mut seen = HashSet::new();
let mut focused_id = None;
layout.with_windows(|mapped, _, ws_id| {
let id = mapped.id().get();
seen.insert(id);
if mapped.is_focused() {
focused_id = Some(id);
}
let Some(ipc_win) = state.windows.get(&id) else {
let window = make_ipc_window(mapped, ws_id);
events.push(Event::WindowOpenedOrChanged { window });
return;
};
let workspace_id = ws_id.map(|id| id.get());
let mut changed =
ipc_win.workspace_id != workspace_id || ipc_win.is_floating != mapped.is_floating();
changed |= with_toplevel_role(mapped.toplevel(), |role| {
ipc_win.title != role.title || ipc_win.app_id != role.app_id
});
if changed {
let window = make_ipc_window(mapped, ws_id);
events.push(Event::WindowOpenedOrChanged { window });
return;
}
if mapped.is_focused() && !ipc_win.is_focused {
events.push(Event::WindowFocusChanged { id: Some(id) });
}
let urgent = mapped.is_urgent();
if urgent != ipc_win.is_urgent {
events.push(Event::WindowUrgencyChanged { id, urgent })
}
});
// Check for closed windows.
let mut ipc_focused_id = None;
for (id, ipc_win) in &state.windows {
if !seen.contains(id) {
events.push(Event::WindowClosed { id: *id });
}
if ipc_win.is_focused {
ipc_focused_id = Some(id);
}
}
// Extra check for focus becoming None, since the checks above only work for focus becoming
// a different window.
if focused_id.is_none() && ipc_focused_id.is_some() {
events.push(Event::WindowFocusChanged { id: None });
}
for event in events {
state.apply(event.clone());
server.send_event(event);
}
}
pub fn ipc_refresh_overview(&mut self) {
let Some(server) = &self.niri.ipc_server else {
return;
};
let mut state = server.event_stream_state.borrow_mut();
let state = &mut state.overview;
let is_open = self.niri.layout.is_overview_open();
if state.is_open == is_open {
return;
}
let event = Event::OverviewOpenedOrClosed { is_open };
state.apply(event.clone());
server.send_event(event);
}
}
+218
View File
@@ -0,0 +1,218 @@
use niri_config::layer_rule::LayerRule;
use niri_config::Config;
use smithay::backend::renderer::element::surface::{
render_elements_from_surface_tree, WaylandSurfaceRenderElement,
};
use smithay::backend::renderer::element::Kind;
use smithay::desktop::{LayerSurface, PopupManager};
use smithay::utils::{Logical, Point, Scale, Size};
use smithay::wayland::shell::wlr_layer::{ExclusiveZone, Layer};
use super::ResolvedLayerRules;
use crate::animation::Clock;
use crate::layout::shadow::Shadow;
use crate::niri_render_elements;
use crate::render_helpers::renderer::NiriRenderer;
use crate::render_helpers::shadow::ShadowRenderElement;
use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
use crate::render_helpers::{RenderTarget, SplitElements};
use crate::utils::{baba_is_float_offset, round_logical_in_physical};
#[derive(Debug)]
pub struct MappedLayer {
/// The surface itself.
surface: LayerSurface,
/// Up-to-date rules.
rules: ResolvedLayerRules,
/// Buffer to draw instead of the surface when it should be blocked out.
block_out_buffer: SolidColorBuffer,
/// The shadow around the surface.
shadow: Shadow,
/// The view size for the layer surface's output.
view_size: Size<f64, Logical>,
/// Scale of the output the layer surface is on (and rounds its sizes to).
scale: f64,
/// Clock for driving animations.
clock: Clock,
}
niri_render_elements! {
LayerSurfaceRenderElement<R> => {
Wayland = WaylandSurfaceRenderElement<R>,
SolidColor = SolidColorRenderElement,
Shadow = ShadowRenderElement,
}
}
impl MappedLayer {
pub fn new(
surface: LayerSurface,
rules: ResolvedLayerRules,
view_size: Size<f64, Logical>,
scale: f64,
clock: Clock,
config: &Config,
) -> Self {
let mut shadow_config = config.layout.shadow;
// Shadows for layer surfaces need to be explicitly enabled.
shadow_config.on = false;
let shadow_config = rules.shadow.resolve_against(shadow_config);
Self {
surface,
rules,
block_out_buffer: SolidColorBuffer::new((0., 0.), [0., 0., 0., 1.]),
view_size,
scale,
shadow: Shadow::new(shadow_config),
clock,
}
}
pub fn update_config(&mut self, config: &Config) {
let mut shadow_config = config.layout.shadow;
// Shadows for layer surfaces need to be explicitly enabled.
shadow_config.on = false;
let shadow_config = self.rules.shadow.resolve_against(shadow_config);
self.shadow.update_config(shadow_config);
}
pub fn update_shaders(&mut self) {
self.shadow.update_shaders();
}
pub fn update_sizes(&mut self, view_size: Size<f64, Logical>, scale: f64) {
self.view_size = view_size;
self.scale = scale;
}
pub fn update_render_elements(&mut self, size: Size<f64, Logical>) {
// Round to physical pixels.
let size = size
.to_physical_precise_round(self.scale)
.to_logical(self.scale);
self.block_out_buffer.resize(size);
let radius = self.rules.geometry_corner_radius.unwrap_or_default();
// FIXME: is_active based on keyboard focus?
self.shadow
.update_render_elements(size, true, radius, self.scale, 1.);
}
pub fn are_animations_ongoing(&self) -> bool {
self.rules.baba_is_float
}
pub fn surface(&self) -> &LayerSurface {
&self.surface
}
pub fn rules(&self) -> &ResolvedLayerRules {
&self.rules
}
/// Recomputes the resolved layer rules and returns whether they changed.
pub fn recompute_layer_rules(&mut self, rules: &[LayerRule], is_at_startup: bool) -> bool {
let new_rules = ResolvedLayerRules::compute(rules, &self.surface, is_at_startup);
if new_rules == self.rules {
return false;
}
self.rules = new_rules;
true
}
pub fn place_within_backdrop(&self) -> bool {
if !self.rules.place_within_backdrop {
return false;
}
if self.surface.layer() != Layer::Background {
return false;
}
let state = self.surface.cached_state();
if state.exclusive_zone != ExclusiveZone::DontCare {
return false;
}
true
}
pub fn bob_offset(&self) -> Point<f64, Logical> {
if !self.rules.baba_is_float {
return Point::from((0., 0.));
}
let y = baba_is_float_offset(self.clock.now(), self.view_size.h);
let y = round_logical_in_physical(self.scale, y);
Point::from((0., y))
}
pub fn render<R: NiriRenderer>(
&self,
renderer: &mut R,
location: Point<f64, Logical>,
target: RenderTarget,
) -> SplitElements<LayerSurfaceRenderElement<R>> {
let mut rv = SplitElements::default();
let scale = Scale::from(self.scale);
let alpha = self.rules.opacity.unwrap_or(1.).clamp(0., 1.);
let location = location + self.bob_offset();
if target.should_block_out(self.rules.block_out_from) {
// Round to physical pixels.
let location = location.to_physical_precise_round(scale).to_logical(scale);
// FIXME: take geometry-corner-radius into account.
let elem = SolidColorRenderElement::from_buffer(
&self.block_out_buffer,
location,
alpha,
Kind::Unspecified,
);
rv.normal.push(elem.into());
} else {
// Layer surfaces don't have extra geometry like windows.
let buf_pos = location;
let surface = self.surface.wl_surface();
for (popup, popup_offset) in PopupManager::popups_for_surface(surface) {
// Layer surfaces don't have extra geometry like windows.
let offset = popup_offset - popup.geometry().loc;
rv.popups.extend(render_elements_from_surface_tree(
renderer,
popup.wl_surface(),
(buf_pos + offset.to_f64()).to_physical_precise_round(scale),
scale,
alpha,
Kind::Unspecified,
));
}
rv.normal = render_elements_from_surface_tree(
renderer,
surface,
buf_pos.to_physical_precise_round(scale),
scale,
alpha,
Kind::Unspecified,
);
}
let location = location.to_physical_precise_round(scale).to_logical(scale);
rv.normal
.extend(self.shadow.render(renderer, location).map(Into::into));
rv
}
}
+106
View File
@@ -0,0 +1,106 @@
use niri_config::layer_rule::{LayerRule, Match};
use niri_config::{BlockOutFrom, CornerRadius, ShadowRule};
use smithay::desktop::LayerSurface;
pub mod mapped;
pub use mapped::MappedLayer;
/// Rules fully resolved for a layer-shell surface.
#[derive(Debug, PartialEq)]
pub struct ResolvedLayerRules {
/// Extra opacity to draw this layer surface with.
pub opacity: Option<f32>,
/// Whether to block out this layer surface from certain render targets.
pub block_out_from: Option<BlockOutFrom>,
/// Shadow overrides.
pub shadow: ShadowRule,
/// Corner radius to assume this layer surface has.
pub geometry_corner_radius: Option<CornerRadius>,
/// Whether to place this layer surface within the overview backdrop.
pub place_within_backdrop: bool,
/// Whether to bob this window up and down.
pub baba_is_float: bool,
}
impl ResolvedLayerRules {
pub const fn empty() -> Self {
Self {
opacity: None,
block_out_from: None,
shadow: ShadowRule {
off: false,
on: false,
offset: None,
softness: None,
spread: None,
draw_behind_window: None,
color: None,
inactive_color: None,
},
geometry_corner_radius: None,
place_within_backdrop: false,
baba_is_float: false,
}
}
pub fn compute(rules: &[LayerRule], surface: &LayerSurface, is_at_startup: bool) -> Self {
let _span = tracy_client::span!("ResolvedLayerRules::compute");
let mut resolved = ResolvedLayerRules::empty();
for rule in rules {
let matches = |m: &Match| {
if let Some(at_startup) = m.at_startup {
if at_startup != is_at_startup {
return false;
}
}
surface_matches(surface, m)
};
if !(rule.matches.is_empty() || rule.matches.iter().any(matches)) {
continue;
}
if rule.excludes.iter().any(matches) {
continue;
}
if let Some(x) = rule.opacity {
resolved.opacity = Some(x);
}
if let Some(x) = rule.block_out_from {
resolved.block_out_from = Some(x);
}
if let Some(x) = rule.geometry_corner_radius {
resolved.geometry_corner_radius = Some(x);
}
if let Some(x) = rule.place_within_backdrop {
resolved.place_within_backdrop = x;
}
if let Some(x) = rule.baba_is_float {
resolved.baba_is_float = x;
}
resolved.shadow.merge_with(&rule.shadow);
}
resolved
}
}
fn surface_matches(surface: &LayerSurface, m: &Match) -> bool {
if let Some(namespace_re) = &m.namespace {
if !namespace_re.0.is_match(surface.namespace()) {
return false;
}
}
true
}
+275
View File
@@ -0,0 +1,275 @@
use std::collections::HashMap;
use anyhow::Context as _;
use glam::{Mat3, Vec2};
use niri_config::BlockOutFrom;
use smithay::backend::allocator::Fourcc;
use smithay::backend::renderer::element::utils::{
Relocate, RelocateRenderElement, RescaleRenderElement,
};
use smithay::backend::renderer::element::{Kind, RenderElement};
use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture, Uniform};
use smithay::backend::renderer::Texture;
use smithay::utils::{Logical, Point, Rectangle, Scale, Size, Transform};
use smithay::wayland::compositor::{Blocker, BlockerState};
use crate::animation::Animation;
use crate::niri_render_elements;
use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;
use crate::render_helpers::shader_element::ShaderRenderElement;
use crate::render_helpers::shaders::{mat3_uniform, ProgramType, Shaders};
use crate::render_helpers::snapshot::RenderSnapshot;
use crate::render_helpers::texture::{TextureBuffer, TextureRenderElement};
use crate::render_helpers::{render_to_encompassing_texture, RenderTarget};
use crate::utils::transaction::TransactionBlocker;
#[derive(Debug)]
pub struct ClosingWindow {
/// Contents of the window.
buffer: TextureBuffer<GlesTexture>,
/// Blocked-out contents of the window.
blocked_out_buffer: TextureBuffer<GlesTexture>,
/// Where the window should be blocked out from.
block_out_from: Option<BlockOutFrom>,
/// Size of the window geometry.
geo_size: Size<f64, Logical>,
/// Position in the workspace.
pos: Point<f64, Logical>,
/// How much the texture should be offset.
buffer_offset: Point<f64, Logical>,
/// How much the blocked-out texture should be offset.
blocked_out_buffer_offset: Point<f64, Logical>,
/// The closing animation.
anim_state: AnimationState,
/// Random seed for the shader.
random_seed: f32,
}
niri_render_elements! {
ClosingWindowRenderElement => {
Texture = RelocateRenderElement<RescaleRenderElement<PrimaryGpuTextureRenderElement>>,
Shader = ShaderRenderElement,
}
}
#[derive(Debug)]
enum AnimationState {
Waiting {
/// Blocker for a transaction before starting the animation.
blocker: TransactionBlocker,
anim: Animation,
},
Animating(Animation),
}
impl AnimationState {
pub fn new(blocker: TransactionBlocker, anim: Animation) -> Self {
if blocker.state() == BlockerState::Pending {
Self::Waiting { blocker, anim }
} else {
// This actually doesn't normally happen because the window is removed only after the
// closing animation is created. Though, it does happen with disable-transactions debug
// flag.
Self::Animating(anim)
}
}
}
impl ClosingWindow {
pub fn new<E: RenderElement<GlesRenderer>>(
renderer: &mut GlesRenderer,
snapshot: RenderSnapshot<E, E>,
scale: Scale<f64>,
geo_size: Size<f64, Logical>,
pos: Point<f64, Logical>,
blocker: TransactionBlocker,
anim: Animation,
) -> anyhow::Result<Self> {
let _span = tracy_client::span!("ClosingWindow::new");
let mut render_to_texture = |elements: Vec<E>| -> anyhow::Result<_> {
let (texture, _sync_point, geo) = render_to_encompassing_texture(
renderer,
scale,
Transform::Normal,
Fourcc::Abgr8888,
&elements,
)
.context("error rendering to texture")?;
let buffer = TextureBuffer::from_texture(
renderer,
texture,
scale,
Transform::Normal,
Vec::new(),
);
let offset = geo.loc.to_f64().to_logical(scale);
Ok((buffer, offset))
};
let (buffer, buffer_offset) =
render_to_texture(snapshot.contents).context("error rendering contents")?;
let (blocked_out_buffer, blocked_out_buffer_offset) =
render_to_texture(snapshot.blocked_out_contents)
.context("error rendering blocked-out contents")?;
Ok(Self {
buffer,
blocked_out_buffer,
block_out_from: snapshot.block_out_from,
geo_size,
pos,
buffer_offset,
blocked_out_buffer_offset,
anim_state: AnimationState::new(blocker, anim),
random_seed: fastrand::f32(),
})
}
pub fn advance_animations(&mut self) {
match &mut self.anim_state {
AnimationState::Waiting { blocker, anim } => {
if blocker.state() != BlockerState::Pending {
let anim = anim.restarted(0., 1., 0.);
self.anim_state = AnimationState::Animating(anim);
}
}
AnimationState::Animating(_anim) => (),
}
}
pub fn are_animations_ongoing(&self) -> bool {
match &self.anim_state {
AnimationState::Waiting { .. } => true,
AnimationState::Animating(anim) => !anim.is_done(),
}
}
pub fn render(
&self,
renderer: &mut GlesRenderer,
view_rect: Rectangle<f64, Logical>,
scale: Scale<f64>,
target: RenderTarget,
) -> ClosingWindowRenderElement {
let (buffer, offset) = if target.should_block_out(self.block_out_from) {
(&self.blocked_out_buffer, self.blocked_out_buffer_offset)
} else {
(&self.buffer, self.buffer_offset)
};
let anim = match &self.anim_state {
AnimationState::Waiting { .. } => {
let elem = TextureRenderElement::from_texture_buffer(
buffer.clone(),
Point::from((0., 0.)),
1.,
None,
None,
Kind::Unspecified,
);
let elem = PrimaryGpuTextureRenderElement(elem);
let elem = RescaleRenderElement::from_element(elem, Point::from((0, 0)), 1.);
let mut location = self.pos + offset;
location.x -= view_rect.loc.x;
let elem = RelocateRenderElement::from_element(
elem,
location.to_physical_precise_round(scale),
Relocate::Relative,
);
return elem.into();
}
AnimationState::Animating(anim) => anim,
};
let progress = anim.value();
let clamped_progress = anim.clamped_value().clamp(0., 1.);
if Shaders::get(renderer).program(ProgramType::Close).is_some() {
let area_loc = Vec2::new(view_rect.loc.x as f32, view_rect.loc.y as f32);
let area_size = Vec2::new(view_rect.size.w as f32, view_rect.size.h as f32);
// Round to physical pixels relative to the view position. This is similar to what
// happens when rendering normal windows.
let relative = self.pos - view_rect.loc;
let pos = view_rect.loc + relative.to_physical_precise_round(scale).to_logical(scale);
let geo_loc = Vec2::new(pos.x as f32, pos.y as f32);
let geo_size = Vec2::new(self.geo_size.w as f32, self.geo_size.h as f32);
let input_to_geo = Mat3::from_scale(area_size / geo_size)
* Mat3::from_translation((area_loc - geo_loc) / area_size);
let tex_scale = self.buffer.texture_scale();
let tex_scale = Vec2::new(tex_scale.x as f32, tex_scale.y as f32);
let tex_loc = Vec2::new(offset.x as f32, offset.y as f32);
let tex_size = self.buffer.texture().size();
let tex_size = Vec2::new(tex_size.w as f32, tex_size.h as f32) / tex_scale;
let geo_to_tex =
Mat3::from_translation(-tex_loc / tex_size) * Mat3::from_scale(geo_size / tex_size);
return ShaderRenderElement::new(
ProgramType::Close,
view_rect.size,
None,
scale.x as f32,
1.,
vec![
mat3_uniform("niri_input_to_geo", input_to_geo),
Uniform::new("niri_geo_size", geo_size.to_array()),
mat3_uniform("niri_geo_to_tex", geo_to_tex),
Uniform::new("niri_progress", progress as f32),
Uniform::new("niri_clamped_progress", clamped_progress as f32),
Uniform::new("niri_random_seed", self.random_seed),
],
HashMap::from([(String::from("niri_tex"), buffer.texture().clone())]),
Kind::Unspecified,
)
.with_location(Point::from((0., 0.)))
.into();
}
let elem = TextureRenderElement::from_texture_buffer(
buffer.clone(),
Point::from((0., 0.)),
1. - clamped_progress as f32,
None,
None,
Kind::Unspecified,
);
let elem = PrimaryGpuTextureRenderElement(elem);
let center = self.geo_size.to_point().downscale(2.);
let elem = RescaleRenderElement::from_element(
elem,
(center - offset).to_physical_precise_round(scale),
((1. - clamped_progress) / 5. + 0.8).max(0.),
);
let mut location = self.pos + offset;
location.x -= view_rect.loc.x;
let elem = RelocateRenderElement::from_element(
elem,
location.to_physical_precise_round(scale),
Relocate::Relative,
);
elem.into()
}
}
File diff suppressed because it is too large Load Diff
+226 -68
View File
@@ -1,116 +1,274 @@
use std::iter::zip;
use arrayvec::ArrayVec;
use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
use smithay::backend::renderer::element::Kind;
use smithay::utils::{Logical, Point, Scale, Size};
use niri_config::{CornerRadius, Gradient, GradientRelativeTo};
use smithay::backend::renderer::element::{Element as _, Kind};
use smithay::utils::{Logical, Point, Rectangle, Size};
use crate::config::{self, Color};
use crate::niri_render_elements;
use crate::render_helpers::border::BorderRenderElement;
use crate::render_helpers::renderer::NiriRenderer;
use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
#[derive(Debug)]
pub struct FocusRing {
buffers: [SolidColorBuffer; 4],
locations: [Point<i32, Logical>; 4],
is_off: bool,
buffers: [SolidColorBuffer; 8],
locations: [Point<f64, Logical>; 8],
sizes: [Size<f64, Logical>; 8],
borders: [BorderRenderElement; 8],
full_size: Size<f64, Logical>,
is_border: bool,
width: i32,
active_color: Color,
inactive_color: Color,
use_border_shader: bool,
config: niri_config::FocusRing,
}
pub type FocusRingRenderElement = SolidColorRenderElement;
niri_render_elements! {
FocusRingRenderElement => {
SolidColor = SolidColorRenderElement,
Gradient = BorderRenderElement,
}
}
impl FocusRing {
pub fn new(config: config::FocusRing) -> Self {
pub fn new(config: niri_config::FocusRing) -> Self {
Self {
buffers: Default::default(),
locations: Default::default(),
is_off: config.off,
sizes: Default::default(),
borders: Default::default(),
full_size: Default::default(),
is_border: false,
width: config.width.into(),
active_color: config.active_color,
inactive_color: config.inactive_color,
use_border_shader: false,
config,
}
}
pub fn update_config(&mut self, config: config::FocusRing) {
self.is_off = config.off;
self.width = config.width.into();
self.active_color = config.active_color;
self.inactive_color = config.inactive_color;
pub fn update_config(&mut self, config: niri_config::FocusRing) {
self.config = config;
}
pub fn update(
&mut self,
win_pos: Point<i32, Logical>,
win_size: Size<i32, Logical>,
is_border: bool,
) {
if is_border {
self.buffers[0].resize((win_size.w + self.width * 2, self.width));
self.buffers[1].resize((win_size.w + self.width * 2, self.width));
self.buffers[2].resize((self.width, win_size.h));
self.buffers[3].resize((self.width, win_size.h));
pub fn update_shaders(&mut self) {
for elem in &mut self.borders {
elem.damage_all();
}
}
self.locations[0] = win_pos + Point::from((-self.width, -self.width));
self.locations[1] = win_pos + Point::from((-self.width, win_size.h));
self.locations[2] = win_pos + Point::from((-self.width, 0));
self.locations[3] = win_pos + Point::from((win_size.w, 0));
#[allow(clippy::too_many_arguments)]
pub fn update_render_elements(
&mut self,
win_size: Size<f64, Logical>,
is_active: bool,
is_border: bool,
is_urgent: bool,
view_rect: Rectangle<f64, Logical>,
radius: CornerRadius,
scale: f64,
alpha: f32,
) {
let width = self.config.width.0;
self.full_size = win_size + Size::from((width, width)).upscale(2.);
let color = if is_urgent {
self.config.urgent_color
} else if is_active {
self.config.active_color
} else {
let size = win_size + Size::from((self.width * 2, self.width * 2));
self.buffers[0].resize(size);
self.locations[0] = win_pos - Point::from((self.width, self.width));
self.config.inactive_color
};
for buf in &mut self.buffers {
buf.set_color(color.to_array_premul());
}
let radius = radius.fit_to(self.full_size.w as f32, self.full_size.h as f32);
let gradient = if is_urgent {
self.config.urgent_gradient
} else if is_active {
self.config.active_gradient
} else {
self.config.inactive_gradient
};
self.use_border_shader = radius != CornerRadius::default() || gradient.is_some();
// Set the defaults for solid color + rounded corners.
let gradient = gradient.unwrap_or_else(|| Gradient::from(color));
let full_rect = Rectangle::new(Point::from((-width, -width)), self.full_size);
let gradient_area = match gradient.relative_to {
GradientRelativeTo::Window => full_rect,
GradientRelativeTo::WorkspaceView => view_rect,
};
let rounded_corner_border_width = if self.is_border {
// HACK: increase the border width used for the inner rounded corners a tiny bit to
// reduce background bleed.
width as f32 + 0.5
} else {
0.
};
let ceil = |logical: f64| (logical * scale).ceil() / scale;
// All of this stuff should end up aligned to physical pixels because:
// * Window size and border width are rounded to physical pixels before being passed to this
// function.
// * We will ceil the corner radii below.
// * We do not divide anything, only add, subtract and multiply by integers.
// * At rendering time, tile positions are rounded to physical pixels.
if is_border {
let top_left = f64::max(width, ceil(f64::from(radius.top_left)));
let top_right = f64::min(
self.full_size.w - top_left,
f64::max(width, ceil(f64::from(radius.top_right))),
);
let bottom_left = f64::min(
self.full_size.h - top_left,
f64::max(width, ceil(f64::from(radius.bottom_left))),
);
let bottom_right = f64::min(
self.full_size.h - top_right,
f64::min(
self.full_size.w - bottom_left,
f64::max(width, ceil(f64::from(radius.bottom_right))),
),
);
// Top edge.
self.sizes[0] = Size::from((win_size.w + width * 2. - top_left - top_right, width));
self.locations[0] = Point::from((-width + top_left, -width));
// Bottom edge.
self.sizes[1] =
Size::from((win_size.w + width * 2. - bottom_left - bottom_right, width));
self.locations[1] = Point::from((-width + bottom_left, win_size.h));
// Left edge.
self.sizes[2] = Size::from((width, win_size.h + width * 2. - top_left - bottom_left));
self.locations[2] = Point::from((-width, -width + top_left));
// Right edge.
self.sizes[3] = Size::from((width, win_size.h + width * 2. - top_right - bottom_right));
self.locations[3] = Point::from((win_size.w, -width + top_right));
// Top-left corner.
self.sizes[4] = Size::from((top_left, top_left));
self.locations[4] = Point::from((-width, -width));
// Top-right corner.
self.sizes[5] = Size::from((top_right, top_right));
self.locations[5] = Point::from((win_size.w + width - top_right, -width));
// Bottom-right corner.
self.sizes[6] = Size::from((bottom_right, bottom_right));
self.locations[6] = Point::from((
win_size.w + width - bottom_right,
win_size.h + width - bottom_right,
));
// Bottom-left corner.
self.sizes[7] = Size::from((bottom_left, bottom_left));
self.locations[7] = Point::from((-width, win_size.h + width - bottom_left));
for (buf, size) in zip(&mut self.buffers, self.sizes) {
buf.resize(size);
}
for (border, (loc, size)) in zip(&mut self.borders, zip(self.locations, self.sizes)) {
border.update(
size,
Rectangle::new(gradient_area.loc - loc, gradient_area.size),
gradient.in_,
gradient.from,
gradient.to,
((gradient.angle as f32) - 90.).to_radians(),
Rectangle::new(full_rect.loc - loc, full_rect.size),
rounded_corner_border_width,
radius,
scale as f32,
alpha,
);
}
} else {
self.sizes[0] = self.full_size;
self.buffers[0].resize(self.sizes[0]);
self.locations[0] = Point::from((-width, -width));
self.borders[0].update(
self.sizes[0],
Rectangle::new(gradient_area.loc - self.locations[0], gradient_area.size),
gradient.in_,
gradient.from,
gradient.to,
((gradient.angle as f32) - 90.).to_radians(),
Rectangle::new(full_rect.loc - self.locations[0], full_rect.size),
rounded_corner_border_width,
radius,
scale as f32,
alpha,
);
}
self.is_border = is_border;
}
pub fn set_active(&mut self, is_active: bool) {
let color = if is_active {
self.active_color.into()
} else {
self.inactive_color.into()
};
pub fn render(
&self,
renderer: &mut impl NiriRenderer,
location: Point<f64, Logical>,
) -> impl Iterator<Item = FocusRingRenderElement> {
let mut rv = ArrayVec::<_, 8>::new();
for buf in &mut self.buffers {
buf.set_color(color);
}
}
pub fn render(&self, scale: Scale<f64>) -> impl Iterator<Item = FocusRingRenderElement> {
let mut rv = ArrayVec::<_, 4>::new();
if self.is_off {
if self.config.off {
return rv.into_iter();
}
let mut push = |buffer, location: Point<i32, Logical>| {
let elem = SolidColorRenderElement::from_buffer(
buffer,
location.to_physical_precise_round(scale),
scale,
1.,
Kind::Unspecified,
);
let border_width = -self.locations[0].y;
// If drawing as a border with width = 0, then there's nothing to draw.
if self.is_border && border_width == 0. {
return rv.into_iter();
}
let has_border_shader = BorderRenderElement::has_shader(renderer);
let mut push = |buffer, border: &BorderRenderElement, location: Point<f64, Logical>| {
let elem = if self.use_border_shader && has_border_shader {
border.clone().with_location(location).into()
} else {
let alpha = border.alpha();
SolidColorRenderElement::from_buffer(buffer, location, alpha, Kind::Unspecified)
.into()
};
rv.push(elem);
};
if self.is_border {
for (buf, loc) in zip(&self.buffers, self.locations) {
push(buf, loc);
for ((buf, border), loc) in zip(zip(&self.buffers, &self.borders), self.locations) {
push(buf, border, location + loc);
}
} else {
push(&self.buffers[0], self.locations[0]);
push(
&self.buffers[0],
&self.borders[0],
location + self.locations[0],
);
}
rv.into_iter()
}
pub fn width(&self) -> i32 {
self.width
pub fn width(&self) -> f64 {
self.config.width.0
}
pub fn is_off(&self) -> bool {
self.is_off
self.config.off
}
pub fn config(&self) -> &niri_config::FocusRing {
&self.config
}
}

Some files were not shown because too many files have changed in this diff Show More