mirror of
https://github.com/niri-wm/niri.git
synced 2026-06-21 02:01:55 +07:00
Compare commits
686 Commits
v0.1.0-alpha.2
...
v0.1.6
| Author | SHA1 | Date | |
|---|---|---|---|
| d96a66ddff | |||
| bfaf9ae060 | |||
| 2da0aaace8 | |||
| ee12bbc9ed | |||
| cc4026f588 | |||
| aa74120143 | |||
| 473ef22de2 | |||
| d76b213e03 | |||
| 4dc7a6ceb8 | |||
| 36d3e70f11 | |||
| a2f74c9bff | |||
| 0ce08b598c | |||
| ae63773737 | |||
| c5ca412829 | |||
| cbfc682f9a | |||
| c64d9e5223 | |||
| 4e31f7e047 | |||
| 109d99fe82 | |||
| eb9bbe3352 | |||
| 229ca90507 | |||
| 17a71bd424 | |||
| a39aaa312d | |||
| 3f802d0193 | |||
| df36eac25b | |||
| 609b1a02d0 | |||
| 5335ef454b | |||
| 496cd59df9 | |||
| 3e385d5c48 | |||
| b87fba2182 | |||
| 3d63f5e644 | |||
| 1096f0cf0e | |||
| 78978219a0 | |||
| 5999ba6a5e | |||
| 94a9b48a0f | |||
| d776ab7763 | |||
| 5f40221051 | |||
| b14405904a | |||
| e06776c5d4 | |||
| 55e550262d | |||
| e5ccc9332c | |||
| 36a54615ca | |||
| 9004c83954 | |||
| 29c7552852 | |||
| d2ed42a157 | |||
| 4073f9f522 | |||
| 464441f9eb | |||
| bc29256b9d | |||
| beba87354a | |||
| 078724369d | |||
| 75393faca3 | |||
| 22cdd044d3 | |||
| 719270854a | |||
| 8900960e76 | |||
| 47a8e75fd5 | |||
| 6d9cfe2882 | |||
| de0ad85711 | |||
| f091e64b12 | |||
| e454cd6282 | |||
| 1c14a0a2a9 | |||
| 2fd9a03bd7 | |||
| b101f9b5f8 | |||
| 34bcc6ea93 | |||
| 9dfa121b8e | |||
| c4ebb9f58e | |||
| 38e329aab9 | |||
| 95a1a01fdc | |||
| c61940c40e | |||
| ed2b6d3894 | |||
| 47925948a3 | |||
| 5248e53499 | |||
| 9847a652af | |||
| 96823eea38 | |||
| ea59091869 | |||
| 2e4a2e13b1 | |||
| df0ee996ee | |||
| 65b9c74f62 | |||
| 2dff674470 | |||
| 23850e1c60 | |||
| 641b44e006 | |||
| 1394afaae9 | |||
| 314ad9d3e5 | |||
| 99eb1227b1 | |||
| 79093baeee | |||
| 7093385b4d | |||
| 3748f6cd6a | |||
| 73cc0079d6 | |||
| 69aeba2a4d | |||
| 7aab413048 | |||
| 74996a2416 | |||
| 8ab50f9d1c | |||
| 5c32031111 | |||
| 85680a57da | |||
| 1a8d6b1f1d | |||
| 185f294200 | |||
| c6d64dae7a | |||
| 5dddc850fc | |||
| 2f42f8ac75 | |||
| 42cef79c69 | |||
| d86df5025c | |||
| 9309b3be61 | |||
| c5be2dd549 | |||
| 365dbacae7 | |||
| af9caa1d9b | |||
| 68ff36f683 | |||
| c0d5001e90 | |||
| f3ded0c2e6 | |||
| f43fa55526 | |||
| c1c43c5393 | |||
| 5899010c96 | |||
| 9f3715b731 | |||
| 8d99e3c015 | |||
| 9df71bcb5d | |||
| 04c5b9ad74 | |||
| fd6c8c7790 | |||
| 3e598c565e | |||
| e261b641ed | |||
| dc1d2b706c | |||
| f9b008163c | |||
| 279659ac90 | |||
| c2d03d82ce | |||
| 5299590290 | |||
| 1681ed16d9 | |||
| d4bed70884 | |||
| 49f5402669 | |||
| 2ecbb3f6f8 | |||
| 6a80078259 | |||
| 303c51ee20 | |||
| 37a836f462 | |||
| 361ede4bcd | |||
| 4fc80124ad | |||
| ba44aeda4a | |||
| b5f7e4bd83 | |||
| b98b95883d | |||
| 568c35ff87 | |||
| c4f600bded | |||
| 2c8d1030ab | |||
| f51dd67f2d | |||
| 3509de6fbf | |||
| 0477986a0d | |||
| 914237fa11 | |||
| 0b93c46ce8 | |||
| 0fcd981b86 | |||
| 5c4153e26b | |||
| 4d010b7943 | |||
| 65c342f2cb | |||
| 47f6c85f64 | |||
| 3b37f1a557 | |||
| dee0abb713 | |||
| bbb4a64126 | |||
| dfe49aa705 | |||
| 7ca39baf9e | |||
| 73e9ef5fe2 | |||
| c40d4f3268 | |||
| 1b496ee21f | |||
| bde46dab52 | |||
| 21ef5aded8 | |||
| b288102866 | |||
| ff42f9b9d3 | |||
| c163e58167 | |||
| a9094b43d4 | |||
| 9e33320b11 | |||
| c40de5364d | |||
| 69f723d68a | |||
| 568fbe26fe | |||
| f8412ecff3 | |||
| 3c6d8062c5 | |||
| 40374942db | |||
| 2c873044e8 | |||
| 1336a581a6 | |||
| 8b0dc1902c | |||
| 9d5f1c7ef7 | |||
| 71be19b234 | |||
| 4fd9300bdb | |||
| 2bb6dd8c48 | |||
| 7319f37f7a | |||
| 0cd149c939 | |||
| 5383a0591f | |||
| 0c68609063 | |||
| 6cd3f96a10 | |||
| 1888696567 | |||
| b9e789619f | |||
| dd011f1012 | |||
| 301a2c0661 | |||
| 956bf7c0a8 | |||
| 209492e700 | |||
| 7e0d3d31f7 | |||
| e448cfb0ef | |||
| 6aceb3a798 | |||
| 4856522a7a | |||
| c1432bfa96 | |||
| ec0531264e | |||
| 03fc439150 | |||
| 83aec41df3 | |||
| 8be9381974 | |||
| dc56f9885c | |||
| 2b3a80b477 | |||
| 294f16f76c | |||
| 4f56ff16f9 | |||
| fe79a6a4e2 | |||
| 950fcf6328 | |||
| 7ff2de19b9 | |||
| f81b51f4c0 | |||
| a90221d924 | |||
| ab22816521 | |||
| 56a55f1ad1 | |||
| f7fde74a8d | |||
| 0470a833a1 | |||
| 092420ec5a | |||
| f46e937949 | |||
| c9a47f8283 | |||
| 9b7ed57d37 | |||
| cf409a4ea6 | |||
| 83bd2317ee | |||
| 0f19003611 | |||
| 470d65a060 | |||
| 4f421907cd | |||
| b4eaaed19e | |||
| d3d178fac7 | |||
| 3091102365 | |||
| a7b3819214 | |||
| 1eff5aeb75 | |||
| 9f0566b1ab | |||
| 3c75082df2 | |||
| 9927c15f68 | |||
| cf87a185a9 | |||
| e276c906bf | |||
| 571768af43 | |||
| c09d5eb048 | |||
| 1a3e31a5cf | |||
| 62f14d42dc | |||
| ce644852d2 | |||
| ffe9a03b58 | |||
| 3c84de5215 | |||
| cd555bbad7 | |||
| 287d9b6b3f | |||
| 9bd812c37a | |||
| 0845eef326 | |||
| 4d8cb3a6e3 | |||
| 48b009ba63 | |||
| addd1f5267 | |||
| b30f8fb2cc | |||
| f5c97faf4a | |||
| 8f1bbea863 | |||
| 5e7eafb2fd | |||
| 41b13aa881 | |||
| fd7f2287f0 | |||
| 1635337504 | |||
| b677592f11 | |||
| ad2795bb27 | |||
| 7826003a81 | |||
| 768fbea14d | |||
| e46003f91f | |||
| 5360ddb320 | |||
| d4b271fead | |||
| de6685f3ab | |||
| 662e2df0e1 | |||
| 26c4824047 | |||
| 78dbb2308e | |||
| 1dce99352e | |||
| 0b6d62f65e | |||
| cf54f75113 | |||
| 0d90876ad8 | |||
| e5bd1113ba | |||
| 6f765db44e | |||
| 5f23d344d5 | |||
| e43e10f44e | |||
| 493c8dc890 | |||
| 8b4a9d68e0 | |||
| a16a0f0e52 | |||
| 6ba195211b | |||
| afaaf36f27 | |||
| f1b36b0dce | |||
| 6ec65bc0d6 | |||
| d65446421f | |||
| 24078cfea2 | |||
| 5cc2c31a5b | |||
| b7ed2fb82a | |||
| f3f02aca20 | |||
| 021a2a1af7 | |||
| 354f0b039a | |||
| d120e0c451 | |||
| 0f724f2011 | |||
| 46131c87a5 | |||
| c66319314e | |||
| b09dbb80c7 | |||
| 54e6a01284 | |||
| 7721e3fc44 | |||
| 0d2fdb49ef | |||
| b06e51da60 | |||
| 6c08ba307a | |||
| 4b2fdd0776 | |||
| 969519b5d8 | |||
| a0c8c39b06 | |||
| 977f1487c2 | |||
| fbe021fbdf | |||
| db49deb7fd | |||
| c61361de3c | |||
| 3963f537a4 | |||
| f31e105043 | |||
| bbb4caeb8c | |||
| d421e1fbf8 | |||
| 23ac3d7323 | |||
| c3327d36da | |||
| e0da101c73 | |||
| 4740682904 | |||
| df9d721f74 | |||
| d970abead8 | |||
| 4f6ed9dfc9 | |||
| 84302796dc | |||
| a39e703fc3 | |||
| a55db6c6c4 | |||
| a011b385d8 | |||
| 2984722f80 | |||
| 118773e17d | |||
| 741bee461c | |||
| 0c57815fbf | |||
| cf89c789c3 | |||
| 642c6e7512 | |||
| 6839a118bb | |||
| 9ae3cad82b | |||
| 89dfaa6cac | |||
| f6ffe8b3ab | |||
| cc83ff008d | |||
| ba4e7481c3 | |||
| c15bc2a028 | |||
| bf1cc98886 | |||
| 5f137b77d3 | |||
| 128d573e74 | |||
| ed8a6afe80 | |||
| 43aa2f95be | |||
| 5c0a1f4d6f | |||
| 8c46611c29 | |||
| 40cec34aa4 | |||
| 1971a41fdd | |||
| 4ea90140d4 | |||
| acd33653b3 | |||
| f7c6516da7 | |||
| b220420fba | |||
| bbeaba16a0 | |||
| 9d7c39b89a | |||
| 03fe864d07 | |||
| e45dbb8ef6 | |||
| 5c4b71a5a4 | |||
| 348690afb6 | |||
| ca22e70cc4 | |||
| 1a784e6e66 | |||
| 3ee2db71a4 | |||
| cedfd4944c | |||
| 431f070481 | |||
| 9cbbffc23c | |||
| c6a1398d51 | |||
| f9127616b0 | |||
| ae89b2e514 | |||
| 732f7f6f33 | |||
| 8bebd54c6d | |||
| 1978e5b0b8 | |||
| 60b02545f3 | |||
| 2750b2038b | |||
| c4145b014a | |||
| 2e51efd3a3 | |||
| caea05433e | |||
| e4f78c26f0 | |||
| 1548db56ce | |||
| 5f416abcf9 | |||
| 66c1272420 | |||
| e0ec6e5b11 | |||
| 93243d7772 | |||
| 24537ec2ba | |||
| 88ac16c99a | |||
| 0add457cf0 | |||
| 6e5426ef22 | |||
| 202406aadf | |||
| 92d9c7ff4f | |||
| 28977d1d3f | |||
| ba10bab010 | |||
| 55038b7c07 | |||
| 8018839f5d | |||
| 077f22edd6 | |||
| 4f7c3300ef | |||
| 5628bf7d77 | |||
| 719697179f | |||
| 5ac350d51c | |||
| 494e98c123 | |||
| ec156a8587 | |||
| e278e871c3 | |||
| ab9d1aab4e | |||
| 506dcd99d7 | |||
| dfbc024127 | |||
| eb2dce1b53 | |||
| f5b776a947 | |||
| 6a587245eb | |||
| 2317021a7c | |||
| af6485cd8c | |||
| f32a25eefe | |||
| aefbad0cf7 | |||
| b091202d86 | |||
| 48f0f6fb3c | |||
| 340bac0690 | |||
| d1b8134337 | |||
| 646e3d8995 | |||
| d1fe6930a7 | |||
| 9e60b344d0 | |||
| 2c01cde9be | |||
| cb9dc9c0cd | |||
| 73d2807b4b | |||
| 7d41f113cb | |||
| 63e5cf8798 | |||
| 9ce19ad7de | |||
| 751f79dc35 | |||
| b8aa0a86e7 | |||
| 82fffdea80 | |||
| 5b3bfd95d9 | |||
| 1a15aa704d | |||
| d58a45a96c | |||
| 9f1b4ee299 | |||
| f0a5e9c933 | |||
| c4c07841d7 | |||
| 6ba24e341f | |||
| 13b6c74cc3 | |||
| d8fb8d5ef0 | |||
| 2b5eeb6162 | |||
| 85be5f746c | |||
| dd7362913e | |||
| 62892d6361 | |||
| 31c13b6a69 | |||
| baaac2f3c4 | |||
| 3fdefae45b | |||
| 6345224e95 | |||
| b3d2096439 | |||
| 94ded2f6a9 | |||
| fa3bc69f94 | |||
| 363e1d8764 | |||
| 8e1d4de0dc | |||
| 72e3fadb9a | |||
| 78cda2e67f | |||
| 924e21f69b | |||
| befdebfa03 | |||
| 7960a73e9d | |||
| 749ee5d627 | |||
| 952dd48115 | |||
| cbd066ab68 | |||
| bccde351fb | |||
| beaffb1b97 | |||
| 385454378b | |||
| 18f06a7acd | |||
| 6e23073019 | |||
| a9fcbf81eb | |||
| a99f34cba8 | |||
| bd2277fa25 | |||
| 67182129ff | |||
| d6b116d229 | |||
| c20a843ab2 | |||
| 1b752fe08f | |||
| 89f74aae98 | |||
| 5e553c2679 | |||
| cabf712821 | |||
| 0931447ec1 | |||
| a388c25795 | |||
| 5c4d9824a4 | |||
| ca4ee5ae25 | |||
| 93e16a6582 | |||
| 3486fa5536 | |||
| c022d74c82 | |||
| e68641c0a7 | |||
| 2a892ef511 | |||
| 90c6721e97 | |||
| e5cd9e9307 | |||
| 573dca10cc | |||
| 577fba82e5 | |||
| b9116c579a | |||
| d8dcadc5b2 | |||
| 6424a2738d | |||
| 753a90430a | |||
| f9085db564 | |||
| 49ce791d13 | |||
| 4b8e04da04 | |||
| 026ad8f377 | |||
| 0761401650 | |||
| 3360517f62 | |||
| 9896fd67a0 | |||
| 15ec699fbb | |||
| a1cc39a437 | |||
| 738d9a2b40 | |||
| 68752db51b | |||
| d4929b8e18 | |||
| 93c547f749 | |||
| e2b91c0c1c | |||
| 322b5cbac7 | |||
| 592791611a | |||
| d073d2ab3d | |||
| b2298db5c5 | |||
| baa6263cbe | |||
| 795da53d53 | |||
| 122afff7d1 | |||
| d2a4e6a0cb | |||
| 8916b18c6b | |||
| b0d0fce5f3 | |||
| 3dc4a5fdac | |||
| 1706a46b2b | |||
| 3789d85588 | |||
| 3a23417e98 | |||
| 6bb83757ee | |||
| b62a07956a | |||
| 96016790b2 | |||
| bf978fe98d | |||
| 57521c69c3 | |||
| da826e42aa | |||
| b824cf90ab | |||
| 7a4bb8ba8a | |||
| 72c8f569ac | |||
| 798d9c55df | |||
| 05613eed1e | |||
| b23dd4b800 | |||
| 1f72089a46 | |||
| fbe9020915 | |||
| 2036116f16 | |||
| 9afd728ae9 | |||
| e51268a39e | |||
| 0a715ce155 | |||
| 89ac958670 | |||
| 2e50f8dee0 | |||
| 7052f0129e | |||
| 962e159db6 | |||
| 11bff3a2f1 | |||
| 15606304f2 | |||
| 85eac9d9d0 | |||
| d3f4583c90 | |||
| fefb1cccd6 | |||
| deef52519a | |||
| 59ff331597 | |||
| b813f99abd | |||
| d9b9cec8b8 | |||
| 597ea62d17 | |||
| 51243a0a50 | |||
| 0ebcc3e0d6 | |||
| 64c85d865e | |||
| 367e4955ea | |||
| dd967554d1 | |||
| 6d7c220137 | |||
| d77aac1afa | |||
| 837a0a20fb | |||
| ecdf756b55 | |||
| 73f3c160b2 | |||
| 5f99eb13ab | |||
| 20326b093c | |||
| 467d92a4b4 | |||
| 15bb69c0b9 | |||
| adfbfdffb3 | |||
| 087ed260c5 | |||
| f5642ab733 | |||
| ab9706cb30 | |||
| 05f2a3709b | |||
| 743173ef64 | |||
| cbbb7a26fc | |||
| 18566e3366 | |||
| df48337d83 | |||
| f5e9b40140 | |||
| 5cacd03e85 | |||
| 6945ccde18 | |||
| e86e9c6c9a | |||
| dc47de178f | |||
| 65e864965e | |||
| 55ad36addc | |||
| 26c8cbb961 | |||
| 031133c052 | |||
| a6f821d3fa | |||
| 475b3df2b5 | |||
| 1541835f00 | |||
| 4b9cb2f0d3 | |||
| 3461c66d2c | |||
| 011c91c98a | |||
| edafa139f6 | |||
| fa9b3ed106 | |||
| cc62a403c0 | |||
| 0f85c79548 | |||
| 6beef26662 | |||
| 616055e205 | |||
| 40c85da102 | |||
| 768b326028 | |||
| f068157f55 | |||
| 6703d5ce72 | |||
| 12590f689a | |||
| 4656332d07 | |||
| 954f711bf3 | |||
| c09c964420 | |||
| 1f9abaaa58 | |||
| eb4946c3d8 | |||
| 5f440f7be3 | |||
| 6644cc16ff | |||
| 9e667efc4c | |||
| 8a7e4bc3cd | |||
| 69907f123d | |||
| 6ca3b6ddb5 | |||
| fc5a080ca5 | |||
| 83719a49b7 | |||
| da4967d43c | |||
| d958a9679c | |||
| e4643c6dbe | |||
| 59763fd0da | |||
| 533659eef8 | |||
| 81443d8e16 | |||
| fb38ae26c9 | |||
| cc4acdf24a | |||
| 2506d43bb9 | |||
| d899bc4712 | |||
| 14552d856c | |||
| 632a00fcca | |||
| 80652a0765 | |||
| a52bf92ae1 | |||
| 952ff02982 | |||
| e1adabed2d | |||
| b5c4f9ed2a | |||
| d39f1897c7 | |||
| e46b614c2b | |||
| 78aa08b100 | |||
| d8626fcab0 | |||
| f4e04ac910 | |||
| 236abd9d9d | |||
| b2df3e104f | |||
| ec2d339a86 | |||
| 629a2ccb47 | |||
| fb93038bd8 | |||
| 71fef2ad2e | |||
| c6841f19e9 | |||
| e1971c4af5 | |||
| 07b1d0e98d | |||
| ffe25f5cc4 | |||
| 43e2cf14d2 | |||
| 2c59131f7f | |||
| 64c41fa2c8 | |||
| 4e0aa39113 | |||
| dcb80efc88 | |||
| 3d5de921cd | |||
| 8703feedee | |||
| a27d22571d | |||
| d10af92aea | |||
| 0bc83eda71 | |||
| 6fce5662e7 | |||
| 1c7c5b3f28 | |||
| b9d7812f1f | |||
| 655b9808b9 | |||
| 5cd31e5730 | |||
| de3fc2def0 | |||
| fd1d4b07fd | |||
| 8b5acd5e6e | |||
| 31bb9096e2 | |||
| dae93ee159 | |||
| 57a7347620 | |||
| 628891db2c | |||
| be6e25f5fb | |||
| e005a795e7 | |||
| 655fe413fb | |||
| ac6ff7ff41 | |||
| 84befb4e91 | |||
| d39f7bebf3 | |||
| 0dd9a42087 | |||
| 658941f2c3 | |||
| 6ccc4147ae | |||
| 46d5f5ec4d | |||
| c64e96d0d8 | |||
| 44d3a5b9a2 | |||
| 5d95de97a0 | |||
| 56174b2c34 | |||
| 310aa2b464 | |||
| d6c553091f | |||
| 097c415036 | |||
| 2d16c04869 | |||
| 249f2b7a21 | |||
| f3e5e13c45 | |||
| b13892ca63 | |||
| 777ad4ee5c | |||
| c21805bf70 | |||
| bfc2418267 | |||
| 77b4715e0b | |||
| c048abc8b5 | |||
| 4dd7578fe7 | |||
| ea72e4dae8 | |||
| 0c671ee493 | |||
| 324c1efd04 | |||
| 99e75b95b7 | |||
| 489a225fae | |||
| 85cb4b42f6 | |||
| be2e551a89 | |||
| ed3080d908 | |||
| 461ce5f363 | |||
| 624c799ebf |
@@ -0,0 +1 @@
|
||||
*.png filter=lfs diff=lfs merge=lfs -text
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
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. -->
|
||||
|
||||
### System Information
|
||||
|
||||
<!-- Paste the output of `niri -V`, e.g. niri 0.1.0-beta.1 (v0.1.0-beta.1) -->
|
||||
* 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:
|
||||
@@ -0,0 +1,4 @@
|
||||
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)
|
||||
+124
-22
@@ -24,6 +24,7 @@ jobs:
|
||||
|
||||
name: test - ${{ matrix.configuration }}
|
||||
runs-on: ubuntu-22.04
|
||||
container: ubuntu:23.10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -32,34 +33,90 @@ 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
|
||||
apt-get update -y
|
||||
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
|
||||
|
||||
- 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 }}
|
||||
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
|
||||
|
||||
visual-tests:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
|
||||
name: visual tests
|
||||
runs-on: ubuntu-22.04
|
||||
container: ubuntu:23.10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
show-progress: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
apt-get update -y
|
||||
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 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 - 1.72.0'
|
||||
runs-on: ubuntu-22.04
|
||||
container: ubuntu:23.10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
show-progress: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
apt-get update -y
|
||||
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 libadwaita-1-dev
|
||||
|
||||
- uses: dtolnay/rust-toolchain@1.72.0
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
|
||||
- run: cargo check --all-targets
|
||||
|
||||
clippy:
|
||||
strategy:
|
||||
@@ -67,6 +124,7 @@ jobs:
|
||||
|
||||
name: clippy
|
||||
runs-on: ubuntu-22.04
|
||||
container: ubuntu:23.10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -75,15 +133,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
|
||||
apt-get update -y
|
||||
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 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
|
||||
|
||||
@@ -107,3 +162,50 @@ jobs:
|
||||
- name: Run rustfmt
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
fedora:
|
||||
runs-on: ubuntu-22.04
|
||||
container: fedora:39
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
show-progress: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo dnf update -y
|
||||
sudo dnf install -y cargo gcc libudev-devel libgbm-devel libxkbcommon-devel wayland-devel libinput-devel dbus-devel systemd-devel libseat-devel pipewire-devel pango-devel cairo-gobject-devel clang libadwaita-devel
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: cargo build --all
|
||||
|
||||
nix:
|
||||
runs-on: ubuntu-22.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 build
|
||||
continue-on-error: true
|
||||
|
||||
publish-wiki:
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
needs: build
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
lfs: true
|
||||
show-progress: false
|
||||
- uses: Andrew-Chen-Wang/github-wiki-action@86138cbd6328b21d759e89ab6e6dd6a139b22270
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
/target
|
||||
/result
|
||||
|
||||
Generated
+1309
-561
File diff suppressed because it is too large
Load Diff
+87
-42
@@ -1,48 +1,85 @@
|
||||
[package]
|
||||
name = "niri"
|
||||
version = "0.1.0-alpha.2"
|
||||
[workspace]
|
||||
members = ["niri-visual-tests"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.6"
|
||||
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"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = { version = "1.0.75" }
|
||||
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.11", 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.12"
|
||||
sd-notify = "0.4.1"
|
||||
serde = { version = "1.0.193", features = ["derive"] }
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
|
||||
[workspace.dependencies]
|
||||
anyhow = "1.0.83"
|
||||
bitflags = "2.5.0"
|
||||
clap = { version = "~4.4.18", features = ["derive"] }
|
||||
serde = { version = "1.0.202", features = ["derive"] }
|
||||
serde_json = "1.0.117"
|
||||
tracing = { version = "0.1.40", features = ["max_level_trace", "release_max_level_debug"] }
|
||||
tracy-client = { version = "0.16.4", default-features = false }
|
||||
url = { version = "2.5.0", optional = true }
|
||||
xcursor = "0.3.5"
|
||||
zbus = { version = "3.14.1", optional = true }
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
|
||||
tracy-client = { version = "0.17.0", default-features = false }
|
||||
|
||||
[dependencies.smithay]
|
||||
[workspace.dependencies.smithay]
|
||||
git = "https://github.com/Smithay/smithay.git"
|
||||
# path = "../smithay"
|
||||
default-features = false
|
||||
|
||||
[workspace.dependencies.smithay-drm-extras]
|
||||
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
|
||||
|
||||
readme = "README.md"
|
||||
keywords = ["wayland", "compositor", "tiling", "smithay", "wm"]
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
arrayvec = "0.7.4"
|
||||
async-channel = "2.3.1"
|
||||
async-io = { version = "1.13.0", optional = true }
|
||||
bitflags.workspace = true
|
||||
bytemuck = { version = "1.16.0", features = ["derive"] }
|
||||
calloop = { version = "0.13.0", features = ["executor", "futures-io"] }
|
||||
clap = { workspace = true, features = ["string"] }
|
||||
directories = "5.0.1"
|
||||
drm-ffi = "0.8.0"
|
||||
fastrand = "2.1.0"
|
||||
futures-util = { version = "0.3.30", default-features = false, features = ["std", "io"] }
|
||||
git-version = "0.3.9"
|
||||
glam = "0.27.0"
|
||||
input = { version = "0.9.0", features = ["libinput_1_21"] }
|
||||
keyframe = { version = "1.1.1", default-features = false }
|
||||
libc = "0.2.154"
|
||||
log = { version = "0.4.21", features = ["max_level_trace", "release_max_level_debug"] }
|
||||
niri-config = { version = "0.1.6", path = "niri-config" }
|
||||
niri-ipc = { version = "0.1.6", path = "niri-ipc", features = ["clap"] }
|
||||
notify-rust = { version = "~4.10.0", optional = true }
|
||||
pangocairo = "0.19.2"
|
||||
pipewire = { version = "0.8.0", optional = true }
|
||||
png = "0.17.13"
|
||||
portable-atomic = { version = "1.6.0", default-features = false, features = ["float"] }
|
||||
profiling = "1.0.15"
|
||||
sd-notify = "0.4.1"
|
||||
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.0", optional = true }
|
||||
xcursor = "0.3.5"
|
||||
zbus = { version = "~3.15.2", optional = true }
|
||||
|
||||
[dependencies.smithay]
|
||||
workspace = true
|
||||
features = [
|
||||
"backend_drm",
|
||||
"backend_egl",
|
||||
@@ -53,35 +90,42 @@ 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]
|
||||
k9 = "0.12.0"
|
||||
proptest = "1.4.0"
|
||||
proptest-derive = "0.4.0"
|
||||
xshell = "0.2.6"
|
||||
|
||||
[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 = ["zbus", "async-io", "notify-rust", "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 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
|
||||
|
||||
[package.metadata.generate-rpm]
|
||||
version = "0.1.0~alpha.2"
|
||||
version = "0.1.6"
|
||||
assets = [
|
||||
{ source = "target/release/niri", dest = "/usr/bin/", mode = "755" },
|
||||
{ source = "resources/niri-session", dest = "/usr/bin/", mode = "755" },
|
||||
@@ -92,3 +136,4 @@ assets = [
|
||||
]
|
||||
[package.metadata.generate-rpm.requires]
|
||||
alacritty = "*"
|
||||
fuzzel = "*"
|
||||
|
||||
@@ -1,154 +1,67 @@
|
||||
# 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/matrix/niri%3Amatrix.org?logo=matrix&label=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>
|
||||
</p>
|
||||
|
||||

|
||||

|
||||
|
||||
## 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
|
||||
|
||||
- Scrollable tiling
|
||||
- Dynamic workspaces like in GNOME
|
||||
- Built-in screenshot UI
|
||||
- Monitor 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
|
||||
- [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
|
||||
- Configurable layout: gaps, borders, struts, window sizes
|
||||
- [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.
|
||||
Feel free to give niri 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.
|
||||
|
||||
https://github.com/YaLTeR/niri/assets/1794388/5d355694-7b06-4f00-8920-8dce54a8721c
|
||||
Note that NVIDIA GPUs may have issues.
|
||||
|
||||
## Idea
|
||||
## Inspiration
|
||||
|
||||
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.
|
||||
Niri is heavily inspired by [PaperWM] which implements scrollable tiling on top of GNOME Shell.
|
||||
|
||||
With multiple monitors, every monitor has its own separate window strip.
|
||||
Windows can never "overflow" onto an adjacent monitor.
|
||||
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.
|
||||
|
||||
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.
|
||||
## Contact
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## Building
|
||||
|
||||
For Fedora users, there's a COPR with built and packaged niri: https://copr.fedorainfracloud.org/coprs/yalter/niri/
|
||||
|
||||
First, install the dependencies for your distribution.
|
||||
|
||||
- Ubuntu:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
- Fedora:
|
||||
|
||||
```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]).
|
||||
|
||||
## 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>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
|
||||
|
||||
|
||||
Generated
+138
@@ -0,0 +1,138 @@
|
||||
{
|
||||
"nodes": {
|
||||
"crane": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1709610799,
|
||||
"narHash": "sha256-5jfLQx0U9hXbi2skYMGodDJkIgffrjIOgMRjZqms2QE=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "81c393c776d5379c030607866afef6406ca1be57",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"fenix": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
],
|
||||
"rust-analyzer-src": "rust-analyzer-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1709274179,
|
||||
"narHash": "sha256-O6EC6QELBLHzhdzBOJj0chx8AOcd4nDRECIagfT5Nd0=",
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"rev": "4be608f4f81d351aacca01b21ffd91028c23cc22",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-community",
|
||||
"ref": "monthly",
|
||||
"repo": "fenix",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1709126324,
|
||||
"narHash": "sha256-q6EQdSeUZOG26WelxqkmR7kArjgWCdw5sfJVHPH/7j8=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "d465f4819400de7c8d874d50b982301f28a84605",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nix-filter": {
|
||||
"locked": {
|
||||
"lastModified": 1705332318,
|
||||
"narHash": "sha256-kcw1yFeJe9N4PjQji9ZeX47jg0p9A0DuU4djKvg1a7I=",
|
||||
"owner": "numtide",
|
||||
"repo": "nix-filter",
|
||||
"rev": "3449dc925982ad46246cfc36469baf66e1b64f17",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "nix-filter",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1709386671,
|
||||
"narHash": "sha256-VPqfBnIJ+cfa78pd4Y5Cr6sOWVW8GYHRVucxJGmRf8Q=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "fa9a51752f1b5de583ad5213eb621be071806663",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixpkgs-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"crane": "crane",
|
||||
"fenix": "fenix",
|
||||
"flake-utils": "flake-utils",
|
||||
"nix-filter": "nix-filter",
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
},
|
||||
"rust-analyzer-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1709219524,
|
||||
"narHash": "sha256-8HHRXm4kYQLdUohNDUuCC3Rge7fXrtkjBUf0GERxrkM=",
|
||||
"owner": "rust-lang",
|
||||
"repo": "rust-analyzer",
|
||||
"rev": "9efa23c4dacee88b93540632eb3d88c5dfebfe17",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "rust-lang",
|
||||
"ref": "nightly",
|
||||
"repo": "rust-analyzer",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
# This flake file is community maintained
|
||||
# Maintainers:
|
||||
# Bill Sun (github/billksun)
|
||||
{
|
||||
description = "Niri: A scrollable-tiling Wayland compositor.";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
|
||||
crane = {
|
||||
url = "github:ipetkov/crane";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
nix-filter.url = "github:numtide/nix-filter";
|
||||
fenix = {
|
||||
url = "github:nix-community/fenix/monthly";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
};
|
||||
|
||||
outputs = {
|
||||
self,
|
||||
nixpkgs,
|
||||
crane,
|
||||
nix-filter,
|
||||
flake-utils,
|
||||
fenix,
|
||||
...
|
||||
}: let
|
||||
systems = ["aarch64-linux" "x86_64-linux"];
|
||||
in
|
||||
flake-utils.lib.eachSystem systems (
|
||||
system: let
|
||||
pkgs = nixpkgs.legacyPackages.${system};
|
||||
toolchain = fenix.packages.${system}.complete.toolchain;
|
||||
craneLib = crane.lib.${system}.overrideToolchain toolchain;
|
||||
|
||||
craneArgs = {
|
||||
pname = "niri";
|
||||
version = self.rev or "dirty";
|
||||
|
||||
src = nixpkgs.lib.cleanSourceWith {
|
||||
src = craneLib.path ./.;
|
||||
filter = path: type:
|
||||
(builtins.match "resources" path == null) ||
|
||||
((craneLib.filterCargoSources path type) &&
|
||||
(builtins.match "niri-visual-tests" path == null));
|
||||
};
|
||||
|
||||
nativeBuildInputs = with pkgs; [
|
||||
pkg-config
|
||||
autoPatchelfHook
|
||||
clang
|
||||
gdk-pixbuf
|
||||
graphene
|
||||
gtk4
|
||||
libadwaita
|
||||
];
|
||||
|
||||
buildInputs = with pkgs; [
|
||||
wayland
|
||||
systemd # For libudev
|
||||
seatd # For libseat
|
||||
libxkbcommon
|
||||
libinput
|
||||
mesa # For libgbm
|
||||
fontconfig
|
||||
stdenv.cc.cc.lib
|
||||
pipewire
|
||||
pango
|
||||
];
|
||||
|
||||
runtimeDependencies = with pkgs; [
|
||||
wayland
|
||||
mesa
|
||||
libglvnd # For libEGL
|
||||
xorg.libXcursor
|
||||
xorg.libXi
|
||||
];
|
||||
|
||||
LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";
|
||||
};
|
||||
|
||||
cargoArtifacts = craneLib.buildDepsOnly craneArgs;
|
||||
niri = craneLib.buildPackage (craneArgs // {inherit cargoArtifacts;});
|
||||
in {
|
||||
formatter = pkgs.alejandra;
|
||||
|
||||
checks.niri = niri;
|
||||
packages.default = niri;
|
||||
|
||||
devShells.default = pkgs.mkShell.override {stdenv = pkgs.clangStdenv;} {
|
||||
inherit (niri) nativeBuildInputs buildInputs LIBCLANG_PATH;
|
||||
packages = niri.runtimeDependencies;
|
||||
|
||||
# Force linking to libEGL, which is always dlopen()ed, and to
|
||||
# libwayland-client, which is always dlopen()ed except by the
|
||||
# obscure winit backend.
|
||||
RUSTFLAGS = map (a: "-C link-arg=${a}") [
|
||||
"-Wl,--push-state,--no-as-needed"
|
||||
"-lEGL"
|
||||
"-lwayland-client"
|
||||
"-Wl,--pop-state"
|
||||
];
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[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.6.2"
|
||||
knuffel = "3.2.0"
|
||||
miette = "5.10.0"
|
||||
niri-ipc = { version = "0.1.6", path = "../niri-ipc" }
|
||||
regex = "1.10.4"
|
||||
smithay = { workspace = true, features = ["backend_libinput"] }
|
||||
tracing.workspace = true
|
||||
tracy-client.workspace = true
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "niri-ipc"
|
||||
version.workspace = true
|
||||
description.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
clap = { workspace = true, optional = true }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[features]
|
||||
clap = ["dep:clap"]
|
||||
@@ -0,0 +1,651 @@
|
||||
//! Types for communicating with niri via IPC.
|
||||
#![warn(missing_docs)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::str::FromStr;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
mod socket;
|
||||
pub use socket::{Socket, SOCKET_PATH_ENV};
|
||||
|
||||
/// Request from client to niri.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub enum Request {
|
||||
/// Request the version string for the running niri instance.
|
||||
Version,
|
||||
/// Request information about connected outputs.
|
||||
Outputs,
|
||||
/// Request information about the focused window.
|
||||
FocusedWindow,
|
||||
/// Perform an action.
|
||||
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.
|
||||
output: String,
|
||||
/// Configuration to apply.
|
||||
action: OutputAction,
|
||||
},
|
||||
/// Request information about workspaces.
|
||||
Workspaces,
|
||||
/// Respond with an error (for testing error handling).
|
||||
ReturnError,
|
||||
}
|
||||
|
||||
/// Reply from niri to client.
|
||||
///
|
||||
/// Every request gets one reply.
|
||||
///
|
||||
/// * If an error had occurred, it will be an `Reply::Err`.
|
||||
/// * If the request does not need any particular response, it will be
|
||||
/// `Reply::Ok(Response::Handled)`. Kind of like an `Ok(())`.
|
||||
/// * Otherwise, it will be `Reply::Ok(response)` with one of the other [`Response`] variants.
|
||||
pub type Reply = Result<Response, String>;
|
||||
|
||||
/// Successful response from niri to client.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub enum Response {
|
||||
/// A request that does not need a response was handled successfully.
|
||||
Handled,
|
||||
/// The version string for the running niri instance.
|
||||
Version(String),
|
||||
/// Information about connected outputs.
|
||||
///
|
||||
/// Map from connector name to output info.
|
||||
Outputs(HashMap<String, Output>),
|
||||
/// Information about the focused window.
|
||||
FocusedWindow(Option<Window>),
|
||||
/// Output configuration change result.
|
||||
OutputConfigChanged(OutputConfigChanged),
|
||||
/// Information about workspaces.
|
||||
Workspaces(Vec<Workspace>),
|
||||
}
|
||||
|
||||
/// Actions that niri can perform.
|
||||
// Variants in this enum should match the spelling of the ones in niri-config. Most, but not all,
|
||||
// variants from niri-config should be present here.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[cfg_attr(feature = "clap", derive(clap::Parser))]
|
||||
#[cfg_attr(feature = "clap", command(subcommand_value_name = "ACTION"))]
|
||||
#[cfg_attr(feature = "clap", command(subcommand_help_heading = "Actions"))]
|
||||
pub enum Action {
|
||||
/// Exit niri.
|
||||
Quit {
|
||||
/// Skip the "Press Enter to confirm" prompt.
|
||||
#[cfg_attr(feature = "clap", arg(short, long))]
|
||||
skip_confirmation: bool,
|
||||
},
|
||||
/// Power off all monitors via DPMS.
|
||||
PowerOffMonitors,
|
||||
/// Spawn a command.
|
||||
Spawn {
|
||||
/// Command to spawn.
|
||||
#[cfg_attr(feature = "clap", arg(last = true, required = true))]
|
||||
command: Vec<String>,
|
||||
},
|
||||
/// Do a screen transition.
|
||||
DoScreenTransition {
|
||||
/// Delay in milliseconds for the screen to freeze before starting the transition.
|
||||
#[cfg_attr(feature = "clap", arg(short, long))]
|
||||
delay_ms: Option<u16>,
|
||||
},
|
||||
/// Open the screenshot UI.
|
||||
Screenshot,
|
||||
/// Screenshot the focused screen.
|
||||
ScreenshotScreen,
|
||||
/// Screenshot the focused window.
|
||||
ScreenshotWindow,
|
||||
/// Close the focused window.
|
||||
CloseWindow,
|
||||
/// Toggle fullscreen on the focused window.
|
||||
FullscreenWindow,
|
||||
/// Focus the column to the left.
|
||||
FocusColumnLeft,
|
||||
/// Focus the column to the right.
|
||||
FocusColumnRight,
|
||||
/// Focus the first column.
|
||||
FocusColumnFirst,
|
||||
/// Focus the last column.
|
||||
FocusColumnLast,
|
||||
/// Focus the window below.
|
||||
FocusWindowDown,
|
||||
/// Focus the window above.
|
||||
FocusWindowUp,
|
||||
/// Focus the window or the workspace above.
|
||||
FocusWindowOrWorkspaceDown,
|
||||
/// Focus the window or the workspace above.
|
||||
FocusWindowOrWorkspaceUp,
|
||||
/// Move the focused column to the left.
|
||||
MoveColumnLeft,
|
||||
/// Move the focused column to the right.
|
||||
MoveColumnRight,
|
||||
/// Move the focused column to the start of the workspace.
|
||||
MoveColumnToFirst,
|
||||
/// Move the focused column to the end of the workspace.
|
||||
MoveColumnToLast,
|
||||
/// Move the focused window down in a column.
|
||||
MoveWindowDown,
|
||||
/// Move the focused window up in a column.
|
||||
MoveWindowUp,
|
||||
/// Move the focused window down in a column or to the workspace below.
|
||||
MoveWindowDownOrToWorkspaceDown,
|
||||
/// Move the focused window up in a column or to the workspace above.
|
||||
MoveWindowUpOrToWorkspaceUp,
|
||||
/// Consume or expel the focused window left.
|
||||
ConsumeOrExpelWindowLeft,
|
||||
/// Consume or expel the focused window right.
|
||||
ConsumeOrExpelWindowRight,
|
||||
/// Consume the window to the right into the focused column.
|
||||
ConsumeWindowIntoColumn,
|
||||
/// Expel the focused window from the column.
|
||||
ExpelWindowFromColumn,
|
||||
/// Center the focused column on the screen.
|
||||
CenterColumn,
|
||||
/// Focus the workspace below.
|
||||
FocusWorkspaceDown,
|
||||
/// Focus the workspace above.
|
||||
FocusWorkspaceUp,
|
||||
/// Focus a workspace by reference (index or name).
|
||||
FocusWorkspace {
|
||||
/// Reference (index or name) of the workspace to focus.
|
||||
#[cfg_attr(feature = "clap", arg())]
|
||||
reference: WorkspaceReferenceArg,
|
||||
},
|
||||
/// Focus the previous workspace.
|
||||
FocusWorkspacePrevious,
|
||||
/// Move the focused window to the workspace below.
|
||||
MoveWindowToWorkspaceDown,
|
||||
/// Move the focused window to the workspace above.
|
||||
MoveWindowToWorkspaceUp,
|
||||
/// Move the focused window to a workspace by reference (index or name).
|
||||
MoveWindowToWorkspace {
|
||||
/// Reference (index or name) of the workspace to move the window to.
|
||||
#[cfg_attr(feature = "clap", arg())]
|
||||
reference: WorkspaceReferenceArg,
|
||||
},
|
||||
/// Move the focused column to the workspace below.
|
||||
MoveColumnToWorkspaceDown,
|
||||
/// Move the focused column to the workspace above.
|
||||
MoveColumnToWorkspaceUp,
|
||||
/// Move the focused column to a workspace by reference (index or name).
|
||||
MoveColumnToWorkspace {
|
||||
/// Reference (index or name) of the workspace to move the column to.
|
||||
#[cfg_attr(feature = "clap", arg())]
|
||||
reference: WorkspaceReferenceArg,
|
||||
},
|
||||
/// Move the focused workspace down.
|
||||
MoveWorkspaceDown,
|
||||
/// Move the focused workspace up.
|
||||
MoveWorkspaceUp,
|
||||
/// Focus the monitor to the left.
|
||||
FocusMonitorLeft,
|
||||
/// Focus the monitor to the right.
|
||||
FocusMonitorRight,
|
||||
/// Focus the monitor below.
|
||||
FocusMonitorDown,
|
||||
/// Focus the monitor above.
|
||||
FocusMonitorUp,
|
||||
/// Move the focused window to the monitor to the left.
|
||||
MoveWindowToMonitorLeft,
|
||||
/// Move the focused window to the monitor to the right.
|
||||
MoveWindowToMonitorRight,
|
||||
/// Move the focused window to the monitor below.
|
||||
MoveWindowToMonitorDown,
|
||||
/// Move the focused window to the monitor above.
|
||||
MoveWindowToMonitorUp,
|
||||
/// Move the focused column to the monitor to the left.
|
||||
MoveColumnToMonitorLeft,
|
||||
/// Move the focused column to the monitor to the right.
|
||||
MoveColumnToMonitorRight,
|
||||
/// Move the focused column to the monitor below.
|
||||
MoveColumnToMonitorDown,
|
||||
/// Move the focused column to the monitor above.
|
||||
MoveColumnToMonitorUp,
|
||||
/// Change the height of the focused window.
|
||||
SetWindowHeight {
|
||||
/// How to change the height.
|
||||
#[cfg_attr(feature = "clap", arg())]
|
||||
change: SizeChange,
|
||||
},
|
||||
/// Reset the height of the focused window back to automatic.
|
||||
ResetWindowHeight,
|
||||
/// Switch between preset column widths.
|
||||
SwitchPresetColumnWidth,
|
||||
/// Toggle the maximized state of the focused column.
|
||||
MaximizeColumn,
|
||||
/// Change the width of the focused column.
|
||||
SetColumnWidth {
|
||||
/// How to change the width.
|
||||
#[cfg_attr(feature = "clap", arg())]
|
||||
change: SizeChange,
|
||||
},
|
||||
/// Switch between keyboard layouts.
|
||||
SwitchLayout {
|
||||
/// Layout to switch to.
|
||||
#[cfg_attr(feature = "clap", arg())]
|
||||
layout: LayoutSwitchTarget,
|
||||
},
|
||||
/// Show the hotkey overlay.
|
||||
ShowHotkeyOverlay,
|
||||
/// Move the focused workspace to the monitor to the left.
|
||||
MoveWorkspaceToMonitorLeft,
|
||||
/// Move the focused workspace to the monitor to the right.
|
||||
MoveWorkspaceToMonitorRight,
|
||||
/// Move the focused workspace to the monitor below.
|
||||
MoveWorkspaceToMonitorDown,
|
||||
/// Move the focused workspace to the monitor above.
|
||||
MoveWorkspaceToMonitorUp,
|
||||
/// Toggle a debug tint on windows.
|
||||
ToggleDebugTint,
|
||||
/// Toggle visualization of render element opaque regions.
|
||||
DebugToggleOpaqueRegions,
|
||||
/// Toggle visualization of output damage.
|
||||
DebugToggleDamage,
|
||||
}
|
||||
|
||||
/// Change in window or column size.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
|
||||
pub enum SizeChange {
|
||||
/// Set the size in logical pixels.
|
||||
SetFixed(i32),
|
||||
/// Set the size as a proportion of the working area.
|
||||
SetProportion(f64),
|
||||
/// Add or subtract to the current size in logical pixels.
|
||||
AdjustFixed(i32),
|
||||
/// Add or subtract to the current size as a proportion of the working area.
|
||||
AdjustProportion(f64),
|
||||
}
|
||||
|
||||
/// Workspace reference (index or name) to operate on.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
|
||||
pub enum WorkspaceReferenceArg {
|
||||
/// Index of the workspace.
|
||||
Index(u8),
|
||||
/// Name of the workspace.
|
||||
Name(String),
|
||||
}
|
||||
|
||||
/// Layout to switch to.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LayoutSwitchTarget {
|
||||
/// The next configured layout.
|
||||
Next,
|
||||
/// The previous configured layout.
|
||||
Prev,
|
||||
}
|
||||
|
||||
/// Output actions that niri can perform.
|
||||
// Variants in this enum should match the spelling of the ones in niri-config. Most thigs from
|
||||
// niri-config should be present here.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[cfg_attr(feature = "clap", derive(clap::Parser))]
|
||||
#[cfg_attr(feature = "clap", command(subcommand_value_name = "ACTION"))]
|
||||
#[cfg_attr(feature = "clap", command(subcommand_help_heading = "Actions"))]
|
||||
pub enum OutputAction {
|
||||
/// Turn off the output.
|
||||
Off,
|
||||
/// Turn on the output.
|
||||
On,
|
||||
/// Set the output mode.
|
||||
Mode {
|
||||
/// Mode to set, or "auto" for automatic selection.
|
||||
///
|
||||
/// Run `niri msg outputs` to see the avaliable modes.
|
||||
#[cfg_attr(feature = "clap", arg())]
|
||||
mode: ModeToSet,
|
||||
},
|
||||
/// Set the output scale.
|
||||
Scale {
|
||||
/// Scale factor to set, or "auto" for automatic selection.
|
||||
#[cfg_attr(feature = "clap", arg())]
|
||||
scale: ScaleToSet,
|
||||
},
|
||||
/// Set the output transform.
|
||||
Transform {
|
||||
/// Transform to set, counter-clockwise.
|
||||
#[cfg_attr(feature = "clap", arg())]
|
||||
transform: Transform,
|
||||
},
|
||||
/// Set the output position.
|
||||
Position {
|
||||
/// Position to set, or "auto" for automatic selection.
|
||||
#[cfg_attr(feature = "clap", command(subcommand))]
|
||||
position: PositionToSet,
|
||||
},
|
||||
/// Toggle variable refresh rate.
|
||||
Vrr {
|
||||
/// Whether to enable variable refresh rate.
|
||||
#[cfg_attr(
|
||||
feature = "clap",
|
||||
arg(
|
||||
value_name = "ON|OFF",
|
||||
action = clap::ArgAction::Set,
|
||||
value_parser = clap::builder::BoolishValueParser::new(),
|
||||
),
|
||||
)]
|
||||
enable: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// Output mode to set.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
|
||||
pub enum ModeToSet {
|
||||
/// Niri will pick the mode automatically.
|
||||
Automatic,
|
||||
/// Specific mode.
|
||||
Specific(ConfiguredMode),
|
||||
}
|
||||
|
||||
/// Output mode as set in the config file.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
|
||||
pub struct ConfiguredMode {
|
||||
/// Width in physical pixels.
|
||||
pub width: u16,
|
||||
/// Height in physical pixels.
|
||||
pub height: u16,
|
||||
/// Refresh rate.
|
||||
pub refresh: Option<f64>,
|
||||
}
|
||||
|
||||
/// Output scale to set.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
|
||||
pub enum ScaleToSet {
|
||||
/// Niri will pick the scale automatically.
|
||||
Automatic,
|
||||
/// Specific scale.
|
||||
Specific(f64),
|
||||
}
|
||||
|
||||
/// Output position to set.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
|
||||
#[cfg_attr(feature = "clap", derive(clap::Subcommand))]
|
||||
#[cfg_attr(feature = "clap", command(subcommand_value_name = "POSITION"))]
|
||||
#[cfg_attr(feature = "clap", command(subcommand_help_heading = "Position Values"))]
|
||||
pub enum PositionToSet {
|
||||
/// Position the output automatically.
|
||||
#[cfg_attr(feature = "clap", command(name = "auto"))]
|
||||
Automatic,
|
||||
/// Set a specific position.
|
||||
#[cfg_attr(feature = "clap", command(name = "set"))]
|
||||
Specific(ConfiguredPosition),
|
||||
}
|
||||
|
||||
/// Output position as set in the config file.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
|
||||
#[cfg_attr(feature = "clap", derive(clap::Args))]
|
||||
pub struct ConfiguredPosition {
|
||||
/// Logical X position.
|
||||
pub x: i32,
|
||||
/// Logical Y position.
|
||||
pub y: i32,
|
||||
}
|
||||
|
||||
/// Connected output.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Output {
|
||||
/// Name of the output.
|
||||
pub name: String,
|
||||
/// Textual description of the manufacturer.
|
||||
pub make: String,
|
||||
/// Textual description of the model.
|
||||
pub model: String,
|
||||
/// Physical width and height of the output in millimeters, if known.
|
||||
pub physical_size: Option<(u32, u32)>,
|
||||
/// Available modes for the output.
|
||||
pub modes: Vec<Mode>,
|
||||
/// Index of the current mode in [`Self::modes`].
|
||||
///
|
||||
/// `None` if the output is disabled.
|
||||
pub current_mode: Option<usize>,
|
||||
/// Whether the output supports variable refresh rate.
|
||||
pub vrr_supported: bool,
|
||||
/// Whether variable refresh rate is enabled on the output.
|
||||
pub vrr_enabled: bool,
|
||||
/// Logical output information.
|
||||
///
|
||||
/// `None` if the output is not mapped to any logical output (for example, if it is disabled).
|
||||
pub logical: Option<LogicalOutput>,
|
||||
}
|
||||
|
||||
/// Output mode.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
|
||||
pub struct Mode {
|
||||
/// Width in physical pixels.
|
||||
pub width: u16,
|
||||
/// Height in physical pixels.
|
||||
pub height: u16,
|
||||
/// Refresh rate in millihertz.
|
||||
pub refresh_rate: u32,
|
||||
/// Whether this mode is preferred by the monitor.
|
||||
pub is_preferred: bool,
|
||||
}
|
||||
|
||||
/// Logical output in the compositor's coordinate space.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
|
||||
pub struct LogicalOutput {
|
||||
/// Logical X position.
|
||||
pub x: i32,
|
||||
/// Logical Y position.
|
||||
pub y: i32,
|
||||
/// Width in logical pixels.
|
||||
pub width: u32,
|
||||
/// Height in logical pixels.
|
||||
pub height: u32,
|
||||
/// Scale factor.
|
||||
pub scale: f64,
|
||||
/// Transform.
|
||||
pub transform: Transform,
|
||||
}
|
||||
|
||||
/// Output transform, which goes counter-clockwise.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
|
||||
pub enum Transform {
|
||||
/// Untransformed.
|
||||
Normal,
|
||||
/// Rotated by 90°.
|
||||
#[serde(rename = "90")]
|
||||
_90,
|
||||
/// Rotated by 180°.
|
||||
#[serde(rename = "180")]
|
||||
_180,
|
||||
/// Rotated by 270°.
|
||||
#[serde(rename = "270")]
|
||||
_270,
|
||||
/// Flipped horizontally.
|
||||
Flipped,
|
||||
/// Rotated by 90° and flipped horizontally.
|
||||
#[cfg_attr(feature = "clap", value(name("flipped-90")))]
|
||||
Flipped90,
|
||||
/// Flipped vertically.
|
||||
#[cfg_attr(feature = "clap", value(name("flipped-180")))]
|
||||
Flipped180,
|
||||
/// Rotated by 270° and flipped horizontally.
|
||||
#[cfg_attr(feature = "clap", value(name("flipped-270")))]
|
||||
Flipped270,
|
||||
}
|
||||
|
||||
/// Toplevel window.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct Window {
|
||||
/// Title, if set.
|
||||
pub title: Option<String>,
|
||||
/// Application ID, if set.
|
||||
pub app_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Output configuration change result.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum OutputConfigChanged {
|
||||
/// The target output was connected and the change was applied.
|
||||
Applied,
|
||||
/// The target output was not found, the change will be applied when it is connected.
|
||||
OutputWasMissing,
|
||||
}
|
||||
|
||||
/// A workspace.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Workspace {
|
||||
/// Index of the workspace on its monitor.
|
||||
///
|
||||
/// This is the same index you can use for requests like `niri msg action focus-workspace`.
|
||||
pub idx: u8,
|
||||
/// Optional name of the workspace.
|
||||
pub name: Option<String>,
|
||||
/// Name of the output that the workspace is on.
|
||||
///
|
||||
/// Can be `None` if no outputs are currently connected.
|
||||
pub output: Option<String>,
|
||||
/// Whether the workspace is currently active on its output.
|
||||
pub is_active: bool,
|
||||
}
|
||||
|
||||
impl FromStr for WorkspaceReferenceArg {
|
||||
type Err = &'static str;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let reference = if let Ok(index) = s.parse::<i32>() {
|
||||
if let Ok(idx) = u8::try_from(index) {
|
||||
Self::Index(idx)
|
||||
} else {
|
||||
return Err("workspace indexes must be between 0 and 255");
|
||||
}
|
||||
} else {
|
||||
Self::Name(s.to_string())
|
||||
};
|
||||
|
||||
Ok(reference)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for SizeChange {
|
||||
type Err = &'static str;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s.split_once('%') {
|
||||
Some((value, empty)) => {
|
||||
if !empty.is_empty() {
|
||||
return Err("trailing characters after '%' are not allowed");
|
||||
}
|
||||
|
||||
match value.bytes().next() {
|
||||
Some(b'-' | b'+') => {
|
||||
let value = value.parse().map_err(|_| "error parsing value")?;
|
||||
Ok(Self::AdjustProportion(value))
|
||||
}
|
||||
Some(_) => {
|
||||
let value = value.parse().map_err(|_| "error parsing value")?;
|
||||
Ok(Self::SetProportion(value))
|
||||
}
|
||||
None => Err("value is missing"),
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let value = s;
|
||||
match value.bytes().next() {
|
||||
Some(b'-' | b'+') => {
|
||||
let value = value.parse().map_err(|_| "error parsing value")?;
|
||||
Ok(Self::AdjustFixed(value))
|
||||
}
|
||||
Some(_) => {
|
||||
let value = value.parse().map_err(|_| "error parsing value")?;
|
||||
Ok(Self::SetFixed(value))
|
||||
}
|
||||
None => Err("value is missing"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for LayoutSwitchTarget {
|
||||
type Err = &'static str;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"next" => Ok(Self::Next),
|
||||
"prev" => Ok(Self::Prev),
|
||||
_ => Err(r#"invalid layout action, can be "next" or "prev""#),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for Transform {
|
||||
type Err = &'static str;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"normal" => Ok(Self::Normal),
|
||||
"90" => Ok(Self::_90),
|
||||
"180" => Ok(Self::_180),
|
||||
"270" => Ok(Self::_270),
|
||||
"flipped" => Ok(Self::Flipped),
|
||||
"flipped-90" => Ok(Self::Flipped90),
|
||||
"flipped-180" => Ok(Self::Flipped180),
|
||||
"flipped-270" => Ok(Self::Flipped270),
|
||||
_ => Err(concat!(
|
||||
r#"invalid transform, can be "90", "180", "270", "#,
|
||||
r#""flipped", "flipped-90", "flipped-180" or "flipped-270""#
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for ModeToSet {
|
||||
type Err = &'static str;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
if s.eq_ignore_ascii_case("auto") {
|
||||
return Ok(Self::Automatic);
|
||||
}
|
||||
|
||||
let mode = s.parse()?;
|
||||
Ok(Self::Specific(mode))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for ConfiguredMode {
|
||||
type Err = &'static str;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let Some((width, rest)) = s.split_once('x') else {
|
||||
return Err("no 'x' separator found");
|
||||
};
|
||||
|
||||
let (height, refresh) = match rest.split_once('@') {
|
||||
Some((height, refresh)) => (height, Some(refresh)),
|
||||
None => (rest, None),
|
||||
};
|
||||
|
||||
let width = width.parse().map_err(|_| "error parsing width")?;
|
||||
let height = height.parse().map_err(|_| "error parsing height")?;
|
||||
let refresh = refresh
|
||||
.map(str::parse)
|
||||
.transpose()
|
||||
.map_err(|_| "error parsing refresh rate")?;
|
||||
|
||||
Ok(Self {
|
||||
width,
|
||||
height,
|
||||
refresh,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for ScaleToSet {
|
||||
type Err = &'static str;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
if s.eq_ignore_ascii_case("auto") {
|
||||
return Ok(Self::Automatic);
|
||||
}
|
||||
|
||||
let scale = s.parse().map_err(|_| "error parsing scale")?;
|
||||
Ok(Self::Specific(scale))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Helper for blocking communication over the niri socket.
|
||||
|
||||
use std::env;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::net::Shutdown;
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::{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: 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())?;
|
||||
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(self, request: Request) -> io::Result<Reply> {
|
||||
let Self { mut stream } = self;
|
||||
|
||||
let mut buf = serde_json::to_vec(&request).unwrap();
|
||||
stream.write_all(&buf)?;
|
||||
stream.shutdown(Shutdown::Write)?;
|
||||
|
||||
buf.clear();
|
||||
stream.read_to_end(&mut buf)?;
|
||||
|
||||
let reply = serde_json::from_slice(&buf)?;
|
||||
Ok(reply)
|
||||
}
|
||||
}
|
||||
@@ -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.6.0", package = "libadwaita", features = ["v1_4"] }
|
||||
anyhow.workspace = true
|
||||
gtk = { version = "0.8.2", package = "gtk4", features = ["v4_12"] }
|
||||
niri = { version = "0.1.6", path = ".." }
|
||||
niri-config = { version = "0.1.6", path = "../niri-config" }
|
||||
smithay.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
@@ -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`.
|
||||
@@ -0,0 +1,3 @@
|
||||
.anim-control-bar {
|
||||
padding: 12px;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
use std::f32::consts::{FRAC_PI_2, PI};
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use niri::animation::ANIMATION_SLOWDOWN;
|
||||
use niri::render_helpers::border::BorderRenderElement;
|
||||
use niri_config::CornerRadius;
|
||||
use smithay::backend::renderer::element::RenderElement;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::utils::{Logical, Physical, Rectangle, Size};
|
||||
|
||||
use super::TestCase;
|
||||
|
||||
pub struct GradientAngle {
|
||||
angle: f32,
|
||||
prev_time: Duration,
|
||||
}
|
||||
|
||||
impl GradientAngle {
|
||||
pub fn new(_size: Size<i32, Logical>) -> 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 mut delta = if self.prev_time.is_zero() {
|
||||
Duration::ZERO
|
||||
} else {
|
||||
current_time.saturating_sub(self.prev_time)
|
||||
};
|
||||
self.prev_time = current_time;
|
||||
|
||||
let slowdown = ANIMATION_SLOWDOWN.load(Ordering::SeqCst);
|
||||
if slowdown == 0. {
|
||||
delta = Duration::ZERO
|
||||
} else {
|
||||
delta = delta.div_f64(slowdown);
|
||||
}
|
||||
|
||||
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::from_loc_and_size((a, b), size);
|
||||
|
||||
[BorderRenderElement::new(
|
||||
area.size,
|
||||
Rectangle::from_loc_and_size((0, 0), area.size),
|
||||
[1., 0., 0., 1.],
|
||||
[0., 1., 0., 1.],
|
||||
self.angle - FRAC_PI_2,
|
||||
Rectangle::from_loc_and_size((0, 0), area.size),
|
||||
0.,
|
||||
CornerRadius::default(),
|
||||
)
|
||||
.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::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use niri::animation::ANIMATION_SLOWDOWN;
|
||||
use niri::layout::focus_ring::FocusRing;
|
||||
use niri::render_helpers::border::BorderRenderElement;
|
||||
use niri_config::{Color, CornerRadius};
|
||||
use smithay::backend::renderer::element::RenderElement;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::utils::{Logical, Physical, Point, Rectangle, Scale, Size};
|
||||
|
||||
use super::TestCase;
|
||||
|
||||
pub struct GradientArea {
|
||||
progress: f32,
|
||||
border: FocusRing,
|
||||
prev_time: Duration,
|
||||
}
|
||||
|
||||
impl GradientArea {
|
||||
pub fn new(_size: Size<i32, Logical>) -> Self {
|
||||
let border = FocusRing::new(niri_config::FocusRing {
|
||||
off: false,
|
||||
width: 1,
|
||||
active_color: Color::new(255, 255, 255, 128),
|
||||
inactive_color: Color::default(),
|
||||
active_gradient: None,
|
||||
inactive_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 mut delta = if self.prev_time.is_zero() {
|
||||
Duration::ZERO
|
||||
} else {
|
||||
current_time.saturating_sub(self.prev_time)
|
||||
};
|
||||
self.prev_time = current_time;
|
||||
|
||||
let slowdown = ANIMATION_SLOWDOWN.load(Ordering::SeqCst);
|
||||
if slowdown == 0. {
|
||||
delta = Duration::ZERO
|
||||
} else {
|
||||
delta = delta.div_f64(slowdown);
|
||||
}
|
||||
|
||||
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.w - a * 2, size.h - b * 2);
|
||||
let area = Rectangle::from_loc_and_size((a, b), rect_size);
|
||||
|
||||
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 = ((size.w - g_size.w) / 2, (size.h - g_size.h) / 2);
|
||||
let mut g_area = Rectangle::from_loc_and_size(g_loc, g_size);
|
||||
g_area.loc -= area.loc;
|
||||
|
||||
self.border.update_render_elements(
|
||||
g_size,
|
||||
true,
|
||||
true,
|
||||
Rectangle::default(),
|
||||
CornerRadius::default(),
|
||||
);
|
||||
rv.extend(
|
||||
self.border
|
||||
.render(renderer, Point::from(g_loc), Scale::from(1.))
|
||||
.map(|elem| Box::new(elem) as _),
|
||||
);
|
||||
|
||||
rv.extend(
|
||||
[BorderRenderElement::new(
|
||||
area.size,
|
||||
g_area,
|
||||
[1., 0., 0., 1.],
|
||||
[0., 1., 0., 1.],
|
||||
FRAC_PI_4,
|
||||
Rectangle::from_loc_and_size((0, 0), rect_size),
|
||||
0.,
|
||||
CornerRadius::default(),
|
||||
)
|
||||
.with_location(area.loc)]
|
||||
.into_iter()
|
||||
.map(|elem| Box::new(elem) as _),
|
||||
);
|
||||
|
||||
rv
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use niri::layout::workspace::ColumnWidth;
|
||||
use niri::layout::{LayoutElement as _, Options};
|
||||
use niri::render_helpers::RenderTarget;
|
||||
use niri::utils::get_monotonic_time;
|
||||
use niri_config::Color;
|
||||
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::{Logical, Physical, Size};
|
||||
|
||||
use super::TestCase;
|
||||
use crate::test_window::TestWindow;
|
||||
|
||||
type DynStepFn = Box<dyn FnOnce(&mut Layout)>;
|
||||
|
||||
pub struct Layout {
|
||||
output: Output,
|
||||
windows: Vec<TestWindow>,
|
||||
layout: niri::layout::Layout<TestWindow>,
|
||||
start_time: Duration,
|
||||
steps: HashMap<Duration, DynStepFn>,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
pub fn new(size: Size<i32, Logical>) -> Self {
|
||||
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);
|
||||
|
||||
let options = Options {
|
||||
focus_ring: niri_config::FocusRing {
|
||||
off: true,
|
||||
..Default::default()
|
||||
},
|
||||
border: niri_config::Border {
|
||||
off: false,
|
||||
width: 4,
|
||||
active_color: Color::new(255, 163, 72, 255),
|
||||
inactive_color: Color::new(50, 50, 50, 255),
|
||||
active_gradient: None,
|
||||
inactive_gradient: None,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let mut layout = niri::layout::Layout::with_options(options);
|
||||
layout.add_output(output.clone());
|
||||
|
||||
Self {
|
||||
output,
|
||||
windows: Vec::new(),
|
||||
layout,
|
||||
start_time: get_monotonic_time(),
|
||||
steps: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open_in_between(size: Size<i32, Logical>) -> Self {
|
||||
let mut rv = Self::new(size);
|
||||
|
||||
rv.add_window(TestWindow::freeform(0), Some(ColumnWidth::Proportion(0.3)));
|
||||
rv.add_window(TestWindow::freeform(1), Some(ColumnWidth::Proportion(0.3)));
|
||||
rv.layout.activate_window(&0);
|
||||
|
||||
rv.add_step(500, |l| {
|
||||
let win = TestWindow::freeform(2);
|
||||
l.add_window(win.clone(), Some(ColumnWidth::Proportion(0.3)));
|
||||
l.layout.start_open_animation_for_window(win.id());
|
||||
});
|
||||
|
||||
rv
|
||||
}
|
||||
|
||||
pub fn open_multiple_quickly(size: Size<i32, Logical>) -> Self {
|
||||
let mut rv = Self::new(size);
|
||||
|
||||
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(ColumnWidth::Proportion(0.3)));
|
||||
l.layout.start_open_animation_for_window(win.id());
|
||||
});
|
||||
}
|
||||
|
||||
rv
|
||||
}
|
||||
|
||||
pub fn open_multiple_quickly_big(size: Size<i32, Logical>) -> Self {
|
||||
let mut rv = Self::new(size);
|
||||
|
||||
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(ColumnWidth::Proportion(0.5)));
|
||||
l.layout.start_open_animation_for_window(win.id());
|
||||
});
|
||||
}
|
||||
|
||||
rv
|
||||
}
|
||||
|
||||
pub fn open_to_the_left(size: Size<i32, Logical>) -> Self {
|
||||
let mut rv = Self::new(size);
|
||||
|
||||
rv.add_window(TestWindow::freeform(0), Some(ColumnWidth::Proportion(0.3)));
|
||||
rv.add_window(TestWindow::freeform(1), Some(ColumnWidth::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(ColumnWidth::Proportion(0.3)));
|
||||
l.layout.start_open_animation_for_window(win.id());
|
||||
});
|
||||
|
||||
rv
|
||||
}
|
||||
|
||||
pub fn open_to_the_left_big(size: Size<i32, Logical>) -> Self {
|
||||
let mut rv = Self::new(size);
|
||||
|
||||
rv.add_window(TestWindow::freeform(0), Some(ColumnWidth::Proportion(0.3)));
|
||||
rv.add_window(TestWindow::freeform(1), Some(ColumnWidth::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(ColumnWidth::Proportion(0.5)));
|
||||
l.layout.start_open_animation_for_window(win.id());
|
||||
});
|
||||
|
||||
rv
|
||||
}
|
||||
|
||||
fn add_window(&mut self, mut window: TestWindow, width: Option<ColumnWidth>) {
|
||||
let ws = self.layout.active_workspace().unwrap();
|
||||
window.request_size(ws.new_window_size(width, window.rules()), false);
|
||||
window.communicate();
|
||||
|
||||
self.layout.add_window(window.clone(), width, false);
|
||||
self.windows.push(window);
|
||||
}
|
||||
|
||||
fn add_window_right_of(
|
||||
&mut self,
|
||||
right_of: &TestWindow,
|
||||
mut window: TestWindow,
|
||||
width: Option<ColumnWidth>,
|
||||
) {
|
||||
let ws = self.layout.active_workspace().unwrap();
|
||||
window.request_size(ws.new_window_size(width, window.rules()), false);
|
||||
window.communicate();
|
||||
|
||||
self.layout
|
||||
.add_window_right_of(right_of.id(), window.clone(), width, false);
|
||||
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
|
||||
.monitor_for_output(&self.output)
|
||||
.unwrap()
|
||||
.are_animations_ongoing()
|
||||
|| !self.steps.is_empty()
|
||||
}
|
||||
|
||||
fn advance_animations(&mut self, mut current_time: Duration) {
|
||||
let run = self
|
||||
.steps
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|delay| self.start_time + *delay <= current_time)
|
||||
.collect::<Vec<_>>();
|
||||
for key in &run {
|
||||
let f = self.steps.remove(key).unwrap();
|
||||
f(self);
|
||||
}
|
||||
if !run.is_empty() {
|
||||
current_time = get_monotonic_time();
|
||||
}
|
||||
|
||||
self.layout.advance_animations(current_time);
|
||||
}
|
||||
|
||||
fn render(
|
||||
&mut self,
|
||||
renderer: &mut GlesRenderer,
|
||||
_size: Size<i32, Physical>,
|
||||
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
|
||||
self.layout.update_render_elements(&self.output);
|
||||
self.layout
|
||||
.monitor_for_output(&self.output)
|
||||
.unwrap()
|
||||
.render_elements(renderer, RenderTarget::Output)
|
||||
.into_iter()
|
||||
.map(|elem| Box::new(elem) as _)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use smithay::backend::renderer::element::RenderElement;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::utils::{Physical, Size};
|
||||
|
||||
pub mod gradient_angle;
|
||||
pub mod gradient_area;
|
||||
pub mod layout;
|
||||
pub mod tile;
|
||||
pub mod window;
|
||||
|
||||
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>>>;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use niri::layout::Options;
|
||||
use niri::render_helpers::RenderTarget;
|
||||
use niri_config::Color;
|
||||
use smithay::backend::renderer::element::RenderElement;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::utils::{Logical, Physical, Point, Rectangle, Scale, Size};
|
||||
|
||||
use super::TestCase;
|
||||
use crate::test_window::TestWindow;
|
||||
|
||||
pub struct Tile {
|
||||
window: TestWindow,
|
||||
tile: niri::layout::tile::Tile<TestWindow>,
|
||||
}
|
||||
|
||||
impl Tile {
|
||||
pub fn freeform(size: Size<i32, Logical>) -> Self {
|
||||
let window = TestWindow::freeform(0);
|
||||
let mut rv = Self::with_window(window);
|
||||
rv.tile.request_tile_size(size, false);
|
||||
rv.window.communicate();
|
||||
rv
|
||||
}
|
||||
|
||||
pub fn fixed_size(size: Size<i32, Logical>) -> Self {
|
||||
let window = TestWindow::fixed_size(0);
|
||||
let mut rv = Self::with_window(window);
|
||||
rv.tile.request_tile_size(size, false);
|
||||
rv.window.communicate();
|
||||
rv
|
||||
}
|
||||
|
||||
pub fn fixed_size_with_csd_shadow(size: Size<i32, Logical>) -> Self {
|
||||
let window = TestWindow::fixed_size(0);
|
||||
window.set_csd_shadow_width(64);
|
||||
let mut rv = Self::with_window(window);
|
||||
rv.tile.request_tile_size(size, false);
|
||||
rv.window.communicate();
|
||||
rv
|
||||
}
|
||||
|
||||
pub fn freeform_open(size: Size<i32, Logical>) -> Self {
|
||||
let mut rv = Self::freeform(size);
|
||||
rv.window.set_color([0.1, 0.1, 0.1, 1.]);
|
||||
rv.tile.start_open_animation();
|
||||
rv
|
||||
}
|
||||
|
||||
pub fn fixed_size_open(size: Size<i32, Logical>) -> Self {
|
||||
let mut rv = Self::fixed_size(size);
|
||||
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(size: Size<i32, Logical>) -> Self {
|
||||
let mut rv = Self::fixed_size_with_csd_shadow(size);
|
||||
rv.window.set_color([0.1, 0.1, 0.1, 1.]);
|
||||
rv.tile.start_open_animation();
|
||||
rv
|
||||
}
|
||||
|
||||
pub fn with_window(window: TestWindow) -> Self {
|
||||
let options = Options {
|
||||
focus_ring: niri_config::FocusRing {
|
||||
off: true,
|
||||
..Default::default()
|
||||
},
|
||||
border: niri_config::Border {
|
||||
off: false,
|
||||
width: 32,
|
||||
active_color: Color::new(255, 163, 72, 255),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let tile = niri::layout::tile::Tile::new(window.clone(), Rc::new(options));
|
||||
Self { window, tile }
|
||||
}
|
||||
}
|
||||
|
||||
impl TestCase for Tile {
|
||||
fn resize(&mut self, width: i32, height: i32) {
|
||||
self.tile
|
||||
.request_tile_size(Size::from((width, height)), false);
|
||||
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(current_time);
|
||||
}
|
||||
|
||||
fn render(
|
||||
&mut self,
|
||||
renderer: &mut GlesRenderer,
|
||||
size: Size<i32, Physical>,
|
||||
) -> Vec<Box<dyn RenderElement<GlesRenderer>>> {
|
||||
let tile_size = self.tile.tile_size().to_physical(1);
|
||||
let location = Point::from(((size.w - tile_size.w) / 2, (size.h - tile_size.h) / 2));
|
||||
|
||||
self.tile.update(
|
||||
true,
|
||||
Rectangle::from_loc_and_size((-location.x, -location.y), size.to_logical(1)),
|
||||
);
|
||||
self.tile
|
||||
.render(
|
||||
renderer,
|
||||
location,
|
||||
Scale::from(1.),
|
||||
true,
|
||||
RenderTarget::Output,
|
||||
)
|
||||
.map(|elem| Box::new(elem) as _)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
use niri::layout::LayoutElement;
|
||||
use niri::render_helpers::RenderTarget;
|
||||
use smithay::backend::renderer::element::RenderElement;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::utils::{Logical, Physical, Point, Scale, Size};
|
||||
|
||||
use super::TestCase;
|
||||
use crate::test_window::TestWindow;
|
||||
|
||||
pub struct Window {
|
||||
window: TestWindow,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
pub fn freeform(size: Size<i32, Logical>) -> Self {
|
||||
let mut window = TestWindow::freeform(0);
|
||||
window.request_size(size, false);
|
||||
window.communicate();
|
||||
Self { window }
|
||||
}
|
||||
|
||||
pub fn fixed_size(size: Size<i32, Logical>) -> Self {
|
||||
let mut window = TestWindow::fixed_size(0);
|
||||
window.request_size(size, false);
|
||||
window.communicate();
|
||||
Self { window }
|
||||
}
|
||||
|
||||
pub fn fixed_size_with_csd_shadow(size: Size<i32, Logical>) -> Self {
|
||||
let mut window = TestWindow::fixed_size(0);
|
||||
window.set_csd_shadow_width(64);
|
||||
window.request_size(size, false);
|
||||
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);
|
||||
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) / 2, (size.h - win_size.h) / 2));
|
||||
|
||||
self.window
|
||||
.render(
|
||||
renderer,
|
||||
location,
|
||||
Scale::from(1.),
|
||||
1.,
|
||||
RenderTarget::Output,
|
||||
)
|
||||
.into_iter()
|
||||
.map(|elem| Box::new(elem) as _)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
#[macro_use]
|
||||
extern crate tracing;
|
||||
|
||||
use std::env;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use adw::prelude::{AdwApplicationWindowExt, NavigationPageExt};
|
||||
use cases::tile::Tile;
|
||||
use cases::window::Window;
|
||||
use gtk::prelude::{
|
||||
AdjustmentExt, ApplicationExt, ApplicationExtManual, BoxExt, GtkWindowExt, WidgetExt,
|
||||
};
|
||||
use gtk::{gdk, gio, glib};
|
||||
use niri::animation::ANIMATION_SLOWDOWN;
|
||||
use smithay::utils::{Logical, Size};
|
||||
use smithay_view::SmithayView;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
use crate::cases::gradient_angle::GradientAngle;
|
||||
use crate::cases::gradient_area::GradientArea;
|
||||
use crate::cases::layout::Layout;
|
||||
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();
|
||||
|
||||
struct S {
|
||||
stack: gtk::Stack,
|
||||
}
|
||||
|
||||
impl S {
|
||||
fn add<T: TestCase + 'static>(
|
||||
&self,
|
||||
make: impl Fn(Size<i32, Logical>) -> T + 'static,
|
||||
title: &str,
|
||||
) {
|
||||
let view = SmithayView::new(make);
|
||||
self.stack.add_titled(&view, None, title);
|
||||
}
|
||||
}
|
||||
|
||||
let s = S {
|
||||
stack: stack.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");
|
||||
|
||||
let content_headerbar = adw::HeaderBar::new();
|
||||
|
||||
let anim_adjustment = gtk::Adjustment::new(1., 0., 10., 0.1, 0.5, 0.);
|
||||
anim_adjustment
|
||||
.connect_value_changed(|adj| ANIMATION_SLOWDOWN.store(adj.value(), Ordering::SeqCst));
|
||||
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(>k::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();
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
use gtk::glib;
|
||||
use gtk::subclass::prelude::*;
|
||||
use smithay::utils::{Logical, Size};
|
||||
|
||||
use crate::cases::TestCase;
|
||||
|
||||
mod imp {
|
||||
use std::cell::{Cell, OnceCell, RefCell};
|
||||
use std::ptr::null;
|
||||
|
||||
use anyhow::{ensure, Context};
|
||||
use gtk::gdk;
|
||||
use gtk::prelude::*;
|
||||
use niri::render_helpers::{resources, shaders};
|
||||
use niri::utils::get_monotonic_time;
|
||||
use smithay::backend::egl::ffi::egl;
|
||||
use smithay::backend::egl::EGLContext;
|
||||
use smithay::backend::renderer::gles::{Capability, GlesRenderer};
|
||||
use smithay::backend::renderer::{Frame, Renderer, Unbind};
|
||||
use smithay::utils::{Physical, Rectangle, Scale, Transform};
|
||||
|
||||
use super::*;
|
||||
|
||||
type DynMakeTestCase = Box<dyn Fn(Size<i32, Logical>) -> Box<dyn TestCase>>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct SmithayView {
|
||||
gl_area: gtk::GLArea,
|
||||
size: Cell<(i32, i32)>,
|
||||
renderer: RefCell<Option<Result<GlesRenderer, ()>>>,
|
||||
pub make_test_case: OnceCell<DynMakeTestCase>,
|
||||
test_case: RefCell<Option<Box<dyn TestCase>>>,
|
||||
}
|
||||
|
||||
#[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 size = self.size.get();
|
||||
|
||||
// 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();
|
||||
make(Size::from(size))
|
||||
});
|
||||
|
||||
case.advance_animations(get_monotonic_time());
|
||||
|
||||
let rect: Rectangle<i32, Physical> = Rectangle::from_loc_and_size((0, 0), size);
|
||||
|
||||
let elements = unsafe {
|
||||
with_framebuffer_save_restore(renderer, |renderer| {
|
||||
case.render(renderer, Size::from(size))
|
||||
})
|
||||
}?;
|
||||
|
||||
let mut frame = renderer
|
||||
.render(rect.size, Transform::Normal)
|
||||
.context("error creating frame")?;
|
||||
|
||||
frame
|
||||
.clear([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<GlesRenderer> {
|
||||
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 capabilities = GlesRenderer::supported_capabilities(&egl_context)
|
||||
.context("error getting supported renderer capabilities")?
|
||||
.into_iter()
|
||||
.filter(|c| *c != Capability::ColorTransformations);
|
||||
|
||||
let mut renderer = GlesRenderer::with_capabilities(egl_context, capabilities)
|
||||
.context("error creating GlesRenderer")?;
|
||||
|
||||
resources::init(&mut renderer);
|
||||
shaders::init(&mut renderer);
|
||||
|
||||
Ok(renderer)
|
||||
}
|
||||
|
||||
unsafe fn with_framebuffer_save_restore<T>(
|
||||
renderer: &mut GlesRenderer,
|
||||
f: impl FnOnce(&mut GlesRenderer) -> T,
|
||||
) -> anyhow::Result<T> {
|
||||
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");
|
||||
|
||||
let rv = f(renderer);
|
||||
|
||||
renderer.unbind().context("error unbinding")?;
|
||||
renderer
|
||||
.with_context(|gl| unsafe {
|
||||
gl.BindFramebuffer(
|
||||
smithay::backend::renderer::gles::ffi::FRAMEBUFFER,
|
||||
framebuffer as u32,
|
||||
);
|
||||
})
|
||||
.context("error running closure in GL context")?;
|
||||
|
||||
Ok(rv)
|
||||
}
|
||||
}
|
||||
|
||||
glib::wrapper! {
|
||||
pub struct SmithayView(ObjectSubclass<imp::SmithayView>)
|
||||
@extends gtk::Widget;
|
||||
}
|
||||
|
||||
impl SmithayView {
|
||||
pub fn new<T: TestCase + 'static>(
|
||||
make_test_case: impl Fn(Size<i32, Logical>) -> T + 'static,
|
||||
) -> Self {
|
||||
let obj: Self = glib::Object::builder().build();
|
||||
|
||||
let make = move |size| Box::new(make_test_case(size)) as Box<dyn TestCase>;
|
||||
let make_test_case = Box::new(make) as _;
|
||||
let _ = obj.imp().make_test_case.set(make_test_case);
|
||||
|
||||
obj
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
use std::cell::RefCell;
|
||||
use std::cmp::{max, min};
|
||||
use std::rc::Rc;
|
||||
|
||||
use niri::layout::{
|
||||
InteractiveResizeData, LayoutElement, LayoutElementRenderElement, LayoutElementRenderSnapshot,
|
||||
};
|
||||
use niri::render_helpers::renderer::NiriRenderer;
|
||||
use niri::render_helpers::{RenderTarget, SplitElements};
|
||||
use niri::window::ResolvedWindowRules;
|
||||
use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
|
||||
use smithay::backend::renderer::element::{Id, Kind};
|
||||
use smithay::output::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, [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.take() {
|
||||
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);
|
||||
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);
|
||||
|
||||
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<i32, 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.to_physical_precise_round(scale),
|
||||
scale,
|
||||
alpha,
|
||||
Kind::Unspecified,
|
||||
)
|
||||
.into(),
|
||||
SolidColorRenderElement::from_buffer(
|
||||
&inner.csd_shadow_buffer,
|
||||
(location - Point::from((inner.csd_shadow_width, inner.csd_shadow_width)))
|
||||
.to_physical_precise_round(scale),
|
||||
scale,
|
||||
alpha,
|
||||
Kind::Unspecified,
|
||||
)
|
||||
.into(),
|
||||
],
|
||||
popups: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn request_size(&mut self, size: Size<i32, Logical>, _animate: bool) {
|
||||
self.inner.borrow_mut().requested_size = Some(size);
|
||||
self.inner.borrow_mut().pending_fullscreen = false;
|
||||
}
|
||||
|
||||
fn request_fullscreen(&self, _size: Size<i32, Logical>) {
|
||||
self.inner.borrow_mut().pending_fullscreen = true;
|
||||
}
|
||||
|
||||
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: i32, _transform: Transform) {}
|
||||
|
||||
fn has_ssd(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn output_enter(&self, _output: &Output) {}
|
||||
|
||||
fn output_leave(&self, _output: &Output) {}
|
||||
|
||||
fn set_offscreen_element_id(&self, _id: Option<Id>) {}
|
||||
|
||||
fn set_activated(&mut self, _active: bool) {}
|
||||
|
||||
fn set_active_in_column(&mut self, _active: bool) {}
|
||||
|
||||
fn set_bounds(&self, _bounds: Size<i32, Logical>) {}
|
||||
|
||||
fn send_pending_configure(&mut self) {}
|
||||
|
||||
fn is_fullscreen(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn is_pending_fullscreen(&self) -> bool {
|
||||
self.inner.borrow().pending_fullscreen
|
||||
}
|
||||
|
||||
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 update_interactive_resize(&mut self, _serial: Serial) {}
|
||||
|
||||
fn interactive_resize_data(&self) -> Option<InteractiveResizeData> {
|
||||
None
|
||||
}
|
||||
}
|
||||
+301
-121
@@ -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:-Overview
|
||||
|
||||
// Input device configuration.
|
||||
// Find the full list of options on the wiki:
|
||||
// https://github.com/YaLTeR/niri/wiki/Configuration:-Input
|
||||
input {
|
||||
keyboard {
|
||||
xkb {
|
||||
@@ -11,129 +16,184 @@ input {
|
||||
// layout "us,ru"
|
||||
// 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"
|
||||
}
|
||||
|
||||
// Next sections include libinput settings.
|
||||
// Omitting settings disables them, or leaves them at their default values.
|
||||
touchpad {
|
||||
tap
|
||||
// dwt
|
||||
// dwtp
|
||||
natural-scroll
|
||||
// accel-speed 0.2
|
||||
// accel-profile "flat"
|
||||
}
|
||||
|
||||
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 {
|
||||
// natural-scroll
|
||||
// accel-speed 0.2
|
||||
// accel-profile "flat"
|
||||
}
|
||||
|
||||
// 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.
|
||||
// focus-follows-mouse
|
||||
}
|
||||
|
||||
// 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"
|
||||
|
||||
// Scale is a floating-point number, but at the moment only integer values work.
|
||||
scale 2.0
|
||||
|
||||
// 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 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.
|
||||
//
|
||||
// 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"
|
||||
|
||||
// active-gradient from="#ffbb66" to="#ffc880" angle=45 relative-to="workspace-view"
|
||||
// inactive-gradient from="#505050" to="#808080" angle=45 relative-to="workspace-view"
|
||||
}
|
||||
|
||||
// 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"
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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.
|
||||
// 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.
|
||||
@@ -142,6 +202,43 @@ 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 {}
|
||||
}
|
||||
|
||||
// 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"
|
||||
}
|
||||
|
||||
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
|
||||
@@ -149,35 +246,48 @@ 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"; }
|
||||
Super+Alt+L { spawn "swaylock"; }
|
||||
|
||||
// You can also use a shell:
|
||||
// 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"; }
|
||||
|
||||
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.
|
||||
@@ -186,38 +296,95 @@ binds {
|
||||
// Mod+Ctrl+J { move-window-down-or-to-workspace-down; }
|
||||
// Mod+Ctrl+K { move-window-up-or-to-workspace-up; }
|
||||
|
||||
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+Home { focus-column-first; }
|
||||
Mod+End { focus-column-last; }
|
||||
Mod+Ctrl+Home { move-column-to-first; }
|
||||
Mod+Ctrl+End { move-column-to-last; }
|
||||
|
||||
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; }
|
||||
@@ -227,20 +394,31 @@ 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; }
|
||||
|
||||
Mod+Comma { consume-window-into-column; }
|
||||
Mod+Period { expel-window-from-column; }
|
||||
|
||||
// There are also commands that consume or expel a single window to the side.
|
||||
// Mod+BracketLeft { consume-or-expel-window-left; }
|
||||
// Mod+BracketRight { consume-or-expel-window-right; }
|
||||
|
||||
Mod+R { switch-preset-column-width; }
|
||||
Mod+Shift+R { reset-window-height; }
|
||||
Mod+F { maximize-column; }
|
||||
Mod+Shift+F { fullscreen-window; }
|
||||
Mod+C { center-column; }
|
||||
@@ -272,8 +450,10 @@ binds {
|
||||
Ctrl+Print { screenshot-screen; }
|
||||
Alt+Print { screenshot-window; }
|
||||
|
||||
// The quit action will show a confirmation dialog to avoid accidental exits.
|
||||
Mod+Shift+E { quit; }
|
||||
Mod+Shift+P { power-off-monitors; }
|
||||
|
||||
Mod+Shift+Ctrl+T { toggle-debug-tint; }
|
||||
// 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; }
|
||||
}
|
||||
|
||||
@@ -20,12 +20,6 @@ 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
|
||||
|
||||
@@ -44,4 +38,4 @@ systemctl --user --wait start niri.service
|
||||
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
|
||||
systemctl --user unset-environment WAYLAND_DISPLAY XDG_SESSION_TYPE XDG_CURRENT_DESKTOP NIRI_SOCKET
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use keyframe::functions::{EaseOutCubic, EaseOutQuad};
|
||||
use keyframe::EasingFunction;
|
||||
use portable_atomic::{AtomicF64, Ordering};
|
||||
|
||||
use crate::utils::get_monotonic_time;
|
||||
|
||||
mod spring;
|
||||
pub use spring::{Spring, SpringParams};
|
||||
|
||||
pub static ANIMATION_SLOWDOWN: AtomicF64 = AtomicF64::new(1.);
|
||||
|
||||
#[derive(Debug)]
|
||||
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,
|
||||
current_time: Duration,
|
||||
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(from: f64, to: f64, initial_velocity: f64, config: niri_config::Animation) -> Self {
|
||||
// Scale the velocity by slowdown to keep the touchpad gestures feeling right.
|
||||
let initial_velocity = initial_velocity * ANIMATION_SLOWDOWN.load(Ordering::Relaxed);
|
||||
|
||||
let mut rv = Self::ease(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;
|
||||
let current_time = self.current_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(spring);
|
||||
}
|
||||
niri_config::AnimationKind::Easing(p) => {
|
||||
*self = Self::ease(
|
||||
self.from,
|
||||
self.to,
|
||||
self.initial_velocity,
|
||||
u64::from(p.duration_ms),
|
||||
Curve::from(p.curve),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
self.start_time = start_time;
|
||||
self.current_time = current_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;
|
||||
}
|
||||
|
||||
// Scale the velocity by slowdown to keep the touchpad gestures feeling right.
|
||||
let initial_velocity = initial_velocity * ANIMATION_SLOWDOWN.load(Ordering::Relaxed);
|
||||
|
||||
match self.kind {
|
||||
Kind::Easing { curve } => Self::ease(
|
||||
from,
|
||||
to,
|
||||
initial_velocity,
|
||||
self.duration.as_millis() as u64,
|
||||
curve,
|
||||
),
|
||||
Kind::Spring(spring) => {
|
||||
let spring = Spring {
|
||||
from: self.from,
|
||||
to: self.to,
|
||||
initial_velocity: self.initial_velocity,
|
||||
params: spring.params,
|
||||
};
|
||||
Self::spring(spring)
|
||||
}
|
||||
Kind::Deceleration {
|
||||
initial_velocity,
|
||||
deceleration_rate,
|
||||
} => {
|
||||
let threshold = 0.001; // FIXME
|
||||
Self::decelerate(from, initial_velocity, deceleration_rate, threshold)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ease(from: f64, to: f64, initial_velocity: f64, duration_ms: u64, curve: Curve) -> 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();
|
||||
|
||||
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: now,
|
||||
current_time: now,
|
||||
kind,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spring(spring: Spring) -> Self {
|
||||
let _span = tracy_client::span!("Animation::spring");
|
||||
|
||||
// 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();
|
||||
|
||||
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: now,
|
||||
current_time: now,
|
||||
kind,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decelerate(
|
||||
from: f64,
|
||||
initial_velocity: f64,
|
||||
deceleration_rate: f64,
|
||||
threshold: f64,
|
||||
) -> 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();
|
||||
|
||||
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: now,
|
||||
current_time: now,
|
||||
kind,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_current_time(&mut self, time: Duration) {
|
||||
if self.duration.is_zero() {
|
||||
self.current_time = time;
|
||||
return;
|
||||
}
|
||||
|
||||
let end_time = self.start_time + self.duration;
|
||||
if end_time <= self.current_time {
|
||||
return;
|
||||
}
|
||||
|
||||
let slowdown = ANIMATION_SLOWDOWN.load(Ordering::Relaxed);
|
||||
if slowdown <= f64::EPSILON {
|
||||
// Zero slowdown will cause the animation to end right away.
|
||||
self.current_time = end_time;
|
||||
return;
|
||||
}
|
||||
|
||||
// We can't change current_time (since the incoming time values are always real-time), so
|
||||
// apply the slowdown by shifting the start time to compensate.
|
||||
if self.current_time <= time {
|
||||
let delta = time - self.current_time;
|
||||
|
||||
let max_delta = end_time - self.current_time;
|
||||
let min_slowdown = delta.as_secs_f64() / max_delta.as_secs_f64();
|
||||
if slowdown <= min_slowdown {
|
||||
// Our slowdown value will cause the animation to end right away.
|
||||
self.current_time = end_time;
|
||||
return;
|
||||
}
|
||||
|
||||
let adjusted_delta = delta.div_f64(slowdown);
|
||||
if adjusted_delta >= delta {
|
||||
self.start_time -= adjusted_delta - delta;
|
||||
} else {
|
||||
self.start_time += delta - adjusted_delta;
|
||||
}
|
||||
} else {
|
||||
let delta = self.current_time - time;
|
||||
|
||||
let min_slowdown = delta.as_secs_f64() / self.current_time.as_secs_f64();
|
||||
if slowdown <= min_slowdown {
|
||||
// Current time was about to jump to before the animation had started; let's just
|
||||
// cancel the animation in this case.
|
||||
self.current_time = end_time;
|
||||
return;
|
||||
}
|
||||
|
||||
let adjusted_delta = delta.div_f64(slowdown);
|
||||
if adjusted_delta >= delta {
|
||||
self.start_time += adjusted_delta - delta;
|
||||
} else {
|
||||
self.start_time -= delta - adjusted_delta;
|
||||
}
|
||||
}
|
||||
|
||||
self.current_time = time;
|
||||
}
|
||||
|
||||
pub fn is_done(&self) -> bool {
|
||||
self.current_time >= self.start_time + self.duration
|
||||
}
|
||||
|
||||
pub fn is_clamped_done(&self) -> bool {
|
||||
self.current_time >= self.start_time + self.clamped_duration
|
||||
}
|
||||
|
||||
pub fn value(&self) -> f64 {
|
||||
if self.is_done() {
|
||||
return self.to;
|
||||
}
|
||||
|
||||
let passed = self.current_time - 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn from(&self) -> f64 {
|
||||
self.from
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
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())
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
-20
@@ -2,12 +2,13 @@ use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
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::OutputRenderElements;
|
||||
use crate::Niri;
|
||||
use crate::niri::Niri;
|
||||
|
||||
pub mod tty;
|
||||
pub use tty::Tty;
|
||||
@@ -26,10 +27,12 @@ pub enum RenderResult {
|
||||
Submitted,
|
||||
/// Rendering succeeded, but there was no damage.
|
||||
NoDamage,
|
||||
/// An error has occurred, the frame was not submitted.
|
||||
Error,
|
||||
/// The frame was not rendered and submitted, due to an error or otherwise.
|
||||
Skipped,
|
||||
}
|
||||
|
||||
pub type IpcOutputMap = HashMap<String, niri_ipc::Output>;
|
||||
|
||||
impl Backend {
|
||||
pub fn init(&mut self, niri: &mut Niri) {
|
||||
match self {
|
||||
@@ -45,10 +48,13 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn renderer(&mut self) -> Option<&mut GlesRenderer> {
|
||||
pub fn with_primary_renderer<T>(
|
||||
&mut self,
|
||||
f: impl FnOnce(&mut GlesRenderer) -> T,
|
||||
) -> Option<T> {
|
||||
match self {
|
||||
Backend::Tty(tty) => tty.renderer(),
|
||||
Backend::Winit(winit) => Some(winit.renderer()),
|
||||
Backend::Tty(tty) => tty.with_primary_renderer(f),
|
||||
Backend::Winit(winit) => winit.with_primary_renderer(f),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,12 +62,11 @@ impl Backend {
|
||||
&mut self,
|
||||
niri: &mut Niri,
|
||||
output: &Output,
|
||||
elements: &[OutputRenderElements<GlesRenderer>],
|
||||
target_presentation_time: Duration,
|
||||
) -> RenderResult {
|
||||
match self {
|
||||
Backend::Tty(tty) => tty.render(niri, output, elements, target_presentation_time),
|
||||
Backend::Winit(winit) => winit.render(niri, output, elements),
|
||||
Backend::Tty(tty) => tty.render(niri, output, target_presentation_time),
|
||||
Backend::Winit(winit) => winit.render(niri, output),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,11 +98,24 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(not(feature = "dbus"), allow(unused))]
|
||||
pub fn connectors(&self) -> Arc<Mutex<HashMap<String, Output>>> {
|
||||
pub fn import_dmabuf(&mut self, dmabuf: &Dmabuf) -> bool {
|
||||
match self {
|
||||
Backend::Tty(tty) => tty.connectors(),
|
||||
Backend::Winit(winit) => winit.connectors(),
|
||||
Backend::Tty(tty) => tty.import_dmabuf(dmabuf),
|
||||
Backend::Winit(winit) => winit.import_dmabuf(dmabuf),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn early_import(&mut self, surface: &WlSurface) {
|
||||
match self {
|
||||
Backend::Tty(tty) => tty.early_import(surface),
|
||||
Backend::Winit(_) => (),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipc_outputs(&self) -> Arc<Mutex<IpcOutputMap>> {
|
||||
match self {
|
||||
Backend::Tty(tty) => tty.ipc_outputs(),
|
||||
Backend::Winit(winit) => winit.ipc_outputs(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,21 +125,28 @@ impl Backend {
|
||||
) -> Option<smithay::backend::allocator::gbm::GbmDevice<smithay::backend::drm::DrmDeviceFd>>
|
||||
{
|
||||
match self {
|
||||
Backend::Tty(tty) => tty.gbm_device(),
|
||||
Backend::Tty(tty) => tty.primary_gbm_device(),
|
||||
Backend::Winit(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_active(&self) -> bool {
|
||||
pub fn set_monitors_active(&mut self, active: bool) {
|
||||
match self {
|
||||
Backend::Tty(tty) => tty.is_active(),
|
||||
Backend::Winit(_) => true,
|
||||
Backend::Tty(tty) => tty.set_monitors_active(active),
|
||||
Backend::Winit(_) => (),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_monitors_active(&self, active: bool) {
|
||||
pub fn on_output_config_changed(&mut self, niri: &mut Niri) {
|
||||
match self {
|
||||
Backend::Tty(tty) => tty.set_monitors_active(active),
|
||||
Backend::Tty(tty) => tty.on_output_config_changed(niri),
|
||||
Backend::Winit(_) => (),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_debug_config_changed(&mut self) {
|
||||
match self {
|
||||
Backend::Tty(tty) => tty.on_debug_config_changed(),
|
||||
Backend::Winit(_) => (),
|
||||
}
|
||||
}
|
||||
|
||||
+1631
-370
File diff suppressed because it is too large
Load Diff
+120
-65
@@ -5,46 +5,42 @@ use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use niri_config::Config;
|
||||
use smithay::backend::allocator::dmabuf::Dmabuf;
|
||||
use smithay::backend::renderer::damage::OutputDamageTracker;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::backend::renderer::{DebugFlags, Renderer};
|
||||
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 super::RenderResult;
|
||||
use crate::config::Config;
|
||||
use crate::niri::{OutputRenderElements, RedrawState, State};
|
||||
use crate::utils::get_monotonic_time;
|
||||
use crate::Niri;
|
||||
use super::{IpcOutputMap, 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 {
|
||||
pub fn new(
|
||||
config: Rc<RefCell<Config>>,
|
||||
event_loop: LoopHandle<State>,
|
||||
) -> Result<Self, winit::Error> {
|
||||
let builder = WindowBuilder::new()
|
||||
.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_builder(builder)?;
|
||||
|
||||
let output = Output::new(
|
||||
"winit".to_string(),
|
||||
@@ -60,18 +56,28 @@ 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([(
|
||||
let physical_properties = output.physical_properties();
|
||||
let ipc_outputs = Arc::new(Mutex::new(HashMap::from([(
|
||||
"winit".to_owned(),
|
||||
output.clone(),
|
||||
niri_ipc::Output {
|
||||
name: output.name(),
|
||||
make: physical_properties.make,
|
||||
model: physical_properties.model,
|
||||
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);
|
||||
@@ -89,65 +95,98 @@ impl Winit {
|
||||
None,
|
||||
None,
|
||||
);
|
||||
state.niri.output_resized(winit.output.clone());
|
||||
|
||||
{
|
||||
let mut ipc_outputs = winit.ipc_outputs.lock().unwrap();
|
||||
let output = ipc_outputs.get_mut("winit").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) {
|
||||
// For some reason, binding the display here causes damage tracker artifacts.
|
||||
//
|
||||
// use smithay::backend::renderer::ImportEgl;
|
||||
//
|
||||
// if let Err(err) = self
|
||||
// .backend
|
||||
// .renderer()
|
||||
// .bind_wl_display(&niri.display_handle)
|
||||
// {
|
||||
// warn!("error binding renderer wl_display: {err}");
|
||||
// }
|
||||
niri.add_output(self.output.clone(), None);
|
||||
let renderer = self.backend.renderer();
|
||||
if let Err(err) = renderer.bind_wl_display(&niri.display_handle) {
|
||||
warn!("error binding renderer wl_display: {err}");
|
||||
}
|
||||
|
||||
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.layout.update_shaders();
|
||||
|
||||
niri.add_output(self.output.clone(), None, false);
|
||||
}
|
||||
|
||||
pub fn seat_name(&self) -> String {
|
||||
"winit".to_owned()
|
||||
}
|
||||
|
||||
pub fn renderer(&mut self) -> &mut GlesRenderer {
|
||||
self.backend.renderer()
|
||||
pub fn with_primary_renderer<T>(
|
||||
&mut self,
|
||||
f: impl FnOnce(&mut GlesRenderer) -> T,
|
||||
) -> Option<T> {
|
||||
Some(f(self.backend.renderer()))
|
||||
}
|
||||
|
||||
pub fn render(
|
||||
&mut self,
|
||||
niri: &mut Niri,
|
||||
output: &Output,
|
||||
elements: &[OutputRenderElements<GlesRenderer>],
|
||||
) -> RenderResult {
|
||||
pub fn render(&mut self, niri: &mut Niri, output: &Output) -> RenderResult {
|
||||
let _span = tracy_client::span!("Winit::render");
|
||||
|
||||
// Render the elements.
|
||||
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])
|
||||
.render_output(self.backend.renderer(), age, &elements, [0.; 4])
|
||||
.unwrap();
|
||||
|
||||
niri.update_primary_scanout_output(output, &res.states);
|
||||
@@ -161,10 +200,12 @@ 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();
|
||||
@@ -184,12 +225,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,7 +247,17 @@ impl Winit {
|
||||
renderer.set_debug_flags(renderer.debug_flags() ^ DebugFlags::TINT);
|
||||
}
|
||||
|
||||
pub fn connectors(&self) -> Arc<Mutex<HashMap<String, Output>>> {
|
||||
self.connectors.clone()
|
||||
pub fn import_dmabuf(&mut self, dmabuf: &Dmabuf) -> bool {
|
||||
match self.backend.renderer().import_dmabuf(dmabuf, None) {
|
||||
Ok(_texture) => true,
|
||||
Err(err) => {
|
||||
debug!("error importing dmabuf: {err:?}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipc_outputs(&self) -> Arc<Mutex<IpcOutputMap>> {
|
||||
self.ipc_outputs.clone()
|
||||
}
|
||||
}
|
||||
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
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`).
|
||||
#[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`).
|
||||
#[arg(short, long)]
|
||||
config: Option<PathBuf>,
|
||||
},
|
||||
/// Cause a panic to check if the backtraces are good.
|
||||
Panic,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum Msg {
|
||||
/// List connected outputs.
|
||||
Outputs,
|
||||
/// List workspaces.
|
||||
Workspaces,
|
||||
/// Print information about the focused window.
|
||||
FocusedWindow,
|
||||
/// 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,
|
||||
},
|
||||
/// Print the version of the running niri instance.
|
||||
Version,
|
||||
/// Request an error from the running niri instance.
|
||||
RequestError,
|
||||
}
|
||||
-816
@@ -1,816 +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)]
|
||||
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,
|
||||
}
|
||||
|
||||
#[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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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 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,
|
||||
FocusWindowDown,
|
||||
FocusWindowUp,
|
||||
FocusWindowOrWorkspaceDown,
|
||||
FocusWindowOrWorkspaceUp,
|
||||
MoveColumnLeft,
|
||||
MoveColumnRight,
|
||||
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,
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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"
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
"#,
|
||||
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()),
|
||||
},
|
||||
},
|
||||
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,
|
||||
},
|
||||
},
|
||||
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.,
|
||||
..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());
|
||||
}
|
||||
}
|
||||
+5
-12
@@ -8,8 +8,7 @@ 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::backend::renderer::element::memory::MemoryRenderBuffer;
|
||||
use smithay::input::pointer::{CursorIcon, CursorImageAttributes, CursorImageStatus};
|
||||
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
|
||||
use smithay::utils::{IsAlive, Logical, Physical, Point, Transform};
|
||||
@@ -224,7 +223,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 +237,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 +250,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]
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
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::names::{OwnedUniqueName, UniqueName};
|
||||
use zbus::zvariant::NoneValue;
|
||||
use zbus::{dbus_interface, MessageHeader, 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<()>>>,
|
||||
}
|
||||
|
||||
#[dbus_interface(name = "org.freedesktop.ScreenSaver")]
|
||||
impl ScreenSaver {
|
||||
async fn inhibit(
|
||||
&mut self,
|
||||
#[zbus(header)] hdr: MessageHeader<'_>,
|
||||
application_name: &str,
|
||||
reason_for_inhibit: &str,
|
||||
) -> fdo::Result<u32> {
|
||||
trace!(
|
||||
"fdo inhibit, app: `{application_name}`, reason: `{reason_for_inhibit}`, owner: {:?}",
|
||||
hdr.sender()
|
||||
);
|
||||
|
||||
let Ok(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)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use smithay::reexports::calloop;
|
||||
use zbus::dbus_interface;
|
||||
use zbus::fdo::{self, RequestNameFlags};
|
||||
|
||||
|
||||
+11
-4
@@ -1,9 +1,9 @@
|
||||
use smithay::reexports::calloop;
|
||||
use zbus::blocking::Connection;
|
||||
use zbus::Interface;
|
||||
|
||||
use crate::niri::State;
|
||||
|
||||
pub mod freedesktop_screensaver;
|
||||
pub mod gnome_shell_screenshot;
|
||||
pub mod mutter_display_config;
|
||||
pub mod mutter_service_channel;
|
||||
@@ -13,6 +13,7 @@ pub mod mutter_screen_cast;
|
||||
#[cfg(feature = "xdp-gnome-screencast")]
|
||||
use mutter_screen_cast::ScreenCast;
|
||||
|
||||
use self::freedesktop_screensaver::ScreenSaver;
|
||||
use self::mutter_display_config::DisplayConfig;
|
||||
use self::mutter_service_channel::ServiceChannel;
|
||||
|
||||
@@ -24,6 +25,7 @@ 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>,
|
||||
#[cfg(feature = "xdp-gnome-screencast")]
|
||||
pub conn_screen_cast: Option<Connection>,
|
||||
@@ -45,9 +47,12 @@ impl DBusServers {
|
||||
}
|
||||
|
||||
if is_session_instance || config.debug.dbus_interfaces_in_non_session_instances {
|
||||
let display_config = DisplayConfig::new(backend.connectors());
|
||||
let display_config = DisplayConfig::new(backend.ipc_outputs());
|
||||
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
|
||||
@@ -62,7 +67,7 @@ impl DBusServers {
|
||||
dbus.conn_screen_shot = try_start(screenshot);
|
||||
|
||||
#[cfg(feature = "xdp-gnome-screencast")]
|
||||
{
|
||||
if niri.pipewire.is_some() {
|
||||
let (to_niri, from_screen_cast) = calloop::channel::channel();
|
||||
niri.event_loop
|
||||
.insert_source(from_screen_cast, {
|
||||
@@ -75,8 +80,10 @@ impl DBusServers {
|
||||
}
|
||||
})
|
||||
.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);
|
||||
} else {
|
||||
warn!("disabling screencast support because we couldn't start PipeWire");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,15 +2,15 @@ use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use serde::Serialize;
|
||||
use smithay::output::Output;
|
||||
use zbus::fdo::RequestNameFlags;
|
||||
use zbus::zvariant::{OwnedValue, Type};
|
||||
use zbus::{dbus_interface, fdo};
|
||||
use zbus::zvariant::{self, OwnedValue, Type};
|
||||
use zbus::{dbus_interface, fdo, SignalContext};
|
||||
|
||||
use super::Start;
|
||||
use crate::backend::IpcOutputMap;
|
||||
|
||||
pub struct DisplayConfig {
|
||||
connectors: Arc<Mutex<HashMap<String, Output>>>,
|
||||
ipc_outputs: Arc<Mutex<IpcOutputMap>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Type)]
|
||||
@@ -53,40 +53,118 @@ impl DisplayConfig {
|
||||
HashMap<String, OwnedValue>,
|
||||
)> {
|
||||
// Construct the DBus response.
|
||||
let monitors: Vec<Monitor> = self
|
||||
.connectors
|
||||
let mut monitors: Vec<(Monitor, LogicalMonitor)> = self
|
||||
.ipc_outputs
|
||||
.lock()
|
||||
.unwrap()
|
||||
.keys()
|
||||
.map(|c| Monitor {
|
||||
names: (c.clone(), String::new(), String::new(), String::new()),
|
||||
modes: vec![],
|
||||
properties: HashMap::new(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
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(),
|
||||
// Take only enabled outputs.
|
||||
.filter(|(_, output)| output.current_mode.is_some() && output.logical.is_some())
|
||||
.map(|(c, output)| {
|
||||
// Loosely matches the check in Mutter.
|
||||
let is_laptop_panel = matches!(c.get(..4), Some("eDP-" | "LVDS" | "DSI-"));
|
||||
|
||||
// FIXME: use proper serial when we have libdisplay-info.
|
||||
// A serial is required for correct session restore by xdp-gnome.
|
||||
let serial = c.clone();
|
||||
|
||||
let mut properties = HashMap::new();
|
||||
if is_laptop_panel {
|
||||
properties.insert(
|
||||
String::from("display-name"),
|
||||
OwnedValue::from(zvariant::Str::from_static("Built-in display")),
|
||||
);
|
||||
}
|
||||
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 refresh = refresh_rate as f64 / 1000.;
|
||||
|
||||
Mode {
|
||||
id: format!("{width}x{height}@{refresh:.3}"),
|
||||
width: i32::from(width),
|
||||
height: i32::from(height),
|
||||
refresh_rate: refresh,
|
||||
preferred_scale: 1.,
|
||||
supported_scales: vec![1., 2., 3.],
|
||||
properties: HashMap::from([(
|
||||
String::from("is-preferred"),
|
||||
OwnedValue::from(is_preferred),
|
||||
)]),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
modes[output.current_mode.unwrap()]
|
||||
.properties
|
||||
.insert(String::from("is-current"), OwnedValue::from(true));
|
||||
|
||||
let monitor = Monitor {
|
||||
names: (c.clone(), String::new(), String::new(), serial),
|
||||
modes,
|
||||
properties,
|
||||
};
|
||||
|
||||
let logical = output.logical.as_ref().unwrap();
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
let logical_monitor = LogicalMonitor {
|
||||
x: logical.x,
|
||||
y: logical.y,
|
||||
scale: logical.scale,
|
||||
transform,
|
||||
is_primary: false,
|
||||
monitors: vec![monitor.names.clone()],
|
||||
properties: HashMap::new(),
|
||||
};
|
||||
|
||||
(monitor, logical_monitor)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok((0, monitors, logical_monitors, HashMap::new()))
|
||||
// Sort the built-in monitor first, then by connector name.
|
||||
monitors.sort_unstable_by(|a, b| {
|
||||
let a_is_builtin = a.0.properties.contains_key("display-name");
|
||||
let b_is_builtin = b.0.properties.contains_key("display-name");
|
||||
a_is_builtin
|
||||
.cmp(&b_is_builtin)
|
||||
.reverse()
|
||||
.then_with(|| a.0.names.0.cmp(&b.0.names.0))
|
||||
});
|
||||
|
||||
let (monitors, logical_monitors) = monitors.into_iter().unzip();
|
||||
let properties = HashMap::from([(String::from("layout-mode"), OwnedValue::from(1u32))]);
|
||||
Ok((0, monitors, logical_monitors, properties))
|
||||
}
|
||||
|
||||
// FIXME: monitors-changed signal.
|
||||
#[dbus_interface(signal)]
|
||||
pub async fn monitors_changed(ctxt: &SignalContext<'_>) -> zbus::Result<()>;
|
||||
}
|
||||
|
||||
impl DisplayConfig {
|
||||
pub fn new(connectors: Arc<Mutex<HashMap<String, Output>>>) -> Self {
|
||||
Self { connectors }
|
||||
pub fn new(ipc_outputs: Arc<Mutex<IpcOutputMap>>) -> Self {
|
||||
Self { ipc_outputs }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,26 +5,29 @@ 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::zvariant::{DeserializeDict, OwnedObjectPath, SerializeDict, Type, Value};
|
||||
use zbus::{dbus_interface, fdo, InterfaceRef, ObjectServer, SignalContext};
|
||||
|
||||
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)]
|
||||
@@ -46,22 +49,33 @@ struct RecordMonitorProperties {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Stream {
|
||||
output: Output,
|
||||
// FIXME: update on scale changes and whatnot.
|
||||
output: niri_ipc::Output,
|
||||
cursor_mode: CursorMode,
|
||||
was_started: Arc<AtomicBool>,
|
||||
to_niri: calloop::channel::Sender<ScreenCastToNiri>,
|
||||
}
|
||||
|
||||
#[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,
|
||||
output: String,
|
||||
cursor_mode: CursorMode,
|
||||
signal_ctx: SignalContext<'static>,
|
||||
},
|
||||
StopCast {
|
||||
session_id: usize,
|
||||
},
|
||||
Redraw(Output),
|
||||
}
|
||||
|
||||
#[dbus_interface(name = "org.gnome.Mutter.ScreenCast")]
|
||||
@@ -82,7 +96,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();
|
||||
@@ -122,6 +136,11 @@ impl Session {
|
||||
) {
|
||||
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 {
|
||||
@@ -149,10 +168,14 @@ impl Session {
|
||||
) -> fdo::Result<OwnedObjectPath> {
|
||||
debug!(connector, ?properties, "record_monitor");
|
||||
|
||||
let Some(output) = self.connectors.lock().unwrap().get(connector).cloned() else {
|
||||
let Some(output) = self.ipc_outputs.lock().unwrap().get(connector).cloned() else {
|
||||
return Err(fdo::Error::Failed("no such monitor".to_owned()));
|
||||
};
|
||||
|
||||
if output.logical.is_none() {
|
||||
return Err(fdo::Error::Failed("monitor is disabled".to_owned()));
|
||||
}
|
||||
|
||||
static NUMBER: AtomicUsize = AtomicUsize::new(0);
|
||||
let path = format!(
|
||||
"/org/gnome/Mutter/ScreenCast/Stream/u{}",
|
||||
@@ -162,7 +185,7 @@ impl Session {
|
||||
|
||||
let cursor_mode = properties.cursor_mode.unwrap_or_default();
|
||||
|
||||
let stream = Stream::new(output, cursor_mode, self.to_niri.clone());
|
||||
let stream = Stream::new(output.clone(), cursor_mode, self.to_niri.clone());
|
||||
match server.at(&path, stream.clone()).await {
|
||||
Ok(true) => {
|
||||
let iface = server.interface(&path).await.unwrap();
|
||||
@@ -188,15 +211,24 @@ impl Stream {
|
||||
#[dbus_interface(signal)]
|
||||
pub async fn pipe_wire_stream_added(ctxt: &SignalContext<'_>, node_id: u32)
|
||||
-> zbus::Result<()>;
|
||||
|
||||
#[dbus_interface(property)]
|
||||
async fn parameters(&self) -> StreamParameters {
|
||||
let logical = self.output.logical.as_ref().unwrap();
|
||||
StreamParameters {
|
||||
position: (logical.x, logical.y),
|
||||
size: (logical.width as i32, logical.height as i32),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 +253,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)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -243,7 +276,7 @@ impl Drop for Session {
|
||||
|
||||
impl Stream {
|
||||
pub fn new(
|
||||
output: Output,
|
||||
output: niri_ipc::Output,
|
||||
cursor_mode: CursorMode,
|
||||
to_niri: calloop::channel::Sender<ScreenCastToNiri>,
|
||||
) -> Self {
|
||||
@@ -262,7 +295,7 @@ impl Stream {
|
||||
|
||||
let msg = ScreenCastToNiri::StartCast {
|
||||
session_id,
|
||||
output: self.output.clone(),
|
||||
output: self.output.name.clone(),
|
||||
cursor_mode: self.cursor_mode,
|
||||
signal_ctx: ctxt,
|
||||
};
|
||||
|
||||
@@ -25,9 +25,13 @@ impl ServiceChannel {
|
||||
}
|
||||
|
||||
let (sock1, sock2) = UnixStream::pair().unwrap();
|
||||
self.display
|
||||
.insert_client(sock2, Arc::new(ClientState::default()))
|
||||
.unwrap();
|
||||
let data = Arc::new(ClientState {
|
||||
compositor_state: Default::default(),
|
||||
// Would be nice to thread config here but for now it's fine.
|
||||
can_view_decoration_globals: false,
|
||||
restricted: false,
|
||||
});
|
||||
self.display.insert_client(sock2, data).unwrap();
|
||||
Ok(unsafe { zbus::zvariant::OwnedFd::from_raw_fd(sock1.into_raw_fd()) })
|
||||
}
|
||||
}
|
||||
|
||||
+20
-2
@@ -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,15 @@ 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 presented(&mut self, presentation_time: Duration) {
|
||||
if presentation_time.is_zero() {
|
||||
// Not interested in these.
|
||||
@@ -71,6 +82,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+193
-36
@@ -13,11 +13,13 @@ use smithay::wayland::compositor::{
|
||||
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 super::xdg_shell::add_mapped_toplevel_pre_commit_hook;
|
||||
use crate::niri::{ClientState, State};
|
||||
use crate::window::{InitialConfigureState, Mapped, ResolvedWindowRules, Unmapped};
|
||||
|
||||
impl CompositorHandler for State {
|
||||
fn compositor_state(&mut self) -> &mut CompositorState {
|
||||
@@ -52,35 +54,38 @@ impl CompositorHandler for State {
|
||||
.buffer
|
||||
.as_ref()
|
||||
.and_then(|assignment| match assignment {
|
||||
BufferAssignment::NewBuffer(buffer) => get_dmabuf(buffer).ok(),
|
||||
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) {
|
||||
let client = surface.client().unwrap();
|
||||
let res = state
|
||||
.niri
|
||||
.event_loop
|
||||
.insert_source(source, move |_, _, state| {
|
||||
let display_handle = state.niri.display_handle.clone();
|
||||
if let Some(client) = surface.client() {
|
||||
let res =
|
||||
state
|
||||
.client_compositor_state(&client)
|
||||
.blocker_cleared(state, &display_handle);
|
||||
Ok(())
|
||||
});
|
||||
if res.is_ok() {
|
||||
add_blocker(surface, blocker);
|
||||
.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
fn commit(&mut self, surface: &WlSurface) {
|
||||
let _span = tracy_client::span!("CompositorHandler::commit");
|
||||
|
||||
on_commit_buffer_handler::<Self>(surface);
|
||||
self.backend.early_import(surface);
|
||||
|
||||
if is_sync_subsurface(surface) {
|
||||
return;
|
||||
@@ -91,54 +96,180 @@ 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());
|
||||
with_renderer_surface_state(surface, |state| state.buffer().is_some())
|
||||
.unwrap_or_else(|| {
|
||||
error!("no renderer surface state even though we use commit handler");
|
||||
false
|
||||
});
|
||||
|
||||
if is_mapped {
|
||||
// The toplevel got mapped.
|
||||
let window = entry.remove();
|
||||
let Unmapped { window, state } = 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, is_full_width, output, workspace_name) =
|
||||
if let InitialConfigureState::Configured {
|
||||
rules,
|
||||
width,
|
||||
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());
|
||||
|
||||
// Chech that the workspace still exists.
|
||||
let workspace_name = workspace_name
|
||||
.filter(|n| self.niri.layout.find_workspace_by_name(n).is_some());
|
||||
|
||||
(rules, width, is_full_width, output, workspace_name)
|
||||
} else {
|
||||
error!("window map must happen after initial configure");
|
||||
(ResolvedWindowRules::empty(), None, false, None, None)
|
||||
};
|
||||
|
||||
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)| {
|
||||
output.is_none() || output.as_ref() == Some(*parent_output)
|
||||
})
|
||||
.map(|(mapped, _)| mapped.window.clone());
|
||||
|
||||
let hook = add_mapped_toplevel_pre_commit_hook(toplevel);
|
||||
let mapped = Mapped::new(window, rules, hook);
|
||||
let window = mapped.window.clone();
|
||||
|
||||
let output = if let Some(p) = parent {
|
||||
// Open dialogs immediately to the right of their parent window.
|
||||
self.niri
|
||||
.layout
|
||||
.add_window_right_of(&p, mapped, width, is_full_width)
|
||||
} else if let Some(workspace_name) = &workspace_name {
|
||||
self.niri.layout.add_window_to_named_workspace(
|
||||
workspace_name,
|
||||
mapped,
|
||||
width,
|
||||
is_full_width,
|
||||
)
|
||||
} else if let Some(output) = &output {
|
||||
self.niri
|
||||
.layout
|
||||
.add_window_on_output(output, mapped, width, is_full_width);
|
||||
Some(output)
|
||||
} else {
|
||||
self.niri.layout.add_window(mapped, width, is_full_width)
|
||||
};
|
||||
|
||||
if let Some(output) = output.cloned() {
|
||||
self.niri.layout.start_open_animation_for_window(&window);
|
||||
|
||||
let new_active_window =
|
||||
self.niri.layout.active_window().map(|(m, _)| &m.window);
|
||||
if new_active_window == Some(&window) {
|
||||
self.maybe_warp_cursor_to_focus();
|
||||
}
|
||||
|
||||
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((window, output)) = self.niri.layout.find_window_and_output(surface) {
|
||||
// This is a commit of a previously-mapped toplevel.
|
||||
window.on_commit();
|
||||
if let Some((mapped, output)) = self.niri.layout.find_window_and_output(surface) {
|
||||
let window = mapped.window.clone();
|
||||
let output = output.clone();
|
||||
|
||||
// This is a commit of a previously-mapped toplevel.
|
||||
let is_mapped =
|
||||
with_renderer_surface_state(surface, |state| state.buffer().is_some());
|
||||
with_renderer_surface_state(surface, |state| state.buffer().is_some())
|
||||
.unwrap_or_else(|| {
|
||||
error!("no renderer surface state even though we use commit handler");
|
||||
false
|
||||
});
|
||||
|
||||
// Must start the close animation before window.on_commit().
|
||||
if !is_mapped {
|
||||
self.backend.with_primary_renderer(|renderer| {
|
||||
self.niri
|
||||
.layout
|
||||
.start_close_animation_for_window(renderer, &window);
|
||||
});
|
||||
}
|
||||
|
||||
window.on_commit();
|
||||
|
||||
if !is_mapped {
|
||||
// The toplevel got unmapped.
|
||||
//
|
||||
// Test client: wleird-unmap.
|
||||
let active_window = self.niri.layout.active_window().map(|(m, _)| &m.window);
|
||||
let was_active = active_window == Some(&window);
|
||||
|
||||
self.niri.layout.remove_window(&window);
|
||||
self.niri.unmapped_windows.insert(surface.clone(), window);
|
||||
self.niri.queue_redraw(output);
|
||||
|
||||
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);
|
||||
|
||||
self.niri.queue_redraw(&output);
|
||||
return;
|
||||
}
|
||||
|
||||
let serial = with_states(surface, |states| {
|
||||
let role = states
|
||||
.data_map
|
||||
.get::<XdgToplevelSurfaceData>()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.unwrap();
|
||||
role.configure_serial
|
||||
});
|
||||
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);
|
||||
|
||||
// Popup placement depends on window size which might have changed.
|
||||
self.update_reactive_popups(&window, &output);
|
||||
|
||||
self.niri.queue_redraw(output);
|
||||
self.niri.queue_redraw(&output);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -147,10 +278,12 @@ 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 {
|
||||
if let Some((mapped, output)) = root_window_output {
|
||||
let window = mapped.window.clone();
|
||||
let output = output.clone();
|
||||
window.on_commit();
|
||||
self.niri.layout.update_window(&window);
|
||||
self.niri.queue_redraw(output);
|
||||
self.niri.layout.update_window(&window, None);
|
||||
self.niri.queue_redraw(&output);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -158,7 +291,7 @@ 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);
|
||||
self.niri.queue_redraw(&output.clone());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,14 +315,38 @@ impl CompositorHandler for State {
|
||||
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());
|
||||
if lock_surface.wl_surface() == &root_surface {
|
||||
self.niri.queue_redraw(&output.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
impl BufferHandler for State {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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;
|
||||
@@ -50,12 +50,12 @@ impl WlrLayerShellHandler for State {
|
||||
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);
|
||||
@@ -107,6 +107,6 @@ impl State {
|
||||
}
|
||||
drop(map);
|
||||
|
||||
self.niri.output_resized(output);
|
||||
self.niri.output_resized(&output);
|
||||
}
|
||||
}
|
||||
|
||||
+266
-24
@@ -9,11 +9,14 @@ use std::sync::Arc;
|
||||
use std::thread;
|
||||
|
||||
use smithay::backend::allocator::dmabuf::Dmabuf;
|
||||
use smithay::backend::renderer::ImportDma;
|
||||
use smithay::backend::drm::DrmNode;
|
||||
use smithay::backend::input::TabletToolDescriptor;
|
||||
use smithay::desktop::{PopupKind, PopupManager};
|
||||
use smithay::input::pointer::{CursorIcon, CursorImageStatus, PointerHandle};
|
||||
use smithay::input::{Seat, SeatHandler, SeatState};
|
||||
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_server::protocol::wl_data_source::WlDataSource;
|
||||
use smithay::reexports::wayland_server::protocol::wl_output::WlOutput;
|
||||
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
|
||||
@@ -21,8 +24,17 @@ use smithay::reexports::wayland_server::Resource;
|
||||
use smithay::utils::{Logical, Rectangle, Size};
|
||||
use smithay::wayland::compositor::{send_surface_state, with_states};
|
||||
use smithay::wayland::dmabuf::{DmabufGlobal, DmabufHandler, DmabufState, ImportNotifier};
|
||||
use smithay::wayland::drm_lease::{
|
||||
DrmLease, DrmLeaseBuilder, DrmLeaseHandler, DrmLeaseRequest, DrmLeaseState, LeaseRejected,
|
||||
};
|
||||
use smithay::wayland::idle_inhibit::IdleInhibitHandler;
|
||||
use smithay::wayland::idle_notify::{IdleNotifierHandler, IdleNotifierState};
|
||||
use smithay::wayland::input_method::{InputMethodHandler, PopupSurface};
|
||||
use smithay::wayland::output::OutputHandler;
|
||||
use smithay::wayland::pointer_constraints::PointerConstraintsHandler;
|
||||
use smithay::wayland::security_context::{
|
||||
SecurityContext, SecurityContextHandler, SecurityContextListenerSource,
|
||||
};
|
||||
use smithay::wayland::selection::data_device::{
|
||||
set_data_device_focus, ClientDndGrabHandler, DataDeviceHandler, DataDeviceState,
|
||||
ServerDndGrabHandler,
|
||||
@@ -35,20 +47,29 @@ use smithay::wayland::selection::{SelectionHandler, SelectionTarget};
|
||||
use smithay::wayland::session_lock::{
|
||||
LockSurface, SessionLockHandler, SessionLockManagerState, SessionLocker,
|
||||
};
|
||||
use smithay::wayland::tablet_manager::TabletSeatHandler;
|
||||
use smithay::{
|
||||
delegate_cursor_shape, delegate_data_control, delegate_data_device, delegate_dmabuf,
|
||||
delegate_input_method_manager, 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_drm_lease, delegate_idle_inhibit, delegate_idle_notify, delegate_input_method_manager,
|
||||
delegate_output, delegate_pointer_constraints, delegate_pointer_gestures,
|
||||
delegate_presentation, delegate_primary_selection, delegate_relative_pointer, delegate_seat,
|
||||
delegate_security_context, delegate_session_lock, delegate_tablet_manager,
|
||||
delegate_text_input_manager, delegate_viewporter, delegate_virtual_keyboard_manager,
|
||||
};
|
||||
|
||||
use crate::layout::output_size;
|
||||
use crate::niri::State;
|
||||
use crate::niri::{ClientState, State};
|
||||
use crate::protocols::foreign_toplevel::{
|
||||
self, ForeignToplevelHandler, ForeignToplevelManagerState,
|
||||
};
|
||||
use crate::protocols::gamma_control::{GammaControlHandler, GammaControlManagerState};
|
||||
use crate::protocols::screencopy::{Screencopy, ScreencopyHandler};
|
||||
use crate::utils::output_size;
|
||||
use crate::{delegate_foreign_toplevel, delegate_gamma_control, delegate_screencopy};
|
||||
|
||||
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
|
||||
@@ -71,14 +92,36 @@ 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(
|
||||
@@ -91,29 +134,39 @@ 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 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);
|
||||
});
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -136,6 +189,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:?}");
|
||||
}
|
||||
@@ -187,13 +244,18 @@ impl DataControlHandler for State {
|
||||
|
||||
delegate_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);
|
||||
|
||||
impl DmabufHandler for State {
|
||||
fn dmabuf_state(&mut self) -> &mut DmabufState {
|
||||
self.backend.tty().dmabuf_state()
|
||||
&mut self.niri.dmabuf_state
|
||||
}
|
||||
|
||||
fn dmabuf_imported(
|
||||
@@ -202,17 +264,10 @@ impl DmabufHandler for State {
|
||||
dmabuf: Dmabuf,
|
||||
notifier: ImportNotifier,
|
||||
) {
|
||||
let renderer = self.backend.renderer().expect(
|
||||
"the dmabuf global must be created and destroyed together with the output device",
|
||||
);
|
||||
match renderer.import_dmabuf(&dmabuf, None) {
|
||||
Ok(_texture) => {
|
||||
let _ = notifier.successful::<State>();
|
||||
}
|
||||
Err(err) => {
|
||||
debug!("error importing dmabuf: {err:?}");
|
||||
notifier.failed();
|
||||
}
|
||||
if self.backend.import_dmabuf(&dmabuf) {
|
||||
let _ = notifier.successful::<State>();
|
||||
} else {
|
||||
notifier.failed();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -256,3 +311,190 @@ pub fn configure_lock_surface(surface: &LockSurface, output: &Output) {
|
||||
});
|
||||
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| {
|
||||
let config = state.niri.config.borrow();
|
||||
let data = Arc::new(ClientState {
|
||||
compositor_state: Default::default(),
|
||||
can_view_decoration_globals: config.prefer_no_csd,
|
||||
restricted: true,
|
||||
});
|
||||
|
||||
if let Err(err) = state.niri.display_handle.insert_client(client, data) {
|
||||
warn!("error inserting client: {err}");
|
||||
} else {
|
||||
trace!("inserted a new restricted client, context={context:?}");
|
||||
}
|
||||
})
|
||||
.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.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)
|
||||
{
|
||||
if !mapped
|
||||
.toplevel()
|
||||
.current_state()
|
||||
.capabilities
|
||||
.contains(xdg_toplevel::WmCapabilities::Fullscreen)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let window = mapped.window.clone();
|
||||
|
||||
if let Some(requested_output) = wl_output.as_ref().and_then(Output::from_resource) {
|
||||
if &requested_output != current_output {
|
||||
self.niri
|
||||
.layout
|
||||
.move_window_to_output(&window, &requested_output);
|
||||
}
|
||||
}
|
||||
|
||||
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, screencopy: Screencopy) {
|
||||
if let Err(err) = self
|
||||
.niri
|
||||
.render_for_screencopy(&mut self.backend, screencopy)
|
||||
{
|
||||
warn!("error rendering for screencopy: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
delegate_screencopy!(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);
|
||||
|
||||
+695
-117
@@ -1,25 +1,41 @@
|
||||
use smithay::desktop::{
|
||||
find_popup_root_surface, get_popup_toplevel_coords, layer_map_for_output, LayerSurface,
|
||||
PopupKind, PopupManager, Window, WindowSurfaceType,
|
||||
find_popup_root_surface, get_popup_toplevel_coords, layer_map_for_output, utils, LayerSurface,
|
||||
PopupKeyboardGrab, PopupKind, PopupManager, PopupPointerGrab, PopupUngrabStrategy, Window,
|
||||
WindowSurfaceType,
|
||||
};
|
||||
use smithay::input::pointer::Focus;
|
||||
use smithay::output::Output;
|
||||
use smithay::reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1;
|
||||
use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_positioner::ConstraintAdjustment;
|
||||
use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::{self, ResizeEdge};
|
||||
use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::{self};
|
||||
use smithay::reexports::wayland_server::protocol::wl_output;
|
||||
use smithay::reexports::wayland_server::protocol::wl_seat::WlSeat;
|
||||
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
|
||||
use smithay::reexports::wayland_server::Resource;
|
||||
use smithay::utils::{Logical, Rectangle, Serial};
|
||||
use smithay::wayland::compositor::{send_surface_state, with_states};
|
||||
use smithay::wayland::compositor::{
|
||||
add_pre_commit_hook, send_surface_state, with_states, BufferAssignment, HookId,
|
||||
SurfaceAttributes,
|
||||
};
|
||||
use smithay::wayland::input_method::InputMethodSeat;
|
||||
use smithay::wayland::shell::kde::decoration::{KdeDecorationHandler, KdeDecorationState};
|
||||
use smithay::wayland::shell::wlr_layer::{self, Layer};
|
||||
use smithay::wayland::shell::xdg::decoration::XdgDecorationHandler;
|
||||
use smithay::wayland::shell::xdg::{
|
||||
PopupSurface, PositionerState, ToplevelSurface, XdgPopupSurfaceData, XdgShellHandler,
|
||||
XdgShellState, XdgToplevelSurfaceData,
|
||||
};
|
||||
use smithay::{delegate_kde_decoration, delegate_xdg_decoration, delegate_xdg_shell};
|
||||
use smithay::wayland::xdg_foreign::{XdgForeignHandler, XdgForeignState};
|
||||
use smithay::{
|
||||
delegate_kde_decoration, delegate_xdg_decoration, delegate_xdg_foreign, delegate_xdg_shell,
|
||||
};
|
||||
|
||||
use crate::niri::State;
|
||||
use crate::input::resize_grab::ResizeGrab;
|
||||
use crate::input::DOUBLE_CLICK_TIME;
|
||||
use crate::layout::workspace::ColumnWidth;
|
||||
use crate::niri::{PopupGrabState, State};
|
||||
use crate::utils::{get_monotonic_time, ResizeEdge};
|
||||
use crate::window::{InitialConfigureState, ResolvedWindowRules, Unmapped, WindowRef};
|
||||
|
||||
impl XdgShellHandler for State {
|
||||
fn xdg_shell_state(&mut self) -> &mut XdgShellState {
|
||||
@@ -28,34 +44,16 @@ impl XdgShellHandler for State {
|
||||
|
||||
fn new_toplevel(&mut self, surface: ToplevelSurface) {
|
||||
let wl_surface = surface.wl_surface().clone();
|
||||
let window = Window::new(surface);
|
||||
|
||||
// Tell the surface the preferred size and bounds for its likely output.
|
||||
if let Some(ws) = self.niri.layout.active_workspace() {
|
||||
ws.configure_new_window(&window);
|
||||
}
|
||||
|
||||
// If the user prefers no CSD, it's a reasonable assumption that they would prefer to get
|
||||
// rid of the various client-side rounded corners also by using the tiled state.
|
||||
let config = self.niri.config.borrow();
|
||||
if config.prefer_no_csd {
|
||||
window.toplevel().with_pending_state(|state| {
|
||||
state.states.set(xdg_toplevel::State::TiledLeft);
|
||||
state.states.set(xdg_toplevel::State::TiledRight);
|
||||
state.states.set(xdg_toplevel::State::TiledTop);
|
||||
state.states.set(xdg_toplevel::State::TiledBottom);
|
||||
});
|
||||
}
|
||||
|
||||
// At the moment of creation, xdg toplevels must have no buffer.
|
||||
let existing = self.niri.unmapped_windows.insert(wl_surface, window);
|
||||
let unmapped = Unmapped::new(Window::new_wayland_window(surface));
|
||||
let existing = self.niri.unmapped_windows.insert(wl_surface, unmapped);
|
||||
assert!(existing.is_none());
|
||||
}
|
||||
|
||||
fn new_popup(&mut self, surface: PopupSurface, _positioner: PositionerState) {
|
||||
self.unconstrain_popup(&surface);
|
||||
let popup = PopupKind::Xdg(surface);
|
||||
self.unconstrain_popup(&popup);
|
||||
|
||||
if let Err(err) = self.niri.popups.track_popup(PopupKind::Xdg(surface)) {
|
||||
if let Err(err) = self.niri.popups.track_popup(popup) {
|
||||
warn!("error tracking popup: {err:?}");
|
||||
}
|
||||
}
|
||||
@@ -66,12 +64,71 @@ impl XdgShellHandler for State {
|
||||
|
||||
fn resize_request(
|
||||
&mut self,
|
||||
_surface: ToplevelSurface,
|
||||
surface: ToplevelSurface,
|
||||
_seat: WlSeat,
|
||||
_serial: Serial,
|
||||
_edges: ResizeEdge,
|
||||
serial: Serial,
|
||||
edges: xdg_toplevel::ResizeEdge,
|
||||
) {
|
||||
// FIXME
|
||||
let pointer = self.niri.seat.get_pointer().unwrap();
|
||||
if !pointer.has_grab(serial) {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(start_data) = pointer.grab_start_data() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some((focus, _)) = &start_data.focus else {
|
||||
return;
|
||||
};
|
||||
|
||||
let wl_surface = surface.wl_surface();
|
||||
if !focus.id().same_client_as(&wl_surface.id()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some((mapped, _)) = self.niri.layout.find_window_and_output(wl_surface) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let edges = ResizeEdge::from(edges);
|
||||
let window = mapped.window.clone();
|
||||
|
||||
// See if we got a double resize-click gesture.
|
||||
let time = get_monotonic_time();
|
||||
let last_cell = mapped.last_interactive_resize_start();
|
||||
let last = last_cell.get();
|
||||
last_cell.set(Some((time, edges)));
|
||||
if let Some((last_time, last_edges)) = last {
|
||||
if time.saturating_sub(last_time) <= DOUBLE_CLICK_TIME {
|
||||
// Allow quick resize after a triple click.
|
||||
last_cell.set(None);
|
||||
|
||||
let intersection = edges.intersection(last_edges);
|
||||
if intersection.intersects(ResizeEdge::LEFT_RIGHT) {
|
||||
// FIXME: don't activate once we can pass specific windows to actions.
|
||||
self.niri.layout.activate_window(&window);
|
||||
self.niri.layout.toggle_full_width();
|
||||
}
|
||||
if intersection.intersects(ResizeEdge::TOP_BOTTOM) {
|
||||
// FIXME: don't activate once we can pass specific windows to actions.
|
||||
self.niri.layout.activate_window(&window);
|
||||
self.niri.layout.reset_window_height();
|
||||
}
|
||||
// FIXME: granular.
|
||||
self.niri.queue_redraw_all();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let grab = ResizeGrab::new(start_data, window.clone());
|
||||
|
||||
if !self.niri.layout.interactive_resize_begin(window, edges) {
|
||||
return;
|
||||
}
|
||||
|
||||
pointer.set_grab(self, grab, serial, Focus::Clear);
|
||||
self.niri.pointer_grab_ongoing = true;
|
||||
}
|
||||
|
||||
fn reposition_request(
|
||||
@@ -85,20 +142,117 @@ impl XdgShellHandler for State {
|
||||
state.geometry = geometry;
|
||||
state.positioner = positioner;
|
||||
});
|
||||
self.unconstrain_popup(&surface);
|
||||
self.unconstrain_popup(&PopupKind::Xdg(surface.clone()));
|
||||
surface.send_repositioned(token);
|
||||
}
|
||||
|
||||
fn grab(&mut self, _surface: PopupSurface, _seat: WlSeat, _serial: Serial) {
|
||||
// FIXME popup grabs
|
||||
fn grab(&mut self, surface: PopupSurface, _seat: WlSeat, serial: Serial) {
|
||||
// HACK: ignore grabs (pretend they work without actually grabbing) if the input method has
|
||||
// a grab. It will likely need refactors in Smithay to support properly since grabs just
|
||||
// replace each other.
|
||||
// FIXME: do this properly.
|
||||
if self.niri.seat.input_method().keyboard_grabbed() {
|
||||
trace!("ignoring popup grab because IME has keyboard grabbed");
|
||||
return;
|
||||
}
|
||||
|
||||
let popup = PopupKind::Xdg(surface);
|
||||
let Ok(root) = find_popup_root_surface(&popup) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// We need to hand out the grab in a way consistent with what update_keyboard_focus()
|
||||
// thinks the current focus is, otherwise it will desync and cause weird issues with
|
||||
// keyboard focus being at the wrong place.
|
||||
if self.niri.is_locked() {
|
||||
if Some(&root) != self.niri.lock_surface_focus().as_ref() {
|
||||
let _ = PopupManager::dismiss_popup(&root, &popup);
|
||||
return;
|
||||
}
|
||||
} else if self.niri.screenshot_ui.is_open() {
|
||||
let _ = PopupManager::dismiss_popup(&root, &popup);
|
||||
return;
|
||||
} else if let Some(output) = self.niri.layout.active_output() {
|
||||
let layers = layer_map_for_output(output);
|
||||
|
||||
if let Some(layer_surface) =
|
||||
layers.layer_for_surface(&root, WindowSurfaceType::TOPLEVEL)
|
||||
{
|
||||
if !matches!(layer_surface.layer(), Layer::Overlay | Layer::Top) {
|
||||
let _ = PopupManager::dismiss_popup(&root, &popup);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if layers.layers_on(Layer::Overlay).any(|l| {
|
||||
l.cached_state().keyboard_interactivity
|
||||
== wlr_layer::KeyboardInteractivity::Exclusive
|
||||
}) {
|
||||
let _ = PopupManager::dismiss_popup(&root, &popup);
|
||||
return;
|
||||
}
|
||||
|
||||
let mon = self.niri.layout.monitor_for_output(output).unwrap();
|
||||
if !mon.render_above_top_layer()
|
||||
&& layers.layers_on(Layer::Top).any(|l| {
|
||||
l.cached_state().keyboard_interactivity
|
||||
== wlr_layer::KeyboardInteractivity::Exclusive
|
||||
})
|
||||
{
|
||||
let _ = PopupManager::dismiss_popup(&root, &popup);
|
||||
return;
|
||||
}
|
||||
|
||||
let layout_focus = self.niri.layout.focus();
|
||||
if Some(&root) != layout_focus.map(|win| win.toplevel().wl_surface()) {
|
||||
let _ = PopupManager::dismiss_popup(&root, &popup);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let _ = PopupManager::dismiss_popup(&root, &popup);
|
||||
return;
|
||||
}
|
||||
|
||||
let seat = &self.niri.seat;
|
||||
let Ok(mut grab) = self
|
||||
.niri
|
||||
.popups
|
||||
.grab_popup(root.clone(), popup, seat, serial)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let keyboard = seat.get_keyboard().unwrap();
|
||||
let pointer = seat.get_pointer().unwrap();
|
||||
|
||||
let keyboard_grab_mismatches = keyboard.is_grabbed()
|
||||
&& !(keyboard.has_grab(serial)
|
||||
|| grab
|
||||
.previous_serial()
|
||||
.map_or(true, |s| keyboard.has_grab(s)));
|
||||
let pointer_grab_mismatches = pointer.is_grabbed()
|
||||
&& !(pointer.has_grab(serial)
|
||||
|| grab.previous_serial().map_or(true, |s| pointer.has_grab(s)));
|
||||
if keyboard_grab_mismatches || pointer_grab_mismatches {
|
||||
grab.ungrab(PopupUngrabStrategy::All);
|
||||
return;
|
||||
}
|
||||
|
||||
trace!("new grab for root {:?}", root);
|
||||
keyboard.set_focus(self, grab.current_grab(), serial);
|
||||
keyboard.set_grab(self, PopupKeyboardGrab::new(&grab), serial);
|
||||
pointer.set_grab(self, PopupPointerGrab::new(&grab), serial, Focus::Keep);
|
||||
self.niri.popup_grab = Some(PopupGrabState { root, grab });
|
||||
}
|
||||
|
||||
fn maximize_request(&mut self, surface: ToplevelSurface) {
|
||||
// FIXME
|
||||
|
||||
// The protocol demands us to always reply with a configure,
|
||||
// regardless of we fulfilled the request or not
|
||||
surface.send_configure();
|
||||
// A configure is required in response to this event. However, if an initial configure
|
||||
// wasn't sent, then we will send this as part of the initial configure later.
|
||||
if initial_configure_sent(&surface) {
|
||||
surface.send_configure();
|
||||
}
|
||||
}
|
||||
|
||||
fn unmaximize_request(&mut self, _surface: ToplevelSurface) {
|
||||
@@ -107,46 +261,181 @@ impl XdgShellHandler for State {
|
||||
|
||||
fn fullscreen_request(
|
||||
&mut self,
|
||||
surface: ToplevelSurface,
|
||||
toplevel: ToplevelSurface,
|
||||
wl_output: Option<wl_output::WlOutput>,
|
||||
) {
|
||||
if surface
|
||||
.current_state()
|
||||
.capabilities
|
||||
.contains(xdg_toplevel::WmCapabilities::Fullscreen)
|
||||
{
|
||||
// NOTE: This is only one part of the solution. We can set the
|
||||
// location and configure size here, but the surface should be rendered fullscreen
|
||||
// independently from its buffer size
|
||||
if let Some((window, current_output)) = self
|
||||
.niri
|
||||
.layout
|
||||
.find_window_and_output(surface.wl_surface())
|
||||
{
|
||||
if let Some(requested_output) = wl_output.as_ref().and_then(Output::from_resource) {
|
||||
if requested_output != current_output {
|
||||
self.niri
|
||||
.layout
|
||||
.move_window_to_output(window.clone(), &requested_output);
|
||||
}
|
||||
}
|
||||
let requested_output = wl_output.as_ref().and_then(Output::from_resource);
|
||||
|
||||
self.niri.layout.set_fullscreen(&window, true);
|
||||
}
|
||||
}
|
||||
|
||||
// The protocol demands us to always reply with a configure,
|
||||
// regardless of we fulfilled the request or not
|
||||
surface.send_configure();
|
||||
}
|
||||
|
||||
fn unfullscreen_request(&mut self, surface: ToplevelSurface) {
|
||||
if let Some((window, _)) = self
|
||||
if let Some((mapped, current_output)) = self
|
||||
.niri
|
||||
.layout
|
||||
.find_window_and_output(surface.wl_surface())
|
||||
.find_window_and_output(toplevel.wl_surface())
|
||||
{
|
||||
let window = mapped.window.clone();
|
||||
|
||||
if let Some(requested_output) = requested_output {
|
||||
if &requested_output != current_output {
|
||||
self.niri
|
||||
.layout
|
||||
.move_window_to_output(&window, &requested_output);
|
||||
}
|
||||
}
|
||||
|
||||
self.niri.layout.set_fullscreen(&window, true);
|
||||
|
||||
// A configure is required in response to this event regardless if there are pending
|
||||
// changes.
|
||||
toplevel.send_configure();
|
||||
} else if let Some(unmapped) = self.niri.unmapped_windows.get_mut(toplevel.wl_surface()) {
|
||||
match &mut unmapped.state {
|
||||
InitialConfigureState::NotConfigured { wants_fullscreen } => {
|
||||
*wants_fullscreen = Some(requested_output);
|
||||
|
||||
// The required configure will be the initial configure.
|
||||
}
|
||||
InitialConfigureState::Configured { rules, output, .. } => {
|
||||
// Figure out the monitor following a similar logic to initial configure.
|
||||
// FIXME: deduplicate.
|
||||
let mon = requested_output
|
||||
.as_ref()
|
||||
// If none requested, try currently configured output.
|
||||
.or(output.as_ref())
|
||||
.and_then(|o| self.niri.layout.monitor_for_output(o))
|
||||
.map(|mon| (mon, false))
|
||||
// If not, check if we have a parent with a monitor.
|
||||
.or_else(|| {
|
||||
toplevel
|
||||
.parent()
|
||||
.and_then(|parent| self.niri.layout.find_window_and_output(&parent))
|
||||
.map(|(_win, output)| output)
|
||||
.and_then(|o| self.niri.layout.monitor_for_output(o))
|
||||
.map(|mon| (mon, true))
|
||||
})
|
||||
// If not, fall back to the active monitor.
|
||||
.or_else(|| {
|
||||
self.niri
|
||||
.layout
|
||||
.active_monitor_ref()
|
||||
.map(|mon| (mon, false))
|
||||
});
|
||||
|
||||
*output = mon
|
||||
.filter(|(_, parent)| !parent)
|
||||
.map(|(mon, _)| mon.output.clone());
|
||||
let mon = mon.map(|(mon, _)| mon);
|
||||
|
||||
let ws = mon
|
||||
.map(|mon| mon.active_workspace_ref())
|
||||
.or_else(|| self.niri.layout.active_workspace());
|
||||
|
||||
if let Some(ws) = ws {
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.states.set(xdg_toplevel::State::Fullscreen);
|
||||
});
|
||||
ws.configure_new_window(&unmapped.window, None, rules);
|
||||
}
|
||||
|
||||
// We already sent the initial configure, so we need to reconfigure.
|
||||
toplevel.send_configure();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
error!("couldn't find the toplevel in fullscreen_request()");
|
||||
toplevel.send_configure();
|
||||
}
|
||||
}
|
||||
|
||||
fn unfullscreen_request(&mut self, toplevel: ToplevelSurface) {
|
||||
if let Some((mapped, _)) = self
|
||||
.niri
|
||||
.layout
|
||||
.find_window_and_output(toplevel.wl_surface())
|
||||
{
|
||||
let window = mapped.window.clone();
|
||||
self.niri.layout.set_fullscreen(&window, false);
|
||||
|
||||
// A configure is required in response to this event regardless if there are pending
|
||||
// changes.
|
||||
toplevel.send_configure();
|
||||
} else if let Some(unmapped) = self.niri.unmapped_windows.get_mut(toplevel.wl_surface()) {
|
||||
match &mut unmapped.state {
|
||||
InitialConfigureState::NotConfigured { wants_fullscreen } => {
|
||||
*wants_fullscreen = None;
|
||||
|
||||
// The required configure will be the initial configure.
|
||||
}
|
||||
InitialConfigureState::Configured {
|
||||
rules,
|
||||
width,
|
||||
is_full_width,
|
||||
output,
|
||||
workspace_name,
|
||||
} => {
|
||||
// Figure out the monitor following a similar logic to initial configure.
|
||||
// FIXME: deduplicate.
|
||||
let mon = workspace_name
|
||||
.as_deref()
|
||||
.and_then(|name| self.niri.layout.monitor_for_workspace(name))
|
||||
.map(|mon| (mon, false));
|
||||
|
||||
let mon = mon.or_else(|| {
|
||||
output
|
||||
.as_ref()
|
||||
.and_then(|o| self.niri.layout.monitor_for_output(o))
|
||||
.map(|mon| (mon, false))
|
||||
// If not, check if we have a parent with a monitor.
|
||||
.or_else(|| {
|
||||
toplevel
|
||||
.parent()
|
||||
.and_then(|parent| {
|
||||
self.niri.layout.find_window_and_output(&parent)
|
||||
})
|
||||
.map(|(_win, output)| output)
|
||||
.and_then(|o| self.niri.layout.monitor_for_output(o))
|
||||
.map(|mon| (mon, true))
|
||||
})
|
||||
// If not, fall back to the active monitor.
|
||||
.or_else(|| {
|
||||
self.niri
|
||||
.layout
|
||||
.active_monitor_ref()
|
||||
.map(|mon| (mon, false))
|
||||
})
|
||||
});
|
||||
|
||||
*output = mon
|
||||
.filter(|(_, parent)| !parent)
|
||||
.map(|(mon, _)| mon.output.clone());
|
||||
let mon = mon.map(|(mon, _)| mon);
|
||||
|
||||
let ws = workspace_name
|
||||
.as_deref()
|
||||
.and_then(|name| mon.map(|mon| mon.find_named_workspace(name)))
|
||||
.unwrap_or_else(|| {
|
||||
mon.map(|mon| mon.active_workspace_ref())
|
||||
.or_else(|| self.niri.layout.active_workspace())
|
||||
});
|
||||
|
||||
if let Some(ws) = ws {
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.states.unset(xdg_toplevel::State::Fullscreen);
|
||||
});
|
||||
|
||||
let configure_width = if *is_full_width {
|
||||
Some(ColumnWidth::Proportion(1.))
|
||||
} else {
|
||||
*width
|
||||
};
|
||||
ws.configure_new_window(&unmapped.window, configure_width, rules);
|
||||
}
|
||||
|
||||
// We already sent the initial configure, so we need to reconfigure.
|
||||
toplevel.send_configure();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
error!("couldn't find the toplevel in unfullscreen_request()");
|
||||
toplevel.send_configure();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,62 +455,91 @@ impl XdgShellHandler for State {
|
||||
.layout
|
||||
.find_window_and_output(surface.wl_surface());
|
||||
|
||||
let Some((window, output)) = win_out else {
|
||||
let Some((mapped, output)) = win_out else {
|
||||
// I have no idea how this can happen, but I saw it happen once, in a weird interaction
|
||||
// involving laptop going to sleep and resuming.
|
||||
error!("toplevel missing from both unmapped_windows and layout");
|
||||
return;
|
||||
};
|
||||
let window = mapped.window.clone();
|
||||
let output = output.clone();
|
||||
|
||||
self.backend.with_primary_renderer(|renderer| {
|
||||
self.niri.layout.store_unmap_snapshot(renderer, &window);
|
||||
});
|
||||
self.backend.with_primary_renderer(|renderer| {
|
||||
self.niri
|
||||
.layout
|
||||
.start_close_animation_for_window(renderer, &window);
|
||||
});
|
||||
|
||||
let active_window = self.niri.layout.active_window().map(|(m, _)| &m.window);
|
||||
let was_active = active_window == Some(&window);
|
||||
|
||||
self.niri.layout.remove_window(&window);
|
||||
self.niri.queue_redraw(output);
|
||||
|
||||
if was_active {
|
||||
self.maybe_warp_cursor_to_focus();
|
||||
}
|
||||
|
||||
self.niri.queue_redraw(&output);
|
||||
}
|
||||
|
||||
fn popup_destroyed(&mut self, surface: PopupSurface) {
|
||||
if let Some(output) = self.output_for_popup(&PopupKind::Xdg(surface)) {
|
||||
self.niri.queue_redraw(output);
|
||||
self.niri.queue_redraw(&output.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn app_id_changed(&mut self, toplevel: ToplevelSurface) {
|
||||
self.update_window_rules(&toplevel);
|
||||
}
|
||||
|
||||
fn title_changed(&mut self, toplevel: ToplevelSurface) {
|
||||
self.update_window_rules(&toplevel);
|
||||
}
|
||||
}
|
||||
|
||||
delegate_xdg_shell!(State);
|
||||
|
||||
impl XdgDecorationHandler for State {
|
||||
fn new_decoration(&mut self, toplevel: ToplevelSurface) {
|
||||
let mode = if self.niri.config.borrow().prefer_no_csd {
|
||||
Some(zxdg_toplevel_decoration_v1::Mode::ServerSide)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// If we want CSD, we hide this global altogether.
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.decoration_mode = mode;
|
||||
state.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide);
|
||||
});
|
||||
}
|
||||
|
||||
fn request_mode(&mut self, toplevel: ToplevelSurface, mode: zxdg_toplevel_decoration_v1::Mode) {
|
||||
// Set whatever the client wants, rather than our preferred mode. This especially matters
|
||||
// for SDL2 which has a bug where forcing a different (client-side) decoration mode during
|
||||
// their window creation sequence would leave the window permanently hidden.
|
||||
//
|
||||
// https://github.com/libsdl-org/SDL/issues/8173
|
||||
//
|
||||
// The bug has been fixed, but there's a ton of apps which will use the buggy version for a
|
||||
// long while...
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.decoration_mode = Some(mode);
|
||||
});
|
||||
|
||||
// Only send configure if it's non-initial.
|
||||
// A configure is required in response to this event. However, if an initial configure
|
||||
// wasn't sent, then we will send this as part of the initial configure later.
|
||||
if initial_configure_sent(&toplevel) {
|
||||
toplevel.send_pending_configure();
|
||||
toplevel.send_configure();
|
||||
}
|
||||
}
|
||||
|
||||
fn unset_mode(&mut self, toplevel: ToplevelSurface) {
|
||||
let mode = if self.niri.config.borrow().prefer_no_csd {
|
||||
Some(zxdg_toplevel_decoration_v1::Mode::ServerSide)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// If we want CSD, we hide this global altogether.
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.decoration_mode = mode;
|
||||
state.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide);
|
||||
});
|
||||
|
||||
// Only send configure if it's non-initial.
|
||||
// A configure is required in response to this event. However, if an initial configure
|
||||
// wasn't sent, then we will send this as part of the initial configure later.
|
||||
if initial_configure_sent(&toplevel) {
|
||||
toplevel.send_pending_configure();
|
||||
toplevel.send_configure();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -232,14 +550,14 @@ impl KdeDecorationHandler for State {
|
||||
&self.niri.kde_decoration_state
|
||||
}
|
||||
}
|
||||
|
||||
delegate_kde_decoration!(State);
|
||||
|
||||
pub fn send_initial_configure_if_needed(toplevel: &ToplevelSurface) {
|
||||
if !initial_configure_sent(toplevel) {
|
||||
toplevel.send_configure();
|
||||
impl XdgForeignHandler for State {
|
||||
fn xdg_foreign_state(&mut self) -> &mut XdgForeignState {
|
||||
&mut self.niri.xdg_foreign_state
|
||||
}
|
||||
}
|
||||
delegate_xdg_foreign!(State);
|
||||
|
||||
fn initial_configure_sent(toplevel: &ToplevelSurface) -> bool {
|
||||
with_states(toplevel.wl_surface(), |states| {
|
||||
@@ -254,6 +572,149 @@ fn initial_configure_sent(toplevel: &ToplevelSurface) -> bool {
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn send_initial_configure(&mut self, toplevel: &ToplevelSurface) {
|
||||
let _span = tracy_client::span!("State::send_initial_configure");
|
||||
|
||||
let Some(unmapped) = self.niri.unmapped_windows.get_mut(toplevel.wl_surface()) else {
|
||||
error!("window must be present in unmapped_windows in send_initial_configure()");
|
||||
return;
|
||||
};
|
||||
|
||||
let config = self.niri.config.borrow();
|
||||
let rules = ResolvedWindowRules::compute(
|
||||
&config.window_rules,
|
||||
WindowRef::Unmapped(unmapped),
|
||||
self.niri.is_at_startup,
|
||||
);
|
||||
|
||||
let Unmapped { window, state } = unmapped;
|
||||
|
||||
let InitialConfigureState::NotConfigured { wants_fullscreen } = state else {
|
||||
error!("window must not be already configured in send_initial_configure()");
|
||||
return;
|
||||
};
|
||||
|
||||
// Pick the target monitor. First, check if we had a workspace set in the window rules.
|
||||
let mon = rules
|
||||
.open_on_workspace
|
||||
.as_deref()
|
||||
.and_then(|name| self.niri.layout.monitor_for_workspace(name));
|
||||
|
||||
// If not, check if we had an output set in the window rules.
|
||||
let mon = mon.or_else(|| {
|
||||
rules
|
||||
.open_on_output
|
||||
.as_deref()
|
||||
.and_then(|name| self.niri.output_by_name.get(name))
|
||||
.and_then(|o| self.niri.layout.monitor_for_output(o))
|
||||
});
|
||||
|
||||
// If not, check if the window requested one for fullscreen.
|
||||
let mon = mon.or_else(|| {
|
||||
wants_fullscreen
|
||||
.as_ref()
|
||||
.and_then(|x| x.as_ref())
|
||||
// The monitor might not exist if the output was disconnected.
|
||||
.and_then(|o| self.niri.layout.monitor_for_output(o))
|
||||
});
|
||||
|
||||
// If not, check if this is a dialog with a parent, to place it next to the parent.
|
||||
let mon = mon.map(|mon| (mon, false)).or_else(|| {
|
||||
toplevel
|
||||
.parent()
|
||||
.and_then(|parent| self.niri.layout.find_window_and_output(&parent))
|
||||
.map(|(_win, output)| output)
|
||||
.and_then(|o| self.niri.layout.monitor_for_output(o))
|
||||
.map(|mon| (mon, true))
|
||||
});
|
||||
|
||||
// If not, use the active monitor.
|
||||
let mon = mon.or_else(|| {
|
||||
self.niri
|
||||
.layout
|
||||
.active_monitor_ref()
|
||||
.map(|mon| (mon, false))
|
||||
});
|
||||
|
||||
// If we're following the parent, don't set the target output, so that when the window is
|
||||
// mapped, it fetches the possibly changed parent's output again, and shows up there.
|
||||
let output = mon
|
||||
.filter(|(_, parent)| !parent)
|
||||
.map(|(mon, _)| mon.output.clone());
|
||||
let mon = mon.map(|(mon, _)| mon);
|
||||
|
||||
let mut width = None;
|
||||
let is_full_width = rules.open_maximized.unwrap_or(false);
|
||||
|
||||
// Tell the surface the preferred size and bounds for its likely output.
|
||||
let ws = rules
|
||||
.open_on_workspace
|
||||
.as_deref()
|
||||
.and_then(|name| mon.map(|mon| mon.find_named_workspace(name)))
|
||||
.unwrap_or_else(|| {
|
||||
mon.map(|mon| mon.active_workspace_ref())
|
||||
.or_else(|| self.niri.layout.active_workspace())
|
||||
});
|
||||
|
||||
if let Some(ws) = ws {
|
||||
// Set a fullscreen state based on window request and window rule.
|
||||
if (wants_fullscreen.is_some() && rules.open_fullscreen.is_none())
|
||||
|| rules.open_fullscreen == Some(true)
|
||||
{
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.states.set(xdg_toplevel::State::Fullscreen);
|
||||
});
|
||||
}
|
||||
|
||||
width = ws.resolve_default_width(rules.default_width);
|
||||
|
||||
let configure_width = if is_full_width {
|
||||
Some(ColumnWidth::Proportion(1.))
|
||||
} else {
|
||||
width
|
||||
};
|
||||
ws.configure_new_window(window, configure_width, &rules);
|
||||
}
|
||||
|
||||
// If the user prefers no CSD, it's a reasonable assumption that they would prefer to get
|
||||
// rid of the various client-side rounded corners also by using the tiled state.
|
||||
if config.prefer_no_csd {
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.states.set(xdg_toplevel::State::TiledLeft);
|
||||
state.states.set(xdg_toplevel::State::TiledRight);
|
||||
state.states.set(xdg_toplevel::State::TiledTop);
|
||||
state.states.set(xdg_toplevel::State::TiledBottom);
|
||||
});
|
||||
}
|
||||
|
||||
// Set the configured settings.
|
||||
*state = InitialConfigureState::Configured {
|
||||
rules,
|
||||
width,
|
||||
is_full_width,
|
||||
output,
|
||||
workspace_name: ws.and_then(|w| w.name.clone()),
|
||||
};
|
||||
|
||||
toplevel.send_configure();
|
||||
}
|
||||
|
||||
pub fn queue_initial_configure(&self, toplevel: ToplevelSurface) {
|
||||
// Send the initial configure in an idle, in case the client sent some more info after the
|
||||
// initial commit.
|
||||
self.niri.event_loop.insert_idle(move |state| {
|
||||
if !toplevel.alive() {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(unmapped) = state.niri.unmapped_windows.get(toplevel.wl_surface()) {
|
||||
if unmapped.needs_initial_configure() {
|
||||
state.send_initial_configure(&toplevel);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Should be called on `WlSurface::commit`
|
||||
pub fn popups_handle_commit(&mut self, surface: &WlSurface) {
|
||||
self.niri.popups.commit(surface);
|
||||
@@ -282,29 +743,32 @@ impl State {
|
||||
popup.send_configure().expect("initial configure failed");
|
||||
}
|
||||
}
|
||||
// Input method popups don't require a configure.
|
||||
PopupKind::InputMethod(_) => (),
|
||||
// Input method popup can arbitrary change its geometry, so we need to unconstrain
|
||||
// it on commit.
|
||||
PopupKind::InputMethod(_) => {
|
||||
self.unconstrain_popup(&popup);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn output_for_popup(&self, popup: &PopupKind) -> Option<Output> {
|
||||
pub fn output_for_popup(&self, popup: &PopupKind) -> Option<&Output> {
|
||||
let root = find_popup_root_surface(popup).ok()?;
|
||||
self.niri.output_for_root(&root)
|
||||
}
|
||||
|
||||
pub fn unconstrain_popup(&self, popup: &PopupSurface) {
|
||||
pub fn unconstrain_popup(&self, popup: &PopupKind) {
|
||||
let _span = tracy_client::span!("Niri::unconstrain_popup");
|
||||
|
||||
// Popups with a NULL parent will get repositioned in their respective protocol handlers
|
||||
// (i.e. layer-shell).
|
||||
let Ok(root) = find_popup_root_surface(&PopupKind::Xdg(popup.clone())) else {
|
||||
let Ok(root) = find_popup_root_surface(popup) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Figure out if the root is a window or a layer surface.
|
||||
if let Some((window, output)) = self.niri.layout.find_window_and_output(&root) {
|
||||
self.unconstrain_window_popup(popup, &window, &output);
|
||||
if let Some((mapped, output)) = self.niri.layout.find_window_and_output(&root) {
|
||||
self.unconstrain_window_popup(popup, &mapped.window, output);
|
||||
} else if let Some((layer_surface, output)) = self.niri.layout.outputs().find_map(|o| {
|
||||
let map = layer_map_for_output(o);
|
||||
let layer_surface = map.layer_for_surface(&root, WindowSurfaceType::TOPLEVEL)?;
|
||||
@@ -314,7 +778,7 @@ impl State {
|
||||
}
|
||||
}
|
||||
|
||||
fn unconstrain_window_popup(&self, popup: &PopupSurface, window: &Window, output: &Output) {
|
||||
fn unconstrain_window_popup(&self, popup: &PopupKind, window: &Window, output: &Output) {
|
||||
let window_geo = window.geometry();
|
||||
let output_geo = self.niri.global_space.output_geometry(output).unwrap();
|
||||
|
||||
@@ -326,17 +790,15 @@ impl State {
|
||||
// height.
|
||||
let mut target =
|
||||
Rectangle::from_loc_and_size((0, 0), (window_geo.size.w, output_geo.size.h));
|
||||
target.loc.y -= self.niri.layout.window_y(window).unwrap();
|
||||
target.loc -= get_popup_toplevel_coords(&PopupKind::Xdg(popup.clone()));
|
||||
target.loc -= self.niri.layout.window_loc(window).unwrap();
|
||||
target.loc -= get_popup_toplevel_coords(popup);
|
||||
|
||||
popup.with_pending_state(|state| {
|
||||
state.geometry = unconstrain_with_padding(state.positioner, target);
|
||||
});
|
||||
self.position_popup_within_rect(popup, target);
|
||||
}
|
||||
|
||||
pub fn unconstrain_layer_shell_popup(
|
||||
&self,
|
||||
popup: &PopupSurface,
|
||||
popup: &PopupKind,
|
||||
layer_surface: &LayerSurface,
|
||||
output: &Output,
|
||||
) {
|
||||
@@ -350,21 +812,58 @@ impl State {
|
||||
// we will compute that here.
|
||||
let mut target = Rectangle::from_loc_and_size((0, 0), output_geo.size);
|
||||
target.loc -= layer_geo.loc;
|
||||
target.loc -= get_popup_toplevel_coords(&PopupKind::Xdg(popup.clone()));
|
||||
target.loc -= get_popup_toplevel_coords(popup);
|
||||
|
||||
popup.with_pending_state(|state| {
|
||||
state.geometry = unconstrain_with_padding(state.positioner, target);
|
||||
});
|
||||
self.position_popup_within_rect(popup, target);
|
||||
}
|
||||
|
||||
fn position_popup_within_rect(&self, popup: &PopupKind, target: Rectangle<i32, Logical>) {
|
||||
match popup {
|
||||
PopupKind::Xdg(popup) => {
|
||||
popup.with_pending_state(|state| {
|
||||
state.geometry = unconstrain_with_padding(state.positioner, target);
|
||||
});
|
||||
}
|
||||
PopupKind::InputMethod(popup) => {
|
||||
let text_input_rectangle = popup.text_input_rectangle();
|
||||
let mut bbox =
|
||||
utils::bbox_from_surface_tree(popup.wl_surface(), text_input_rectangle.loc);
|
||||
|
||||
// Position bbox horizontally first.
|
||||
let overflow_x = (bbox.loc.x + bbox.size.w) - (target.loc.x + target.size.w);
|
||||
if overflow_x > 0 {
|
||||
bbox.loc.x -= overflow_x;
|
||||
}
|
||||
|
||||
// Ensure that the popup starts within the window.
|
||||
bbox.loc.x = bbox.loc.x.max(target.loc.x);
|
||||
|
||||
// Try to position IME popup below the text input rectangle.
|
||||
let mut below = bbox;
|
||||
below.loc.y += text_input_rectangle.size.h;
|
||||
|
||||
let mut above = bbox;
|
||||
above.loc.y -= bbox.size.h;
|
||||
|
||||
if target.loc.y + target.size.h >= below.loc.y + below.size.h {
|
||||
popup.set_location(below.loc);
|
||||
} else {
|
||||
popup.set_location(above.loc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_reactive_popups(&self, window: &Window, output: &Output) {
|
||||
let _span = tracy_client::span!("Niri::update_reactive_popups");
|
||||
|
||||
for (popup, _) in PopupManager::popups_for_surface(window.toplevel().wl_surface()) {
|
||||
match popup {
|
||||
PopupKind::Xdg(ref popup) => {
|
||||
for (popup, _) in PopupManager::popups_for_surface(
|
||||
window.toplevel().expect("no x11 support").wl_surface(),
|
||||
) {
|
||||
match &popup {
|
||||
xdg_popup @ PopupKind::Xdg(popup) => {
|
||||
if popup.with_pending_state(|state| state.positioner.reactive) {
|
||||
self.unconstrain_window_popup(popup, window, output);
|
||||
self.unconstrain_window_popup(xdg_popup, window, output);
|
||||
if let Err(err) = popup.send_pending_configure() {
|
||||
warn!("error re-configuring reactive popup: {err:?}");
|
||||
}
|
||||
@@ -374,6 +873,37 @@ impl State {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_window_rules(&mut self, toplevel: &ToplevelSurface) {
|
||||
let config = self.niri.config.borrow();
|
||||
let window_rules = &config.window_rules;
|
||||
|
||||
if let Some(unmapped) = self.niri.unmapped_windows.get_mut(toplevel.wl_surface()) {
|
||||
let new_rules = ResolvedWindowRules::compute(
|
||||
window_rules,
|
||||
WindowRef::Unmapped(unmapped),
|
||||
self.niri.is_at_startup,
|
||||
);
|
||||
if let InitialConfigureState::Configured { rules, .. } = &mut unmapped.state {
|
||||
*rules = new_rules;
|
||||
}
|
||||
} else if let Some((mapped, output)) = self
|
||||
.niri
|
||||
.layout
|
||||
.find_window_and_output_mut(toplevel.wl_surface())
|
||||
{
|
||||
if mapped.recompute_window_rules(window_rules, self.niri.is_at_startup) {
|
||||
drop(config);
|
||||
let output = output.cloned();
|
||||
let window = mapped.window.clone();
|
||||
self.niri.layout.update_window(&window, None);
|
||||
|
||||
if let Some(output) = output {
|
||||
self.niri.queue_redraw(&output);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn unconstrain_with_padding(
|
||||
@@ -416,3 +946,51 @@ fn unconstrain_with_padding(
|
||||
// Could not unconstrain into the padded target, so resort to the regular one.
|
||||
positioner.get_unconstrained_geometry(target)
|
||||
}
|
||||
|
||||
pub fn add_mapped_toplevel_pre_commit_hook(toplevel: &ToplevelSurface) -> HookId {
|
||||
add_pre_commit_hook::<State, _>(toplevel.wl_surface(), move |state, _dh, surface| {
|
||||
let _span = tracy_client::span!("mapped toplevel pre-commit");
|
||||
|
||||
let Some((mapped, _)) = state.niri.layout.find_window_and_output_mut(surface) else {
|
||||
error!("pre-commit hook for mapped surfaces must be removed upon unmapping");
|
||||
return;
|
||||
};
|
||||
|
||||
let (got_unmapped, commit_serial) = with_states(surface, |states| {
|
||||
let attrs = states.cached_state.pending::<SurfaceAttributes>();
|
||||
let got_unmapped = matches!(attrs.buffer, Some(BufferAssignment::Removed));
|
||||
|
||||
let role = states
|
||||
.data_map
|
||||
.get::<XdgToplevelSurfaceData>()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.unwrap();
|
||||
|
||||
(got_unmapped, role.configure_serial)
|
||||
});
|
||||
|
||||
let animate = if let Some(serial) = commit_serial {
|
||||
mapped.should_animate_commit(serial)
|
||||
} else {
|
||||
error!("commit on a mapped surface without a configured serial");
|
||||
false
|
||||
};
|
||||
|
||||
let window = mapped.window.clone();
|
||||
if got_unmapped {
|
||||
state.backend.with_primary_renderer(|renderer| {
|
||||
state.niri.layout.store_unmap_snapshot(renderer, &window);
|
||||
});
|
||||
} else {
|
||||
if animate {
|
||||
state.backend.with_primary_renderer(|renderer| {
|
||||
mapped.store_animation_snapshot(renderer);
|
||||
});
|
||||
}
|
||||
|
||||
// The toplevel remains mapped; clear any stored unmap snapshot.
|
||||
state.niri.layout.clear_unmap_snapshot(&window);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
-1431
File diff suppressed because it is too large
Load Diff
+2627
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,176 @@
|
||||
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.pointer_grab_ongoing = false;
|
||||
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<i32, 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<i32, 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);
|
||||
}
|
||||
}
|
||||
@@ -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.;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
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::utils::{Logical, Point};
|
||||
|
||||
use crate::niri::State;
|
||||
|
||||
pub struct ViewOffsetGrab {
|
||||
start_data: PointerGrabStartData<State>,
|
||||
last_location: Point<f64, Logical>,
|
||||
}
|
||||
|
||||
impl ViewOffsetGrab {
|
||||
pub fn new(start_data: PointerGrabStartData<State>) -> Self {
|
||||
Self {
|
||||
last_location: start_data.location,
|
||||
start_data,
|
||||
}
|
||||
}
|
||||
|
||||
fn on_ungrab(&mut self, state: &mut State) {
|
||||
let res = state
|
||||
.niri
|
||||
.layout
|
||||
.view_offset_gesture_end(false, Some(false));
|
||||
if let Some(output) = res {
|
||||
state.niri.queue_redraw(&output);
|
||||
}
|
||||
|
||||
state.niri.pointer_grab_ongoing = false;
|
||||
state
|
||||
.niri
|
||||
.cursor_manager
|
||||
.set_cursor_image(CursorImageStatus::default_named());
|
||||
}
|
||||
}
|
||||
|
||||
impl PointerGrab<State> for ViewOffsetGrab {
|
||||
fn motion(
|
||||
&mut self,
|
||||
data: &mut State,
|
||||
handle: &mut PointerInnerHandle<'_, State>,
|
||||
_focus: Option<(<State as SeatHandler>::PointerFocus, Point<i32, 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 res = data
|
||||
.niri
|
||||
.layout
|
||||
.view_offset_gesture_update(-delta.x, timestamp, false);
|
||||
if let Some(output) = res {
|
||||
if let Some(output) = output {
|
||||
data.niri.queue_redraw(&output);
|
||||
}
|
||||
} else {
|
||||
// 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<i32, 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
use anyhow::{anyhow, bail, Context};
|
||||
use niri_ipc::{
|
||||
LogicalOutput, Mode, Output, OutputConfigChanged, Request, Response, Socket, Transform,
|
||||
};
|
||||
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::Action { action } => Request::Action(action.clone()),
|
||||
Msg::Output { output, action } => Request::Output {
|
||||
output: output.clone(),
|
||||
action: action.clone(),
|
||||
},
|
||||
Msg::Workspaces => Request::Workspaces,
|
||||
Msg::RequestError => Request::ReturnError,
|
||||
};
|
||||
|
||||
let socket = Socket::connect().context("error connecting to the niri socket")?;
|
||||
|
||||
let reply = socket
|
||||
.send(request)
|
||||
.context("error communicating with niri")?;
|
||||
|
||||
let compositor_version = match reply {
|
||||
Err(_) if !matches!(msg, Msg::Version) => {
|
||||
// If we got an error, it might be that the CLI is a different version from the running
|
||||
// niri instance. Request the running instance version to compare and print a message.
|
||||
Socket::connect()
|
||||
.and_then(|socket| socket.send(Request::Version))
|
||||
.ok()
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// Default SIGPIPE so that our prints don't panic on stdout closing.
|
||||
unsafe {
|
||||
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
|
||||
}
|
||||
|
||||
let response = reply.map_err(|err_msg| {
|
||||
// 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.
|
||||
// Don't add irrelevant context.
|
||||
}
|
||||
}
|
||||
|
||||
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_iter().collect::<Vec<_>>();
|
||||
outputs.sort_unstable_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
for (connector, output) in outputs.into_iter() {
|
||||
let Output {
|
||||
name,
|
||||
make,
|
||||
model,
|
||||
physical_size,
|
||||
modes,
|
||||
current_mode,
|
||||
vrr_supported,
|
||||
vrr_enabled,
|
||||
logical,
|
||||
} = output;
|
||||
|
||||
println!(r#"Output "{connector}" ({make} - {model} - {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}");
|
||||
}
|
||||
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 {
|
||||
println!("Focused window:");
|
||||
|
||||
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)");
|
||||
}
|
||||
} else {
|
||||
println!("No window is focused.");
|
||||
}
|
||||
}
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod client;
|
||||
pub mod server;
|
||||
@@ -0,0 +1,214 @@
|
||||
use std::os::unix::net::{UnixListener, UnixStream};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::{env, io, process};
|
||||
|
||||
use anyhow::Context;
|
||||
use calloop::io::Async;
|
||||
use directories::BaseDirs;
|
||||
use futures_util::io::{AsyncReadExt, BufReader};
|
||||
use futures_util::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use niri_ipc::{OutputConfigChanged, Reply, Request, Response};
|
||||
use smithay::desktop::Window;
|
||||
use smithay::reexports::calloop::generic::Generic;
|
||||
use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
|
||||
use smithay::reexports::rustix::fs::unlink;
|
||||
use smithay::wayland::compositor::with_states;
|
||||
use smithay::wayland::shell::xdg::XdgToplevelSurfaceData;
|
||||
|
||||
use crate::backend::IpcOutputMap;
|
||||
use crate::niri::State;
|
||||
use crate::utils::version;
|
||||
|
||||
pub struct IpcServer {
|
||||
pub socket_path: PathBuf,
|
||||
}
|
||||
|
||||
struct ClientCtx {
|
||||
event_loop: LoopHandle<'static, State>,
|
||||
ipc_outputs: Arc<Mutex<IpcOutputMap>>,
|
||||
ipc_focused_window: Arc<Mutex<Option<Window>>>,
|
||||
}
|
||||
|
||||
impl IpcServer {
|
||||
pub fn start(
|
||||
event_loop: &LoopHandle<'static, State>,
|
||||
wayland_socket_name: &str,
|
||||
) -> anyhow::Result<Self> {
|
||||
let _span = tracy_client::span!("Ipc::start");
|
||||
|
||||
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();
|
||||
|
||||
Ok(Self { socket_path })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for IpcServer {
|
||||
fn drop(&mut self) {
|
||||
let _ = unlink(&self.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 ctx = ClientCtx {
|
||||
event_loop: state.niri.event_loop.clone(),
|
||||
ipc_outputs: state.backend.ipc_outputs(),
|
||||
ipc_focused_window: state.niri.ipc_focused_window.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<'_, UnixStream>) -> anyhow::Result<()> {
|
||||
let (read, mut write) = stream.split();
|
||||
let mut buf = String::new();
|
||||
|
||||
// Read a single line to allow extensibility in the future to keep reading.
|
||||
BufReader::new(read)
|
||||
.read_line(&mut buf)
|
||||
.await
|
||||
.context("error reading request")?;
|
||||
|
||||
let request = serde_json::from_str(&buf)
|
||||
.context("error parsing request")
|
||||
.map_err(|err| err.to_string());
|
||||
let requested_error = matches!(request, Ok(Request::ReturnError));
|
||||
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
let buf = serde_json::to_vec(&reply).context("error formatting reply")?;
|
||||
write.write_all(&buf).await.context("error writing reply")?;
|
||||
|
||||
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();
|
||||
Response::Outputs(ipc_outputs)
|
||||
}
|
||||
Request::FocusedWindow => {
|
||||
let window = ctx.ipc_focused_window.lock().unwrap().clone();
|
||||
let window = window.map(|window| {
|
||||
let wl_surface = window.toplevel().expect("no X11 support").wl_surface();
|
||||
with_states(wl_surface, |states| {
|
||||
let role = states
|
||||
.data_map
|
||||
.get::<XdgToplevelSurfaceData>()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.unwrap();
|
||||
|
||||
niri_ipc::Window {
|
||||
title: role.title.clone(),
|
||||
app_id: role.app_id.clone(),
|
||||
}
|
||||
})
|
||||
});
|
||||
Response::FocusedWindow(window)
|
||||
}
|
||||
Request::Action(action) => {
|
||||
let (tx, rx) = async_channel::bounded(1);
|
||||
|
||||
let action = niri_config::Action::from(action);
|
||||
ctx.event_loop.insert_idle(move |state| {
|
||||
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
|
||||
.keys()
|
||||
.any(|name| name.eq_ignore_ascii_case(&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::Workspaces => {
|
||||
let (tx, rx) = async_channel::bounded(1);
|
||||
ctx.event_loop.insert_idle(move |state| {
|
||||
let workspaces = state.niri.layout.ipc_workspaces();
|
||||
let _ = tx.send_blocking(workspaces);
|
||||
});
|
||||
let result = rx.recv().await;
|
||||
let workspaces = result.map_err(|_| String::from("error getting workspace info"))?;
|
||||
Response::Workspaces(workspaces)
|
||||
}
|
||||
};
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
-4025
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,209 @@
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use glam::{Mat3, Vec2};
|
||||
use niri_config::BlockOutFrom;
|
||||
use smithay::backend::allocator::Fourcc;
|
||||
use smithay::backend::renderer::element::texture::TextureRenderElement;
|
||||
use smithay::backend::renderer::element::utils::{
|
||||
Relocate, RelocateRenderElement, RescaleRenderElement,
|
||||
};
|
||||
use smithay::backend::renderer::element::{Id, Kind, RenderElement};
|
||||
use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture, Uniform};
|
||||
use smithay::backend::renderer::{Renderer as _, Texture};
|
||||
use smithay::utils::{Logical, Point, Rectangle, Scale, Size, Transform};
|
||||
|
||||
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::{render_to_encompassing_texture, RenderTarget};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ClosingWindow {
|
||||
/// Contents of the window.
|
||||
texture: GlesTexture,
|
||||
|
||||
/// Blocked-out contents of the window.
|
||||
blocked_out_texture: GlesTexture,
|
||||
|
||||
/// Scale that the textures was rendered with.
|
||||
texture_scale: Scale<f64>,
|
||||
|
||||
/// ID of the textures' renderer.
|
||||
texture_renderer_id: usize,
|
||||
|
||||
/// Where the window should be blocked out from.
|
||||
block_out_from: Option<BlockOutFrom>,
|
||||
|
||||
/// Size of the window geometry.
|
||||
geo_size: Size<i32, Logical>,
|
||||
|
||||
/// Position in the workspace.
|
||||
pos: Point<i32, Logical>,
|
||||
|
||||
/// How much the texture should be offset.
|
||||
texture_offset: Point<f64, Logical>,
|
||||
|
||||
/// How much the blocked-out texture should be offset.
|
||||
blocked_out_texture_offset: Point<f64, Logical>,
|
||||
|
||||
/// The closing animation.
|
||||
anim: Animation,
|
||||
|
||||
/// Random seed for the shader.
|
||||
random_seed: f32,
|
||||
}
|
||||
|
||||
niri_render_elements! {
|
||||
ClosingWindowRenderElement => {
|
||||
Texture = RelocateRenderElement<RescaleRenderElement<PrimaryGpuTextureRenderElement>>,
|
||||
Shader = ShaderRenderElement,
|
||||
}
|
||||
}
|
||||
|
||||
impl ClosingWindow {
|
||||
pub fn new<E: RenderElement<GlesRenderer>>(
|
||||
renderer: &mut GlesRenderer,
|
||||
snapshot: RenderSnapshot<E, E>,
|
||||
scale: Scale<f64>,
|
||||
geo_size: Size<i32, Logical>,
|
||||
pos: Point<i32, Logical>,
|
||||
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 offset = geo.loc.to_f64().to_logical(scale);
|
||||
|
||||
Ok((texture, offset))
|
||||
};
|
||||
|
||||
let (texture, texture_offset) =
|
||||
render_to_texture(snapshot.contents).context("error rendering contents")?;
|
||||
let (blocked_out_texture, blocked_out_texture_offset) =
|
||||
render_to_texture(snapshot.blocked_out_contents)
|
||||
.context("error rendering blocked-out contents")?;
|
||||
|
||||
Ok(Self {
|
||||
texture,
|
||||
blocked_out_texture,
|
||||
texture_scale: scale,
|
||||
texture_renderer_id: renderer.id(),
|
||||
block_out_from: snapshot.block_out_from,
|
||||
geo_size,
|
||||
pos,
|
||||
texture_offset,
|
||||
blocked_out_texture_offset,
|
||||
anim,
|
||||
random_seed: fastrand::f32(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn advance_animations(&mut self, current_time: Duration) {
|
||||
self.anim.set_current_time(current_time);
|
||||
}
|
||||
|
||||
pub fn are_animations_ongoing(&self) -> bool {
|
||||
!self.anim.is_done()
|
||||
}
|
||||
|
||||
pub fn render(
|
||||
&self,
|
||||
renderer: &mut GlesRenderer,
|
||||
view_rect: Rectangle<i32, Logical>,
|
||||
scale: Scale<f64>,
|
||||
target: RenderTarget,
|
||||
) -> ClosingWindowRenderElement {
|
||||
let progress = self.anim.value();
|
||||
let clamped_progress = self.anim.clamped_value().clamp(0., 1.);
|
||||
|
||||
let (texture, offset) = if target.should_block_out(self.block_out_from) {
|
||||
(&self.blocked_out_texture, self.blocked_out_texture_offset)
|
||||
} else {
|
||||
(&self.texture, self.texture_offset)
|
||||
};
|
||||
|
||||
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);
|
||||
|
||||
let geo_loc = Vec2::new(self.pos.x as f32, self.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 = Vec2::new(self.texture_scale.x as f32, self.texture_scale.y as f32);
|
||||
let tex_loc = Vec2::new(offset.x as f32, offset.y as f32);
|
||||
let tex_size = Vec2::new(texture.width() as f32, texture.height() 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,
|
||||
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"), texture.clone())]),
|
||||
Kind::Unspecified,
|
||||
)
|
||||
.with_location(Point::from((0, 0)))
|
||||
.into();
|
||||
}
|
||||
|
||||
let elem = TextureRenderElement::from_static_texture(
|
||||
Id::new(),
|
||||
self.texture_renderer_id,
|
||||
Point::from((0., 0.)),
|
||||
texture.clone(),
|
||||
self.texture_scale.x as i32,
|
||||
Transform::Normal,
|
||||
Some(1. - clamped_progress as f32),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Kind::Unspecified,
|
||||
);
|
||||
|
||||
let elem = PrimaryGpuTextureRenderElement(elem);
|
||||
|
||||
let center = self.geo_size.to_point().to_f64().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.to_f64() + offset;
|
||||
location.x -= view_rect.loc.x as f64;
|
||||
let elem = RelocateRenderElement::from_element(
|
||||
elem,
|
||||
location.to_physical_precise_round(scale),
|
||||
Relocate::Relative,
|
||||
);
|
||||
|
||||
elem.into()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
use std::cmp::{max, min};
|
||||
use std::iter::zip;
|
||||
|
||||
use arrayvec::ArrayVec;
|
||||
use niri_config::{CornerRadius, Gradient, GradientRelativeTo};
|
||||
use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
|
||||
use smithay::backend::renderer::element::Kind;
|
||||
use smithay::utils::{Logical, Point, Rectangle, Scale, Size};
|
||||
|
||||
use crate::niri_render_elements;
|
||||
use crate::render_helpers::border::BorderRenderElement;
|
||||
use crate::render_helpers::renderer::NiriRenderer;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct FocusRing {
|
||||
buffers: [SolidColorBuffer; 8],
|
||||
locations: [Point<i32, Logical>; 8],
|
||||
sizes: [Size<i32, Logical>; 8],
|
||||
borders: [BorderRenderElement; 8],
|
||||
full_size: Size<i32, Logical>,
|
||||
is_border: bool,
|
||||
use_border_shader: bool,
|
||||
config: niri_config::FocusRing,
|
||||
}
|
||||
|
||||
niri_render_elements! {
|
||||
FocusRingRenderElement => {
|
||||
SolidColor = SolidColorRenderElement,
|
||||
Gradient = BorderRenderElement,
|
||||
}
|
||||
}
|
||||
|
||||
impl FocusRing {
|
||||
pub fn new(config: niri_config::FocusRing) -> Self {
|
||||
Self {
|
||||
buffers: Default::default(),
|
||||
locations: Default::default(),
|
||||
sizes: Default::default(),
|
||||
borders: Default::default(),
|
||||
full_size: Default::default(),
|
||||
is_border: false,
|
||||
use_border_shader: false,
|
||||
config,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_config(&mut self, config: niri_config::FocusRing) {
|
||||
self.config = config;
|
||||
}
|
||||
|
||||
pub fn update_shaders(&mut self) {
|
||||
for elem in &mut self.borders {
|
||||
elem.damage_all();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_render_elements(
|
||||
&mut self,
|
||||
win_size: Size<i32, Logical>,
|
||||
is_active: bool,
|
||||
is_border: bool,
|
||||
view_rect: Rectangle<i32, Logical>,
|
||||
radius: CornerRadius,
|
||||
) {
|
||||
let width = i32::from(self.config.width);
|
||||
self.full_size = win_size + Size::from((width * 2, width * 2));
|
||||
|
||||
let color = if is_active {
|
||||
self.config.active_color
|
||||
} else {
|
||||
self.config.inactive_color
|
||||
};
|
||||
|
||||
for buf in &mut self.buffers {
|
||||
buf.set_color(color.into());
|
||||
}
|
||||
|
||||
let radius = radius.fit_to(self.full_size.w as f32, self.full_size.h as f32);
|
||||
|
||||
let gradient = 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(Gradient {
|
||||
from: color,
|
||||
to: color,
|
||||
angle: 0,
|
||||
relative_to: GradientRelativeTo::Window,
|
||||
});
|
||||
|
||||
let full_rect = Rectangle::from_loc_and_size((-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.
|
||||
};
|
||||
|
||||
if is_border {
|
||||
let top_left = max(width, radius.top_left.ceil() as i32);
|
||||
let top_right = min(
|
||||
self.full_size.w - top_left,
|
||||
max(width, radius.top_right.ceil() as i32),
|
||||
);
|
||||
let bottom_left = min(
|
||||
self.full_size.h - top_left,
|
||||
max(width, radius.bottom_left.ceil() as i32),
|
||||
);
|
||||
let bottom_right = min(
|
||||
self.full_size.h - top_right,
|
||||
min(
|
||||
self.full_size.w - bottom_left,
|
||||
max(width, radius.bottom_right.ceil() as i32),
|
||||
),
|
||||
);
|
||||
|
||||
// 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::from_loc_and_size(gradient_area.loc - loc, gradient_area.size),
|
||||
gradient.from.into(),
|
||||
gradient.to.into(),
|
||||
((gradient.angle as f32) - 90.).to_radians(),
|
||||
Rectangle::from_loc_and_size(full_rect.loc - loc, full_rect.size),
|
||||
rounded_corner_border_width,
|
||||
radius,
|
||||
);
|
||||
}
|
||||
} 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::from_loc_and_size(
|
||||
gradient_area.loc - self.locations[0],
|
||||
gradient_area.size,
|
||||
),
|
||||
gradient.from.into(),
|
||||
gradient.to.into(),
|
||||
((gradient.angle as f32) - 90.).to_radians(),
|
||||
Rectangle::from_loc_and_size(full_rect.loc - self.locations[0], full_rect.size),
|
||||
rounded_corner_border_width,
|
||||
radius,
|
||||
);
|
||||
}
|
||||
|
||||
self.is_border = is_border;
|
||||
}
|
||||
|
||||
pub fn render(
|
||||
&self,
|
||||
renderer: &mut impl NiriRenderer,
|
||||
location: Point<i32, Logical>,
|
||||
scale: Scale<f64>,
|
||||
) -> impl Iterator<Item = FocusRingRenderElement> {
|
||||
let mut rv = ArrayVec::<_, 8>::new();
|
||||
|
||||
if self.config.off {
|
||||
return rv.into_iter();
|
||||
}
|
||||
|
||||
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<i32, Logical>| {
|
||||
let elem = if self.use_border_shader && has_border_shader {
|
||||
border.clone().with_location(location).into()
|
||||
} else {
|
||||
SolidColorRenderElement::from_buffer(
|
||||
buffer,
|
||||
location.to_physical_precise_round(scale),
|
||||
scale,
|
||||
1.,
|
||||
Kind::Unspecified,
|
||||
)
|
||||
.into()
|
||||
};
|
||||
rv.push(elem);
|
||||
};
|
||||
|
||||
if self.is_border {
|
||||
for ((buf, border), loc) in zip(zip(&self.buffers, &self.borders), self.locations) {
|
||||
push(buf, border, location + loc);
|
||||
}
|
||||
} else {
|
||||
push(
|
||||
&self.buffers[0],
|
||||
&self.borders[0],
|
||||
location + self.locations[0],
|
||||
);
|
||||
}
|
||||
|
||||
rv.into_iter()
|
||||
}
|
||||
|
||||
pub fn width(&self) -> i32 {
|
||||
self.config.width.into()
|
||||
}
|
||||
|
||||
pub fn is_off(&self) -> bool {
|
||||
self.config.off
|
||||
}
|
||||
}
|
||||
+3863
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,993 @@
|
||||
use std::cmp::min;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use niri_ipc::SizeChange;
|
||||
use smithay::backend::renderer::element::utils::{
|
||||
CropRenderElement, Relocate, RelocateRenderElement,
|
||||
};
|
||||
use smithay::output::Output;
|
||||
use smithay::utils::{Logical, Point, Rectangle, Scale};
|
||||
|
||||
use super::workspace::{
|
||||
compute_working_area, Column, ColumnWidth, OutputId, Workspace, WorkspaceId,
|
||||
WorkspaceRenderElement,
|
||||
};
|
||||
use super::{LayoutElement, Options};
|
||||
use crate::animation::Animation;
|
||||
use crate::input::swipe_tracker::SwipeTracker;
|
||||
use crate::render_helpers::renderer::NiriRenderer;
|
||||
use crate::render_helpers::RenderTarget;
|
||||
use crate::rubber_band::RubberBand;
|
||||
use crate::utils::{output_size, ResizeEdge};
|
||||
|
||||
/// Amount of touchpad movement to scroll the height of one workspace.
|
||||
const WORKSPACE_GESTURE_MOVEMENT: f64 = 300.;
|
||||
|
||||
const WORKSPACE_GESTURE_RUBBER_BAND: RubberBand = RubberBand {
|
||||
stiffness: 0.5,
|
||||
limit: 0.05,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Monitor<W: LayoutElement> {
|
||||
/// Output for this monitor.
|
||||
pub output: Output,
|
||||
// Must always contain at least one.
|
||||
pub workspaces: Vec<Workspace<W>>,
|
||||
/// Index of the currently active workspace.
|
||||
pub active_workspace_idx: usize,
|
||||
/// ID of the previously active workspace.
|
||||
pub previous_workspace_id: Option<WorkspaceId>,
|
||||
/// In-progress switch between workspaces.
|
||||
pub workspace_switch: Option<WorkspaceSwitch>,
|
||||
/// Configurable properties of the layout.
|
||||
pub options: Rc<Options>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum WorkspaceSwitch {
|
||||
Animation(Animation),
|
||||
Gesture(WorkspaceSwitchGesture),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct WorkspaceSwitchGesture {
|
||||
/// Index of the workspace where the gesture was started.
|
||||
pub center_idx: usize,
|
||||
/// Current, fractional workspace index.
|
||||
pub current_idx: f64,
|
||||
pub tracker: SwipeTracker,
|
||||
}
|
||||
|
||||
pub type MonitorRenderElement<R> =
|
||||
RelocateRenderElement<CropRenderElement<WorkspaceRenderElement<R>>>;
|
||||
|
||||
impl WorkspaceSwitch {
|
||||
pub fn current_idx(&self) -> f64 {
|
||||
match self {
|
||||
WorkspaceSwitch::Animation(anim) => anim.value(),
|
||||
WorkspaceSwitch::Gesture(gesture) => gesture.current_idx,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn target_idx(&self) -> f64 {
|
||||
match self {
|
||||
WorkspaceSwitch::Animation(anim) => anim.to(),
|
||||
WorkspaceSwitch::Gesture(gesture) => gesture.current_idx,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if the workspace switch is [`Animation`].
|
||||
///
|
||||
/// [`Animation`]: WorkspaceSwitch::Animation
|
||||
#[must_use]
|
||||
fn is_animation(&self) -> bool {
|
||||
matches!(self, Self::Animation(..))
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: LayoutElement> Monitor<W> {
|
||||
pub fn new(output: Output, workspaces: Vec<Workspace<W>>, options: Rc<Options>) -> Self {
|
||||
Self {
|
||||
output,
|
||||
workspaces,
|
||||
active_workspace_idx: 0,
|
||||
previous_workspace_id: None,
|
||||
workspace_switch: None,
|
||||
options,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn active_workspace_ref(&self) -> &Workspace<W> {
|
||||
&self.workspaces[self.active_workspace_idx]
|
||||
}
|
||||
|
||||
pub fn find_named_workspace(&self, workspace_name: &str) -> Option<&Workspace<W>> {
|
||||
self.workspaces.iter().find(|ws| {
|
||||
ws.name
|
||||
.as_ref()
|
||||
.map_or(false, |name| name.eq_ignore_ascii_case(workspace_name))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn find_named_workspace_index(&self, workspace_name: &str) -> Option<usize> {
|
||||
self.workspaces.iter().position(|ws| {
|
||||
ws.name
|
||||
.as_ref()
|
||||
.map_or(false, |name| name.eq_ignore_ascii_case(workspace_name))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn active_workspace(&mut self) -> &mut Workspace<W> {
|
||||
&mut self.workspaces[self.active_workspace_idx]
|
||||
}
|
||||
|
||||
fn activate_workspace(&mut self, idx: usize) {
|
||||
if self.active_workspace_idx == idx {
|
||||
return;
|
||||
}
|
||||
|
||||
// FIXME: also compute and use current velocity.
|
||||
let current_idx = self
|
||||
.workspace_switch
|
||||
.as_ref()
|
||||
.map(|s| s.current_idx())
|
||||
.unwrap_or(self.active_workspace_idx as f64);
|
||||
|
||||
self.previous_workspace_id = Some(self.workspaces[self.active_workspace_idx].id());
|
||||
|
||||
self.active_workspace_idx = idx;
|
||||
|
||||
self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
|
||||
current_idx,
|
||||
idx as f64,
|
||||
0.,
|
||||
self.options.animations.workspace_switch.0,
|
||||
)));
|
||||
}
|
||||
|
||||
pub fn add_window(
|
||||
&mut self,
|
||||
workspace_idx: usize,
|
||||
window: W,
|
||||
activate: bool,
|
||||
width: ColumnWidth,
|
||||
is_full_width: bool,
|
||||
) {
|
||||
let workspace = &mut self.workspaces[workspace_idx];
|
||||
|
||||
workspace.add_window(window, activate, width, is_full_width);
|
||||
|
||||
// After adding a new window, workspace becomes this output's own.
|
||||
workspace.original_output = OutputId::new(&self.output);
|
||||
|
||||
if workspace_idx == self.workspaces.len() - 1 {
|
||||
// Insert a new empty workspace.
|
||||
let ws = Workspace::new(self.output.clone(), self.options.clone());
|
||||
self.workspaces.push(ws);
|
||||
}
|
||||
|
||||
if activate {
|
||||
self.activate_workspace(workspace_idx);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_window_right_of(
|
||||
&mut self,
|
||||
right_of: &W::Id,
|
||||
window: W,
|
||||
width: ColumnWidth,
|
||||
is_full_width: bool,
|
||||
) {
|
||||
let workspace_idx = self
|
||||
.workspaces
|
||||
.iter_mut()
|
||||
.position(|ws| ws.has_window(right_of))
|
||||
.unwrap();
|
||||
let workspace = &mut self.workspaces[workspace_idx];
|
||||
|
||||
workspace.add_window_right_of(right_of, window, width, is_full_width);
|
||||
|
||||
// After adding a new window, workspace becomes this output's own.
|
||||
workspace.original_output = OutputId::new(&self.output);
|
||||
}
|
||||
|
||||
pub fn add_column(&mut self, workspace_idx: usize, column: Column<W>, activate: bool) {
|
||||
let workspace = &mut self.workspaces[workspace_idx];
|
||||
|
||||
workspace.add_column(column, activate);
|
||||
|
||||
// After adding a new window, workspace becomes this output's own.
|
||||
workspace.original_output = OutputId::new(&self.output);
|
||||
|
||||
if workspace_idx == self.workspaces.len() - 1 {
|
||||
// Insert a new empty workspace.
|
||||
let ws = Workspace::new(self.output.clone(), self.options.clone());
|
||||
self.workspaces.push(ws);
|
||||
}
|
||||
|
||||
if activate {
|
||||
self.activate_workspace(workspace_idx);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clean_up_workspaces(&mut self) {
|
||||
assert!(self.workspace_switch.is_none());
|
||||
|
||||
for idx in (0..self.workspaces.len() - 1).rev() {
|
||||
if self.active_workspace_idx == idx {
|
||||
continue;
|
||||
}
|
||||
|
||||
if !self.workspaces[idx].has_windows() && self.workspaces[idx].name.is_none() {
|
||||
self.workspaces.remove(idx);
|
||||
if self.active_workspace_idx > idx {
|
||||
self.active_workspace_idx -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unname_workspace(&mut self, workspace_name: &str) -> bool {
|
||||
for ws in &mut self.workspaces {
|
||||
if ws
|
||||
.name
|
||||
.as_ref()
|
||||
.map_or(false, |name| name.eq_ignore_ascii_case(workspace_name))
|
||||
{
|
||||
ws.unname();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn move_left(&mut self) {
|
||||
self.active_workspace().move_left();
|
||||
}
|
||||
|
||||
pub fn move_right(&mut self) {
|
||||
self.active_workspace().move_right();
|
||||
}
|
||||
|
||||
pub fn move_column_to_first(&mut self) {
|
||||
self.active_workspace().move_column_to_first();
|
||||
}
|
||||
|
||||
pub fn move_column_to_last(&mut self) {
|
||||
self.active_workspace().move_column_to_last();
|
||||
}
|
||||
|
||||
pub fn move_down(&mut self) {
|
||||
self.active_workspace().move_down();
|
||||
}
|
||||
|
||||
pub fn move_up(&mut self) {
|
||||
self.active_workspace().move_up();
|
||||
}
|
||||
|
||||
pub fn move_down_or_to_workspace_down(&mut self) {
|
||||
let workspace = self.active_workspace();
|
||||
if workspace.columns.is_empty() {
|
||||
return;
|
||||
}
|
||||
let column = &mut workspace.columns[workspace.active_column_idx];
|
||||
let curr_idx = column.active_tile_idx;
|
||||
let new_idx = min(column.active_tile_idx + 1, column.tiles.len() - 1);
|
||||
if curr_idx == new_idx {
|
||||
self.move_to_workspace_down();
|
||||
} else {
|
||||
workspace.move_down();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn move_up_or_to_workspace_up(&mut self) {
|
||||
let workspace = self.active_workspace();
|
||||
if workspace.columns.is_empty() {
|
||||
return;
|
||||
}
|
||||
let curr_idx = workspace.columns[workspace.active_column_idx].active_tile_idx;
|
||||
let new_idx = curr_idx.saturating_sub(1);
|
||||
if curr_idx == new_idx {
|
||||
self.move_to_workspace_up();
|
||||
} else {
|
||||
workspace.move_up();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn consume_or_expel_window_left(&mut self) {
|
||||
self.active_workspace().consume_or_expel_window_left();
|
||||
}
|
||||
|
||||
pub fn consume_or_expel_window_right(&mut self) {
|
||||
self.active_workspace().consume_or_expel_window_right();
|
||||
}
|
||||
|
||||
pub fn focus_left(&mut self) {
|
||||
self.active_workspace().focus_left();
|
||||
}
|
||||
|
||||
pub fn focus_right(&mut self) {
|
||||
self.active_workspace().focus_right();
|
||||
}
|
||||
|
||||
pub fn focus_column_first(&mut self) {
|
||||
self.active_workspace().focus_column_first();
|
||||
}
|
||||
|
||||
pub fn focus_column_last(&mut self) {
|
||||
self.active_workspace().focus_column_last();
|
||||
}
|
||||
|
||||
pub fn focus_down(&mut self) {
|
||||
self.active_workspace().focus_down();
|
||||
}
|
||||
|
||||
pub fn focus_up(&mut self) {
|
||||
self.active_workspace().focus_up();
|
||||
}
|
||||
|
||||
pub fn focus_window_or_workspace_down(&mut self) {
|
||||
let workspace = self.active_workspace();
|
||||
if workspace.columns.is_empty() {
|
||||
self.switch_workspace_down();
|
||||
} else {
|
||||
let column = &workspace.columns[workspace.active_column_idx];
|
||||
let curr_idx = column.active_tile_idx;
|
||||
let new_idx = min(column.active_tile_idx + 1, column.tiles.len() - 1);
|
||||
if curr_idx == new_idx {
|
||||
self.switch_workspace_down();
|
||||
} else {
|
||||
workspace.focus_down();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn focus_window_or_workspace_up(&mut self) {
|
||||
let workspace = self.active_workspace();
|
||||
if workspace.columns.is_empty() {
|
||||
self.switch_workspace_up();
|
||||
} else {
|
||||
let curr_idx = workspace.columns[workspace.active_column_idx].active_tile_idx;
|
||||
let new_idx = curr_idx.saturating_sub(1);
|
||||
if curr_idx == new_idx {
|
||||
self.switch_workspace_up();
|
||||
} else {
|
||||
workspace.focus_up();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn move_to_workspace_up(&mut self) {
|
||||
let source_workspace_idx = self.active_workspace_idx;
|
||||
|
||||
let new_idx = source_workspace_idx.saturating_sub(1);
|
||||
if new_idx == source_workspace_idx {
|
||||
return;
|
||||
}
|
||||
|
||||
let workspace = &mut self.workspaces[source_workspace_idx];
|
||||
if workspace.columns.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let column = &workspace.columns[workspace.active_column_idx];
|
||||
let width = column.width;
|
||||
let is_full_width = column.is_full_width;
|
||||
let window = workspace
|
||||
.remove_tile_by_idx(workspace.active_column_idx, column.active_tile_idx, None)
|
||||
.into_window();
|
||||
|
||||
self.add_window(new_idx, window, true, width, is_full_width);
|
||||
}
|
||||
|
||||
pub fn move_to_workspace_down(&mut self) {
|
||||
let source_workspace_idx = self.active_workspace_idx;
|
||||
|
||||
let new_idx = min(source_workspace_idx + 1, self.workspaces.len() - 1);
|
||||
if new_idx == source_workspace_idx {
|
||||
return;
|
||||
}
|
||||
|
||||
let workspace = &mut self.workspaces[source_workspace_idx];
|
||||
if workspace.columns.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let column = &workspace.columns[workspace.active_column_idx];
|
||||
let width = column.width;
|
||||
let is_full_width = column.is_full_width;
|
||||
let window = workspace
|
||||
.remove_tile_by_idx(workspace.active_column_idx, column.active_tile_idx, None)
|
||||
.into_window();
|
||||
|
||||
self.add_window(new_idx, window, true, width, is_full_width);
|
||||
}
|
||||
|
||||
pub fn move_to_workspace(&mut self, idx: usize) {
|
||||
let source_workspace_idx = self.active_workspace_idx;
|
||||
|
||||
let new_idx = min(idx, self.workspaces.len() - 1);
|
||||
if new_idx == source_workspace_idx {
|
||||
return;
|
||||
}
|
||||
|
||||
let workspace = &mut self.workspaces[source_workspace_idx];
|
||||
if workspace.columns.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let column = &workspace.columns[workspace.active_column_idx];
|
||||
let width = column.width;
|
||||
let is_full_width = column.is_full_width;
|
||||
let window = workspace
|
||||
.remove_tile_by_idx(workspace.active_column_idx, column.active_tile_idx, None)
|
||||
.into_window();
|
||||
|
||||
self.add_window(new_idx, window, true, width, is_full_width);
|
||||
|
||||
// Don't animate this action.
|
||||
self.workspace_switch = None;
|
||||
|
||||
self.clean_up_workspaces();
|
||||
}
|
||||
|
||||
pub fn move_column_to_workspace_up(&mut self) {
|
||||
let source_workspace_idx = self.active_workspace_idx;
|
||||
|
||||
let new_idx = source_workspace_idx.saturating_sub(1);
|
||||
if new_idx == source_workspace_idx {
|
||||
return;
|
||||
}
|
||||
|
||||
let workspace = &mut self.workspaces[source_workspace_idx];
|
||||
if workspace.columns.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let column = workspace.remove_column_by_idx(workspace.active_column_idx);
|
||||
self.add_column(new_idx, column, true);
|
||||
}
|
||||
|
||||
pub fn move_column_to_workspace_down(&mut self) {
|
||||
let source_workspace_idx = self.active_workspace_idx;
|
||||
|
||||
let new_idx = min(source_workspace_idx + 1, self.workspaces.len() - 1);
|
||||
if new_idx == source_workspace_idx {
|
||||
return;
|
||||
}
|
||||
|
||||
let workspace = &mut self.workspaces[source_workspace_idx];
|
||||
if workspace.columns.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let column = workspace.remove_column_by_idx(workspace.active_column_idx);
|
||||
self.add_column(new_idx, column, true);
|
||||
}
|
||||
|
||||
pub fn move_column_to_workspace(&mut self, idx: usize) {
|
||||
let source_workspace_idx = self.active_workspace_idx;
|
||||
|
||||
let new_idx = min(idx, self.workspaces.len() - 1);
|
||||
if new_idx == source_workspace_idx {
|
||||
return;
|
||||
}
|
||||
|
||||
let workspace = &mut self.workspaces[source_workspace_idx];
|
||||
if workspace.columns.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let column = workspace.remove_column_by_idx(workspace.active_column_idx);
|
||||
self.add_column(new_idx, column, true);
|
||||
|
||||
// Don't animate this action.
|
||||
self.workspace_switch = None;
|
||||
|
||||
self.clean_up_workspaces();
|
||||
}
|
||||
|
||||
pub fn switch_workspace_up(&mut self) {
|
||||
self.activate_workspace(self.active_workspace_idx.saturating_sub(1));
|
||||
}
|
||||
|
||||
pub fn switch_workspace_down(&mut self) {
|
||||
self.activate_workspace(min(
|
||||
self.active_workspace_idx + 1,
|
||||
self.workspaces.len() - 1,
|
||||
));
|
||||
}
|
||||
|
||||
fn previous_workspace_idx(&self) -> Option<usize> {
|
||||
let id = self.previous_workspace_id?;
|
||||
self.workspaces.iter().position(|w| w.id() == id)
|
||||
}
|
||||
|
||||
pub fn switch_workspace(&mut self, idx: usize) {
|
||||
self.activate_workspace(min(idx, self.workspaces.len() - 1));
|
||||
// Don't animate this action.
|
||||
self.workspace_switch = None;
|
||||
|
||||
self.clean_up_workspaces();
|
||||
}
|
||||
|
||||
pub fn switch_workspace_auto_back_and_forth(&mut self, idx: usize) {
|
||||
let idx = min(idx, self.workspaces.len() - 1);
|
||||
|
||||
if idx == self.active_workspace_idx {
|
||||
if let Some(prev_idx) = self.previous_workspace_idx() {
|
||||
self.switch_workspace(prev_idx);
|
||||
}
|
||||
} else {
|
||||
self.switch_workspace(idx);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn switch_workspace_previous(&mut self) {
|
||||
if let Some(idx) = self.previous_workspace_idx() {
|
||||
self.switch_workspace(idx);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn consume_into_column(&mut self) {
|
||||
self.active_workspace().consume_into_column();
|
||||
}
|
||||
|
||||
pub fn expel_from_column(&mut self) {
|
||||
self.active_workspace().expel_from_column();
|
||||
}
|
||||
|
||||
pub fn center_column(&mut self) {
|
||||
self.active_workspace().center_column();
|
||||
}
|
||||
|
||||
pub fn focus(&self) -> Option<&W> {
|
||||
let workspace = &self.workspaces[self.active_workspace_idx];
|
||||
if !workspace.has_windows() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let column = &workspace.columns[workspace.active_column_idx];
|
||||
Some(column.tiles[column.active_tile_idx].window())
|
||||
}
|
||||
|
||||
pub fn advance_animations(&mut self, current_time: Duration) {
|
||||
if let Some(WorkspaceSwitch::Animation(anim)) = &mut self.workspace_switch {
|
||||
anim.set_current_time(current_time);
|
||||
if anim.is_done() {
|
||||
self.workspace_switch = None;
|
||||
self.clean_up_workspaces();
|
||||
}
|
||||
}
|
||||
|
||||
for ws in &mut self.workspaces {
|
||||
ws.advance_animations(current_time);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn are_animations_ongoing(&self) -> bool {
|
||||
self.workspace_switch
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.is_animation())
|
||||
|| self.workspaces.iter().any(|ws| ws.are_animations_ongoing())
|
||||
}
|
||||
|
||||
pub fn are_transitions_ongoing(&self) -> bool {
|
||||
self.workspace_switch.is_some()
|
||||
|| self
|
||||
.workspaces
|
||||
.iter()
|
||||
.any(|ws| ws.are_transitions_ongoing())
|
||||
}
|
||||
|
||||
pub fn update_render_elements(&mut self, is_active: bool) {
|
||||
match &self.workspace_switch {
|
||||
Some(switch) => {
|
||||
let render_idx = switch.current_idx();
|
||||
let before_idx = render_idx.floor();
|
||||
let after_idx = render_idx.ceil();
|
||||
|
||||
if after_idx < 0. || before_idx as usize >= self.workspaces.len() {
|
||||
return;
|
||||
}
|
||||
|
||||
let after_idx = after_idx as usize;
|
||||
if after_idx < self.workspaces.len() {
|
||||
self.workspaces[after_idx].update_render_elements(is_active);
|
||||
|
||||
if before_idx < 0. {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let before_idx = before_idx as usize;
|
||||
self.workspaces[before_idx].update_render_elements(is_active);
|
||||
}
|
||||
None => {
|
||||
self.workspaces[self.active_workspace_idx].update_render_elements(is_active);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_config(&mut self, options: Rc<Options>) {
|
||||
for ws in &mut self.workspaces {
|
||||
ws.update_config(options.clone());
|
||||
}
|
||||
|
||||
if self.options.struts != options.struts {
|
||||
let view_size = output_size(&self.output);
|
||||
let working_area = compute_working_area(&self.output, options.struts);
|
||||
|
||||
for ws in &mut self.workspaces {
|
||||
ws.set_view_size(view_size, working_area);
|
||||
}
|
||||
}
|
||||
|
||||
self.options = options;
|
||||
}
|
||||
|
||||
pub fn toggle_width(&mut self) {
|
||||
self.active_workspace().toggle_width();
|
||||
}
|
||||
|
||||
pub fn toggle_full_width(&mut self) {
|
||||
self.active_workspace().toggle_full_width();
|
||||
}
|
||||
|
||||
pub fn set_column_width(&mut self, change: SizeChange) {
|
||||
self.active_workspace().set_column_width(change);
|
||||
}
|
||||
|
||||
pub fn set_window_height(&mut self, change: SizeChange) {
|
||||
self.active_workspace().set_window_height(change);
|
||||
}
|
||||
|
||||
pub fn reset_window_height(&mut self) {
|
||||
self.active_workspace().reset_window_height();
|
||||
}
|
||||
|
||||
pub fn move_workspace_down(&mut self) {
|
||||
let new_idx = min(self.active_workspace_idx + 1, self.workspaces.len() - 1);
|
||||
if new_idx == self.active_workspace_idx {
|
||||
return;
|
||||
}
|
||||
|
||||
self.workspaces.swap(self.active_workspace_idx, new_idx);
|
||||
|
||||
if new_idx == self.workspaces.len() - 1 {
|
||||
// Insert a new empty workspace.
|
||||
let ws = Workspace::new(self.output.clone(), self.options.clone());
|
||||
self.workspaces.push(ws);
|
||||
}
|
||||
|
||||
let previous_workspace_id = self.previous_workspace_id;
|
||||
self.activate_workspace(new_idx);
|
||||
self.workspace_switch = None;
|
||||
self.previous_workspace_id = previous_workspace_id;
|
||||
|
||||
self.clean_up_workspaces();
|
||||
}
|
||||
|
||||
pub fn move_workspace_up(&mut self) {
|
||||
let new_idx = self.active_workspace_idx.saturating_sub(1);
|
||||
if new_idx == self.active_workspace_idx {
|
||||
return;
|
||||
}
|
||||
|
||||
self.workspaces.swap(self.active_workspace_idx, new_idx);
|
||||
|
||||
if self.active_workspace_idx == self.workspaces.len() - 1 {
|
||||
// Insert a new empty workspace.
|
||||
let ws = Workspace::new(self.output.clone(), self.options.clone());
|
||||
self.workspaces.push(ws);
|
||||
}
|
||||
|
||||
let previous_workspace_id = self.previous_workspace_id;
|
||||
self.activate_workspace(new_idx);
|
||||
self.workspace_switch = None;
|
||||
self.previous_workspace_id = previous_workspace_id;
|
||||
|
||||
self.clean_up_workspaces();
|
||||
}
|
||||
|
||||
/// Returns the geometry of the active tile relative to and clamped to the output.
|
||||
///
|
||||
/// During animations, assumes the final view position.
|
||||
pub fn active_tile_visual_rectangle(&self) -> Option<Rectangle<i32, Logical>> {
|
||||
let mut rect = self.active_workspace_ref().active_tile_visual_rectangle()?;
|
||||
|
||||
if let Some(switch) = &self.workspace_switch {
|
||||
let size = output_size(&self.output);
|
||||
|
||||
let offset = switch.target_idx() - self.active_workspace_idx as f64;
|
||||
let offset = (offset * size.h as f64).round() as i32;
|
||||
|
||||
let clip_rect = Rectangle::from_loc_and_size((0, -offset), size);
|
||||
rect = rect.intersection(clip_rect)?;
|
||||
}
|
||||
|
||||
Some(rect)
|
||||
}
|
||||
|
||||
pub fn window_under(
|
||||
&self,
|
||||
pos_within_output: Point<f64, Logical>,
|
||||
) -> Option<(&W, Option<Point<i32, Logical>>)> {
|
||||
match &self.workspace_switch {
|
||||
Some(switch) => {
|
||||
let size = output_size(&self.output);
|
||||
|
||||
let render_idx = switch.current_idx();
|
||||
let before_idx = render_idx.floor();
|
||||
let after_idx = render_idx.ceil();
|
||||
|
||||
let offset = ((render_idx - before_idx) * size.h as f64).round() as i32;
|
||||
|
||||
if after_idx < 0. || before_idx as usize >= self.workspaces.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let after_idx = after_idx as usize;
|
||||
|
||||
let (idx, ws_offset) = if pos_within_output.y < (size.h - offset) as f64 {
|
||||
if before_idx < 0. {
|
||||
return None;
|
||||
}
|
||||
|
||||
(before_idx as usize, Point::from((0, offset)))
|
||||
} else {
|
||||
if after_idx >= self.workspaces.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
(after_idx, Point::from((0, -size.h + offset)))
|
||||
};
|
||||
|
||||
let ws = &self.workspaces[idx];
|
||||
let (win, win_pos) = ws.window_under(pos_within_output + ws_offset.to_f64())?;
|
||||
Some((win, win_pos.map(|p| p - ws_offset)))
|
||||
}
|
||||
None => {
|
||||
let ws = &self.workspaces[self.active_workspace_idx];
|
||||
ws.window_under(pos_within_output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resize_edges_under(&self, pos_within_output: Point<f64, Logical>) -> Option<ResizeEdge> {
|
||||
match &self.workspace_switch {
|
||||
Some(switch) => {
|
||||
let size = output_size(&self.output);
|
||||
|
||||
let render_idx = switch.current_idx();
|
||||
let before_idx = render_idx.floor();
|
||||
let after_idx = render_idx.ceil();
|
||||
|
||||
let offset = ((render_idx - before_idx) * size.h as f64).round() as i32;
|
||||
|
||||
if after_idx < 0. || before_idx as usize >= self.workspaces.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let after_idx = after_idx as usize;
|
||||
|
||||
let (idx, ws_offset) = if pos_within_output.y < (size.h - offset) as f64 {
|
||||
if before_idx < 0. {
|
||||
return None;
|
||||
}
|
||||
|
||||
(before_idx as usize, Point::from((0, offset)))
|
||||
} else {
|
||||
if after_idx >= self.workspaces.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
(after_idx, Point::from((0, -size.h + offset)))
|
||||
};
|
||||
|
||||
let ws = &self.workspaces[idx];
|
||||
ws.resize_edges_under(pos_within_output + ws_offset.to_f64())
|
||||
}
|
||||
None => {
|
||||
let ws = &self.workspaces[self.active_workspace_idx];
|
||||
ws.resize_edges_under(pos_within_output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render_above_top_layer(&self) -> bool {
|
||||
// Render above the top layer only if the view is stationary.
|
||||
if self.workspace_switch.is_some() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let ws = &self.workspaces[self.active_workspace_idx];
|
||||
ws.render_above_top_layer()
|
||||
}
|
||||
|
||||
pub fn render_elements<R: NiriRenderer>(
|
||||
&self,
|
||||
renderer: &mut R,
|
||||
target: RenderTarget,
|
||||
) -> Vec<MonitorRenderElement<R>> {
|
||||
let _span = tracy_client::span!("Monitor::render_elements");
|
||||
|
||||
let output_scale = Scale::from(self.output.current_scale().fractional_scale());
|
||||
let output_transform = self.output.current_transform();
|
||||
let output_mode = self.output.current_mode().unwrap();
|
||||
let size = output_transform.transform_size(output_mode.size);
|
||||
|
||||
match &self.workspace_switch {
|
||||
Some(switch) => {
|
||||
let render_idx = switch.current_idx();
|
||||
let before_idx = render_idx.floor();
|
||||
let after_idx = render_idx.ceil();
|
||||
|
||||
let offset = ((render_idx - before_idx) * size.h as f64).round() as i32;
|
||||
|
||||
if after_idx < 0. || before_idx as usize >= self.workspaces.len() {
|
||||
return vec![];
|
||||
}
|
||||
|
||||
let after_idx = after_idx as usize;
|
||||
let after = if after_idx < self.workspaces.len() {
|
||||
let after = self.workspaces[after_idx].render_elements(renderer, target);
|
||||
let after = after.into_iter().filter_map(|elem| {
|
||||
Some(RelocateRenderElement::from_element(
|
||||
CropRenderElement::from_element(
|
||||
elem,
|
||||
output_scale,
|
||||
// HACK: crop to infinite bounds for all sides except the side
|
||||
// where the workspaces join,
|
||||
// otherwise it will cut pixel shaders and mess up
|
||||
// the coordinate space.
|
||||
Rectangle::from_extemities(
|
||||
(-i32::MAX / 2, 0),
|
||||
(i32::MAX / 2, i32::MAX / 2),
|
||||
),
|
||||
)?,
|
||||
(0, -offset + size.h),
|
||||
Relocate::Relative,
|
||||
))
|
||||
});
|
||||
|
||||
if before_idx < 0. {
|
||||
return after.collect();
|
||||
}
|
||||
|
||||
Some(after)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let before_idx = before_idx as usize;
|
||||
let before = self.workspaces[before_idx].render_elements(renderer, target);
|
||||
let before = before.into_iter().filter_map(|elem| {
|
||||
Some(RelocateRenderElement::from_element(
|
||||
CropRenderElement::from_element(
|
||||
elem,
|
||||
output_scale,
|
||||
Rectangle::from_extemities(
|
||||
(-i32::MAX / 2, -i32::MAX / 2),
|
||||
(i32::MAX / 2, size.h),
|
||||
),
|
||||
)?,
|
||||
(0, -offset),
|
||||
Relocate::Relative,
|
||||
))
|
||||
});
|
||||
before.chain(after.into_iter().flatten()).collect()
|
||||
}
|
||||
None => {
|
||||
let elements =
|
||||
self.workspaces[self.active_workspace_idx].render_elements(renderer, target);
|
||||
elements
|
||||
.into_iter()
|
||||
.filter_map(|elem| {
|
||||
Some(RelocateRenderElement::from_element(
|
||||
CropRenderElement::from_element(
|
||||
elem,
|
||||
output_scale,
|
||||
// HACK: set infinite crop bounds due to a damage tracking bug
|
||||
// which causes glitched rendering for maximized GTK windows.
|
||||
// FIXME: use proper bounds after fixing the Crop element.
|
||||
Rectangle::from_loc_and_size(
|
||||
(-i32::MAX / 2, -i32::MAX / 2),
|
||||
(i32::MAX, i32::MAX),
|
||||
),
|
||||
// Rectangle::from_loc_and_size((0, 0), size),
|
||||
)?,
|
||||
(0, 0),
|
||||
Relocate::Relative,
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn workspace_switch_gesture_begin(&mut self) {
|
||||
let center_idx = self.active_workspace_idx;
|
||||
let current_idx = self
|
||||
.workspace_switch
|
||||
.as_ref()
|
||||
.map(|s| s.current_idx())
|
||||
.unwrap_or(center_idx as f64);
|
||||
|
||||
let gesture = WorkspaceSwitchGesture {
|
||||
center_idx,
|
||||
current_idx,
|
||||
tracker: SwipeTracker::new(),
|
||||
};
|
||||
self.workspace_switch = Some(WorkspaceSwitch::Gesture(gesture));
|
||||
}
|
||||
|
||||
pub fn workspace_switch_gesture_update(
|
||||
&mut self,
|
||||
delta_y: f64,
|
||||
timestamp: Duration,
|
||||
) -> Option<bool> {
|
||||
let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
|
||||
return None;
|
||||
};
|
||||
|
||||
gesture.tracker.push(delta_y, timestamp);
|
||||
|
||||
let pos = gesture.tracker.pos() / WORKSPACE_GESTURE_MOVEMENT;
|
||||
|
||||
let min = gesture.center_idx.saturating_sub(1) as f64;
|
||||
let max = (gesture.center_idx + 1).min(self.workspaces.len() - 1) as f64;
|
||||
let new_idx = gesture.center_idx as f64 + pos;
|
||||
let new_idx = WORKSPACE_GESTURE_RUBBER_BAND.clamp(min, max, new_idx);
|
||||
|
||||
if gesture.current_idx == new_idx {
|
||||
return Some(false);
|
||||
}
|
||||
|
||||
gesture.current_idx = new_idx;
|
||||
Some(true)
|
||||
}
|
||||
|
||||
pub fn workspace_switch_gesture_end(&mut self, cancelled: bool) -> bool {
|
||||
let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if cancelled {
|
||||
self.workspace_switch = None;
|
||||
self.clean_up_workspaces();
|
||||
return true;
|
||||
}
|
||||
|
||||
let mut velocity = gesture.tracker.velocity() / WORKSPACE_GESTURE_MOVEMENT;
|
||||
let current_pos = gesture.tracker.pos() / WORKSPACE_GESTURE_MOVEMENT;
|
||||
let pos = gesture.tracker.projected_end_pos() / WORKSPACE_GESTURE_MOVEMENT;
|
||||
|
||||
let min = gesture.center_idx.saturating_sub(1) as f64;
|
||||
let max = (gesture.center_idx + 1).min(self.workspaces.len() - 1) as f64;
|
||||
let new_idx = gesture.center_idx as f64 + pos;
|
||||
|
||||
let new_idx = WORKSPACE_GESTURE_RUBBER_BAND.clamp(min, max, new_idx);
|
||||
let new_idx = new_idx.round() as usize;
|
||||
|
||||
velocity *= WORKSPACE_GESTURE_RUBBER_BAND.clamp_derivative(
|
||||
min,
|
||||
max,
|
||||
gesture.center_idx as f64 + current_pos,
|
||||
);
|
||||
|
||||
self.previous_workspace_id = Some(self.workspaces[self.active_workspace_idx].id());
|
||||
|
||||
self.active_workspace_idx = new_idx;
|
||||
self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
|
||||
gesture.current_idx,
|
||||
new_idx as f64,
|
||||
velocity,
|
||||
self.options.animations.workspace_switch.0,
|
||||
)));
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use glam::{Mat3, Vec2};
|
||||
use smithay::backend::allocator::Fourcc;
|
||||
use smithay::backend::renderer::element::texture::TextureRenderElement;
|
||||
use smithay::backend::renderer::element::utils::{
|
||||
Relocate, RelocateRenderElement, RescaleRenderElement,
|
||||
};
|
||||
use smithay::backend::renderer::element::{Id, Kind, RenderElement};
|
||||
use smithay::backend::renderer::gles::{GlesRenderer, Uniform};
|
||||
use smithay::backend::renderer::{Renderer as _, Texture};
|
||||
use smithay::utils::{Logical, Point, Rectangle, Scale, Size, Transform};
|
||||
|
||||
use crate::animation::Animation;
|
||||
use crate::niri_render_elements;
|
||||
use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;
|
||||
use crate::render_helpers::render_to_encompassing_texture;
|
||||
use crate::render_helpers::shader_element::ShaderRenderElement;
|
||||
use crate::render_helpers::shaders::{mat3_uniform, ProgramType, Shaders};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct OpenAnimation {
|
||||
anim: Animation,
|
||||
random_seed: f32,
|
||||
}
|
||||
|
||||
niri_render_elements! {
|
||||
OpeningWindowRenderElement => {
|
||||
Texture = RelocateRenderElement<RescaleRenderElement<PrimaryGpuTextureRenderElement>>,
|
||||
Shader = ShaderRenderElement,
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenAnimation {
|
||||
pub fn new(anim: Animation) -> Self {
|
||||
Self {
|
||||
anim,
|
||||
random_seed: fastrand::f32(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn advance_animations(&mut self, current_time: Duration) {
|
||||
self.anim.set_current_time(current_time);
|
||||
}
|
||||
|
||||
pub fn is_done(&self) -> bool {
|
||||
self.anim.is_done()
|
||||
}
|
||||
|
||||
// We can't depend on view_rect here, because the result of window opening can be snapshot and
|
||||
// then rendered elsewhere.
|
||||
pub fn render(
|
||||
&self,
|
||||
renderer: &mut GlesRenderer,
|
||||
elements: &[impl RenderElement<GlesRenderer>],
|
||||
geo_size: Size<i32, Logical>,
|
||||
location: Point<i32, Logical>,
|
||||
scale: Scale<f64>,
|
||||
) -> anyhow::Result<OpeningWindowRenderElement> {
|
||||
let progress = self.anim.value();
|
||||
let clamped_progress = self.anim.clamped_value().clamp(0., 1.);
|
||||
|
||||
let (texture, _sync_point, geo) = render_to_encompassing_texture(
|
||||
renderer,
|
||||
scale,
|
||||
Transform::Normal,
|
||||
Fourcc::Abgr8888,
|
||||
elements,
|
||||
)
|
||||
.context("error rendering to texture")?;
|
||||
|
||||
let offset = geo.loc.to_f64().to_logical(scale);
|
||||
let texture_size = geo.size.to_f64().to_logical(scale);
|
||||
|
||||
if Shaders::get(renderer).program(ProgramType::Open).is_some() {
|
||||
let mut area = Rectangle::from_loc_and_size(location.to_f64() + offset, texture_size);
|
||||
|
||||
// Expand the area a bit to allow for more varied effects.
|
||||
let mut target_size = area.size.upscale(1.5);
|
||||
target_size.w = f64::max(area.size.w + 1000., target_size.w);
|
||||
target_size.h = f64::max(area.size.h + 1000., target_size.h);
|
||||
let diff = target_size.to_point() - area.size.to_point();
|
||||
area.loc -= diff.downscale(2.);
|
||||
area.size += diff.to_size();
|
||||
|
||||
let area = area.to_i32_up();
|
||||
let area_loc = Vec2::new(area.loc.x as f32, area.loc.y as f32);
|
||||
let area_size = Vec2::new(area.size.w as f32, area.size.h as f32);
|
||||
|
||||
let geo_loc = Vec2::new(location.x as f32, location.y as f32);
|
||||
let geo_size = Vec2::new(geo_size.w as f32, 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 = Vec2::new(scale.x as f32, scale.y as f32);
|
||||
let tex_loc = Vec2::new(offset.x as f32, offset.y as f32);
|
||||
let tex_size = Vec2::new(texture.width() as f32, texture.height() as f32) / tex_scale;
|
||||
|
||||
let geo_to_tex =
|
||||
Mat3::from_translation(-tex_loc / tex_size) * Mat3::from_scale(geo_size / tex_size);
|
||||
|
||||
return Ok(ShaderRenderElement::new(
|
||||
ProgramType::Open,
|
||||
area.size,
|
||||
None,
|
||||
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"), texture.clone())]),
|
||||
Kind::Unspecified,
|
||||
)
|
||||
.with_location(area.loc)
|
||||
.into());
|
||||
}
|
||||
|
||||
let elem = TextureRenderElement::from_static_texture(
|
||||
Id::new(),
|
||||
renderer.id(),
|
||||
Point::from((0., 0.)),
|
||||
texture.clone(),
|
||||
scale.x as i32,
|
||||
Transform::Normal,
|
||||
Some(clamped_progress as f32),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Kind::Unspecified,
|
||||
);
|
||||
|
||||
let elem = PrimaryGpuTextureRenderElement(elem);
|
||||
|
||||
let center = geo_size.to_point().to_f64().downscale(2.);
|
||||
let elem = RescaleRenderElement::from_element(
|
||||
elem,
|
||||
(center - offset).to_physical_precise_round(scale),
|
||||
(progress / 2. + 0.5).max(0.),
|
||||
);
|
||||
|
||||
let elem = RelocateRenderElement::from_element(
|
||||
elem,
|
||||
(location.to_f64() + offset).to_physical_precise_round(scale),
|
||||
Relocate::Relative,
|
||||
);
|
||||
|
||||
Ok(elem.into())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,874 @@
|
||||
use std::cmp::max;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use niri_config::CornerRadius;
|
||||
use smithay::backend::allocator::Fourcc;
|
||||
use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
|
||||
use smithay::backend::renderer::element::{Element, Kind};
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::utils::{Logical, Point, Rectangle, Scale, Size, Transform};
|
||||
|
||||
use super::focus_ring::{FocusRing, FocusRingRenderElement};
|
||||
use super::opening_window::{OpenAnimation, OpeningWindowRenderElement};
|
||||
use super::{
|
||||
LayoutElement, LayoutElementRenderElement, LayoutElementRenderSnapshot, Options,
|
||||
RESIZE_ANIMATION_THRESHOLD,
|
||||
};
|
||||
use crate::animation::Animation;
|
||||
use crate::niri_render_elements;
|
||||
use crate::render_helpers::border::BorderRenderElement;
|
||||
use crate::render_helpers::clipped_surface::{ClippedSurfaceRenderElement, RoundedCornerDamage};
|
||||
use crate::render_helpers::damage::ExtraDamage;
|
||||
use crate::render_helpers::renderer::NiriRenderer;
|
||||
use crate::render_helpers::resize::ResizeRenderElement;
|
||||
use crate::render_helpers::snapshot::RenderSnapshot;
|
||||
use crate::render_helpers::{render_to_encompassing_texture, RenderTarget};
|
||||
|
||||
/// Toplevel window with decorations.
|
||||
#[derive(Debug)]
|
||||
pub struct Tile<W: LayoutElement> {
|
||||
/// The toplevel window itself.
|
||||
window: W,
|
||||
|
||||
/// The border around the window.
|
||||
border: FocusRing,
|
||||
|
||||
/// The focus ring around the window.
|
||||
///
|
||||
/// It's supposed to be on the Workspace, but for the sake of a nicer open animation it's
|
||||
/// currently here.
|
||||
focus_ring: FocusRing,
|
||||
|
||||
/// Whether this tile is fullscreen.
|
||||
///
|
||||
/// This will update only when the `window` actually goes fullscreen, rather than right away,
|
||||
/// to avoid black backdrop flicker before the window has had a chance to resize.
|
||||
is_fullscreen: bool,
|
||||
|
||||
/// The black backdrop for fullscreen windows.
|
||||
fullscreen_backdrop: SolidColorBuffer,
|
||||
|
||||
/// The size we were requested to fullscreen into.
|
||||
fullscreen_size: Size<i32, Logical>,
|
||||
|
||||
/// The animation upon opening a window.
|
||||
open_animation: Option<OpenAnimation>,
|
||||
|
||||
/// The animation of the window resizing.
|
||||
resize_animation: Option<ResizeAnimation>,
|
||||
|
||||
/// The animation of a tile visually moving horizontally.
|
||||
move_x_animation: Option<MoveAnimation>,
|
||||
|
||||
/// The animation of a tile visually moving vertically.
|
||||
move_y_animation: Option<MoveAnimation>,
|
||||
|
||||
/// Snapshot of the last render for use in the close animation.
|
||||
unmap_snapshot: Option<TileRenderSnapshot>,
|
||||
|
||||
/// Extra damage for clipped surface corner radius changes.
|
||||
rounded_corner_damage: RoundedCornerDamage,
|
||||
|
||||
/// Configurable properties of the layout.
|
||||
pub options: Rc<Options>,
|
||||
}
|
||||
|
||||
niri_render_elements! {
|
||||
TileRenderElement<R> => {
|
||||
LayoutElement = LayoutElementRenderElement<R>,
|
||||
FocusRing = FocusRingRenderElement,
|
||||
SolidColor = SolidColorRenderElement,
|
||||
Opening = OpeningWindowRenderElement,
|
||||
Resize = ResizeRenderElement,
|
||||
Border = BorderRenderElement,
|
||||
ClippedSurface = ClippedSurfaceRenderElement<R>,
|
||||
ExtraDamage = ExtraDamage,
|
||||
}
|
||||
}
|
||||
|
||||
type TileRenderSnapshot =
|
||||
RenderSnapshot<TileRenderElement<GlesRenderer>, TileRenderElement<GlesRenderer>>;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ResizeAnimation {
|
||||
anim: Animation,
|
||||
size_from: Size<i32, Logical>,
|
||||
snapshot: LayoutElementRenderSnapshot,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MoveAnimation {
|
||||
anim: Animation,
|
||||
from: i32,
|
||||
}
|
||||
|
||||
impl<W: LayoutElement> Tile<W> {
|
||||
pub fn new(window: W, options: Rc<Options>) -> Self {
|
||||
let rules = window.rules();
|
||||
let border_config = rules.border.resolve_against(options.border);
|
||||
let focus_ring_config = rules.focus_ring.resolve_against(options.focus_ring.into());
|
||||
|
||||
Self {
|
||||
window,
|
||||
border: FocusRing::new(border_config.into()),
|
||||
focus_ring: FocusRing::new(focus_ring_config.into()),
|
||||
is_fullscreen: false, // FIXME: up-to-date fullscreen right away, but we need size.
|
||||
fullscreen_backdrop: SolidColorBuffer::new((0, 0), [0., 0., 0., 1.]),
|
||||
fullscreen_size: Default::default(),
|
||||
open_animation: None,
|
||||
resize_animation: None,
|
||||
move_x_animation: None,
|
||||
move_y_animation: None,
|
||||
unmap_snapshot: None,
|
||||
rounded_corner_damage: Default::default(),
|
||||
options,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_config(&mut self, options: Rc<Options>) {
|
||||
self.options = options;
|
||||
|
||||
let rules = self.window.rules();
|
||||
|
||||
let border_config = rules.border.resolve_against(self.options.border);
|
||||
self.border.update_config(border_config.into());
|
||||
|
||||
let focus_ring_config = rules
|
||||
.focus_ring
|
||||
.resolve_against(self.options.focus_ring.into());
|
||||
self.focus_ring.update_config(focus_ring_config.into());
|
||||
}
|
||||
|
||||
pub fn update_shaders(&mut self) {
|
||||
self.border.update_shaders();
|
||||
self.focus_ring.update_shaders();
|
||||
}
|
||||
|
||||
pub fn update_window(&mut self) {
|
||||
// FIXME: remove when we can get a fullscreen size right away.
|
||||
if self.fullscreen_size != Size::from((0, 0)) {
|
||||
self.is_fullscreen = self.window.is_fullscreen();
|
||||
}
|
||||
|
||||
if let Some(animate_from) = self.window.take_animation_snapshot() {
|
||||
let size_from = if let Some(resize) = self.resize_animation.take() {
|
||||
// Compute like in animated_window_size(), but using the snapshot geometry (since
|
||||
// the current one is already overwritten).
|
||||
let mut size = animate_from.size;
|
||||
|
||||
let val = resize.anim.value();
|
||||
let size_from = resize.size_from;
|
||||
|
||||
size.w = (size_from.w as f64 + (size.w - size_from.w) as f64 * val).round() as i32;
|
||||
size.h = (size_from.h as f64 + (size.h - size_from.h) as f64 * val).round() as i32;
|
||||
|
||||
size
|
||||
} else {
|
||||
animate_from.size
|
||||
};
|
||||
|
||||
let change = self.window.size().to_point() - size_from.to_point();
|
||||
let change = max(change.x.abs(), change.y.abs());
|
||||
if change > RESIZE_ANIMATION_THRESHOLD {
|
||||
let anim = Animation::new(0., 1., 0., self.options.animations.window_resize.anim);
|
||||
self.resize_animation = Some(ResizeAnimation {
|
||||
anim,
|
||||
size_from,
|
||||
snapshot: animate_from,
|
||||
});
|
||||
} else {
|
||||
self.resize_animation = None;
|
||||
}
|
||||
}
|
||||
|
||||
let rules = self.window.rules();
|
||||
let border_config = rules.border.resolve_against(self.options.border);
|
||||
self.border.update_config(border_config.into());
|
||||
let focus_ring_config = rules
|
||||
.focus_ring
|
||||
.resolve_against(self.options.focus_ring.into());
|
||||
self.focus_ring.update_config(focus_ring_config.into());
|
||||
|
||||
let window_size = self.window_size();
|
||||
let radius = rules
|
||||
.geometry_corner_radius
|
||||
.unwrap_or_default()
|
||||
.fit_to(window_size.w as f32, window_size.h as f32);
|
||||
self.rounded_corner_damage.set_corner_radius(radius);
|
||||
self.rounded_corner_damage.set_size(window_size);
|
||||
}
|
||||
|
||||
pub fn advance_animations(&mut self, current_time: Duration) {
|
||||
if let Some(open) = &mut self.open_animation {
|
||||
open.advance_animations(current_time);
|
||||
if open.is_done() {
|
||||
self.open_animation = None;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(resize) = &mut self.resize_animation {
|
||||
resize.anim.set_current_time(current_time);
|
||||
if resize.anim.is_done() {
|
||||
self.resize_animation = None;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(move_) = &mut self.move_x_animation {
|
||||
move_.anim.set_current_time(current_time);
|
||||
if move_.anim.is_done() {
|
||||
self.move_x_animation = None;
|
||||
}
|
||||
}
|
||||
if let Some(move_) = &mut self.move_y_animation {
|
||||
move_.anim.set_current_time(current_time);
|
||||
if move_.anim.is_done() {
|
||||
self.move_y_animation = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn are_animations_ongoing(&self) -> bool {
|
||||
self.open_animation.is_some()
|
||||
|| self.resize_animation.is_some()
|
||||
|| self.move_x_animation.is_some()
|
||||
|| self.move_y_animation.is_some()
|
||||
}
|
||||
|
||||
pub fn update(&mut self, is_active: bool, view_rect: Rectangle<i32, Logical>) {
|
||||
let rules = self.window.rules();
|
||||
|
||||
let draw_border_with_background = rules
|
||||
.draw_border_with_background
|
||||
.unwrap_or_else(|| !self.window.has_ssd());
|
||||
let border_width = self.effective_border_width().unwrap_or(0);
|
||||
let radius = if self.is_fullscreen {
|
||||
CornerRadius::default()
|
||||
} else {
|
||||
rules
|
||||
.geometry_corner_radius
|
||||
.map_or(CornerRadius::default(), |radius| {
|
||||
radius.expanded_by(border_width as f32)
|
||||
})
|
||||
};
|
||||
self.border.update_render_elements(
|
||||
self.animated_window_size(),
|
||||
is_active,
|
||||
!draw_border_with_background,
|
||||
Rectangle::from_loc_and_size(
|
||||
view_rect.loc - Point::from((border_width, border_width)),
|
||||
view_rect.size,
|
||||
),
|
||||
radius,
|
||||
);
|
||||
|
||||
let draw_focus_ring_with_background = if self.effective_border_width().is_some() {
|
||||
false
|
||||
} else {
|
||||
draw_border_with_background
|
||||
};
|
||||
let radius = if self.is_fullscreen {
|
||||
CornerRadius::default()
|
||||
} else if self.effective_border_width().is_some() {
|
||||
radius
|
||||
} else {
|
||||
rules.geometry_corner_radius.unwrap_or_default()
|
||||
}
|
||||
.expanded_by(self.focus_ring.width() as f32);
|
||||
self.focus_ring.update_render_elements(
|
||||
self.animated_tile_size(),
|
||||
is_active,
|
||||
!draw_focus_ring_with_background,
|
||||
view_rect,
|
||||
radius,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn render_offset(&self) -> Point<i32, Logical> {
|
||||
let mut offset = Point::from((0., 0.));
|
||||
|
||||
if let Some(move_) = &self.move_x_animation {
|
||||
offset.x += f64::from(move_.from) * move_.anim.value();
|
||||
}
|
||||
if let Some(move_) = &self.move_y_animation {
|
||||
offset.y += f64::from(move_.from) * move_.anim.value();
|
||||
}
|
||||
|
||||
offset.to_i32_round()
|
||||
}
|
||||
|
||||
pub fn start_open_animation(&mut self) {
|
||||
self.open_animation = Some(OpenAnimation::new(Animation::new(
|
||||
0.,
|
||||
1.,
|
||||
0.,
|
||||
self.options.animations.window_open.anim,
|
||||
)));
|
||||
}
|
||||
|
||||
pub fn resize_animation(&self) -> Option<&Animation> {
|
||||
self.resize_animation.as_ref().map(|resize| &resize.anim)
|
||||
}
|
||||
|
||||
pub fn animate_move_from(&mut self, from: Point<i32, Logical>) {
|
||||
self.animate_move_x_from(from.x);
|
||||
self.animate_move_y_from(from.y);
|
||||
}
|
||||
|
||||
pub fn animate_move_x_from(&mut self, from: i32) {
|
||||
self.animate_move_x_from_with_config(from, self.options.animations.window_movement.0);
|
||||
}
|
||||
|
||||
pub fn animate_move_x_from_with_config(&mut self, from: i32, config: niri_config::Animation) {
|
||||
let current_offset = self.render_offset().x;
|
||||
|
||||
// Preserve the previous config if ongoing.
|
||||
let anim = self.move_x_animation.take().map(|move_| move_.anim);
|
||||
let anim = anim
|
||||
.map(|anim| anim.restarted(1., 0., 0.))
|
||||
.unwrap_or_else(|| Animation::new(1., 0., 0., config));
|
||||
|
||||
self.move_x_animation = Some(MoveAnimation {
|
||||
anim,
|
||||
from: from + current_offset,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn animate_move_y_from(&mut self, from: i32) {
|
||||
self.animate_move_y_from_with_config(from, self.options.animations.window_movement.0);
|
||||
}
|
||||
|
||||
pub fn animate_move_y_from_with_config(&mut self, from: i32, config: niri_config::Animation) {
|
||||
let current_offset = self.render_offset().y;
|
||||
|
||||
// Preserve the previous config if ongoing.
|
||||
let anim = self.move_y_animation.take().map(|move_| move_.anim);
|
||||
let anim = anim
|
||||
.map(|anim| anim.restarted(1., 0., 0.))
|
||||
.unwrap_or_else(|| Animation::new(1., 0., 0., config));
|
||||
|
||||
self.move_y_animation = Some(MoveAnimation {
|
||||
anim,
|
||||
from: from + current_offset,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn window(&self) -> &W {
|
||||
&self.window
|
||||
}
|
||||
|
||||
pub fn window_mut(&mut self) -> &mut W {
|
||||
&mut self.window
|
||||
}
|
||||
|
||||
pub fn into_window(self) -> W {
|
||||
self.window
|
||||
}
|
||||
|
||||
pub fn is_fullscreen(&self) -> bool {
|
||||
self.is_fullscreen
|
||||
}
|
||||
|
||||
/// Returns `None` if the border is hidden and `Some(width)` if it should be shown.
|
||||
fn effective_border_width(&self) -> Option<i32> {
|
||||
if self.is_fullscreen {
|
||||
return None;
|
||||
}
|
||||
|
||||
if self.border.is_off() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(self.border.width())
|
||||
}
|
||||
|
||||
/// Returns the location of the window's visual geometry within this Tile.
|
||||
pub fn window_loc(&self) -> Point<i32, Logical> {
|
||||
let mut loc = Point::from((0, 0));
|
||||
|
||||
// In fullscreen, center the window in the given size.
|
||||
if self.is_fullscreen {
|
||||
let window_size = self.window.size();
|
||||
let target_size = self.fullscreen_size;
|
||||
|
||||
// Windows aren't supposed to be larger than the fullscreen size, but in case we get
|
||||
// one, leave it at the top-left as usual.
|
||||
if window_size.w < target_size.w {
|
||||
loc.x += (target_size.w - window_size.w) / 2;
|
||||
}
|
||||
if window_size.h < target_size.h {
|
||||
loc.y += (target_size.h - window_size.h) / 2;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(width) = self.effective_border_width() {
|
||||
loc += (width, width).into();
|
||||
}
|
||||
|
||||
loc
|
||||
}
|
||||
|
||||
pub fn tile_size(&self) -> Size<i32, Logical> {
|
||||
let mut size = self.window.size();
|
||||
|
||||
if self.is_fullscreen {
|
||||
// Normally we'd just return the fullscreen size here, but this makes things a bit
|
||||
// nicer if a fullscreen window is bigger than the fullscreen size for some reason.
|
||||
size.w = max(size.w, self.fullscreen_size.w);
|
||||
size.h = max(size.h, self.fullscreen_size.h);
|
||||
return size;
|
||||
}
|
||||
|
||||
if let Some(width) = self.effective_border_width() {
|
||||
size.w = size.w.saturating_add(width * 2);
|
||||
size.h = size.h.saturating_add(width * 2);
|
||||
}
|
||||
|
||||
size
|
||||
}
|
||||
|
||||
pub fn window_size(&self) -> Size<i32, Logical> {
|
||||
self.window.size()
|
||||
}
|
||||
|
||||
fn animated_window_size(&self) -> Size<i32, Logical> {
|
||||
let mut size = self.window.size();
|
||||
|
||||
if let Some(resize) = &self.resize_animation {
|
||||
let val = resize.anim.value();
|
||||
let size_from = resize.size_from;
|
||||
|
||||
size.w = (size_from.w as f64 + (size.w - size_from.w) as f64 * val).round() as i32;
|
||||
size.w = max(1, size.w);
|
||||
size.h = (size_from.h as f64 + (size.h - size_from.h) as f64 * val).round() as i32;
|
||||
size.h = max(1, size.h);
|
||||
}
|
||||
|
||||
size
|
||||
}
|
||||
|
||||
fn animated_tile_size(&self) -> Size<i32, Logical> {
|
||||
let mut size = self.animated_window_size();
|
||||
|
||||
if self.is_fullscreen {
|
||||
// Normally we'd just return the fullscreen size here, but this makes things a bit
|
||||
// nicer if a fullscreen window is bigger than the fullscreen size for some reason.
|
||||
size.w = max(size.w, self.fullscreen_size.w);
|
||||
size.h = max(size.h, self.fullscreen_size.h);
|
||||
return size;
|
||||
}
|
||||
|
||||
if let Some(width) = self.effective_border_width() {
|
||||
size.w = size.w.saturating_add(width * 2);
|
||||
size.h = size.h.saturating_add(width * 2);
|
||||
}
|
||||
|
||||
size
|
||||
}
|
||||
|
||||
pub fn buf_loc(&self) -> Point<i32, Logical> {
|
||||
let mut loc = Point::from((0, 0));
|
||||
loc += self.window_loc();
|
||||
loc += self.window.buf_loc();
|
||||
loc
|
||||
}
|
||||
|
||||
pub fn is_in_input_region(&self, mut point: Point<f64, Logical>) -> bool {
|
||||
point -= self.window_loc().to_f64();
|
||||
self.window.is_in_input_region(point)
|
||||
}
|
||||
|
||||
pub fn is_in_activation_region(&self, point: Point<f64, Logical>) -> bool {
|
||||
let activation_region = Rectangle::from_loc_and_size((0, 0), self.tile_size());
|
||||
activation_region.to_f64().contains(point)
|
||||
}
|
||||
|
||||
pub fn request_tile_size(&mut self, mut size: Size<i32, Logical>, animate: bool) {
|
||||
// Can't go through effective_border_width() because we might be fullscreen.
|
||||
if !self.border.is_off() {
|
||||
let width = self.border.width();
|
||||
size.w = max(1, size.w - width * 2);
|
||||
size.h = max(1, size.h - width * 2);
|
||||
}
|
||||
|
||||
self.window.request_size(size, animate);
|
||||
}
|
||||
|
||||
pub fn tile_width_for_window_width(&self, size: i32) -> i32 {
|
||||
if self.border.is_off() {
|
||||
size
|
||||
} else {
|
||||
size.saturating_add(self.border.width() * 2)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tile_height_for_window_height(&self, size: i32) -> i32 {
|
||||
if self.border.is_off() {
|
||||
size
|
||||
} else {
|
||||
size.saturating_add(self.border.width() * 2)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn window_height_for_tile_height(&self, size: i32) -> i32 {
|
||||
if self.border.is_off() {
|
||||
size
|
||||
} else {
|
||||
size.saturating_sub(self.border.width() * 2)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn request_fullscreen(&mut self, size: Size<i32, Logical>) {
|
||||
self.fullscreen_backdrop.resize(size);
|
||||
self.fullscreen_size = size;
|
||||
self.window.request_fullscreen(size);
|
||||
}
|
||||
|
||||
pub fn min_size(&self) -> Size<i32, Logical> {
|
||||
let mut size = self.window.min_size();
|
||||
|
||||
if let Some(width) = self.effective_border_width() {
|
||||
size.w = max(1, size.w);
|
||||
size.h = max(1, size.h);
|
||||
|
||||
size.w = size.w.saturating_add(width * 2);
|
||||
size.h = size.h.saturating_add(width * 2);
|
||||
}
|
||||
|
||||
size
|
||||
}
|
||||
|
||||
pub fn max_size(&self) -> Size<i32, Logical> {
|
||||
let mut size = self.window.max_size();
|
||||
|
||||
if let Some(width) = self.effective_border_width() {
|
||||
if size.w > 0 {
|
||||
size.w = size.w.saturating_add(width * 2);
|
||||
}
|
||||
if size.h > 0 {
|
||||
size.h = size.h.saturating_add(width * 2);
|
||||
}
|
||||
}
|
||||
|
||||
size
|
||||
}
|
||||
|
||||
pub fn draw_border_with_background(&self) -> bool {
|
||||
if self.effective_border_width().is_some() {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.window
|
||||
.rules()
|
||||
.draw_border_with_background
|
||||
.unwrap_or_else(|| !self.window.has_ssd())
|
||||
}
|
||||
|
||||
fn render_inner<R: NiriRenderer>(
|
||||
&self,
|
||||
renderer: &mut R,
|
||||
location: Point<i32, Logical>,
|
||||
scale: Scale<f64>,
|
||||
focus_ring: bool,
|
||||
target: RenderTarget,
|
||||
) -> impl Iterator<Item = TileRenderElement<R>> {
|
||||
let _span = tracy_client::span!("Tile::render_inner");
|
||||
|
||||
let alpha = if self.is_fullscreen {
|
||||
1.
|
||||
} else {
|
||||
self.window.rules().opacity.unwrap_or(1.).clamp(0., 1.)
|
||||
};
|
||||
|
||||
let window_loc = self.window_loc();
|
||||
let window_size = self.window_size();
|
||||
let animated_window_size = self.animated_window_size();
|
||||
let window_render_loc = location + window_loc;
|
||||
let area = Rectangle::from_loc_and_size(window_render_loc, animated_window_size);
|
||||
|
||||
let rules = self.window.rules();
|
||||
let clip_to_geometry = !self.is_fullscreen && rules.clip_to_geometry == Some(true);
|
||||
let radius = rules.geometry_corner_radius.unwrap_or_default();
|
||||
|
||||
// If we're resizing, try to render a shader, or a fallback.
|
||||
let mut resize_shader = None;
|
||||
let mut resize_popups = None;
|
||||
let mut resize_fallback = None;
|
||||
|
||||
if let Some(resize) = &self.resize_animation {
|
||||
resize_popups = Some(
|
||||
self.window
|
||||
.render_popups(renderer, window_render_loc, scale, alpha, target)
|
||||
.into_iter()
|
||||
.map(Into::into),
|
||||
);
|
||||
|
||||
if ResizeRenderElement::has_shader(renderer) {
|
||||
let gles_renderer = renderer.as_gles_renderer();
|
||||
|
||||
if let Some(texture_from) = resize.snapshot.texture(gles_renderer, scale, target) {
|
||||
let window_elements = self.window.render_normal(
|
||||
gles_renderer,
|
||||
Point::from((0, 0)),
|
||||
scale,
|
||||
1.,
|
||||
target,
|
||||
);
|
||||
|
||||
let current = render_to_encompassing_texture(
|
||||
gles_renderer,
|
||||
scale,
|
||||
Transform::Normal,
|
||||
Fourcc::Abgr8888,
|
||||
&window_elements,
|
||||
)
|
||||
.map_err(|err| warn!("error rendering window to texture: {err:?}"))
|
||||
.ok();
|
||||
|
||||
// Clip blocked-out resizes unconditionally because they use solid color render
|
||||
// elements.
|
||||
let clip_to_geometry = if target
|
||||
.should_block_out(resize.snapshot.block_out_from)
|
||||
&& target.should_block_out(rules.block_out_from)
|
||||
{
|
||||
true
|
||||
} else {
|
||||
clip_to_geometry
|
||||
};
|
||||
|
||||
if let Some((texture_current, _sync_point, texture_current_geo)) = current {
|
||||
let elem = ResizeRenderElement::new(
|
||||
area,
|
||||
scale,
|
||||
texture_from.clone(),
|
||||
resize.snapshot.size,
|
||||
(texture_current, texture_current_geo),
|
||||
window_size,
|
||||
resize.anim.value() as f32,
|
||||
resize.anim.clamped_value().clamp(0., 1.) as f32,
|
||||
radius,
|
||||
clip_to_geometry,
|
||||
alpha,
|
||||
);
|
||||
// FIXME: with split popups, this will use the resize element ID for
|
||||
// popups, but we want the real IDs.
|
||||
self.window
|
||||
.set_offscreen_element_id(Some(elem.id().clone()));
|
||||
resize_shader = Some(elem.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if resize_shader.is_none() {
|
||||
let fallback_buffer = SolidColorBuffer::new(area.size, [1., 0., 0., 1.]);
|
||||
resize_fallback = Some(
|
||||
SolidColorRenderElement::from_buffer(
|
||||
&fallback_buffer,
|
||||
area.loc.to_physical_precise_round(scale),
|
||||
scale,
|
||||
alpha,
|
||||
Kind::Unspecified,
|
||||
)
|
||||
.into(),
|
||||
);
|
||||
self.window.set_offscreen_element_id(None);
|
||||
}
|
||||
}
|
||||
|
||||
// If we're not resizing, render the window itself.
|
||||
let mut window_surface = None;
|
||||
let mut window_popups = None;
|
||||
let mut rounded_corner_damage = None;
|
||||
if resize_shader.is_none() && resize_fallback.is_none() {
|
||||
let window = self
|
||||
.window
|
||||
.render(renderer, window_render_loc, scale, alpha, target);
|
||||
|
||||
let geo = Rectangle::from_loc_and_size(window_render_loc, window_size);
|
||||
let radius = radius.fit_to(window_size.w as f32, window_size.h as f32);
|
||||
|
||||
let clip_shader = ClippedSurfaceRenderElement::shader(renderer).cloned();
|
||||
let has_border_shader = BorderRenderElement::has_shader(renderer);
|
||||
|
||||
if clip_to_geometry && clip_shader.is_some() {
|
||||
let damage = self.rounded_corner_damage.element();
|
||||
rounded_corner_damage = Some(damage.with_location(window_render_loc).into());
|
||||
}
|
||||
|
||||
window_surface = Some(window.normal.into_iter().map(move |elem| match elem {
|
||||
LayoutElementRenderElement::Wayland(elem) => {
|
||||
// If we should clip to geometry, render a clipped window.
|
||||
if clip_to_geometry {
|
||||
if let Some(shader) = clip_shader.clone() {
|
||||
if ClippedSurfaceRenderElement::will_clip(&elem, scale, geo, radius) {
|
||||
return ClippedSurfaceRenderElement::new(
|
||||
elem,
|
||||
scale,
|
||||
geo,
|
||||
shader.clone(),
|
||||
radius,
|
||||
)
|
||||
.into();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, render it normally.
|
||||
LayoutElementRenderElement::Wayland(elem).into()
|
||||
}
|
||||
LayoutElementRenderElement::SolidColor(elem) => {
|
||||
// In this branch we're rendering a blocked-out window with a solid
|
||||
// color. We need to render it with a rounded corner shader even if
|
||||
// clip_to_geometry is false, because in this case we're assuming that
|
||||
// the unclipped window CSD already has corners rounded to the
|
||||
// user-provided radius, so our blocked-out rendering should match that
|
||||
// radius.
|
||||
if radius != CornerRadius::default() && has_border_shader {
|
||||
return BorderRenderElement::new(
|
||||
geo.size,
|
||||
Rectangle::from_loc_and_size((0, 0), geo.size),
|
||||
elem.color(),
|
||||
elem.color(),
|
||||
0.,
|
||||
Rectangle::from_loc_and_size((0, 0), geo.size),
|
||||
0.,
|
||||
radius,
|
||||
)
|
||||
.with_location(geo.loc)
|
||||
.into();
|
||||
}
|
||||
|
||||
// Otherwise, render the solid color as is.
|
||||
LayoutElementRenderElement::SolidColor(elem).into()
|
||||
}
|
||||
}));
|
||||
|
||||
window_popups = Some(window.popups.into_iter().map(Into::into));
|
||||
}
|
||||
|
||||
let rv = resize_popups
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.chain(resize_shader)
|
||||
.chain(resize_fallback)
|
||||
.chain(window_popups.into_iter().flatten())
|
||||
.chain(rounded_corner_damage)
|
||||
.chain(window_surface.into_iter().flatten());
|
||||
|
||||
let elem = self.is_fullscreen.then(|| {
|
||||
SolidColorRenderElement::from_buffer(
|
||||
&self.fullscreen_backdrop,
|
||||
location.to_physical_precise_round(scale),
|
||||
scale,
|
||||
1.,
|
||||
Kind::Unspecified,
|
||||
)
|
||||
.into()
|
||||
});
|
||||
let rv = rv.chain(elem);
|
||||
|
||||
let elem = self.effective_border_width().map(|width| {
|
||||
self.border
|
||||
.render(renderer, location + Point::from((width, width)), scale)
|
||||
.map(Into::into)
|
||||
});
|
||||
let rv = rv.chain(elem.into_iter().flatten());
|
||||
|
||||
let elem = focus_ring.then(|| {
|
||||
self.focus_ring
|
||||
.render(renderer, location, scale)
|
||||
.map(Into::into)
|
||||
});
|
||||
rv.chain(elem.into_iter().flatten())
|
||||
}
|
||||
|
||||
pub fn render<R: NiriRenderer>(
|
||||
&self,
|
||||
renderer: &mut R,
|
||||
location: Point<i32, Logical>,
|
||||
scale: Scale<f64>,
|
||||
focus_ring: bool,
|
||||
target: RenderTarget,
|
||||
) -> impl Iterator<Item = TileRenderElement<R>> {
|
||||
let _span = tracy_client::span!("Tile::render");
|
||||
|
||||
let mut open_anim_elem = None;
|
||||
let mut window_elems = None;
|
||||
|
||||
if let Some(open) = &self.open_animation {
|
||||
let renderer = renderer.as_gles_renderer();
|
||||
let elements =
|
||||
self.render_inner(renderer, Point::from((0, 0)), scale, focus_ring, target);
|
||||
let elements = elements.collect::<Vec<TileRenderElement<_>>>();
|
||||
match open.render(renderer, &elements, self.tile_size(), location, scale) {
|
||||
Ok(elem) => {
|
||||
self.window()
|
||||
.set_offscreen_element_id(Some(elem.id().clone()));
|
||||
open_anim_elem = Some(elem.into());
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("error rendering window opening animation: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if open_anim_elem.is_none() {
|
||||
self.window().set_offscreen_element_id(None);
|
||||
window_elems = Some(self.render_inner(renderer, location, scale, focus_ring, target));
|
||||
}
|
||||
|
||||
open_anim_elem
|
||||
.into_iter()
|
||||
.chain(window_elems.into_iter().flatten())
|
||||
}
|
||||
|
||||
pub fn store_unmap_snapshot_if_empty(
|
||||
&mut self,
|
||||
renderer: &mut GlesRenderer,
|
||||
scale: Scale<f64>,
|
||||
) {
|
||||
if self.unmap_snapshot.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.unmap_snapshot = Some(self.render_snapshot(renderer, scale));
|
||||
}
|
||||
|
||||
fn render_snapshot(
|
||||
&self,
|
||||
renderer: &mut GlesRenderer,
|
||||
scale: Scale<f64>,
|
||||
) -> TileRenderSnapshot {
|
||||
let _span = tracy_client::span!("Tile::render_snapshot");
|
||||
|
||||
let contents = self.render(
|
||||
renderer,
|
||||
Point::from((0, 0)),
|
||||
scale,
|
||||
false,
|
||||
RenderTarget::Output,
|
||||
);
|
||||
|
||||
// A bit of a hack to render blocked out as for screencast, but I think it's fine here.
|
||||
let blocked_out_contents = self.render(
|
||||
renderer,
|
||||
Point::from((0, 0)),
|
||||
scale,
|
||||
false,
|
||||
RenderTarget::Screencast,
|
||||
);
|
||||
|
||||
RenderSnapshot {
|
||||
contents: contents.collect(),
|
||||
blocked_out_contents: blocked_out_contents.collect(),
|
||||
block_out_from: self.window.rules().block_out_from,
|
||||
size: self.animated_tile_size(),
|
||||
texture: Default::default(),
|
||||
blocked_out_texture: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_unmap_snapshot(&mut self) -> Option<TileRenderSnapshot> {
|
||||
self.unmap_snapshot.take()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+29
@@ -0,0 +1,29 @@
|
||||
#[macro_use]
|
||||
extern crate tracing;
|
||||
|
||||
pub mod animation;
|
||||
pub mod backend;
|
||||
pub mod cli;
|
||||
pub mod cursor;
|
||||
#[cfg(feature = "dbus")]
|
||||
pub mod dbus;
|
||||
pub mod frame_clock;
|
||||
pub mod handlers;
|
||||
pub mod input;
|
||||
pub mod ipc;
|
||||
pub mod layout;
|
||||
pub mod niri;
|
||||
pub mod protocols;
|
||||
pub mod render_helpers;
|
||||
pub mod rubber_band;
|
||||
pub mod ui;
|
||||
pub mod utils;
|
||||
pub mod window;
|
||||
|
||||
#[cfg(not(feature = "xdp-gnome-screencast"))]
|
||||
pub mod dummy_pw_utils;
|
||||
#[cfg(feature = "xdp-gnome-screencast")]
|
||||
pub mod pw_utils;
|
||||
|
||||
#[cfg(not(feature = "xdp-gnome-screencast"))]
|
||||
pub use dummy_pw_utils as pw_utils;
|
||||
+197
-97
@@ -1,74 +1,35 @@
|
||||
#[macro_use]
|
||||
extern crate tracing;
|
||||
|
||||
mod animation;
|
||||
mod backend;
|
||||
mod config;
|
||||
mod cursor;
|
||||
#[cfg(feature = "dbus")]
|
||||
mod dbus;
|
||||
mod frame_clock;
|
||||
mod handlers;
|
||||
mod input;
|
||||
mod layout;
|
||||
mod niri;
|
||||
mod screenshot_ui;
|
||||
mod utils;
|
||||
mod watcher;
|
||||
|
||||
#[cfg(not(feature = "xdp-gnome-screencast"))]
|
||||
mod dummy_pw_utils;
|
||||
#[cfg(feature = "xdp-gnome-screencast")]
|
||||
mod pw_utils;
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Write};
|
||||
use std::os::fd::FromRawFd;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::{env, mem};
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
use config::Config;
|
||||
#[cfg(not(feature = "xdp-gnome-screencast"))]
|
||||
use dummy_pw_utils as pw_utils;
|
||||
use git_version::git_version;
|
||||
use miette::{Context, NarratableReportHandler};
|
||||
use niri::{Niri, State};
|
||||
use clap::Parser;
|
||||
use directories::ProjectDirs;
|
||||
use niri::animation;
|
||||
use niri::cli::{Cli, Sub};
|
||||
#[cfg(feature = "dbus")]
|
||||
use niri::dbus;
|
||||
use niri::ipc::client::handle_msg;
|
||||
use niri::niri::State;
|
||||
use niri::utils::spawning::{
|
||||
spawn, CHILD_ENV, REMOVE_ENV_RUST_BACKTRACE, REMOVE_ENV_RUST_LIB_BACKTRACE,
|
||||
};
|
||||
use niri::utils::watcher::Watcher;
|
||||
use niri::utils::{cause_panic, version, IS_SYSTEMD_SERVICE};
|
||||
use niri_config::Config;
|
||||
use portable_atomic::Ordering;
|
||||
use sd_notify::NotifyState;
|
||||
use smithay::reexports::calloop::{self, EventLoop};
|
||||
use smithay::reexports::calloop::EventLoop;
|
||||
use smithay::reexports::wayland_server::Display;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use utils::spawn;
|
||||
use watcher::Watcher;
|
||||
|
||||
use crate::utils::{REMOVE_ENV_RUST_BACKTRACE, REMOVE_ENV_RUST_LIB_BACKTRACE};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(author, version, about, long_about = None)]
|
||||
#[command(args_conflicts_with_subcommands = true)]
|
||||
#[command(subcommand_value_name = "SUBCOMMAND")]
|
||||
#[command(subcommand_help_heading = "Subcommands")]
|
||||
struct Cli {
|
||||
/// Path to config file (default: `$XDG_CONFIG_HOME/niri/config.kdl`).
|
||||
#[arg(short, long)]
|
||||
config: Option<PathBuf>,
|
||||
/// Command to run upon compositor startup.
|
||||
#[arg(last = true)]
|
||||
command: Vec<OsString>,
|
||||
|
||||
#[command(subcommand)]
|
||||
subcommand: Option<Sub>,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Sub {
|
||||
/// Validate the config file.
|
||||
Validate {
|
||||
/// Path to config file (default: `$XDG_CONFIG_HOME/niri/config.kdl`).
|
||||
#[arg(short, long)]
|
||||
config: Option<PathBuf>,
|
||||
},
|
||||
}
|
||||
const DEFAULT_LOG_FILTER: &str = "niri=debug,smithay::backend::renderer::gles=error";
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Set backtrace defaults if not set.
|
||||
@@ -81,63 +42,136 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
REMOVE_ENV_RUST_LIB_BACKTRACE.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
let is_systemd_service = env::var_os("NOTIFY_SOCKET").is_some();
|
||||
if env::var_os("NOTIFY_SOCKET").is_some() {
|
||||
IS_SYSTEMD_SERVICE.store(true, Ordering::Relaxed);
|
||||
|
||||
let directives = env::var("RUST_LOG").unwrap_or_else(|_| "niri=debug".to_owned());
|
||||
#[cfg(not(feature = "systemd"))]
|
||||
warn!(
|
||||
"running as a systemd service, but systemd support is compiled out. \
|
||||
Are you sure you did not forget to set `--features systemd`?"
|
||||
);
|
||||
}
|
||||
|
||||
let directives = env::var("RUST_LOG").unwrap_or_else(|_| DEFAULT_LOG_FILTER.to_owned());
|
||||
let env_filter = EnvFilter::builder().parse_lossy(directives);
|
||||
tracing_subscriber::fmt()
|
||||
.compact()
|
||||
.with_env_filter(env_filter)
|
||||
.init();
|
||||
|
||||
if is_systemd_service {
|
||||
// If we're starting as a systemd service, assume that the intention is to start on a TTY.
|
||||
// Remove DISPLAY or WAYLAND_DISPLAY from our environment if they are set, since they will
|
||||
// cause the winit backend to be selected instead.
|
||||
let cli = Cli::parse();
|
||||
|
||||
if cli.session {
|
||||
// If we're starting as a session, assume that the intention is to start on a TTY. Remove
|
||||
// DISPLAY or WAYLAND_DISPLAY from our environment if they are set, since they will cause
|
||||
// the winit backend to be selected instead.
|
||||
if env::var_os("DISPLAY").is_some() {
|
||||
debug!("we're running as a systemd service but DISPLAY is set, removing it");
|
||||
warn!("running as a session but DISPLAY is set, removing it");
|
||||
env::remove_var("DISPLAY");
|
||||
}
|
||||
if env::var_os("WAYLAND_DISPLAY").is_some() {
|
||||
debug!("we're running as a systemd service but WAYLAND_DISPLAY is set, removing it");
|
||||
warn!("running as a session but WAYLAND_DISPLAY is set, removing it");
|
||||
env::remove_var("WAYLAND_DISPLAY");
|
||||
}
|
||||
|
||||
// Set the current desktop for xdg-desktop-portal.
|
||||
env::set_var("XDG_CURRENT_DESKTOP", "niri");
|
||||
// Ensure the session type is set to Wayland for xdg-autostart and Qt apps.
|
||||
env::set_var("XDG_SESSION_TYPE", "wayland");
|
||||
}
|
||||
|
||||
let cli = Cli::parse();
|
||||
|
||||
let _client = tracy_client::Client::start();
|
||||
|
||||
// Set a better error printer for config loading.
|
||||
miette::set_hook(Box::new(|_| Box::new(NarratableReportHandler::new()))).unwrap();
|
||||
niri_config::set_miette_hook().unwrap();
|
||||
|
||||
// Handle subcommands.
|
||||
if let Some(subcommand) = cli.subcommand {
|
||||
match subcommand {
|
||||
Sub::Validate { config } => {
|
||||
Config::load(config).context("error loading config")?;
|
||||
tracy_client::Client::start();
|
||||
|
||||
let path = config
|
||||
.or_else(default_config_path)
|
||||
.expect("error getting config path");
|
||||
Config::load(&path)?;
|
||||
info!("config is valid");
|
||||
return Ok(());
|
||||
}
|
||||
Sub::Msg { msg, json } => {
|
||||
handle_msg(msg, json)?;
|
||||
return Ok(());
|
||||
}
|
||||
Sub::Panic => cause_panic(),
|
||||
}
|
||||
}
|
||||
|
||||
info!(
|
||||
"starting version {} ({})",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
git_version!(fallback = "unknown commit"),
|
||||
);
|
||||
// Avoid starting Tracy for the `niri msg` code path since starting/stopping Tracy is a bit
|
||||
// slow.
|
||||
tracy_client::Client::start();
|
||||
|
||||
info!("starting version {}", &version());
|
||||
|
||||
// Load the config.
|
||||
let (mut config, path) = match Config::load(cli.config).context("error loading config") {
|
||||
Ok((config, path)) => (config, Some(path)),
|
||||
Err(err) => {
|
||||
warn!("{err:?}");
|
||||
(Config::default(), None)
|
||||
let mut config_created = false;
|
||||
let path = cli.config.or_else(|| {
|
||||
let default_path = default_config_path()?;
|
||||
let default_parent = default_path.parent().unwrap();
|
||||
|
||||
if let Err(err) = fs::create_dir_all(default_parent) {
|
||||
warn!(
|
||||
"error creating config directories {:?}: {err:?}",
|
||||
default_parent
|
||||
);
|
||||
return Some(default_path);
|
||||
}
|
||||
|
||||
// Create the config and fill it with the default config if it doesn't exist.
|
||||
let new_file = File::options()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&default_path);
|
||||
match new_file {
|
||||
Ok(mut new_file) => {
|
||||
let default = include_bytes!("../resources/default-config.kdl");
|
||||
match new_file.write_all(default) {
|
||||
Ok(()) => {
|
||||
config_created = true;
|
||||
info!("wrote default config to {:?}", &default_path);
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("error writing config file at {:?}: {err:?}", &default_path)
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
|
||||
Err(err) => warn!("error creating config file at {:?}: {err:?}", &default_path),
|
||||
}
|
||||
|
||||
Some(default_path)
|
||||
});
|
||||
|
||||
let mut config_errored = false;
|
||||
let mut config = path
|
||||
.as_deref()
|
||||
.and_then(|path| match Config::load(path) {
|
||||
Ok(config) => Some(config),
|
||||
Err(err) => {
|
||||
warn!("{err:?}");
|
||||
config_errored = true;
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let slowdown = if config.animations.off {
|
||||
0.
|
||||
} else {
|
||||
config.animations.slowdown.clamp(0., 100.)
|
||||
};
|
||||
animation::ANIMATION_SLOWDOWN.store(config.debug.animation_slowdown, Ordering::Relaxed);
|
||||
animation::ANIMATION_SLOWDOWN.store(slowdown, Ordering::Relaxed);
|
||||
|
||||
let spawn_at_startup = mem::take(&mut config.spawn_at_startup);
|
||||
*CHILD_ENV.write().unwrap() = mem::take(&mut config.environment);
|
||||
|
||||
// Create the compositor.
|
||||
let mut event_loop = EventLoop::try_new().unwrap();
|
||||
@@ -147,7 +181,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
event_loop.handle(),
|
||||
event_loop.get_signal(),
|
||||
display,
|
||||
);
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Set WAYLAND_DISPLAY for children.
|
||||
let socket_name = &state.niri.socket_name;
|
||||
@@ -157,27 +192,40 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
socket_name.to_string_lossy()
|
||||
);
|
||||
|
||||
if is_systemd_service {
|
||||
// We're starting as a systemd service. Export our variables.
|
||||
import_env_to_systemd();
|
||||
// Set NIRI_SOCKET for children.
|
||||
if let Some(ipc) = &state.niri.ipc_server {
|
||||
env::set_var(niri_ipc::SOCKET_PATH_ENV, &ipc.socket_path);
|
||||
info!("IPC listening on: {}", ipc.socket_path.to_string_lossy());
|
||||
}
|
||||
|
||||
if cli.session {
|
||||
// We're starting as a session. Import our variables.
|
||||
import_environment();
|
||||
|
||||
// Inhibit power key handling so we can suspend on it.
|
||||
#[cfg(feature = "dbus")]
|
||||
if let Err(err) = state.niri.inhibit_power_key() {
|
||||
warn!("error inhibiting power key: {err:?}");
|
||||
if !state.niri.config.borrow().input.disable_power_key_handling {
|
||||
if let Err(err) = state.niri.inhibit_power_key() {
|
||||
warn!("error inhibiting power key: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "dbus")]
|
||||
dbus::DBusServers::start(&mut state, is_systemd_service);
|
||||
dbus::DBusServers::start(&mut state, cli.session);
|
||||
|
||||
// Notify systemd we're ready.
|
||||
if let Err(err) = sd_notify::notify(true, &[NotifyState::Ready]) {
|
||||
warn!("error notifying systemd: {err:?}");
|
||||
};
|
||||
|
||||
// Send ready notification to the NOTIFY_FD file descriptor.
|
||||
if let Err(err) = notify_fd() {
|
||||
warn!("error notifying fd: {err:?}");
|
||||
}
|
||||
|
||||
// Set up config file watcher.
|
||||
let _watcher = if let Some(path) = path {
|
||||
let _watcher = if let Some(path) = path.clone() {
|
||||
let (tx, rx) = calloop::channel::sync_channel(1);
|
||||
let watcher = Watcher::new(path.clone(), tx);
|
||||
event_loop
|
||||
@@ -199,6 +247,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
spawn(elem.command);
|
||||
}
|
||||
|
||||
// Show the config error notification right away if needed.
|
||||
if config_errored {
|
||||
state.niri.config_error_notification.show();
|
||||
} else if config_created {
|
||||
state.niri.config_error_notification.show_created(path);
|
||||
}
|
||||
|
||||
// Run the compositor.
|
||||
event_loop
|
||||
.run(None, &mut state, |state| state.refresh_and_flush_clients())
|
||||
@@ -207,13 +262,35 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn import_env_to_systemd() {
|
||||
fn import_environment() {
|
||||
let variables = [
|
||||
"WAYLAND_DISPLAY",
|
||||
"XDG_CURRENT_DESKTOP",
|
||||
"XDG_SESSION_TYPE",
|
||||
niri_ipc::SOCKET_PATH_ENV,
|
||||
]
|
||||
.join(" ");
|
||||
|
||||
let mut init_system_import = String::new();
|
||||
if cfg!(feature = "systemd") {
|
||||
write!(
|
||||
init_system_import,
|
||||
"systemctl --user import-environment {variables};"
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
if cfg!(feature = "dinit") {
|
||||
write!(init_system_import, "dinitctl setenv {variables};").unwrap();
|
||||
}
|
||||
|
||||
let rv = Command::new("/bin/sh")
|
||||
.args([
|
||||
"-c",
|
||||
"systemctl --user import-environment WAYLAND_DISPLAY && \
|
||||
hash dbus-update-activation-environment 2>/dev/null && \
|
||||
dbus-update-activation-environment WAYLAND_DISPLAY",
|
||||
&format!(
|
||||
"{init_system_import}\
|
||||
hash dbus-update-activation-environment 2>/dev/null && \
|
||||
dbus-update-activation-environment {variables}"
|
||||
),
|
||||
])
|
||||
.spawn();
|
||||
// Wait for the import process to complete, otherwise services will start too fast without
|
||||
@@ -230,7 +307,30 @@ fn import_env_to_systemd() {
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
warn!("error spawning shell to import environment into systemd: {err:?}");
|
||||
warn!("error spawning shell to import environment: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_config_path() -> Option<PathBuf> {
|
||||
let Some(dirs) = ProjectDirs::from("", "", "niri") else {
|
||||
warn!("error retrieving home directory");
|
||||
return None;
|
||||
};
|
||||
|
||||
let mut path = dirs.config_dir().to_owned();
|
||||
path.push("config.kdl");
|
||||
Some(path)
|
||||
}
|
||||
|
||||
fn notify_fd() -> anyhow::Result<()> {
|
||||
let fd = match env::var("NOTIFY_FD") {
|
||||
Ok(notify_fd) => notify_fd.parse()?,
|
||||
Err(env::VarError::NotPresent) => return Ok(()),
|
||||
Err(err) => return Err(err.into()),
|
||||
};
|
||||
env::remove_var("NOTIFY_FD");
|
||||
let mut notif = unsafe { File::from_raw_fd(fd) };
|
||||
notif.write_all(b"READY=1\n")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+2027
-573
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,466 @@
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use arrayvec::ArrayVec;
|
||||
use smithay::output::Output;
|
||||
use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
|
||||
use smithay::reexports::wayland_protocols_wlr;
|
||||
use smithay::reexports::wayland_server::backend::ClientId;
|
||||
use smithay::reexports::wayland_server::protocol::wl_output::WlOutput;
|
||||
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
|
||||
use smithay::reexports::wayland_server::{
|
||||
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource,
|
||||
};
|
||||
use smithay::wayland::compositor::with_states;
|
||||
use smithay::wayland::shell::xdg::{
|
||||
ToplevelStateSet, XdgToplevelSurfaceData, XdgToplevelSurfaceRoleAttributes,
|
||||
};
|
||||
use wayland_protocols_wlr::foreign_toplevel::v1::server::{
|
||||
zwlr_foreign_toplevel_handle_v1, zwlr_foreign_toplevel_manager_v1,
|
||||
};
|
||||
use zwlr_foreign_toplevel_handle_v1::ZwlrForeignToplevelHandleV1;
|
||||
use zwlr_foreign_toplevel_manager_v1::ZwlrForeignToplevelManagerV1;
|
||||
|
||||
use crate::niri::State;
|
||||
|
||||
const VERSION: u32 = 3;
|
||||
|
||||
pub struct ForeignToplevelManagerState {
|
||||
display: DisplayHandle,
|
||||
instances: Vec<ZwlrForeignToplevelManagerV1>,
|
||||
toplevels: HashMap<WlSurface, ToplevelData>,
|
||||
}
|
||||
|
||||
pub trait ForeignToplevelHandler {
|
||||
fn foreign_toplevel_manager_state(&mut self) -> &mut ForeignToplevelManagerState;
|
||||
fn activate(&mut self, wl_surface: WlSurface);
|
||||
fn close(&mut self, wl_surface: WlSurface);
|
||||
fn set_fullscreen(&mut self, wl_surface: WlSurface, wl_output: Option<WlOutput>);
|
||||
fn unset_fullscreen(&mut self, wl_surface: WlSurface);
|
||||
}
|
||||
|
||||
struct ToplevelData {
|
||||
title: Option<String>,
|
||||
app_id: Option<String>,
|
||||
states: ArrayVec<u32, 3>,
|
||||
output: Option<Output>,
|
||||
instances: HashMap<ZwlrForeignToplevelHandleV1, Vec<WlOutput>>,
|
||||
// FIXME: parent.
|
||||
}
|
||||
|
||||
pub struct ForeignToplevelGlobalData {
|
||||
filter: Box<dyn for<'c> Fn(&'c Client) -> bool + Send + Sync>,
|
||||
}
|
||||
|
||||
impl ForeignToplevelManagerState {
|
||||
pub fn new<D, F>(display: &DisplayHandle, filter: F) -> Self
|
||||
where
|
||||
D: GlobalDispatch<ZwlrForeignToplevelManagerV1, ForeignToplevelGlobalData>,
|
||||
D: Dispatch<ZwlrForeignToplevelManagerV1, ()>,
|
||||
D: 'static,
|
||||
F: for<'c> Fn(&'c Client) -> bool + Send + Sync + 'static,
|
||||
{
|
||||
let global_data = ForeignToplevelGlobalData {
|
||||
filter: Box::new(filter),
|
||||
};
|
||||
display.create_global::<D, ZwlrForeignToplevelManagerV1, _>(VERSION, global_data);
|
||||
Self {
|
||||
display: display.clone(),
|
||||
instances: Vec::new(),
|
||||
toplevels: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn refresh(state: &mut State) {
|
||||
let _span = tracy_client::span!("foreign_toplevel::refresh");
|
||||
|
||||
let protocol_state = &mut state.niri.foreign_toplevel_state;
|
||||
|
||||
// Handle closed windows.
|
||||
protocol_state.toplevels.retain(|surface, data| {
|
||||
if state.niri.layout.find_window_and_output(surface).is_some() {
|
||||
return true;
|
||||
}
|
||||
|
||||
for instance in data.instances.keys() {
|
||||
instance.closed();
|
||||
}
|
||||
|
||||
false
|
||||
});
|
||||
|
||||
// Handle new and existing windows.
|
||||
//
|
||||
// Save the focused window for last, this way when the focus changes, we will first deactivate
|
||||
// the previous window and only then activate the newly focused window.
|
||||
let mut focused = None;
|
||||
state.niri.layout.with_windows(|mapped, output| {
|
||||
let wl_surface = mapped.toplevel().wl_surface();
|
||||
|
||||
with_states(wl_surface, |states| {
|
||||
let role = states
|
||||
.data_map
|
||||
.get::<XdgToplevelSurfaceData>()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.unwrap();
|
||||
|
||||
if state.niri.keyboard_focus.surface() == Some(wl_surface) {
|
||||
focused = Some((mapped.window.clone(), output.cloned()));
|
||||
} else {
|
||||
refresh_toplevel(protocol_state, wl_surface, &role, output, false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Finally, refresh the focused window.
|
||||
if let Some((window, output)) = focused {
|
||||
let wl_surface = window.toplevel().expect("no x11 support").wl_surface();
|
||||
|
||||
with_states(wl_surface, |states| {
|
||||
let role = states
|
||||
.data_map
|
||||
.get::<XdgToplevelSurfaceData>()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.unwrap();
|
||||
|
||||
refresh_toplevel(protocol_state, wl_surface, &role, output.as_ref(), true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_output_bound(state: &mut State, output: &Output, wl_output: &WlOutput) {
|
||||
let _span = tracy_client::span!("foreign_toplevel::on_output_bound");
|
||||
|
||||
let Some(client) = wl_output.client() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let protocol_state = &mut state.niri.foreign_toplevel_state;
|
||||
for data in protocol_state.toplevels.values_mut() {
|
||||
if data.output.as_ref() != Some(output) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (instance, outputs) in &mut data.instances {
|
||||
if instance.client().as_ref() != Some(&client) {
|
||||
continue;
|
||||
}
|
||||
|
||||
instance.output_enter(wl_output);
|
||||
instance.done();
|
||||
outputs.push(wl_output.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_toplevel(
|
||||
protocol_state: &mut ForeignToplevelManagerState,
|
||||
wl_surface: &WlSurface,
|
||||
role: &XdgToplevelSurfaceRoleAttributes,
|
||||
output: Option<&Output>,
|
||||
has_focus: bool,
|
||||
) {
|
||||
let states = to_state_vec(&role.current.states, has_focus);
|
||||
|
||||
match protocol_state.toplevels.entry(wl_surface.clone()) {
|
||||
Entry::Occupied(entry) => {
|
||||
// Existing window, check if anything changed.
|
||||
let data = entry.into_mut();
|
||||
|
||||
let mut new_title = None;
|
||||
if data.title != role.title {
|
||||
data.title.clone_from(&role.title);
|
||||
new_title = role.title.as_deref();
|
||||
|
||||
if new_title.is_none() {
|
||||
error!("toplevel title changed to None");
|
||||
}
|
||||
}
|
||||
|
||||
let mut new_app_id = None;
|
||||
if data.app_id != role.app_id {
|
||||
data.app_id.clone_from(&role.app_id);
|
||||
new_app_id = role.app_id.as_deref();
|
||||
|
||||
if new_app_id.is_none() {
|
||||
error!("toplevel app_id changed to None");
|
||||
}
|
||||
}
|
||||
|
||||
let mut states_changed = false;
|
||||
if data.states != states {
|
||||
data.states = states;
|
||||
states_changed = true;
|
||||
}
|
||||
|
||||
let mut output_changed = false;
|
||||
if data.output.as_ref() != output {
|
||||
data.output = output.cloned();
|
||||
output_changed = true;
|
||||
}
|
||||
|
||||
let something_changed =
|
||||
new_title.is_some() || new_app_id.is_some() || states_changed || output_changed;
|
||||
|
||||
if something_changed {
|
||||
for (instance, outputs) in &mut data.instances {
|
||||
if let Some(new_title) = new_title {
|
||||
instance.title(new_title.to_owned());
|
||||
}
|
||||
if let Some(new_app_id) = new_app_id {
|
||||
instance.app_id(new_app_id.to_owned());
|
||||
}
|
||||
if states_changed {
|
||||
instance.state(data.states.iter().flat_map(|x| x.to_ne_bytes()).collect());
|
||||
}
|
||||
if output_changed {
|
||||
for wl_output in outputs.drain(..) {
|
||||
instance.output_leave(&wl_output);
|
||||
}
|
||||
if let Some(output) = &data.output {
|
||||
if let Some(client) = instance.client() {
|
||||
for wl_output in output.client_outputs(&client) {
|
||||
instance.output_enter(&wl_output);
|
||||
outputs.push(wl_output);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
instance.done();
|
||||
}
|
||||
}
|
||||
|
||||
for outputs in data.instances.values_mut() {
|
||||
// Clean up dead wl_outputs.
|
||||
outputs.retain(|x| x.is_alive());
|
||||
}
|
||||
}
|
||||
Entry::Vacant(entry) => {
|
||||
// New window, start tracking it.
|
||||
let mut data = ToplevelData {
|
||||
title: role.title.clone(),
|
||||
app_id: role.app_id.clone(),
|
||||
states,
|
||||
output: output.cloned(),
|
||||
instances: HashMap::new(),
|
||||
};
|
||||
|
||||
for manager in &protocol_state.instances {
|
||||
if let Some(client) = manager.client() {
|
||||
data.add_instance::<State>(&protocol_state.display, &client, manager);
|
||||
}
|
||||
}
|
||||
|
||||
entry.insert(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToplevelData {
|
||||
fn add_instance<D>(
|
||||
&mut self,
|
||||
handle: &DisplayHandle,
|
||||
client: &Client,
|
||||
manager: &ZwlrForeignToplevelManagerV1,
|
||||
) where
|
||||
D: Dispatch<ZwlrForeignToplevelHandleV1, ()>,
|
||||
D: 'static,
|
||||
{
|
||||
let toplevel = client
|
||||
.create_resource::<ZwlrForeignToplevelHandleV1, _, D>(handle, manager.version(), ())
|
||||
.unwrap();
|
||||
manager.toplevel(&toplevel);
|
||||
|
||||
if let Some(title) = &self.title {
|
||||
toplevel.title(title.clone());
|
||||
}
|
||||
if let Some(app_id) = &self.app_id {
|
||||
toplevel.app_id(app_id.clone());
|
||||
}
|
||||
|
||||
toplevel.state(self.states.iter().flat_map(|x| x.to_ne_bytes()).collect());
|
||||
|
||||
let mut outputs = Vec::new();
|
||||
if let Some(output) = &self.output {
|
||||
for wl_output in output.client_outputs(client) {
|
||||
toplevel.output_enter(&wl_output);
|
||||
outputs.push(wl_output);
|
||||
}
|
||||
}
|
||||
|
||||
toplevel.done();
|
||||
|
||||
self.instances.insert(toplevel, outputs);
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> GlobalDispatch<ZwlrForeignToplevelManagerV1, ForeignToplevelGlobalData, D>
|
||||
for ForeignToplevelManagerState
|
||||
where
|
||||
D: GlobalDispatch<ZwlrForeignToplevelManagerV1, ForeignToplevelGlobalData>,
|
||||
D: Dispatch<ZwlrForeignToplevelManagerV1, ()>,
|
||||
D: Dispatch<ZwlrForeignToplevelHandleV1, ()>,
|
||||
D: ForeignToplevelHandler,
|
||||
{
|
||||
fn bind(
|
||||
state: &mut D,
|
||||
handle: &DisplayHandle,
|
||||
client: &Client,
|
||||
resource: New<ZwlrForeignToplevelManagerV1>,
|
||||
_global_data: &ForeignToplevelGlobalData,
|
||||
data_init: &mut DataInit<'_, D>,
|
||||
) {
|
||||
let manager = data_init.init(resource, ());
|
||||
|
||||
let state = state.foreign_toplevel_manager_state();
|
||||
|
||||
for data in state.toplevels.values_mut() {
|
||||
data.add_instance::<D>(handle, client, &manager);
|
||||
}
|
||||
|
||||
state.instances.push(manager);
|
||||
}
|
||||
|
||||
fn can_view(client: Client, global_data: &ForeignToplevelGlobalData) -> bool {
|
||||
(global_data.filter)(&client)
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> Dispatch<ZwlrForeignToplevelManagerV1, (), D> for ForeignToplevelManagerState
|
||||
where
|
||||
D: Dispatch<ZwlrForeignToplevelManagerV1, ()>,
|
||||
D: ForeignToplevelHandler,
|
||||
{
|
||||
fn request(
|
||||
state: &mut D,
|
||||
_client: &Client,
|
||||
resource: &ZwlrForeignToplevelManagerV1,
|
||||
request: <ZwlrForeignToplevelManagerV1 as Resource>::Request,
|
||||
_data: &(),
|
||||
_dhandle: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, D>,
|
||||
) {
|
||||
match request {
|
||||
zwlr_foreign_toplevel_manager_v1::Request::Stop => {
|
||||
resource.finished();
|
||||
|
||||
let state = state.foreign_toplevel_manager_state();
|
||||
state.instances.retain(|x| x != resource);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn destroyed(
|
||||
state: &mut D,
|
||||
_client: ClientId,
|
||||
resource: &ZwlrForeignToplevelManagerV1,
|
||||
_data: &(),
|
||||
) {
|
||||
let state = state.foreign_toplevel_manager_state();
|
||||
state.instances.retain(|x| x != resource);
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> Dispatch<ZwlrForeignToplevelHandleV1, (), D> for ForeignToplevelManagerState
|
||||
where
|
||||
D: Dispatch<ZwlrForeignToplevelHandleV1, ()>,
|
||||
D: ForeignToplevelHandler,
|
||||
{
|
||||
fn request(
|
||||
state: &mut D,
|
||||
_client: &Client,
|
||||
resource: &ZwlrForeignToplevelHandleV1,
|
||||
request: <ZwlrForeignToplevelHandleV1 as Resource>::Request,
|
||||
_data: &(),
|
||||
_dhandle: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, D>,
|
||||
) {
|
||||
let protocol_state = state.foreign_toplevel_manager_state();
|
||||
|
||||
let Some((surface, _)) = protocol_state
|
||||
.toplevels
|
||||
.iter()
|
||||
.find(|(_, data)| data.instances.contains_key(resource))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let surface = surface.clone();
|
||||
|
||||
match request {
|
||||
zwlr_foreign_toplevel_handle_v1::Request::SetMaximized => (),
|
||||
zwlr_foreign_toplevel_handle_v1::Request::UnsetMaximized => (),
|
||||
zwlr_foreign_toplevel_handle_v1::Request::SetMinimized => (),
|
||||
zwlr_foreign_toplevel_handle_v1::Request::UnsetMinimized => (),
|
||||
zwlr_foreign_toplevel_handle_v1::Request::Activate { .. } => {
|
||||
state.activate(surface);
|
||||
}
|
||||
zwlr_foreign_toplevel_handle_v1::Request::Close => {
|
||||
state.close(surface);
|
||||
}
|
||||
zwlr_foreign_toplevel_handle_v1::Request::SetRectangle { .. } => (),
|
||||
zwlr_foreign_toplevel_handle_v1::Request::Destroy => (),
|
||||
zwlr_foreign_toplevel_handle_v1::Request::SetFullscreen { output } => {
|
||||
state.set_fullscreen(surface, output);
|
||||
}
|
||||
zwlr_foreign_toplevel_handle_v1::Request::UnsetFullscreen => {
|
||||
state.unset_fullscreen(surface);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn destroyed(
|
||||
state: &mut D,
|
||||
_client: ClientId,
|
||||
resource: &ZwlrForeignToplevelHandleV1,
|
||||
_data: &(),
|
||||
) {
|
||||
let state = state.foreign_toplevel_manager_state();
|
||||
for data in state.toplevels.values_mut() {
|
||||
data.instances.retain(|instance, _| instance != resource);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn to_state_vec(states: &ToplevelStateSet, has_focus: bool) -> ArrayVec<u32, 3> {
|
||||
let mut rv = ArrayVec::new();
|
||||
if states.contains(xdg_toplevel::State::Maximized) {
|
||||
rv.push(zwlr_foreign_toplevel_handle_v1::State::Maximized as u32);
|
||||
}
|
||||
if states.contains(xdg_toplevel::State::Fullscreen) {
|
||||
rv.push(zwlr_foreign_toplevel_handle_v1::State::Fullscreen as u32);
|
||||
}
|
||||
|
||||
// HACK: wlr-foreign-toplevel-management states:
|
||||
//
|
||||
// These have the same meaning as the states with the same names defined in xdg-toplevel
|
||||
//
|
||||
// However, clients such as sfwbar and fcitx seem to treat the activated state as keyboard
|
||||
// focus, i.e. they don't expect multiple windows to have it set at once. Even Waybar which
|
||||
// handles multiple activated windows correctly uses it in its design in such a way that
|
||||
// keyboard focus would make more sense. Let's do what the clients expect.
|
||||
if has_focus {
|
||||
rv.push(zwlr_foreign_toplevel_handle_v1::State::Activated as u32);
|
||||
}
|
||||
|
||||
rv
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! delegate_foreign_toplevel {
|
||||
($(@<$( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+>)? $ty: ty) => {
|
||||
smithay::reexports::wayland_server::delegate_global_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
|
||||
smithay::reexports::wayland_protocols_wlr::foreign_toplevel::v1::server::zwlr_foreign_toplevel_manager_v1::ZwlrForeignToplevelManagerV1: $crate::protocols::foreign_toplevel::ForeignToplevelGlobalData
|
||||
] => $crate::protocols::foreign_toplevel::ForeignToplevelManagerState);
|
||||
smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
|
||||
smithay::reexports::wayland_protocols_wlr::foreign_toplevel::v1::server::zwlr_foreign_toplevel_manager_v1::ZwlrForeignToplevelManagerV1: ()
|
||||
] => $crate::protocols::foreign_toplevel::ForeignToplevelManagerState);
|
||||
smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
|
||||
smithay::reexports::wayland_protocols_wlr::foreign_toplevel::v1::server::zwlr_foreign_toplevel_handle_v1::ZwlrForeignToplevelHandleV1: ()
|
||||
] => $crate::protocols::foreign_toplevel::ForeignToplevelManagerState);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
|
||||
use smithay::output::Output;
|
||||
use smithay::reexports::wayland_protocols_wlr;
|
||||
use smithay::reexports::wayland_server::backend::ClientId;
|
||||
use smithay::reexports::wayland_server::{
|
||||
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource,
|
||||
};
|
||||
use wayland_protocols_wlr::gamma_control::v1::server::{
|
||||
zwlr_gamma_control_manager_v1, zwlr_gamma_control_v1,
|
||||
};
|
||||
use zwlr_gamma_control_manager_v1::ZwlrGammaControlManagerV1;
|
||||
use zwlr_gamma_control_v1::ZwlrGammaControlV1;
|
||||
|
||||
const VERSION: u32 = 1;
|
||||
|
||||
pub struct GammaControlManagerState {
|
||||
// Active gamma controls only. Failed ones are removed.
|
||||
gamma_controls: HashMap<Output, ZwlrGammaControlV1>,
|
||||
}
|
||||
|
||||
pub struct GammaControlManagerGlobalData {
|
||||
filter: Box<dyn for<'c> Fn(&'c Client) -> bool + Send + Sync>,
|
||||
}
|
||||
|
||||
pub trait GammaControlHandler {
|
||||
fn gamma_control_manager_state(&mut self) -> &mut GammaControlManagerState;
|
||||
fn get_gamma_size(&mut self, output: &Output) -> Option<u32>;
|
||||
fn set_gamma(&mut self, output: &Output, ramp: Option<Vec<u16>>) -> Option<()>;
|
||||
}
|
||||
|
||||
pub struct GammaControlState {
|
||||
gamma_size: u32,
|
||||
}
|
||||
|
||||
impl GammaControlManagerState {
|
||||
pub fn new<D, F>(display: &DisplayHandle, filter: F) -> Self
|
||||
where
|
||||
D: GlobalDispatch<ZwlrGammaControlManagerV1, GammaControlManagerGlobalData>,
|
||||
D: Dispatch<ZwlrGammaControlManagerV1, ()>,
|
||||
D: Dispatch<ZwlrGammaControlV1, GammaControlState>,
|
||||
D: GammaControlHandler,
|
||||
D: 'static,
|
||||
F: for<'c> Fn(&'c Client) -> bool + Send + Sync + 'static,
|
||||
{
|
||||
let global_data = GammaControlManagerGlobalData {
|
||||
filter: Box::new(filter),
|
||||
};
|
||||
display.create_global::<D, ZwlrGammaControlManagerV1, _>(VERSION, global_data);
|
||||
|
||||
Self {
|
||||
gamma_controls: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn output_removed(&mut self, output: &Output) {
|
||||
if let Some(gamma_control) = self.gamma_controls.remove(output) {
|
||||
gamma_control.failed();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> GlobalDispatch<ZwlrGammaControlManagerV1, GammaControlManagerGlobalData, D>
|
||||
for GammaControlManagerState
|
||||
where
|
||||
D: GlobalDispatch<ZwlrGammaControlManagerV1, GammaControlManagerGlobalData>,
|
||||
D: Dispatch<ZwlrGammaControlManagerV1, ()>,
|
||||
D: Dispatch<ZwlrGammaControlV1, GammaControlState>,
|
||||
D: GammaControlHandler,
|
||||
D: 'static,
|
||||
{
|
||||
fn bind(
|
||||
_state: &mut D,
|
||||
_handle: &DisplayHandle,
|
||||
_client: &Client,
|
||||
manager: New<ZwlrGammaControlManagerV1>,
|
||||
_manager_state: &GammaControlManagerGlobalData,
|
||||
data_init: &mut DataInit<'_, D>,
|
||||
) {
|
||||
data_init.init(manager, ());
|
||||
}
|
||||
|
||||
fn can_view(client: Client, global_data: &GammaControlManagerGlobalData) -> bool {
|
||||
(global_data.filter)(&client)
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> Dispatch<ZwlrGammaControlManagerV1, (), D> for GammaControlManagerState
|
||||
where
|
||||
D: Dispatch<ZwlrGammaControlManagerV1, ()>,
|
||||
D: Dispatch<ZwlrGammaControlV1, GammaControlState>,
|
||||
D: GammaControlHandler,
|
||||
D: 'static,
|
||||
{
|
||||
fn request(
|
||||
state: &mut D,
|
||||
_client: &Client,
|
||||
_resource: &ZwlrGammaControlManagerV1,
|
||||
request: <ZwlrGammaControlManagerV1 as Resource>::Request,
|
||||
_data: &(),
|
||||
_dhandle: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, D>,
|
||||
) {
|
||||
match request {
|
||||
zwlr_gamma_control_manager_v1::Request::GetGammaControl { id, output } => {
|
||||
if let Some(output) = Output::from_resource(&output) {
|
||||
// We borrow state in the middle.
|
||||
#[allow(clippy::map_entry)]
|
||||
if !state
|
||||
.gamma_control_manager_state()
|
||||
.gamma_controls
|
||||
.contains_key(&output)
|
||||
{
|
||||
if let Some(gamma_size) = state.get_gamma_size(&output) {
|
||||
let zwlr_gamma_control =
|
||||
data_init.init(id, GammaControlState { gamma_size });
|
||||
zwlr_gamma_control.gamma_size(gamma_size);
|
||||
state
|
||||
.gamma_control_manager_state()
|
||||
.gamma_controls
|
||||
.insert(output, zwlr_gamma_control);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data_init
|
||||
.init(id, GammaControlState { gamma_size: 0 })
|
||||
.failed();
|
||||
}
|
||||
zwlr_gamma_control_manager_v1::Request::Destroy => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> Dispatch<ZwlrGammaControlV1, GammaControlState, D> for GammaControlManagerState
|
||||
where
|
||||
D: Dispatch<ZwlrGammaControlV1, GammaControlState>,
|
||||
D: GammaControlHandler,
|
||||
D: 'static,
|
||||
{
|
||||
fn request(
|
||||
state: &mut D,
|
||||
_client: &Client,
|
||||
resource: &ZwlrGammaControlV1,
|
||||
request: <ZwlrGammaControlV1 as Resource>::Request,
|
||||
data: &GammaControlState,
|
||||
_dhandle: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, D>,
|
||||
) {
|
||||
match request {
|
||||
zwlr_gamma_control_v1::Request::SetGamma { fd } => {
|
||||
let gamma_controls = &mut state.gamma_control_manager_state().gamma_controls;
|
||||
let Some((output, _)) = gamma_controls.iter().find(|(_, x)| *x == resource) else {
|
||||
return;
|
||||
};
|
||||
let output = output.clone();
|
||||
|
||||
trace!("setting gamma for output {}", output.name());
|
||||
|
||||
// Start with a u16 slice so it's aligned correctly.
|
||||
let mut gamma = vec![0u16; data.gamma_size as usize * 3];
|
||||
let buf = bytemuck::cast_slice_mut(&mut gamma);
|
||||
let mut file = File::from(fd);
|
||||
{
|
||||
let _span = tracy_client::span!("read gamma from fd");
|
||||
|
||||
if let Err(err) = file.read_exact(buf) {
|
||||
warn!("failed to read gamma data: {err:?}");
|
||||
resource.failed();
|
||||
gamma_controls.remove(&output);
|
||||
let _ = state.set_gamma(&output, None);
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify that there's no more data.
|
||||
#[allow(clippy::unused_io_amount)] // False positive on 1.77.0
|
||||
{
|
||||
match file.read(&mut [0]) {
|
||||
Ok(0) => (),
|
||||
Ok(_) => {
|
||||
warn!("gamma data is too large");
|
||||
resource.failed();
|
||||
gamma_controls.remove(&output);
|
||||
let _ = state.set_gamma(&output, None);
|
||||
return;
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("error reading gamma data: {err:?}");
|
||||
resource.failed();
|
||||
gamma_controls.remove(&output);
|
||||
let _ = state.set_gamma(&output, None);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if state.set_gamma(&output, Some(gamma)).is_none() {
|
||||
resource.failed();
|
||||
let gamma_controls = &mut state.gamma_control_manager_state().gamma_controls;
|
||||
gamma_controls.remove(&output);
|
||||
let _ = state.set_gamma(&output, None);
|
||||
}
|
||||
}
|
||||
zwlr_gamma_control_v1::Request::Destroy => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn destroyed(
|
||||
state: &mut D,
|
||||
_client: ClientId,
|
||||
resource: &ZwlrGammaControlV1,
|
||||
_data: &GammaControlState,
|
||||
) {
|
||||
let gamma_controls = &mut state.gamma_control_manager_state().gamma_controls;
|
||||
let Some((output, _)) = gamma_controls.iter().find(|(_, x)| *x == resource) else {
|
||||
return;
|
||||
};
|
||||
let output = output.clone();
|
||||
gamma_controls.remove(&output);
|
||||
|
||||
let _ = state.set_gamma(&output, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! delegate_gamma_control {
|
||||
($(@<$( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+>)? $ty: ty) => {
|
||||
smithay::reexports::wayland_server::delegate_global_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
|
||||
smithay::reexports::wayland_protocols_wlr::gamma_control::v1::server::zwlr_gamma_control_manager_v1::ZwlrGammaControlManagerV1: $crate::protocols::gamma_control::GammaControlManagerGlobalData
|
||||
] => $crate::protocols::gamma_control::GammaControlManagerState);
|
||||
|
||||
smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
|
||||
smithay::reexports::wayland_protocols_wlr::gamma_control::v1::server::zwlr_gamma_control_manager_v1::ZwlrGammaControlManagerV1: ()
|
||||
] => $crate::protocols::gamma_control::GammaControlManagerState);
|
||||
|
||||
smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
|
||||
smithay::reexports::wayland_protocols_wlr::gamma_control::v1::server::zwlr_gamma_control_v1::ZwlrGammaControlV1: $crate::protocols::gamma_control::GammaControlState
|
||||
] => $crate::protocols::gamma_control::GammaControlManagerState);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod foreign_toplevel;
|
||||
pub mod gamma_control;
|
||||
pub mod screencopy;
|
||||
@@ -0,0 +1,386 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use smithay::output::Output;
|
||||
use smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_frame_v1::{
|
||||
Flags, ZwlrScreencopyFrameV1,
|
||||
};
|
||||
use smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1;
|
||||
use smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::{
|
||||
zwlr_screencopy_frame_v1, zwlr_screencopy_manager_v1,
|
||||
};
|
||||
use smithay::reexports::wayland_server::protocol::wl_buffer::WlBuffer;
|
||||
use smithay::reexports::wayland_server::protocol::wl_shm;
|
||||
use smithay::reexports::wayland_server::{
|
||||
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource,
|
||||
};
|
||||
use smithay::utils::{Physical, Point, Rectangle, Size};
|
||||
use smithay::wayland::shm;
|
||||
|
||||
// We do not support copy_with_damage() semantics yet.
|
||||
const VERSION: u32 = 1;
|
||||
|
||||
pub struct ScreencopyManagerState;
|
||||
|
||||
pub struct ScreencopyManagerGlobalData {
|
||||
filter: Box<dyn for<'c> Fn(&'c Client) -> bool + Send + Sync>,
|
||||
}
|
||||
|
||||
impl ScreencopyManagerState {
|
||||
pub fn new<D, F>(display: &DisplayHandle, filter: F) -> Self
|
||||
where
|
||||
D: GlobalDispatch<ZwlrScreencopyManagerV1, ScreencopyManagerGlobalData>,
|
||||
D: Dispatch<ZwlrScreencopyManagerV1, ()>,
|
||||
D: Dispatch<ZwlrScreencopyFrameV1, ScreencopyFrameState>,
|
||||
D: ScreencopyHandler,
|
||||
D: 'static,
|
||||
F: for<'c> Fn(&'c Client) -> bool + Send + Sync + 'static,
|
||||
{
|
||||
let global_data = ScreencopyManagerGlobalData {
|
||||
filter: Box::new(filter),
|
||||
};
|
||||
display.create_global::<D, ZwlrScreencopyManagerV1, _>(VERSION, global_data);
|
||||
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> GlobalDispatch<ZwlrScreencopyManagerV1, ScreencopyManagerGlobalData, D>
|
||||
for ScreencopyManagerState
|
||||
where
|
||||
D: GlobalDispatch<ZwlrScreencopyManagerV1, ScreencopyManagerGlobalData>,
|
||||
D: Dispatch<ZwlrScreencopyManagerV1, ()>,
|
||||
D: Dispatch<ZwlrScreencopyFrameV1, ScreencopyFrameState>,
|
||||
D: ScreencopyHandler,
|
||||
D: 'static,
|
||||
{
|
||||
fn bind(
|
||||
_state: &mut D,
|
||||
_display: &DisplayHandle,
|
||||
_client: &Client,
|
||||
manager: New<ZwlrScreencopyManagerV1>,
|
||||
_manager_state: &ScreencopyManagerGlobalData,
|
||||
data_init: &mut DataInit<'_, D>,
|
||||
) {
|
||||
data_init.init(manager, ());
|
||||
}
|
||||
|
||||
fn can_view(client: Client, global_data: &ScreencopyManagerGlobalData) -> bool {
|
||||
(global_data.filter)(&client)
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> Dispatch<ZwlrScreencopyManagerV1, (), D> for ScreencopyManagerState
|
||||
where
|
||||
D: GlobalDispatch<ZwlrScreencopyManagerV1, ScreencopyManagerGlobalData>,
|
||||
D: Dispatch<ZwlrScreencopyManagerV1, ()>,
|
||||
D: Dispatch<ZwlrScreencopyFrameV1, ScreencopyFrameState>,
|
||||
D: ScreencopyHandler,
|
||||
D: 'static,
|
||||
{
|
||||
fn request(
|
||||
_state: &mut D,
|
||||
_client: &Client,
|
||||
_manager: &ZwlrScreencopyManagerV1,
|
||||
request: zwlr_screencopy_manager_v1::Request,
|
||||
_data: &(),
|
||||
_display: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, D>,
|
||||
) {
|
||||
let (frame, overlay_cursor, buffer_size, region_loc, output) = match request {
|
||||
zwlr_screencopy_manager_v1::Request::CaptureOutput {
|
||||
frame,
|
||||
overlay_cursor,
|
||||
output,
|
||||
} => {
|
||||
let output = Output::from_resource(&output).unwrap();
|
||||
let buffer_size = output.current_mode().unwrap().size;
|
||||
let region_loc = Point::from((0, 0));
|
||||
|
||||
(frame, overlay_cursor, buffer_size, region_loc, output)
|
||||
}
|
||||
zwlr_screencopy_manager_v1::Request::CaptureOutputRegion {
|
||||
frame,
|
||||
overlay_cursor,
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
output,
|
||||
} => {
|
||||
if width <= 0 || height <= 0 {
|
||||
trace!("screencopy client requested invalid sized region");
|
||||
let frame = data_init.init(frame, ScreencopyFrameState::Failed);
|
||||
frame.failed();
|
||||
return;
|
||||
}
|
||||
|
||||
let output = Output::from_resource(&output).unwrap();
|
||||
let output_transform = output.current_transform();
|
||||
let output_physical_size =
|
||||
output_transform.transform_size(output.current_mode().unwrap().size);
|
||||
let output_rect = Rectangle::from_loc_and_size((0, 0), output_physical_size);
|
||||
|
||||
let rect = Rectangle::from_loc_and_size((x, y), (width, height));
|
||||
|
||||
let output_scale = output.current_scale().integer_scale();
|
||||
let physical_rect = rect.to_physical(output_scale);
|
||||
|
||||
// Clamp captured region to the output.
|
||||
let Some(clamped_rect) = physical_rect.intersection(output_rect) else {
|
||||
trace!("screencopy client requested region outside of output");
|
||||
let frame = data_init.init(frame, ScreencopyFrameState::Failed);
|
||||
frame.failed();
|
||||
return;
|
||||
};
|
||||
|
||||
let untransformed_rect = output_transform
|
||||
.invert()
|
||||
.transform_rect_in(clamped_rect, &output_physical_size);
|
||||
|
||||
(
|
||||
frame,
|
||||
overlay_cursor,
|
||||
untransformed_rect.size,
|
||||
clamped_rect.loc,
|
||||
output,
|
||||
)
|
||||
}
|
||||
zwlr_screencopy_manager_v1::Request::Destroy => return,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
// Create the frame.
|
||||
let overlay_cursor = overlay_cursor != 0;
|
||||
let info = ScreencopyFrameInfo {
|
||||
output,
|
||||
overlay_cursor,
|
||||
buffer_size,
|
||||
region_loc,
|
||||
};
|
||||
let frame = data_init.init(
|
||||
frame,
|
||||
ScreencopyFrameState::Pending {
|
||||
info,
|
||||
copied: Arc::new(AtomicBool::new(false)),
|
||||
},
|
||||
);
|
||||
|
||||
// Send desired SHM buffer parameters.
|
||||
frame.buffer(
|
||||
wl_shm::Format::Argb8888,
|
||||
buffer_size.w as u32,
|
||||
buffer_size.h as u32,
|
||||
buffer_size.w as u32 * 4,
|
||||
);
|
||||
|
||||
// if manager.version() >= 3 {
|
||||
// // Send desired DMA buffer parameters.
|
||||
// frame.linux_dmabuf(
|
||||
// Fourcc::Argb8888 as u32,
|
||||
// buffer_size.w as u32,
|
||||
// buffer_size.h as u32,
|
||||
// );
|
||||
//
|
||||
// // Notify client that all supported buffers were enumerated.
|
||||
// frame.buffer_done();
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
/// Handler trait for wlr-screencopy.
|
||||
pub trait ScreencopyHandler {
|
||||
/// Handle new screencopy request.
|
||||
fn frame(&mut self, frame: Screencopy);
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[macro_export]
|
||||
macro_rules! delegate_screencopy {
|
||||
($(@<$( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+>)? $ty: ty) => {
|
||||
smithay::reexports::wayland_server::delegate_global_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
|
||||
smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1: $crate::protocols::screencopy::ScreencopyManagerGlobalData
|
||||
] => $crate::protocols::screencopy::ScreencopyManagerState);
|
||||
|
||||
smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
|
||||
smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1: ()
|
||||
] => $crate::protocols::screencopy::ScreencopyManagerState);
|
||||
|
||||
smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
|
||||
smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_frame_v1::ZwlrScreencopyFrameV1: $crate::protocols::screencopy::ScreencopyFrameState
|
||||
] => $crate::protocols::screencopy::ScreencopyManagerState);
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ScreencopyFrameInfo {
|
||||
output: Output,
|
||||
buffer_size: Size<i32, Physical>,
|
||||
region_loc: Point<i32, Physical>,
|
||||
overlay_cursor: bool,
|
||||
}
|
||||
|
||||
pub enum ScreencopyFrameState {
|
||||
Failed,
|
||||
Pending {
|
||||
info: ScreencopyFrameInfo,
|
||||
copied: Arc<AtomicBool>,
|
||||
},
|
||||
}
|
||||
|
||||
impl<D> Dispatch<ZwlrScreencopyFrameV1, ScreencopyFrameState, D> for ScreencopyManagerState
|
||||
where
|
||||
D: Dispatch<ZwlrScreencopyFrameV1, ScreencopyFrameState>,
|
||||
D: ScreencopyHandler,
|
||||
D: 'static,
|
||||
{
|
||||
fn request(
|
||||
state: &mut D,
|
||||
_client: &Client,
|
||||
frame: &ZwlrScreencopyFrameV1,
|
||||
request: zwlr_screencopy_frame_v1::Request,
|
||||
data: &ScreencopyFrameState,
|
||||
_display: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, D>,
|
||||
) {
|
||||
if matches!(request, zwlr_screencopy_frame_v1::Request::Destroy) {
|
||||
return;
|
||||
}
|
||||
|
||||
let (info, copied) = match data {
|
||||
ScreencopyFrameState::Failed => return,
|
||||
ScreencopyFrameState::Pending { info, copied } => (info, copied),
|
||||
};
|
||||
|
||||
if copied.load(Ordering::SeqCst) {
|
||||
frame.post_error(
|
||||
zwlr_screencopy_frame_v1::Error::AlreadyUsed,
|
||||
"copy was already requested",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let (buffer, with_damage) = match request {
|
||||
zwlr_screencopy_frame_v1::Request::Copy { buffer } => (buffer, false),
|
||||
// zwlr_screencopy_frame_v1::Request::CopyWithDamage { buffer } => (buffer, true),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
if !shm::with_buffer_contents(&buffer, |_buf, shm_len, buffer_data| {
|
||||
buffer_data.format == wl_shm::Format::Argb8888
|
||||
&& buffer_data.stride == info.buffer_size.w * 4
|
||||
&& buffer_data.height == info.buffer_size.h
|
||||
&& shm_len as i32 == buffer_data.stride * buffer_data.height
|
||||
})
|
||||
.unwrap_or(false)
|
||||
{
|
||||
frame.post_error(
|
||||
zwlr_screencopy_frame_v1::Error::InvalidBuffer,
|
||||
"invalid buffer",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
copied.store(true, Ordering::SeqCst);
|
||||
|
||||
state.frame(Screencopy {
|
||||
with_damage,
|
||||
buffer,
|
||||
frame: frame.clone(),
|
||||
info: info.clone(),
|
||||
submitted: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Screencopy frame.
|
||||
pub struct Screencopy {
|
||||
info: ScreencopyFrameInfo,
|
||||
frame: ZwlrScreencopyFrameV1,
|
||||
#[allow(unused)]
|
||||
with_damage: bool,
|
||||
buffer: WlBuffer,
|
||||
submitted: bool,
|
||||
}
|
||||
|
||||
impl Drop for Screencopy {
|
||||
fn drop(&mut self) {
|
||||
if !self.submitted {
|
||||
self.frame.failed();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Screencopy {
|
||||
/// Get the target buffer to copy to.
|
||||
pub fn buffer(&self) -> &WlBuffer {
|
||||
&self.buffer
|
||||
}
|
||||
|
||||
pub fn region_loc(&self) -> Point<i32, Physical> {
|
||||
self.info.region_loc
|
||||
}
|
||||
|
||||
pub fn buffer_size(&self) -> Size<i32, Physical> {
|
||||
self.info.buffer_size
|
||||
}
|
||||
|
||||
pub fn output(&self) -> &Output {
|
||||
&self.info.output
|
||||
}
|
||||
|
||||
pub fn overlay_cursor(&self) -> bool {
|
||||
self.info.overlay_cursor
|
||||
}
|
||||
|
||||
// pub fn damage(&mut self, damage: &[Rectangle<i32, Physical>]) {
|
||||
// assert!(self.with_damage);
|
||||
//
|
||||
// for Rectangle { loc, size } in damage {
|
||||
// self.frame
|
||||
// .damage(loc.x as u32, loc.y as u32, size.w as u32, size.h as u32);
|
||||
// }
|
||||
// }
|
||||
|
||||
/// Submit the copied content.
|
||||
pub fn submit(mut self, y_invert: bool) {
|
||||
// Notify client that buffer is ordinary.
|
||||
self.frame.flags(if y_invert {
|
||||
Flags::YInvert
|
||||
} else {
|
||||
Flags::empty()
|
||||
});
|
||||
|
||||
// Notify client about successful copy.
|
||||
let time = UNIX_EPOCH.elapsed().unwrap();
|
||||
let tv_sec_hi = (time.as_secs() >> 32) as u32;
|
||||
let tv_sec_lo = (time.as_secs() & 0xFFFFFFFF) as u32;
|
||||
let tv_nsec = time.subsec_nanos();
|
||||
self.frame.ready(tv_sec_hi, tv_sec_lo, tv_nsec);
|
||||
|
||||
// Mark frame as submitted to ensure destructor isn't run.
|
||||
self.submitted = true;
|
||||
}
|
||||
|
||||
// pub fn submit_after_sync<T>(
|
||||
// self,
|
||||
// y_invert: bool,
|
||||
// sync_point: Option<OwnedFd>,
|
||||
// event_loop: &LoopHandle<'_, T>,
|
||||
// ) {
|
||||
// match sync_point {
|
||||
// None => self.submit(y_invert),
|
||||
// Some(sync_fd) => {
|
||||
// let source = Generic::new(sync_fd, Interest::READ, Mode::OneShot);
|
||||
// let mut screencopy = Some(self);
|
||||
// event_loop
|
||||
// .insert_source(source, move |_, _, _| {
|
||||
// screencopy.take().unwrap().submit(y_invert);
|
||||
// Ok(PostAction::Remove)
|
||||
// })
|
||||
// .unwrap();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
+39
-22
@@ -7,42 +7,48 @@ use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use pipewire::spa::data::DataType;
|
||||
use pipewire::spa::format::{FormatProperties, MediaSubtype, MediaType};
|
||||
use pipewire::context::Context;
|
||||
use pipewire::core::Core;
|
||||
use pipewire::main_loop::MainLoop;
|
||||
use pipewire::properties::Properties;
|
||||
use pipewire::spa::buffer::DataType;
|
||||
use pipewire::spa::param::format::{FormatProperties, MediaSubtype, MediaType};
|
||||
use pipewire::spa::param::format_utils::parse_format;
|
||||
use pipewire::spa::param::video::{VideoFormat, VideoInfoRaw};
|
||||
use pipewire::spa::param::ParamType;
|
||||
use pipewire::spa::pod::serialize::PodSerializer;
|
||||
use pipewire::spa::pod::{self, ChoiceValue, Pod, Property, PropertyFlags};
|
||||
use pipewire::spa::sys::*;
|
||||
use pipewire::spa::utils::{Choice, ChoiceEnum, ChoiceFlags, Fraction, Rectangle, SpaTypes};
|
||||
use pipewire::spa::Direction;
|
||||
use pipewire::spa::utils::{
|
||||
Choice, ChoiceEnum, ChoiceFlags, Direction, Fraction, Rectangle, SpaTypes,
|
||||
};
|
||||
use pipewire::stream::{Stream, StreamFlags, StreamListener, StreamState};
|
||||
use pipewire::{Context, Core, MainLoop, Properties};
|
||||
use smithay::backend::allocator::dmabuf::{AsDmabuf, Dmabuf};
|
||||
use smithay::backend::allocator::gbm::{GbmBufferFlags, GbmDevice};
|
||||
use smithay::backend::allocator::gbm::{GbmBuffer, GbmBufferFlags, GbmDevice};
|
||||
use smithay::backend::allocator::Fourcc;
|
||||
use smithay::backend::drm::DrmDeviceFd;
|
||||
use smithay::output::Output;
|
||||
use smithay::reexports::calloop::generic::Generic;
|
||||
use smithay::reexports::calloop::{self, Interest, LoopHandle, Mode, PostAction};
|
||||
use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
|
||||
use smithay::reexports::gbm::Modifier;
|
||||
use smithay::utils::{Physical, Size};
|
||||
use zbus::SignalContext;
|
||||
|
||||
use crate::dbus::mutter_screen_cast::{self, CursorMode, ScreenCastToNiri};
|
||||
use crate::niri::State;
|
||||
|
||||
pub struct PipeWire {
|
||||
_context: Context<MainLoop>,
|
||||
_context: Context,
|
||||
pub core: Core,
|
||||
}
|
||||
|
||||
pub struct Cast {
|
||||
pub session_id: usize,
|
||||
pub stream: Rc<Stream>,
|
||||
pub stream: Stream,
|
||||
_listener: StreamListener<()>,
|
||||
pub is_active: Rc<Cell<bool>>,
|
||||
pub output: Output,
|
||||
pub size: Size<i32, Physical>,
|
||||
pub cursor_mode: CursorMode,
|
||||
pub last_frame_time: Duration,
|
||||
pub min_time_between_frames: Rc<Cell<Duration>>,
|
||||
@@ -51,7 +57,7 @@ pub struct Cast {
|
||||
|
||||
impl PipeWire {
|
||||
pub fn new(event_loop: &LoopHandle<'static, State>) -> anyhow::Result<Self> {
|
||||
let main_loop = MainLoop::new().context("error creating MainLoop")?;
|
||||
let main_loop = MainLoop::new(None).context("error creating MainLoop")?;
|
||||
let context = Context::new(&main_loop).context("error creating Context")?;
|
||||
let core = context.connect(None).context("error creating Core")?;
|
||||
|
||||
@@ -66,14 +72,14 @@ impl PipeWire {
|
||||
struct AsFdWrapper(MainLoop);
|
||||
impl AsFd for AsFdWrapper {
|
||||
fn as_fd(&self) -> BorrowedFd<'_> {
|
||||
self.0.fd()
|
||||
self.0.loop_().fd()
|
||||
}
|
||||
}
|
||||
let generic = Generic::new(AsFdWrapper(main_loop), Interest::READ, Mode::Level);
|
||||
event_loop
|
||||
.insert_source(generic, move |_, wrapper, _| {
|
||||
let _span = tracy_client::span!("pipewire iteration");
|
||||
wrapper.0.iterate(Duration::ZERO);
|
||||
wrapper.0.loop_().iterate(Duration::ZERO);
|
||||
Ok(PostAction::Continue)
|
||||
})
|
||||
.unwrap();
|
||||
@@ -95,21 +101,31 @@ impl PipeWire {
|
||||
) -> anyhow::Result<Cast> {
|
||||
let _span = tracy_client::span!("PipeWire::start_cast");
|
||||
|
||||
let to_niri_ = to_niri.clone();
|
||||
let stop_cast = move || {
|
||||
if let Err(err) = to_niri.send(ScreenCastToNiri::StopCast { session_id }) {
|
||||
if let Err(err) = to_niri_.send(ScreenCastToNiri::StopCast { session_id }) {
|
||||
warn!("error sending StopCast to niri: {err:?}");
|
||||
}
|
||||
};
|
||||
let weak = output.downgrade();
|
||||
let redraw = move || {
|
||||
if let Some(output) = weak.upgrade() {
|
||||
if let Err(err) = to_niri.send(ScreenCastToNiri::Redraw(output)) {
|
||||
warn!("error sending Redraw to niri: {err:?}");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mode = output.current_mode().unwrap();
|
||||
let size = mode.size;
|
||||
let transform = output.current_transform();
|
||||
let size = transform.transform_size(size);
|
||||
let refresh = mode.refresh;
|
||||
|
||||
let stream = Stream::new(&self.core, "niri-screen-cast-src", Properties::new())
|
||||
.context("error creating Stream")?;
|
||||
|
||||
// Like in good old wayland-rs times...
|
||||
let stream = Rc::new(stream);
|
||||
let node_id = Rc::new(Cell::new(None));
|
||||
let is_active = Rc::new(Cell::new(false));
|
||||
let min_time_between_frames = Rc::new(Cell::new(Duration::ZERO));
|
||||
@@ -118,10 +134,9 @@ impl PipeWire {
|
||||
let listener = stream
|
||||
.add_local_listener_with_user_data(())
|
||||
.state_changed({
|
||||
let stream = stream.clone();
|
||||
let is_active = is_active.clone();
|
||||
let stop_cast = stop_cast.clone();
|
||||
move |old, new| {
|
||||
move |stream, (), old, new| {
|
||||
debug!("pw stream: state changed: {old:?} -> {new:?}");
|
||||
|
||||
match new {
|
||||
@@ -158,13 +173,14 @@ impl PipeWire {
|
||||
StreamState::Connecting => (),
|
||||
StreamState::Streaming => {
|
||||
is_active.set(true);
|
||||
redraw();
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.param_changed({
|
||||
let min_time_between_frames = min_time_between_frames.clone();
|
||||
move |stream, id, _data, pod| {
|
||||
move |stream, (), id, pod| {
|
||||
let id = ParamType::from_raw(id);
|
||||
trace!(?id, "pw stream: param_changed");
|
||||
|
||||
@@ -246,8 +262,7 @@ impl PipeWire {
|
||||
let mut b1 = vec![];
|
||||
// let mut b2 = vec![];
|
||||
let mut params = [
|
||||
make_pod(&mut b1, o1).as_raw_ptr().cast_const(),
|
||||
// make_pod(&mut b2, o2).as_raw_ptr().cast_const(),
|
||||
make_pod(&mut b1, o1), // make_pod(&mut b2, o2)
|
||||
];
|
||||
stream.update_params(&mut params).unwrap();
|
||||
}
|
||||
@@ -255,7 +270,7 @@ impl PipeWire {
|
||||
.add_buffer({
|
||||
let dmabufs = dmabufs.clone();
|
||||
let stop_cast = stop_cast.clone();
|
||||
move |buffer| {
|
||||
move |_stream, (), buffer| {
|
||||
trace!("pw stream: add_buffer");
|
||||
|
||||
unsafe {
|
||||
@@ -277,7 +292,8 @@ impl PipeWire {
|
||||
return;
|
||||
}
|
||||
};
|
||||
let dmabuf = match bo.export() {
|
||||
let buffer = GbmBuffer::from_bo(bo, true);
|
||||
let dmabuf = match buffer.export() {
|
||||
Ok(dmabuf) => dmabuf,
|
||||
Err(err) => {
|
||||
warn!("error exporting GBM buffer object as dmabuf: {err:?}");
|
||||
@@ -299,7 +315,7 @@ impl PipeWire {
|
||||
})
|
||||
.remove_buffer({
|
||||
let dmabufs = dmabufs.clone();
|
||||
move |buffer| {
|
||||
move |_stream, (), buffer| {
|
||||
trace!("pw stream: remove_buffer");
|
||||
|
||||
unsafe {
|
||||
@@ -373,6 +389,7 @@ impl PipeWire {
|
||||
_listener: listener,
|
||||
is_active,
|
||||
output,
|
||||
size,
|
||||
cursor_mode,
|
||||
last_frame_time: Duration::ZERO,
|
||||
min_time_between_frames,
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use glam::{Mat3, Vec2};
|
||||
use niri_config::CornerRadius;
|
||||
use smithay::backend::renderer::element::{Element, Id, Kind, RenderElement, UnderlyingStorage};
|
||||
use smithay::backend::renderer::gles::{GlesError, GlesFrame, GlesRenderer, Uniform};
|
||||
use smithay::backend::renderer::utils::{CommitCounter, DamageSet, OpaqueRegions};
|
||||
use smithay::utils::{Buffer, Logical, Physical, Point, Rectangle, Scale, Size, Transform};
|
||||
|
||||
use super::renderer::NiriRenderer;
|
||||
use super::shader_element::ShaderRenderElement;
|
||||
use super::shaders::{mat3_uniform, ProgramType, Shaders};
|
||||
use crate::backend::tty::{TtyFrame, TtyRenderer, TtyRendererError};
|
||||
|
||||
/// Renders a wide variety of borders and border parts.
|
||||
///
|
||||
/// This includes:
|
||||
/// * sub- or super-rect of an angled linear gradient like CSS linear-gradient(angle, a, b).
|
||||
/// * corner rounding.
|
||||
/// * as a background rectangle and as parts of a border line.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BorderRenderElement {
|
||||
inner: ShaderRenderElement,
|
||||
params: Parameters,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
struct Parameters {
|
||||
size: Size<i32, Logical>,
|
||||
gradient_area: Rectangle<i32, Logical>,
|
||||
color_from: [f32; 4],
|
||||
color_to: [f32; 4],
|
||||
angle: f32,
|
||||
geometry: Rectangle<i32, Logical>,
|
||||
border_width: f32,
|
||||
corner_radius: CornerRadius,
|
||||
}
|
||||
|
||||
impl BorderRenderElement {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
size: Size<i32, Logical>,
|
||||
gradient_area: Rectangle<i32, Logical>,
|
||||
color_from: [f32; 4],
|
||||
color_to: [f32; 4],
|
||||
angle: f32,
|
||||
geometry: Rectangle<i32, Logical>,
|
||||
border_width: f32,
|
||||
corner_radius: CornerRadius,
|
||||
) -> Self {
|
||||
let inner = ShaderRenderElement::empty(ProgramType::Border, Kind::Unspecified);
|
||||
let mut rv = Self {
|
||||
inner,
|
||||
params: Parameters {
|
||||
size,
|
||||
gradient_area,
|
||||
color_from,
|
||||
color_to,
|
||||
angle,
|
||||
geometry,
|
||||
border_width,
|
||||
corner_radius,
|
||||
},
|
||||
};
|
||||
rv.update_inner();
|
||||
rv
|
||||
}
|
||||
|
||||
pub fn empty() -> Self {
|
||||
let inner = ShaderRenderElement::empty(ProgramType::Border, Kind::Unspecified);
|
||||
Self {
|
||||
inner,
|
||||
params: Parameters {
|
||||
size: Default::default(),
|
||||
gradient_area: Default::default(),
|
||||
color_from: Default::default(),
|
||||
color_to: Default::default(),
|
||||
angle: 0.,
|
||||
geometry: Default::default(),
|
||||
border_width: 0.,
|
||||
corner_radius: Default::default(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn damage_all(&mut self) {
|
||||
self.inner.damage_all();
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn update(
|
||||
&mut self,
|
||||
size: Size<i32, Logical>,
|
||||
gradient_area: Rectangle<i32, Logical>,
|
||||
color_from: [f32; 4],
|
||||
color_to: [f32; 4],
|
||||
angle: f32,
|
||||
geometry: Rectangle<i32, Logical>,
|
||||
border_width: f32,
|
||||
corner_radius: CornerRadius,
|
||||
) {
|
||||
let params = Parameters {
|
||||
size,
|
||||
gradient_area,
|
||||
color_from,
|
||||
color_to,
|
||||
angle,
|
||||
geometry,
|
||||
border_width,
|
||||
corner_radius,
|
||||
};
|
||||
if self.params == params {
|
||||
return;
|
||||
}
|
||||
|
||||
self.params = params;
|
||||
self.update_inner();
|
||||
}
|
||||
|
||||
fn update_inner(&mut self) {
|
||||
let Parameters {
|
||||
size,
|
||||
gradient_area,
|
||||
color_from,
|
||||
color_to,
|
||||
angle,
|
||||
geometry,
|
||||
border_width,
|
||||
corner_radius,
|
||||
} = self.params;
|
||||
|
||||
let grad_offset = geometry.loc - gradient_area.loc;
|
||||
let grad_offset = Vec2::new(grad_offset.x as f32, grad_offset.y as f32);
|
||||
|
||||
let grad_dir = Vec2::from_angle(angle);
|
||||
|
||||
let (w, h) = (gradient_area.size.w as f32, gradient_area.size.h as f32);
|
||||
|
||||
let mut grad_area_diag = Vec2::new(w, h);
|
||||
if (grad_dir.x < 0. && 0. <= grad_dir.y) || (0. <= grad_dir.x && grad_dir.y < 0.) {
|
||||
grad_area_diag.x = -w;
|
||||
}
|
||||
|
||||
let mut grad_vec = grad_area_diag.project_onto(grad_dir);
|
||||
if grad_dir.y <= 0. {
|
||||
grad_vec = -grad_vec;
|
||||
}
|
||||
|
||||
let area_size = Vec2::new(size.w as f32, size.h as f32);
|
||||
|
||||
let geo_loc = Vec2::new(geometry.loc.x as f32, geometry.loc.y as f32);
|
||||
let geo_size = Vec2::new(geometry.size.w as f32, geometry.size.h as f32);
|
||||
|
||||
let input_to_geo =
|
||||
Mat3::from_scale(area_size) * Mat3::from_translation(-geo_loc / area_size);
|
||||
|
||||
self.inner.update(
|
||||
size,
|
||||
None,
|
||||
vec![
|
||||
Uniform::new("color_from", color_from),
|
||||
Uniform::new("color_to", color_to),
|
||||
Uniform::new("grad_offset", grad_offset.to_array()),
|
||||
Uniform::new("grad_width", w),
|
||||
Uniform::new("grad_vec", grad_vec.to_array()),
|
||||
mat3_uniform("input_to_geo", input_to_geo),
|
||||
Uniform::new("geo_size", geo_size.to_array()),
|
||||
Uniform::new("outer_radius", <[f32; 4]>::from(corner_radius)),
|
||||
Uniform::new("border_width", border_width),
|
||||
],
|
||||
HashMap::new(),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn with_location(mut self, location: Point<i32, Logical>) -> Self {
|
||||
self.inner = self.inner.with_location(location);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn has_shader(renderer: &mut impl NiriRenderer) -> bool {
|
||||
Shaders::get(renderer)
|
||||
.program(ProgramType::Border)
|
||||
.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BorderRenderElement {
|
||||
fn default() -> Self {
|
||||
Self::empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl Element for BorderRenderElement {
|
||||
fn id(&self) -> &Id {
|
||||
self.inner.id()
|
||||
}
|
||||
|
||||
fn current_commit(&self) -> CommitCounter {
|
||||
self.inner.current_commit()
|
||||
}
|
||||
|
||||
fn geometry(&self, scale: Scale<f64>) -> Rectangle<i32, Physical> {
|
||||
self.inner.geometry(scale)
|
||||
}
|
||||
|
||||
fn transform(&self) -> Transform {
|
||||
self.inner.transform()
|
||||
}
|
||||
|
||||
fn src(&self) -> Rectangle<f64, Buffer> {
|
||||
self.inner.src()
|
||||
}
|
||||
|
||||
fn damage_since(
|
||||
&self,
|
||||
scale: Scale<f64>,
|
||||
commit: Option<CommitCounter>,
|
||||
) -> DamageSet<i32, Physical> {
|
||||
self.inner.damage_since(scale, commit)
|
||||
}
|
||||
|
||||
fn opaque_regions(&self, scale: Scale<f64>) -> OpaqueRegions<i32, Physical> {
|
||||
self.inner.opaque_regions(scale)
|
||||
}
|
||||
|
||||
fn alpha(&self) -> f32 {
|
||||
self.inner.alpha()
|
||||
}
|
||||
|
||||
fn kind(&self) -> Kind {
|
||||
self.inner.kind()
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderElement<GlesRenderer> for BorderRenderElement {
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut GlesFrame<'_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dst: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), GlesError> {
|
||||
RenderElement::<GlesRenderer>::draw(&self.inner, frame, src, dst, damage)
|
||||
}
|
||||
|
||||
fn underlying_storage(&self, renderer: &mut GlesRenderer) -> Option<UnderlyingStorage> {
|
||||
self.inner.underlying_storage(renderer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'render> RenderElement<TtyRenderer<'render>> for BorderRenderElement {
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut TtyFrame<'_, '_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dst: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), TtyRendererError<'render>> {
|
||||
RenderElement::<TtyRenderer<'_>>::draw(&self.inner, frame, src, dst, damage)
|
||||
}
|
||||
|
||||
fn underlying_storage(&self, renderer: &mut TtyRenderer<'render>) -> Option<UnderlyingStorage> {
|
||||
self.inner.underlying_storage(renderer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
use glam::{Mat3, Vec2};
|
||||
use niri_config::CornerRadius;
|
||||
use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;
|
||||
use smithay::backend::renderer::element::{Element, Id, Kind, RenderElement, UnderlyingStorage};
|
||||
use smithay::backend::renderer::gles::{
|
||||
GlesError, GlesFrame, GlesRenderer, GlesTexProgram, Uniform,
|
||||
};
|
||||
use smithay::backend::renderer::utils::{CommitCounter, DamageSet, OpaqueRegions};
|
||||
use smithay::utils::{Buffer, Logical, Physical, Rectangle, Scale, Size, Transform};
|
||||
|
||||
use super::damage::ExtraDamage;
|
||||
use super::renderer::{AsGlesFrame as _, NiriRenderer};
|
||||
use super::shaders::{mat3_uniform, Shaders};
|
||||
use crate::backend::tty::{TtyFrame, TtyRenderer, TtyRendererError};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ClippedSurfaceRenderElement<R: NiriRenderer> {
|
||||
inner: WaylandSurfaceRenderElement<R>,
|
||||
program: GlesTexProgram,
|
||||
corner_radius: CornerRadius,
|
||||
geometry: Rectangle<i32, Logical>,
|
||||
input_to_geo: Mat3,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct RoundedCornerDamage {
|
||||
damage: ExtraDamage,
|
||||
corner_radius: CornerRadius,
|
||||
}
|
||||
|
||||
impl<R: NiriRenderer> ClippedSurfaceRenderElement<R> {
|
||||
pub fn new(
|
||||
elem: WaylandSurfaceRenderElement<R>,
|
||||
scale: Scale<f64>,
|
||||
geometry: Rectangle<i32, Logical>,
|
||||
program: GlesTexProgram,
|
||||
corner_radius: CornerRadius,
|
||||
) -> Self {
|
||||
let elem_geo = elem.geometry(scale);
|
||||
|
||||
let elem_geo_loc = Vec2::new(elem_geo.loc.x as f32, elem_geo.loc.y as f32);
|
||||
let elem_geo_size = Vec2::new(elem_geo.size.w as f32, elem_geo.size.h as f32);
|
||||
|
||||
let geo = geometry.to_physical_precise_round(scale);
|
||||
let geo_loc = Vec2::new(geo.loc.x, geo.loc.y);
|
||||
let geo_size = Vec2::new(geo.size.w, geo.size.h);
|
||||
|
||||
let buf_size = elem.buffer_size();
|
||||
let buf_size = Vec2::new(buf_size.w as f32, buf_size.h as f32);
|
||||
|
||||
let view = elem.view();
|
||||
let src_loc = Vec2::new(view.src.loc.x as f32, view.src.loc.y as f32);
|
||||
let src_size = Vec2::new(view.src.size.w as f32, view.src.size.h as f32);
|
||||
|
||||
let transform = elem.transform();
|
||||
// HACK: ??? for some reason flipped ones are fine.
|
||||
let transform = match transform {
|
||||
Transform::_90 => Transform::_270,
|
||||
Transform::_270 => Transform::_90,
|
||||
x => x,
|
||||
};
|
||||
let transform_matrix = Mat3::from_translation(Vec2::new(0.5, 0.5))
|
||||
* Mat3::from_cols_array(transform.matrix().as_ref())
|
||||
* Mat3::from_translation(-Vec2::new(0.5, 0.5));
|
||||
|
||||
// FIXME: y_inverted
|
||||
let input_to_geo = transform_matrix * Mat3::from_scale(elem_geo_size / geo_size)
|
||||
* Mat3::from_translation((elem_geo_loc - geo_loc) / elem_geo_size)
|
||||
// Apply viewporter src.
|
||||
* Mat3::from_scale(buf_size / src_size)
|
||||
* Mat3::from_translation(-src_loc / buf_size);
|
||||
|
||||
Self {
|
||||
inner: elem,
|
||||
program,
|
||||
corner_radius,
|
||||
geometry,
|
||||
input_to_geo,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shader(renderer: &mut R) -> Option<&GlesTexProgram> {
|
||||
Shaders::get(renderer).clipped_surface.as_ref()
|
||||
}
|
||||
|
||||
pub fn will_clip(
|
||||
elem: &WaylandSurfaceRenderElement<R>,
|
||||
scale: Scale<f64>,
|
||||
geometry: Rectangle<i32, Logical>,
|
||||
corner_radius: CornerRadius,
|
||||
) -> bool {
|
||||
let elem_geo = elem.geometry(scale);
|
||||
let geo = geometry.to_physical_precise_round(scale);
|
||||
|
||||
if corner_radius == CornerRadius::default() {
|
||||
!geo.contains_rect(elem_geo)
|
||||
} else {
|
||||
let corners = Self::rounded_corners(geometry.to_f64(), corner_radius);
|
||||
let corners = corners
|
||||
.into_iter()
|
||||
.map(|rect| rect.to_physical_precise_round(scale));
|
||||
let geo = Rectangle::subtract_rects_many([geo], corners);
|
||||
!Rectangle::subtract_rects_many([elem_geo], geo).is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn rounded_corners(
|
||||
geo: Rectangle<f64, Logical>,
|
||||
corner_radius: CornerRadius,
|
||||
) -> [Rectangle<f64, Logical>; 4] {
|
||||
let top_left = corner_radius.top_left as f64;
|
||||
let top_right = corner_radius.top_right as f64;
|
||||
let bottom_right = corner_radius.bottom_right as f64;
|
||||
let bottom_left = corner_radius.bottom_left as f64;
|
||||
|
||||
[
|
||||
Rectangle::from_loc_and_size(geo.loc, (top_left, top_left)),
|
||||
Rectangle::from_loc_and_size(
|
||||
(geo.loc.x + geo.size.w - top_right, geo.loc.y),
|
||||
(top_right, top_right),
|
||||
),
|
||||
Rectangle::from_loc_and_size(
|
||||
(
|
||||
geo.loc.x + geo.size.w - bottom_right,
|
||||
geo.loc.y + geo.size.h - bottom_right,
|
||||
),
|
||||
(bottom_right, bottom_right),
|
||||
),
|
||||
Rectangle::from_loc_and_size(
|
||||
(geo.loc.x, geo.loc.y + geo.size.h - bottom_left),
|
||||
(bottom_left, bottom_left),
|
||||
),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: NiriRenderer> Element for ClippedSurfaceRenderElement<R> {
|
||||
fn id(&self) -> &Id {
|
||||
self.inner.id()
|
||||
}
|
||||
|
||||
fn current_commit(&self) -> CommitCounter {
|
||||
self.inner.current_commit()
|
||||
}
|
||||
|
||||
fn geometry(&self, scale: Scale<f64>) -> Rectangle<i32, Physical> {
|
||||
self.inner.geometry(scale)
|
||||
}
|
||||
|
||||
fn src(&self) -> Rectangle<f64, Buffer> {
|
||||
self.inner.src()
|
||||
}
|
||||
|
||||
fn transform(&self) -> Transform {
|
||||
self.inner.transform()
|
||||
}
|
||||
|
||||
fn damage_since(
|
||||
&self,
|
||||
scale: Scale<f64>,
|
||||
commit: Option<CommitCounter>,
|
||||
) -> DamageSet<i32, Physical> {
|
||||
// FIXME: radius changes need to cause damage.
|
||||
let damage = self.inner.damage_since(scale, commit);
|
||||
|
||||
// Intersect with geometry, since we're clipping by it.
|
||||
let mut geo = self.geometry.to_physical_precise_round(scale);
|
||||
geo.loc -= self.geometry(scale).loc;
|
||||
damage
|
||||
.into_iter()
|
||||
.filter_map(|rect| rect.intersection(geo))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn opaque_regions(&self, scale: Scale<f64>) -> OpaqueRegions<i32, Physical> {
|
||||
let regions = self.inner.opaque_regions(scale);
|
||||
|
||||
// Intersect with geometry, since we're clipping by it.
|
||||
let mut geo = self.geometry.to_physical_precise_round(scale);
|
||||
geo.loc -= self.geometry(scale).loc;
|
||||
let regions = regions
|
||||
.into_iter()
|
||||
.filter_map(|rect| rect.intersection(geo));
|
||||
|
||||
// Subtract the rounded corners.
|
||||
if self.corner_radius == CornerRadius::default() {
|
||||
regions.collect()
|
||||
} else {
|
||||
let corners = Self::rounded_corners(self.geometry.to_f64(), self.corner_radius);
|
||||
|
||||
let elem_loc = self.geometry(scale).loc;
|
||||
let corners = corners.into_iter().map(|rect| {
|
||||
let mut rect = rect.to_physical_precise_round(scale);
|
||||
rect.loc -= elem_loc;
|
||||
rect
|
||||
});
|
||||
|
||||
OpaqueRegions::from_slice(&Rectangle::subtract_rects_many(regions, corners))
|
||||
}
|
||||
}
|
||||
|
||||
fn alpha(&self) -> f32 {
|
||||
self.inner.alpha()
|
||||
}
|
||||
|
||||
fn kind(&self) -> Kind {
|
||||
self.inner.kind()
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderElement<GlesRenderer> for ClippedSurfaceRenderElement<GlesRenderer> {
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut GlesFrame<'_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dst: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), GlesError> {
|
||||
frame.override_default_tex_program(
|
||||
self.program.clone(),
|
||||
vec![
|
||||
Uniform::new(
|
||||
"geo_size",
|
||||
(self.geometry.size.w as f32, self.geometry.size.h as f32),
|
||||
),
|
||||
Uniform::new("corner_radius", <[f32; 4]>::from(self.corner_radius)),
|
||||
mat3_uniform("input_to_geo", self.input_to_geo),
|
||||
],
|
||||
);
|
||||
RenderElement::<GlesRenderer>::draw(&self.inner, frame, src, dst, damage)?;
|
||||
frame.clear_tex_program_override();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn underlying_storage(&self, _renderer: &mut GlesRenderer) -> Option<UnderlyingStorage> {
|
||||
// If scanout for things other than Wayland buffers is implemented, this will need to take
|
||||
// the target GPU into account.
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<'render> RenderElement<TtyRenderer<'render>>
|
||||
for ClippedSurfaceRenderElement<TtyRenderer<'render>>
|
||||
{
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut TtyFrame<'render, '_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dst: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), TtyRendererError<'render>> {
|
||||
frame.as_gles_frame().override_default_tex_program(
|
||||
self.program.clone(),
|
||||
vec![
|
||||
Uniform::new(
|
||||
"geo_size",
|
||||
(self.geometry.size.w as f32, self.geometry.size.h as f32),
|
||||
),
|
||||
Uniform::new("corner_radius", <[f32; 4]>::from(self.corner_radius)),
|
||||
mat3_uniform("input_to_geo", self.input_to_geo),
|
||||
],
|
||||
);
|
||||
RenderElement::draw(&self.inner, frame, src, dst, damage)?;
|
||||
frame.as_gles_frame().clear_tex_program_override();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn underlying_storage(
|
||||
&self,
|
||||
_renderer: &mut TtyRenderer<'render>,
|
||||
) -> Option<UnderlyingStorage> {
|
||||
// If scanout for things other than Wayland buffers is implemented, this will need to take
|
||||
// the target GPU into account.
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl RoundedCornerDamage {
|
||||
pub fn set_size(&mut self, size: Size<i32, Logical>) {
|
||||
self.damage.set_size(size);
|
||||
}
|
||||
|
||||
pub fn set_corner_radius(&mut self, corner_radius: CornerRadius) {
|
||||
if self.corner_radius == corner_radius {
|
||||
return;
|
||||
}
|
||||
|
||||
// FIXME: make the damage granular.
|
||||
self.corner_radius = corner_radius;
|
||||
self.damage.damage_all();
|
||||
}
|
||||
|
||||
pub fn element(&self) -> ExtraDamage {
|
||||
self.damage.clone()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
use smithay::backend::renderer::element::{Element, Id, RenderElement};
|
||||
use smithay::backend::renderer::utils::CommitCounter;
|
||||
use smithay::backend::renderer::Renderer;
|
||||
use smithay::utils::{Buffer, Logical, Physical, Point, Rectangle, Scale, Size};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExtraDamage {
|
||||
id: Id,
|
||||
commit: CommitCounter,
|
||||
geometry: Rectangle<i32, Logical>,
|
||||
}
|
||||
|
||||
impl ExtraDamage {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
id: Id::new(),
|
||||
commit: Default::default(),
|
||||
geometry: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_size(&mut self, size: Size<i32, Logical>) {
|
||||
if self.geometry.size == size {
|
||||
return;
|
||||
}
|
||||
|
||||
self.geometry.size = size;
|
||||
self.commit.increment();
|
||||
}
|
||||
|
||||
pub fn damage_all(&mut self) {
|
||||
self.commit.increment();
|
||||
}
|
||||
|
||||
pub fn with_location(mut self, location: Point<i32, Logical>) -> Self {
|
||||
self.geometry.loc = location;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ExtraDamage {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Element for ExtraDamage {
|
||||
fn id(&self) -> &Id {
|
||||
&self.id
|
||||
}
|
||||
|
||||
fn current_commit(&self) -> CommitCounter {
|
||||
self.commit
|
||||
}
|
||||
|
||||
fn src(&self) -> Rectangle<f64, Buffer> {
|
||||
Rectangle::from_loc_and_size((0., 0.), (1., 1.))
|
||||
}
|
||||
|
||||
fn geometry(&self, scale: Scale<f64>) -> Rectangle<i32, Physical> {
|
||||
self.geometry.to_physical_precise_round(scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Renderer> RenderElement<R> for ExtraDamage {
|
||||
fn draw(
|
||||
&self,
|
||||
_frame: &mut <R as Renderer>::Frame<'_>,
|
||||
_src: Rectangle<f64, Buffer>,
|
||||
_dst: Rectangle<i32, Physical>,
|
||||
_damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), R::Error> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
use smithay::backend::renderer::damage::OutputDamageTracker;
|
||||
use smithay::backend::renderer::element::solid::SolidColorRenderElement;
|
||||
use smithay::backend::renderer::element::{Element, Id, Kind};
|
||||
use smithay::backend::renderer::utils::CommitCounter;
|
||||
use smithay::utils::Scale;
|
||||
|
||||
use super::renderer::NiriRenderer;
|
||||
use crate::niri::OutputRenderElements;
|
||||
|
||||
pub fn draw_opaque_regions<R: NiriRenderer>(
|
||||
elements: &mut Vec<OutputRenderElements<R>>,
|
||||
scale: Scale<f64>,
|
||||
) {
|
||||
let _span = tracy_client::span!("draw_opaque_regions");
|
||||
|
||||
let mut i = 0;
|
||||
while i < elements.len() {
|
||||
let elem = &elements[i];
|
||||
i += 1;
|
||||
|
||||
// HACK
|
||||
if format!("{elem:?}").contains("ExtraDamage") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let geo = elem.geometry(scale);
|
||||
let mut opaque = elem.opaque_regions(scale).to_vec();
|
||||
|
||||
for rect in &mut opaque {
|
||||
rect.loc += geo.loc;
|
||||
}
|
||||
|
||||
let semitransparent = geo.subtract_rects(opaque.iter().copied());
|
||||
|
||||
for rect in opaque {
|
||||
let color = SolidColorRenderElement::new(
|
||||
Id::new(),
|
||||
rect,
|
||||
CommitCounter::default(),
|
||||
[0., 0., 0.2, 0.2],
|
||||
Kind::Unspecified,
|
||||
);
|
||||
elements.insert(i - 1, OutputRenderElements::SolidColor(color));
|
||||
i += 1;
|
||||
}
|
||||
|
||||
for rect in semitransparent {
|
||||
let color = SolidColorRenderElement::new(
|
||||
Id::new(),
|
||||
rect,
|
||||
CommitCounter::default(),
|
||||
[0.3, 0., 0., 0.3],
|
||||
Kind::Unspecified,
|
||||
);
|
||||
elements.insert(i - 1, OutputRenderElements::SolidColor(color));
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_damage<R: NiriRenderer>(
|
||||
damage_tracker: &mut OutputDamageTracker,
|
||||
elements: &mut Vec<OutputRenderElements<R>>,
|
||||
) {
|
||||
let _span = tracy_client::span!("draw_damage");
|
||||
|
||||
let Ok((Some(damage), _)) = damage_tracker.damage_output(1, elements) else {
|
||||
return;
|
||||
};
|
||||
|
||||
for rect in damage {
|
||||
let color = SolidColorRenderElement::new(
|
||||
Id::new(),
|
||||
*rect,
|
||||
CommitCounter::default(),
|
||||
[0.3, 0., 0., 0.3],
|
||||
Kind::Unspecified,
|
||||
);
|
||||
elements.insert(0, OutputRenderElements::SolidColor(color));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
use std::ptr;
|
||||
|
||||
use anyhow::{ensure, Context};
|
||||
use niri_config::BlockOutFrom;
|
||||
use smithay::backend::allocator::Fourcc;
|
||||
use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
|
||||
use smithay::backend::renderer::element::texture::{TextureBuffer, TextureRenderElement};
|
||||
use smithay::backend::renderer::element::utils::{Relocate, RelocateRenderElement};
|
||||
use smithay::backend::renderer::element::{Kind, RenderElement};
|
||||
use smithay::backend::renderer::gles::{GlesMapping, GlesRenderer, GlesTexture};
|
||||
use smithay::backend::renderer::sync::SyncPoint;
|
||||
use smithay::backend::renderer::{buffer_dimensions, Bind, ExportMem, Frame, Offscreen, Renderer};
|
||||
use smithay::reexports::wayland_server::protocol::wl_buffer::WlBuffer;
|
||||
use smithay::reexports::wayland_server::protocol::wl_shm;
|
||||
use smithay::utils::{Logical, Physical, Point, Rectangle, Scale, Size, Transform};
|
||||
use smithay::wayland::shm;
|
||||
|
||||
use self::primary_gpu_texture::PrimaryGpuTextureRenderElement;
|
||||
|
||||
pub mod border;
|
||||
pub mod clipped_surface;
|
||||
pub mod damage;
|
||||
pub mod debug;
|
||||
pub mod offscreen;
|
||||
pub mod primary_gpu_texture;
|
||||
pub mod render_elements;
|
||||
pub mod renderer;
|
||||
pub mod resize;
|
||||
pub mod resources;
|
||||
pub mod shader_element;
|
||||
pub mod shaders;
|
||||
pub mod snapshot;
|
||||
pub mod surface;
|
||||
|
||||
/// What we're rendering for.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RenderTarget {
|
||||
/// Rendering to display on screen.
|
||||
Output,
|
||||
/// Rendering for a screencast.
|
||||
Screencast,
|
||||
/// Rendering for any other screen capture.
|
||||
ScreenCapture,
|
||||
}
|
||||
|
||||
/// Buffer with location, src and dst.
|
||||
#[derive(Debug)]
|
||||
pub struct BakedBuffer<B> {
|
||||
pub buffer: B,
|
||||
pub location: Point<i32, Logical>,
|
||||
pub src: Option<Rectangle<f64, Logical>>,
|
||||
pub dst: Option<Size<i32, Logical>>,
|
||||
}
|
||||
|
||||
/// Render elements split into normal and popup.
|
||||
#[derive(Debug)]
|
||||
pub struct SplitElements<E> {
|
||||
pub normal: Vec<E>,
|
||||
pub popups: Vec<E>,
|
||||
}
|
||||
|
||||
pub trait ToRenderElement {
|
||||
type RenderElement;
|
||||
|
||||
fn to_render_element(
|
||||
&self,
|
||||
location: Point<i32, Logical>,
|
||||
scale: Scale<f64>,
|
||||
alpha: f32,
|
||||
kind: Kind,
|
||||
) -> Self::RenderElement;
|
||||
}
|
||||
|
||||
impl RenderTarget {
|
||||
pub fn should_block_out(self, block_out_from: Option<BlockOutFrom>) -> bool {
|
||||
match block_out_from {
|
||||
None => false,
|
||||
Some(BlockOutFrom::Screencast) => self == RenderTarget::Screencast,
|
||||
Some(BlockOutFrom::ScreenCapture) => self != RenderTarget::Output,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> Default for SplitElements<E> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
normal: Vec::new(),
|
||||
popups: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> IntoIterator for SplitElements<E> {
|
||||
type Item = E;
|
||||
type IntoIter = std::iter::Chain<std::vec::IntoIter<E>, std::vec::IntoIter<E>>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.popups.into_iter().chain(self.normal)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> SplitElements<E> {
|
||||
pub fn iter(&self) -> std::iter::Chain<std::slice::Iter<E>, std::slice::Iter<E>> {
|
||||
self.popups.iter().chain(&self.normal)
|
||||
}
|
||||
|
||||
pub fn into_vec(self) -> Vec<E> {
|
||||
let Self { normal, mut popups } = self;
|
||||
popups.extend(normal);
|
||||
popups
|
||||
}
|
||||
}
|
||||
|
||||
impl ToRenderElement for BakedBuffer<TextureBuffer<GlesTexture>> {
|
||||
type RenderElement = PrimaryGpuTextureRenderElement;
|
||||
|
||||
fn to_render_element(
|
||||
&self,
|
||||
location: Point<i32, Logical>,
|
||||
scale: Scale<f64>,
|
||||
alpha: f32,
|
||||
kind: Kind,
|
||||
) -> Self::RenderElement {
|
||||
let elem = TextureRenderElement::from_texture_buffer(
|
||||
(location + self.location).to_physical_precise_round(scale),
|
||||
&self.buffer,
|
||||
Some(alpha),
|
||||
self.src,
|
||||
self.dst,
|
||||
kind,
|
||||
);
|
||||
PrimaryGpuTextureRenderElement(elem)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToRenderElement for BakedBuffer<SolidColorBuffer> {
|
||||
type RenderElement = SolidColorRenderElement;
|
||||
|
||||
fn to_render_element(
|
||||
&self,
|
||||
location: Point<i32, Logical>,
|
||||
scale: Scale<f64>,
|
||||
alpha: f32,
|
||||
kind: Kind,
|
||||
) -> Self::RenderElement {
|
||||
SolidColorRenderElement::from_buffer(
|
||||
&self.buffer,
|
||||
(location + self.location)
|
||||
.to_physical_precise_round(scale)
|
||||
.to_i32_round(),
|
||||
scale,
|
||||
alpha,
|
||||
kind,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render_to_encompassing_texture(
|
||||
renderer: &mut GlesRenderer,
|
||||
scale: Scale<f64>,
|
||||
transform: Transform,
|
||||
fourcc: Fourcc,
|
||||
elements: &[impl RenderElement<GlesRenderer>],
|
||||
) -> anyhow::Result<(GlesTexture, SyncPoint, Rectangle<i32, Physical>)> {
|
||||
let geo = elements
|
||||
.iter()
|
||||
.map(|ele| ele.geometry(scale))
|
||||
.reduce(|a, b| a.merge(b))
|
||||
.unwrap_or_default();
|
||||
let elements = elements.iter().rev().map(|ele| {
|
||||
RelocateRenderElement::from_element(ele, (-geo.loc.x, -geo.loc.y), Relocate::Relative)
|
||||
});
|
||||
|
||||
let (texture, sync_point) =
|
||||
render_to_texture(renderer, geo.size, scale, transform, fourcc, elements)?;
|
||||
|
||||
Ok((texture, sync_point, geo))
|
||||
}
|
||||
|
||||
pub fn render_to_texture(
|
||||
renderer: &mut GlesRenderer,
|
||||
size: Size<i32, Physical>,
|
||||
scale: Scale<f64>,
|
||||
transform: Transform,
|
||||
fourcc: Fourcc,
|
||||
elements: impl Iterator<Item = impl RenderElement<GlesRenderer>>,
|
||||
) -> anyhow::Result<(GlesTexture, SyncPoint)> {
|
||||
let _span = tracy_client::span!();
|
||||
|
||||
let buffer_size = size.to_logical(1).to_buffer(1, Transform::Normal);
|
||||
|
||||
let texture: GlesTexture = renderer
|
||||
.create_buffer(fourcc, buffer_size)
|
||||
.context("error creating texture")?;
|
||||
|
||||
renderer
|
||||
.bind(texture.clone())
|
||||
.context("error binding texture")?;
|
||||
|
||||
let sync_point = render_elements(renderer, size, scale, transform, elements)?;
|
||||
Ok((texture, sync_point))
|
||||
}
|
||||
|
||||
pub fn render_and_download(
|
||||
renderer: &mut GlesRenderer,
|
||||
size: Size<i32, Physical>,
|
||||
scale: Scale<f64>,
|
||||
transform: Transform,
|
||||
fourcc: Fourcc,
|
||||
elements: impl Iterator<Item = impl RenderElement<GlesRenderer>>,
|
||||
) -> anyhow::Result<GlesMapping> {
|
||||
let _span = tracy_client::span!();
|
||||
|
||||
let (_, _) = render_to_texture(renderer, size, scale, transform, fourcc, elements)?;
|
||||
|
||||
let buffer_size = size.to_logical(1).to_buffer(1, Transform::Normal);
|
||||
let mapping = renderer
|
||||
.copy_framebuffer(Rectangle::from_loc_and_size((0, 0), buffer_size), fourcc)
|
||||
.context("error copying framebuffer")?;
|
||||
Ok(mapping)
|
||||
}
|
||||
|
||||
pub fn render_to_vec(
|
||||
renderer: &mut GlesRenderer,
|
||||
size: Size<i32, Physical>,
|
||||
scale: Scale<f64>,
|
||||
transform: Transform,
|
||||
fourcc: Fourcc,
|
||||
elements: impl Iterator<Item = impl RenderElement<GlesRenderer>>,
|
||||
) -> anyhow::Result<Vec<u8>> {
|
||||
let _span = tracy_client::span!();
|
||||
|
||||
let mapping = render_and_download(renderer, size, scale, transform, fourcc, elements)
|
||||
.context("error rendering")?;
|
||||
let copy = renderer
|
||||
.map_texture(&mapping)
|
||||
.context("error mapping texture")?;
|
||||
Ok(copy.to_vec())
|
||||
}
|
||||
|
||||
#[cfg(feature = "xdp-gnome-screencast")]
|
||||
pub fn render_to_dmabuf(
|
||||
renderer: &mut GlesRenderer,
|
||||
dmabuf: smithay::backend::allocator::dmabuf::Dmabuf,
|
||||
size: Size<i32, Physical>,
|
||||
scale: Scale<f64>,
|
||||
transform: Transform,
|
||||
elements: impl Iterator<Item = impl RenderElement<GlesRenderer>>,
|
||||
) -> anyhow::Result<SyncPoint> {
|
||||
let _span = tracy_client::span!();
|
||||
renderer.bind(dmabuf).context("error binding texture")?;
|
||||
render_elements(renderer, size, scale, transform, elements)
|
||||
}
|
||||
|
||||
pub fn render_to_shm(
|
||||
renderer: &mut GlesRenderer,
|
||||
buffer: &WlBuffer,
|
||||
scale: Scale<f64>,
|
||||
transform: Transform,
|
||||
elements: impl Iterator<Item = impl RenderElement<GlesRenderer>>,
|
||||
) -> anyhow::Result<()> {
|
||||
let _span = tracy_client::span!();
|
||||
|
||||
let buffer_size = buffer_dimensions(buffer).context("error getting buffer dimensions")?;
|
||||
let size = buffer_size.to_logical(1, Transform::Normal).to_physical(1);
|
||||
|
||||
let mapping =
|
||||
render_and_download(renderer, size, scale, transform, Fourcc::Argb8888, elements)?;
|
||||
let bytes = renderer
|
||||
.map_texture(&mapping)
|
||||
.context("error mapping texture")?;
|
||||
|
||||
shm::with_buffer_contents_mut(buffer, |shm_buffer, shm_len, buffer_data| {
|
||||
ensure!(
|
||||
// The buffer prefers pixels in little endian ...
|
||||
buffer_data.format == wl_shm::Format::Argb8888
|
||||
&& buffer_data.stride == size.w * 4
|
||||
&& buffer_data.height == size.h
|
||||
&& shm_len as i32 == buffer_data.stride * buffer_data.height,
|
||||
"invalid buffer format or size"
|
||||
);
|
||||
|
||||
ensure!(bytes.len() == shm_len, "mapped buffer has wrong length");
|
||||
|
||||
unsafe {
|
||||
let _span = tracy_client::span!("copy_nonoverlapping");
|
||||
ptr::copy_nonoverlapping(bytes.as_ptr(), shm_buffer.cast(), shm_len);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.context("expected shm buffer, but didn't get one")?
|
||||
}
|
||||
|
||||
fn render_elements(
|
||||
renderer: &mut GlesRenderer,
|
||||
size: Size<i32, Physical>,
|
||||
scale: Scale<f64>,
|
||||
transform: Transform,
|
||||
elements: impl Iterator<Item = impl RenderElement<GlesRenderer>>,
|
||||
) -> anyhow::Result<SyncPoint> {
|
||||
let transform = transform.invert();
|
||||
let output_rect = Rectangle::from_loc_and_size((0, 0), transform.transform_size(size));
|
||||
|
||||
let mut frame = renderer
|
||||
.render(size, transform)
|
||||
.context("error starting frame")?;
|
||||
|
||||
frame
|
||||
.clear([0., 0., 0., 0.], &[output_rect])
|
||||
.context("error clearing")?;
|
||||
|
||||
for element in elements {
|
||||
let src = element.src();
|
||||
let dst = element.geometry(scale);
|
||||
|
||||
if let Some(mut damage) = output_rect.intersection(dst) {
|
||||
damage.loc -= dst.loc;
|
||||
element
|
||||
.draw(&mut frame, src, dst, &[damage])
|
||||
.context("error drawing element")?;
|
||||
}
|
||||
}
|
||||
|
||||
frame.finish().context("error finishing frame")
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
use smithay::backend::allocator::Fourcc;
|
||||
use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
|
||||
use smithay::backend::renderer::element::texture::{TextureBuffer, TextureRenderElement};
|
||||
use smithay::backend::renderer::element::utils::{Relocate, RelocateRenderElement};
|
||||
use smithay::backend::renderer::element::{Element, Id, Kind, RenderElement, UnderlyingStorage};
|
||||
use smithay::backend::renderer::gles::{GlesError, GlesFrame, GlesRenderer};
|
||||
use smithay::backend::renderer::utils::{CommitCounter, DamageSet, OpaqueRegions};
|
||||
use smithay::utils::{Buffer, Physical, Rectangle, Scale, Transform};
|
||||
|
||||
use super::primary_gpu_texture::PrimaryGpuTextureRenderElement;
|
||||
use super::render_to_texture;
|
||||
use super::renderer::AsGlesFrame;
|
||||
use crate::backend::tty::{TtyFrame, TtyRenderer, TtyRendererError};
|
||||
|
||||
/// Renders elements into an off-screen buffer.
|
||||
#[derive(Debug)]
|
||||
pub struct OffscreenRenderElement {
|
||||
// The texture, if rendering succeeded.
|
||||
texture: Option<PrimaryGpuTextureRenderElement>,
|
||||
// The fallback buffer in case the rendering fails.
|
||||
fallback: SolidColorRenderElement,
|
||||
}
|
||||
|
||||
impl OffscreenRenderElement {
|
||||
pub fn new(
|
||||
renderer: &mut GlesRenderer,
|
||||
scale: i32,
|
||||
elements: &[impl RenderElement<GlesRenderer>],
|
||||
result_alpha: f32,
|
||||
) -> Self {
|
||||
let _span = tracy_client::span!("OffscreenRenderElement::new");
|
||||
|
||||
let geo = elements
|
||||
.iter()
|
||||
.map(|ele| ele.geometry(Scale::from(f64::from(scale))))
|
||||
.reduce(|a, b| a.merge(b))
|
||||
.unwrap_or_default();
|
||||
let logical_size = geo.size.to_logical(scale);
|
||||
|
||||
let fallback_buffer = SolidColorBuffer::new(logical_size, [1., 0., 0., 1.]);
|
||||
let fallback = SolidColorRenderElement::from_buffer(
|
||||
&fallback_buffer,
|
||||
geo.loc,
|
||||
Scale::from(scale as f64),
|
||||
result_alpha,
|
||||
Kind::Unspecified,
|
||||
);
|
||||
|
||||
let elements = elements.iter().rev().map(|ele| {
|
||||
RelocateRenderElement::from_element(ele, (-geo.loc.x, -geo.loc.y), Relocate::Relative)
|
||||
});
|
||||
|
||||
match render_to_texture(
|
||||
renderer,
|
||||
geo.size,
|
||||
Scale::from(scale as f64),
|
||||
Transform::Normal,
|
||||
Fourcc::Abgr8888,
|
||||
elements,
|
||||
) {
|
||||
Ok((texture, _sync_point)) => {
|
||||
let buffer =
|
||||
TextureBuffer::from_texture(renderer, texture, scale, Transform::Normal, None);
|
||||
let element = TextureRenderElement::from_texture_buffer(
|
||||
geo.loc.to_f64(),
|
||||
&buffer,
|
||||
Some(result_alpha),
|
||||
None,
|
||||
None,
|
||||
Kind::Unspecified,
|
||||
);
|
||||
Self {
|
||||
texture: Some(PrimaryGpuTextureRenderElement(element)),
|
||||
fallback,
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("error off-screening elements: {err:?}");
|
||||
Self {
|
||||
texture: None,
|
||||
fallback,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Element for OffscreenRenderElement {
|
||||
fn id(&self) -> &Id {
|
||||
if let Some(texture) = &self.texture {
|
||||
texture.id()
|
||||
} else {
|
||||
self.fallback.id()
|
||||
}
|
||||
}
|
||||
|
||||
fn current_commit(&self) -> CommitCounter {
|
||||
if let Some(texture) = &self.texture {
|
||||
texture.current_commit()
|
||||
} else {
|
||||
self.fallback.current_commit()
|
||||
}
|
||||
}
|
||||
|
||||
fn geometry(&self, scale: Scale<f64>) -> Rectangle<i32, Physical> {
|
||||
if let Some(texture) = &self.texture {
|
||||
texture.geometry(scale)
|
||||
} else {
|
||||
self.fallback.geometry(scale)
|
||||
}
|
||||
}
|
||||
|
||||
fn transform(&self) -> Transform {
|
||||
if let Some(texture) = &self.texture {
|
||||
texture.transform()
|
||||
} else {
|
||||
self.fallback.transform()
|
||||
}
|
||||
}
|
||||
|
||||
fn src(&self) -> Rectangle<f64, Buffer> {
|
||||
if let Some(texture) = &self.texture {
|
||||
texture.src()
|
||||
} else {
|
||||
self.fallback.src()
|
||||
}
|
||||
}
|
||||
|
||||
fn damage_since(
|
||||
&self,
|
||||
scale: Scale<f64>,
|
||||
commit: Option<CommitCounter>,
|
||||
) -> DamageSet<i32, Physical> {
|
||||
if let Some(texture) = &self.texture {
|
||||
texture.damage_since(scale, commit)
|
||||
} else {
|
||||
self.fallback.damage_since(scale, commit)
|
||||
}
|
||||
}
|
||||
|
||||
fn opaque_regions(&self, scale: Scale<f64>) -> OpaqueRegions<i32, Physical> {
|
||||
if let Some(texture) = &self.texture {
|
||||
texture.opaque_regions(scale)
|
||||
} else {
|
||||
self.fallback.opaque_regions(scale)
|
||||
}
|
||||
}
|
||||
|
||||
fn alpha(&self) -> f32 {
|
||||
if let Some(texture) = &self.texture {
|
||||
texture.alpha()
|
||||
} else {
|
||||
self.fallback.alpha()
|
||||
}
|
||||
}
|
||||
|
||||
fn kind(&self) -> Kind {
|
||||
if let Some(texture) = &self.texture {
|
||||
texture.kind()
|
||||
} else {
|
||||
self.fallback.kind()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderElement<GlesRenderer> for OffscreenRenderElement {
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut GlesFrame<'_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dst: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), GlesError> {
|
||||
let gles_frame = frame.as_gles_frame();
|
||||
if let Some(texture) = &self.texture {
|
||||
RenderElement::<GlesRenderer>::draw(texture, gles_frame, src, dst, damage)?;
|
||||
} else {
|
||||
RenderElement::<GlesRenderer>::draw(&self.fallback, gles_frame, src, dst, damage)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn underlying_storage(&self, renderer: &mut GlesRenderer) -> Option<UnderlyingStorage> {
|
||||
if let Some(texture) = &self.texture {
|
||||
texture.underlying_storage(renderer)
|
||||
} else {
|
||||
self.fallback.underlying_storage(renderer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'render> RenderElement<TtyRenderer<'render>> for OffscreenRenderElement {
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut TtyFrame<'_, '_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dst: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), TtyRendererError<'render>> {
|
||||
let gles_frame = frame.as_gles_frame();
|
||||
if let Some(texture) = &self.texture {
|
||||
RenderElement::<GlesRenderer>::draw(texture, gles_frame, src, dst, damage)?;
|
||||
} else {
|
||||
RenderElement::<GlesRenderer>::draw(&self.fallback, gles_frame, src, dst, damage)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn underlying_storage(&self, renderer: &mut TtyRenderer<'render>) -> Option<UnderlyingStorage> {
|
||||
if let Some(texture) = &self.texture {
|
||||
texture.underlying_storage(renderer)
|
||||
} else {
|
||||
self.fallback.underlying_storage(renderer)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
use smithay::backend::renderer::element::texture::TextureRenderElement;
|
||||
use smithay::backend::renderer::element::{Element, Id, Kind, RenderElement, UnderlyingStorage};
|
||||
use smithay::backend::renderer::gles::{GlesError, GlesFrame, GlesRenderer, GlesTexture};
|
||||
use smithay::backend::renderer::utils::{CommitCounter, DamageSet, OpaqueRegions};
|
||||
use smithay::utils::{Buffer, Physical, Rectangle, Scale, Transform};
|
||||
|
||||
use super::renderer::AsGlesFrame;
|
||||
use crate::backend::tty::{TtyFrame, TtyRenderer, TtyRendererError};
|
||||
|
||||
/// Wrapper for a texture from the primary GPU for rendering with the primary GPU.
|
||||
#[derive(Debug)]
|
||||
pub struct PrimaryGpuTextureRenderElement(pub TextureRenderElement<GlesTexture>);
|
||||
|
||||
impl Element for PrimaryGpuTextureRenderElement {
|
||||
fn id(&self) -> &Id {
|
||||
self.0.id()
|
||||
}
|
||||
|
||||
fn current_commit(&self) -> CommitCounter {
|
||||
self.0.current_commit()
|
||||
}
|
||||
|
||||
fn geometry(&self, scale: Scale<f64>) -> Rectangle<i32, Physical> {
|
||||
self.0.geometry(scale)
|
||||
}
|
||||
|
||||
fn transform(&self) -> Transform {
|
||||
self.0.transform()
|
||||
}
|
||||
|
||||
fn src(&self) -> Rectangle<f64, Buffer> {
|
||||
self.0.src()
|
||||
}
|
||||
|
||||
fn damage_since(
|
||||
&self,
|
||||
scale: Scale<f64>,
|
||||
commit: Option<CommitCounter>,
|
||||
) -> DamageSet<i32, Physical> {
|
||||
self.0.damage_since(scale, commit)
|
||||
}
|
||||
|
||||
fn opaque_regions(&self, scale: Scale<f64>) -> OpaqueRegions<i32, Physical> {
|
||||
self.0.opaque_regions(scale)
|
||||
}
|
||||
|
||||
fn alpha(&self) -> f32 {
|
||||
self.0.alpha()
|
||||
}
|
||||
|
||||
fn kind(&self) -> Kind {
|
||||
self.0.kind()
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderElement<GlesRenderer> for PrimaryGpuTextureRenderElement {
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut GlesFrame<'_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dst: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), GlesError> {
|
||||
let gles_frame = frame.as_gles_frame();
|
||||
RenderElement::<GlesRenderer>::draw(&self.0, gles_frame, src, dst, damage)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn underlying_storage(&self, _renderer: &mut GlesRenderer) -> Option<UnderlyingStorage> {
|
||||
// If scanout for things other than Wayland buffers is implemented, this will need to take
|
||||
// the target GPU into account.
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<'render> RenderElement<TtyRenderer<'render>> for PrimaryGpuTextureRenderElement {
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut TtyFrame<'_, '_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dst: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), TtyRendererError<'render>> {
|
||||
let gles_frame = frame.as_gles_frame();
|
||||
RenderElement::<GlesRenderer>::draw(&self.0, gles_frame, src, dst, damage)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn underlying_storage(
|
||||
&self,
|
||||
_renderer: &mut TtyRenderer<'render>,
|
||||
) -> Option<UnderlyingStorage> {
|
||||
// If scanout for things other than Wayland buffers is implemented, this will need to take
|
||||
// the target GPU into account.
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// We need to implement RenderElement manually due to AsGlesFrame requirement.
|
||||
// This macro does it for us.
|
||||
#[macro_export]
|
||||
macro_rules! niri_render_elements {
|
||||
// The two callable variants: with <R> and without <R>. They include From impls because nested
|
||||
// repetitions ($type and $variant with + and $R with ?) don't work properly.
|
||||
($name:ident<R> => { $($variant:ident = $type:ty),+ $(,)? }) => {
|
||||
$crate::niri_render_elements!(@impl $name () ($name<R>) => { $($variant = $type),+ });
|
||||
|
||||
$(impl<R: $crate::render_helpers::renderer::NiriRenderer> From<$type> for $name<R> {
|
||||
fn from(x: $type) -> Self {
|
||||
Self::$variant(x)
|
||||
}
|
||||
})+
|
||||
};
|
||||
|
||||
($name:ident => { $($variant:ident = $type:ty),+ $(,)? }) => {
|
||||
$crate::niri_render_elements!(@impl $name ($name) () => { $($variant = $type),+ });
|
||||
|
||||
$(impl From<$type> for $name {
|
||||
fn from(x: $type) -> Self {
|
||||
Self::$variant(x)
|
||||
}
|
||||
})+
|
||||
};
|
||||
|
||||
// The internal variant that generates most of the code. $name_no_R and $name_R are necessary
|
||||
// for the impl RenderElement<SomeRenderer> for $name<SomeRenderer>: since $R does not appear
|
||||
// in this line, we cannot condition based on $R like elsewhere, so we condition on duplicate
|
||||
// names instead. Like this: $($name_R<SomeRenderer>)? $($name_no_R)? so only one is chosen.
|
||||
(@impl $name:ident ($($name_no_R:ident)?) ($($name_R:ident<$R:ident>)?) => { $($variant:ident = $type:ty),+ }) => {
|
||||
#[derive(Debug)]
|
||||
pub enum $name$(<$R: $crate::render_helpers::renderer::NiriRenderer>)? {
|
||||
$($variant($type)),+
|
||||
}
|
||||
|
||||
impl$(<$R: $crate::render_helpers::renderer::NiriRenderer>)? smithay::backend::renderer::element::Element for $name$(<$R>)? {
|
||||
fn id(&self) -> &smithay::backend::renderer::element::Id {
|
||||
match self {
|
||||
$($name::$variant(elem) => elem.id()),+
|
||||
}
|
||||
}
|
||||
|
||||
fn current_commit(&self) -> smithay::backend::renderer::utils::CommitCounter {
|
||||
match self {
|
||||
$($name::$variant(elem) => elem.current_commit()),+
|
||||
}
|
||||
}
|
||||
|
||||
fn geometry(&self, scale: smithay::utils::Scale<f64>) -> smithay::utils::Rectangle<i32, smithay::utils::Physical> {
|
||||
match self {
|
||||
$($name::$variant(elem) => elem.geometry(scale)),+
|
||||
}
|
||||
}
|
||||
|
||||
fn transform(&self) -> smithay::utils::Transform {
|
||||
match self {
|
||||
$($name::$variant(elem) => elem.transform()),+
|
||||
}
|
||||
}
|
||||
|
||||
fn src(&self) -> smithay::utils::Rectangle<f64, smithay::utils::Buffer> {
|
||||
match self {
|
||||
$($name::$variant(elem) => elem.src()),+
|
||||
}
|
||||
}
|
||||
|
||||
fn damage_since(
|
||||
&self,
|
||||
scale: smithay::utils::Scale<f64>,
|
||||
commit: Option<smithay::backend::renderer::utils::CommitCounter>,
|
||||
) -> smithay::backend::renderer::utils::DamageSet<i32, smithay::utils::Physical> {
|
||||
match self {
|
||||
$($name::$variant(elem) => elem.damage_since(scale, commit)),+
|
||||
}
|
||||
}
|
||||
|
||||
fn opaque_regions(&self, scale: smithay::utils::Scale<f64>) -> smithay::backend::renderer::utils::OpaqueRegions<i32, smithay::utils::Physical> {
|
||||
match self {
|
||||
$($name::$variant(elem) => elem.opaque_regions(scale)),+
|
||||
}
|
||||
}
|
||||
|
||||
fn alpha(&self) -> f32 {
|
||||
match self {
|
||||
$($name::$variant(elem) => elem.alpha()),+
|
||||
}
|
||||
}
|
||||
|
||||
fn kind(&self) -> smithay::backend::renderer::element::Kind {
|
||||
match self {
|
||||
$($name::$variant(elem) => elem.kind()),+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl smithay::backend::renderer::element::RenderElement<smithay::backend::renderer::gles::GlesRenderer>
|
||||
for $($name_R<smithay::backend::renderer::gles::GlesRenderer>)? $($name_no_R)?
|
||||
{
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut smithay::backend::renderer::gles::GlesFrame<'_>,
|
||||
src: smithay::utils::Rectangle<f64, smithay::utils::Buffer>,
|
||||
dst: smithay::utils::Rectangle<i32, smithay::utils::Physical>,
|
||||
damage: &[smithay::utils::Rectangle<i32, smithay::utils::Physical>],
|
||||
) -> Result<(), smithay::backend::renderer::gles::GlesError> {
|
||||
match self {
|
||||
$($name::$variant(elem) => {
|
||||
smithay::backend::renderer::element::RenderElement::<smithay::backend::renderer::gles::GlesRenderer>::draw(elem, frame, src, dst, damage)
|
||||
})+
|
||||
}
|
||||
}
|
||||
|
||||
fn underlying_storage(&self, renderer: &mut smithay::backend::renderer::gles::GlesRenderer) -> Option<smithay::backend::renderer::element::UnderlyingStorage> {
|
||||
match self {
|
||||
$($name::$variant(elem) => elem.underlying_storage(renderer)),+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'render> smithay::backend::renderer::element::RenderElement<$crate::backend::tty::TtyRenderer<'render>>
|
||||
for $($name_R<$crate::backend::tty::TtyRenderer<'render>>)? $($name_no_R)?
|
||||
{
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut $crate::backend::tty::TtyFrame<'render, '_>,
|
||||
src: smithay::utils::Rectangle<f64, smithay::utils::Buffer>,
|
||||
dst: smithay::utils::Rectangle<i32, smithay::utils::Physical>,
|
||||
damage: &[smithay::utils::Rectangle<i32, smithay::utils::Physical>],
|
||||
) -> Result<(), $crate::backend::tty::TtyRendererError<'render>> {
|
||||
match self {
|
||||
$($name::$variant(elem) => {
|
||||
smithay::backend::renderer::element::RenderElement::<$crate::backend::tty::TtyRenderer<'render>>::draw(elem, frame, src, dst, damage)
|
||||
})+
|
||||
}
|
||||
}
|
||||
|
||||
fn underlying_storage(
|
||||
&self,
|
||||
renderer: &mut $crate::backend::tty::TtyRenderer<'render>,
|
||||
) -> Option<smithay::backend::renderer::element::UnderlyingStorage> {
|
||||
match self {
|
||||
$($name::$variant(elem) => elem.underlying_storage(renderer)),+
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use smithay::backend::allocator::dmabuf::Dmabuf;
|
||||
use smithay::backend::renderer::gles::{GlesFrame, GlesRenderer, GlesTexture};
|
||||
use smithay::backend::renderer::{
|
||||
Bind, ExportMem, ImportAll, ImportMem, Offscreen, Renderer, Texture,
|
||||
};
|
||||
|
||||
use crate::backend::tty::{TtyFrame, TtyRenderer};
|
||||
|
||||
/// Trait with our main renderer requirements to save on the typing.
|
||||
pub trait NiriRenderer:
|
||||
ImportAll
|
||||
+ ImportMem
|
||||
+ ExportMem
|
||||
+ Bind<Dmabuf>
|
||||
+ Offscreen<GlesTexture>
|
||||
+ Renderer<TextureId = Self::NiriTextureId, Error = Self::NiriError>
|
||||
+ AsGlesRenderer
|
||||
{
|
||||
// Associated types to work around the instability of associated type bounds.
|
||||
type NiriTextureId: Texture + Clone + 'static;
|
||||
type NiriError: std::error::Error
|
||||
+ Send
|
||||
+ Sync
|
||||
+ From<<GlesRenderer as Renderer>::Error>
|
||||
+ 'static;
|
||||
}
|
||||
|
||||
impl<R> NiriRenderer for R
|
||||
where
|
||||
R: ImportAll + ImportMem + ExportMem + Bind<Dmabuf> + Offscreen<GlesTexture> + AsGlesRenderer,
|
||||
R::TextureId: Texture + Clone + 'static,
|
||||
R::Error: std::error::Error + Send + Sync + From<<GlesRenderer as Renderer>::Error> + 'static,
|
||||
{
|
||||
type NiriTextureId = R::TextureId;
|
||||
type NiriError = R::Error;
|
||||
}
|
||||
|
||||
/// Trait for getting the underlying `GlesRenderer`.
|
||||
pub trait AsGlesRenderer {
|
||||
fn as_gles_renderer(&mut self) -> &mut GlesRenderer;
|
||||
}
|
||||
|
||||
impl AsGlesRenderer for GlesRenderer {
|
||||
fn as_gles_renderer(&mut self) -> &mut GlesRenderer {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'render> AsGlesRenderer for TtyRenderer<'render> {
|
||||
fn as_gles_renderer(&mut self) -> &mut GlesRenderer {
|
||||
self.as_mut()
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for getting the underlying `GlesFrame`.
|
||||
pub trait AsGlesFrame<'frame>
|
||||
where
|
||||
Self: 'frame,
|
||||
{
|
||||
fn as_gles_frame(&mut self) -> &mut GlesFrame<'frame>;
|
||||
}
|
||||
|
||||
impl<'frame> AsGlesFrame<'frame> for GlesFrame<'frame> {
|
||||
fn as_gles_frame(&mut self) -> &mut GlesFrame<'frame> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'render, 'frame> AsGlesFrame<'frame> for TtyFrame<'render, 'frame> {
|
||||
fn as_gles_frame(&mut self) -> &mut GlesFrame<'frame> {
|
||||
self.as_mut()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use glam::{Mat3, Vec2};
|
||||
use niri_config::CornerRadius;
|
||||
use smithay::backend::renderer::element::{Element, Id, Kind, RenderElement, UnderlyingStorage};
|
||||
use smithay::backend::renderer::gles::{GlesError, GlesFrame, GlesRenderer, GlesTexture, Uniform};
|
||||
use smithay::backend::renderer::utils::{CommitCounter, DamageSet, OpaqueRegions};
|
||||
use smithay::utils::{Buffer, Logical, Physical, Rectangle, Scale, Size, Transform};
|
||||
|
||||
use super::renderer::{AsGlesFrame, NiriRenderer};
|
||||
use super::shader_element::ShaderRenderElement;
|
||||
use super::shaders::{mat3_uniform, ProgramType, Shaders};
|
||||
use crate::backend::tty::{TtyFrame, TtyRenderer, TtyRendererError};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ResizeRenderElement(ShaderRenderElement);
|
||||
|
||||
impl ResizeRenderElement {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
area: Rectangle<i32, Logical>,
|
||||
scale: Scale<f64>,
|
||||
texture_prev: (GlesTexture, Rectangle<i32, Physical>),
|
||||
size_prev: Size<i32, Logical>,
|
||||
texture_next: (GlesTexture, Rectangle<i32, Physical>),
|
||||
size_next: Size<i32, Logical>,
|
||||
progress: f32,
|
||||
clamped_progress: f32,
|
||||
corner_radius: CornerRadius,
|
||||
clip_to_geometry: bool,
|
||||
result_alpha: f32,
|
||||
) -> Self {
|
||||
let curr_geo = area;
|
||||
|
||||
let (texture_prev, tex_prev_geo) = texture_prev;
|
||||
let (texture_next, tex_next_geo) = texture_next;
|
||||
|
||||
let scale_prev = area.size.to_f64() / size_prev.to_f64();
|
||||
let scale_next = area.size.to_f64() / size_next.to_f64();
|
||||
|
||||
// Compute the area necessary to fit a crossfade.
|
||||
let tex_prev_geo_scaled = tex_prev_geo.to_f64().upscale(scale_prev);
|
||||
let tex_next_geo_scaled = tex_next_geo.to_f64().upscale(scale_next);
|
||||
let combined_geo = tex_prev_geo_scaled.merge(tex_next_geo_scaled);
|
||||
|
||||
let area = Rectangle::from_loc_and_size(
|
||||
area.loc + combined_geo.loc.to_logical(scale).to_i32_round(),
|
||||
combined_geo.size.to_logical(scale).to_i32_round(),
|
||||
);
|
||||
|
||||
// Convert Smithay types into glam types.
|
||||
let area_loc = Vec2::new(area.loc.x as f32, area.loc.y as f32);
|
||||
let area_size = Vec2::new(area.size.w as f32, area.size.h as f32);
|
||||
|
||||
let curr_geo_loc = Vec2::new(curr_geo.loc.x as f32, curr_geo.loc.y as f32);
|
||||
let curr_geo_size = Vec2::new(curr_geo.size.w as f32, curr_geo.size.h as f32);
|
||||
|
||||
let tex_prev_geo_loc = Vec2::new(tex_prev_geo.loc.x as f32, tex_prev_geo.loc.y as f32);
|
||||
let tex_prev_geo_size = Vec2::new(tex_prev_geo.size.w as f32, tex_prev_geo.size.h as f32);
|
||||
|
||||
let tex_next_geo_loc = Vec2::new(tex_next_geo.loc.x as f32, tex_next_geo.loc.y as f32);
|
||||
let tex_next_geo_size = Vec2::new(tex_next_geo.size.w as f32, tex_next_geo.size.h as f32);
|
||||
|
||||
let size_prev = Vec2::new(size_prev.w as f32, size_prev.h as f32);
|
||||
let size_next = Vec2::new(size_next.w as f32, size_next.h as f32);
|
||||
|
||||
let scale = Vec2::new(scale.x as f32, scale.y as f32);
|
||||
|
||||
// Compute the transformation matrices.
|
||||
let input_to_curr_geo = Mat3::from_scale(area_size / curr_geo_size)
|
||||
* Mat3::from_translation((area_loc - curr_geo_loc) / area_size);
|
||||
|
||||
let curr_geo_to_prev_geo = Mat3::from_scale(curr_geo_size / size_prev);
|
||||
let curr_geo_to_next_geo = Mat3::from_scale(curr_geo_size / size_next);
|
||||
|
||||
let geo_to_tex_prev = Mat3::from_translation(-tex_prev_geo_loc / tex_prev_geo_size)
|
||||
* Mat3::from_scale(size_prev / tex_prev_geo_size * scale);
|
||||
let geo_to_tex_next = Mat3::from_translation(-tex_next_geo_loc / tex_next_geo_size)
|
||||
* Mat3::from_scale(size_next / tex_next_geo_size * scale);
|
||||
|
||||
let corner_radius = corner_radius.fit_to(curr_geo_size.x, curr_geo_size.y);
|
||||
let clip_to_geometry = if clip_to_geometry { 1. } else { 0. };
|
||||
|
||||
// Create the shader.
|
||||
Self(
|
||||
ShaderRenderElement::new(
|
||||
ProgramType::Resize,
|
||||
area.size,
|
||||
None,
|
||||
result_alpha,
|
||||
vec![
|
||||
mat3_uniform("niri_input_to_curr_geo", input_to_curr_geo),
|
||||
mat3_uniform("niri_curr_geo_to_prev_geo", curr_geo_to_prev_geo),
|
||||
mat3_uniform("niri_curr_geo_to_next_geo", curr_geo_to_next_geo),
|
||||
Uniform::new("niri_curr_geo_size", curr_geo_size.to_array()),
|
||||
mat3_uniform("niri_geo_to_tex_prev", geo_to_tex_prev),
|
||||
mat3_uniform("niri_geo_to_tex_next", geo_to_tex_next),
|
||||
Uniform::new("niri_progress", progress),
|
||||
Uniform::new("niri_clamped_progress", clamped_progress),
|
||||
Uniform::new("niri_corner_radius", <[f32; 4]>::from(corner_radius)),
|
||||
Uniform::new("niri_clip_to_geometry", clip_to_geometry),
|
||||
],
|
||||
HashMap::from([
|
||||
(String::from("niri_tex_prev"), texture_prev),
|
||||
(String::from("niri_tex_next"), texture_next),
|
||||
]),
|
||||
Kind::Unspecified,
|
||||
)
|
||||
.with_location(area.loc),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn has_shader(renderer: &mut impl NiriRenderer) -> bool {
|
||||
Shaders::get(renderer)
|
||||
.program(ProgramType::Resize)
|
||||
.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
impl Element for ResizeRenderElement {
|
||||
fn id(&self) -> &Id {
|
||||
self.0.id()
|
||||
}
|
||||
|
||||
fn current_commit(&self) -> CommitCounter {
|
||||
self.0.current_commit()
|
||||
}
|
||||
|
||||
fn geometry(&self, scale: Scale<f64>) -> Rectangle<i32, Physical> {
|
||||
self.0.geometry(scale)
|
||||
}
|
||||
|
||||
fn transform(&self) -> Transform {
|
||||
self.0.transform()
|
||||
}
|
||||
|
||||
fn src(&self) -> Rectangle<f64, Buffer> {
|
||||
self.0.src()
|
||||
}
|
||||
|
||||
fn damage_since(
|
||||
&self,
|
||||
scale: Scale<f64>,
|
||||
commit: Option<CommitCounter>,
|
||||
) -> DamageSet<i32, Physical> {
|
||||
self.0.damage_since(scale, commit)
|
||||
}
|
||||
|
||||
fn opaque_regions(&self, scale: Scale<f64>) -> OpaqueRegions<i32, Physical> {
|
||||
self.0.opaque_regions(scale)
|
||||
}
|
||||
|
||||
fn alpha(&self) -> f32 {
|
||||
self.0.alpha()
|
||||
}
|
||||
|
||||
fn kind(&self) -> Kind {
|
||||
self.0.kind()
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderElement<GlesRenderer> for ResizeRenderElement {
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut GlesFrame<'_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dst: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), GlesError> {
|
||||
RenderElement::<GlesRenderer>::draw(&self.0, frame, src, dst, damage)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn underlying_storage(&self, renderer: &mut GlesRenderer) -> Option<UnderlyingStorage> {
|
||||
self.0.underlying_storage(renderer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'render> RenderElement<TtyRenderer<'render>> for ResizeRenderElement {
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut TtyFrame<'_, '_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dst: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), TtyRendererError<'render>> {
|
||||
let gles_frame = frame.as_gles_frame();
|
||||
RenderElement::<GlesRenderer>::draw(&self.0, gles_frame, src, dst, damage)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn underlying_storage(&self, renderer: &mut TtyRenderer<'render>) -> Option<UnderlyingStorage> {
|
||||
self.0.underlying_storage(renderer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use smithay::backend::renderer::gles::{ffi, Capability, GlesError, GlesFrame, GlesRenderer};
|
||||
|
||||
pub struct Resources {
|
||||
pub vertices: Vec<f32>,
|
||||
pub vbos: [ffi::types::GLuint; 2],
|
||||
}
|
||||
|
||||
static INSTANCED_VERTS: [ffi::types::GLfloat; 8] = [
|
||||
1.0, 0.0, // top right
|
||||
0.0, 0.0, // top left
|
||||
1.0, 1.0, // bottom right
|
||||
0.0, 1.0, // bottom left
|
||||
];
|
||||
|
||||
/// Vertices for rendering individual triangles.
|
||||
const MAX_RECTS_PER_DRAW: usize = 10;
|
||||
const TRIANGLE_VERTS: [ffi::types::GLfloat; 12 * MAX_RECTS_PER_DRAW] = triangle_verts();
|
||||
const fn triangle_verts() -> [ffi::types::GLfloat; 12 * MAX_RECTS_PER_DRAW] {
|
||||
let mut verts = [0.; 12 * MAX_RECTS_PER_DRAW];
|
||||
let mut i = 0;
|
||||
loop {
|
||||
// Top Left.
|
||||
verts[i * 12] = 0.0;
|
||||
verts[i * 12 + 1] = 0.0;
|
||||
|
||||
// Bottom left.
|
||||
verts[i * 12 + 2] = 0.0;
|
||||
verts[i * 12 + 3] = 1.0;
|
||||
|
||||
// Bottom right.
|
||||
verts[i * 12 + 4] = 1.0;
|
||||
verts[i * 12 + 5] = 1.0;
|
||||
|
||||
// Top left.
|
||||
verts[i * 12 + 6] = 0.0;
|
||||
verts[i * 12 + 7] = 0.0;
|
||||
|
||||
// Bottom right.
|
||||
verts[i * 12 + 8] = 1.0;
|
||||
verts[i * 12 + 9] = 1.0;
|
||||
|
||||
// Top right.
|
||||
verts[i * 12 + 10] = 1.0;
|
||||
verts[i * 12 + 11] = 0.0;
|
||||
|
||||
i += 1;
|
||||
if i == MAX_RECTS_PER_DRAW {
|
||||
break;
|
||||
}
|
||||
}
|
||||
verts
|
||||
}
|
||||
|
||||
impl Resources {
|
||||
fn create(renderer: &mut GlesRenderer) -> Result<Self, GlesError> {
|
||||
let _span = tracy_client::span!("Resources::init");
|
||||
|
||||
let supports_instancing = renderer.capabilities().contains(&Capability::Instancing);
|
||||
renderer.with_context(|gl| unsafe {
|
||||
let vertices: &[ffi::types::GLfloat] = if supports_instancing {
|
||||
&INSTANCED_VERTS
|
||||
} else {
|
||||
&TRIANGLE_VERTS
|
||||
};
|
||||
|
||||
let mut vbos = [0; 2];
|
||||
gl.GenBuffers(vbos.len() as i32, vbos.as_mut_ptr());
|
||||
gl.BindBuffer(ffi::ARRAY_BUFFER, vbos[0]);
|
||||
gl.BufferData(
|
||||
ffi::ARRAY_BUFFER,
|
||||
std::mem::size_of_val(vertices) as isize,
|
||||
vertices.as_ptr() as *const _,
|
||||
ffi::STATIC_DRAW,
|
||||
);
|
||||
|
||||
gl.BindBuffer(ffi::ARRAY_BUFFER, 0);
|
||||
|
||||
Self {
|
||||
vertices: vec![],
|
||||
vbos,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get(frame: &mut GlesFrame) -> Option<Rc<RefCell<Self>>> {
|
||||
let data = frame.egl_context().user_data();
|
||||
data.get().cloned()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(renderer: &mut GlesRenderer) {
|
||||
match Resources::create(renderer) {
|
||||
Ok(resources) => {
|
||||
let data = renderer.egl_context().user_data();
|
||||
if !data.insert_if_missing(|| Rc::new(RefCell::new(resources))) {
|
||||
error!("resources were already initialized");
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("error creating resources for rendering: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::rc::Rc;
|
||||
|
||||
use glam::{Mat3, Vec2};
|
||||
use smithay::backend::renderer::element::{Element, Id, Kind, RenderElement, UnderlyingStorage};
|
||||
use smithay::backend::renderer::gles::{
|
||||
ffi, link_program, Capability, GlesError, GlesFrame, GlesRenderer, GlesTexture, Uniform,
|
||||
UniformDesc, UniformName,
|
||||
};
|
||||
use smithay::backend::renderer::utils::{CommitCounter, OpaqueRegions};
|
||||
use smithay::backend::renderer::DebugFlags;
|
||||
use smithay::utils::{Buffer, Logical, Physical, Point, Rectangle, Scale, Size};
|
||||
|
||||
use super::renderer::AsGlesFrame;
|
||||
use super::resources::Resources;
|
||||
use super::shaders::{ProgramType, Shaders};
|
||||
use crate::backend::tty::{TtyFrame, TtyRenderer, TtyRendererError};
|
||||
|
||||
/// Renders a shader with optional texture input, on the primary GPU.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ShaderRenderElement {
|
||||
program: ProgramType,
|
||||
id: Id,
|
||||
commit_counter: CommitCounter,
|
||||
area: Rectangle<i32, Logical>,
|
||||
opaque_regions: Vec<Rectangle<i32, Logical>>,
|
||||
alpha: f32,
|
||||
additional_uniforms: Vec<Uniform<'static>>,
|
||||
textures: HashMap<String, GlesTexture>,
|
||||
kind: Kind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ShaderProgram(Rc<ShaderProgramInner>);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ShaderProgramInner {
|
||||
normal: ShaderProgramInternal,
|
||||
debug: ShaderProgramInternal,
|
||||
uniform_tint: ffi::types::GLint,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ShaderProgramInternal {
|
||||
program: ffi::types::GLuint,
|
||||
uniform_tex_matrix: ffi::types::GLint,
|
||||
uniform_matrix: ffi::types::GLint,
|
||||
uniform_size: ffi::types::GLint,
|
||||
uniform_alpha: ffi::types::GLint,
|
||||
attrib_vert: ffi::types::GLint,
|
||||
attrib_vert_position: ffi::types::GLint,
|
||||
additional_uniforms: HashMap<String, UniformDesc>,
|
||||
texture_uniforms: HashMap<String, ffi::types::GLint>,
|
||||
}
|
||||
|
||||
impl PartialEq for ShaderProgram {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Rc::ptr_eq(&self.0, &other.0)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn compile_program(
|
||||
gl: &ffi::Gles2,
|
||||
src: &str,
|
||||
additional_uniforms: &[UniformName<'_>],
|
||||
texture_uniforms: &[&str],
|
||||
// destruction_callback_sender: Sender<CleanupResource>,
|
||||
) -> Result<ShaderProgram, GlesError> {
|
||||
let shader = format!("#version 100\n{}", src);
|
||||
let program = unsafe { link_program(gl, include_str!("shaders/texture.vert"), &shader)? };
|
||||
let debug_shader = format!("#version 100\n#define DEBUG_FLAGS\n{}", src);
|
||||
let debug_program =
|
||||
unsafe { link_program(gl, include_str!("shaders/texture.vert"), &debug_shader)? };
|
||||
|
||||
let vert = CStr::from_bytes_with_nul(b"vert\0").expect("NULL terminated");
|
||||
let vert_position = CStr::from_bytes_with_nul(b"vert_position\0").expect("NULL terminated");
|
||||
let matrix = CStr::from_bytes_with_nul(b"matrix\0").expect("NULL terminated");
|
||||
let tex_matrix = CStr::from_bytes_with_nul(b"tex_matrix\0").expect("NULL terminated");
|
||||
let size = CStr::from_bytes_with_nul(b"niri_size\0").expect("NULL terminated");
|
||||
let alpha = CStr::from_bytes_with_nul(b"niri_alpha\0").expect("NULL terminated");
|
||||
let tint = CStr::from_bytes_with_nul(b"niri_tint\0").expect("NULL terminated");
|
||||
|
||||
Ok(ShaderProgram(Rc::new(ShaderProgramInner {
|
||||
normal: ShaderProgramInternal {
|
||||
program,
|
||||
uniform_matrix: gl
|
||||
.GetUniformLocation(program, matrix.as_ptr() as *const ffi::types::GLchar),
|
||||
uniform_tex_matrix: gl
|
||||
.GetUniformLocation(program, tex_matrix.as_ptr() as *const ffi::types::GLchar),
|
||||
uniform_size: gl
|
||||
.GetUniformLocation(program, size.as_ptr() as *const ffi::types::GLchar),
|
||||
uniform_alpha: gl
|
||||
.GetUniformLocation(program, alpha.as_ptr() as *const ffi::types::GLchar),
|
||||
attrib_vert: gl.GetAttribLocation(program, vert.as_ptr() as *const ffi::types::GLchar),
|
||||
attrib_vert_position: gl
|
||||
.GetAttribLocation(program, vert_position.as_ptr() as *const ffi::types::GLchar),
|
||||
additional_uniforms: additional_uniforms
|
||||
.iter()
|
||||
.map(|uniform| {
|
||||
let name =
|
||||
CString::new(uniform.name.as_bytes()).expect("Interior null in name");
|
||||
let location =
|
||||
gl.GetUniformLocation(program, name.as_ptr() as *const ffi::types::GLchar);
|
||||
(
|
||||
uniform.name.clone().into_owned(),
|
||||
UniformDesc {
|
||||
location,
|
||||
type_: uniform.type_,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
texture_uniforms: texture_uniforms
|
||||
.iter()
|
||||
.map(|name_| {
|
||||
let name = CString::new(name_.as_bytes()).expect("Interior null in name");
|
||||
let location =
|
||||
gl.GetUniformLocation(program, name.as_ptr() as *const ffi::types::GLchar);
|
||||
(name_.to_string(), location)
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
debug: ShaderProgramInternal {
|
||||
program: debug_program,
|
||||
uniform_matrix: gl
|
||||
.GetUniformLocation(debug_program, matrix.as_ptr() as *const ffi::types::GLchar),
|
||||
uniform_tex_matrix: gl.GetUniformLocation(
|
||||
debug_program,
|
||||
tex_matrix.as_ptr() as *const ffi::types::GLchar,
|
||||
),
|
||||
uniform_size: gl
|
||||
.GetUniformLocation(debug_program, size.as_ptr() as *const ffi::types::GLchar),
|
||||
uniform_alpha: gl
|
||||
.GetUniformLocation(debug_program, alpha.as_ptr() as *const ffi::types::GLchar),
|
||||
attrib_vert: gl
|
||||
.GetAttribLocation(debug_program, vert.as_ptr() as *const ffi::types::GLchar),
|
||||
attrib_vert_position: gl.GetAttribLocation(
|
||||
debug_program,
|
||||
vert_position.as_ptr() as *const ffi::types::GLchar,
|
||||
),
|
||||
additional_uniforms: additional_uniforms
|
||||
.iter()
|
||||
.map(|uniform| {
|
||||
let name =
|
||||
CString::new(uniform.name.as_bytes()).expect("Interior null in name");
|
||||
let location = gl.GetUniformLocation(
|
||||
debug_program,
|
||||
name.as_ptr() as *const ffi::types::GLchar,
|
||||
);
|
||||
(
|
||||
uniform.name.clone().into_owned(),
|
||||
UniformDesc {
|
||||
location,
|
||||
type_: uniform.type_,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
texture_uniforms: texture_uniforms
|
||||
.iter()
|
||||
.map(|name_| {
|
||||
let name = CString::new(name_.as_bytes()).expect("Interior null in name");
|
||||
let location = gl.GetUniformLocation(
|
||||
debug_program,
|
||||
name.as_ptr() as *const ffi::types::GLchar,
|
||||
);
|
||||
(name_.to_string(), location)
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
uniform_tint: gl
|
||||
.GetUniformLocation(debug_program, tint.as_ptr() as *const ffi::types::GLchar),
|
||||
})))
|
||||
}
|
||||
|
||||
impl ShaderProgram {
|
||||
pub fn compile(
|
||||
renderer: &mut GlesRenderer,
|
||||
src: &str,
|
||||
additional_uniforms: &[UniformName<'_>],
|
||||
texture_uniforms: &[&str],
|
||||
) -> Result<Self, GlesError> {
|
||||
renderer.with_context(move |gl| unsafe {
|
||||
compile_program(gl, src, additional_uniforms, texture_uniforms)
|
||||
})?
|
||||
}
|
||||
|
||||
pub fn destroy(self, renderer: &mut GlesRenderer) -> Result<(), GlesError> {
|
||||
renderer.with_context(move |gl| unsafe {
|
||||
gl.DeleteProgram(self.0.normal.program);
|
||||
gl.DeleteProgram(self.0.debug.program);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ShaderRenderElement {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
program: ProgramType,
|
||||
size: Size<i32, Logical>,
|
||||
opaque_regions: Option<Vec<Rectangle<i32, Logical>>>,
|
||||
alpha: f32,
|
||||
uniforms: Vec<Uniform<'_>>,
|
||||
textures: HashMap<String, GlesTexture>,
|
||||
kind: Kind,
|
||||
) -> Self {
|
||||
Self {
|
||||
program,
|
||||
id: Id::new(),
|
||||
commit_counter: CommitCounter::default(),
|
||||
area: Rectangle::from_loc_and_size((0, 0), size),
|
||||
opaque_regions: opaque_regions.unwrap_or_default(),
|
||||
alpha,
|
||||
additional_uniforms: uniforms.into_iter().map(|u| u.into_owned()).collect(),
|
||||
textures,
|
||||
kind,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn empty(program: ProgramType, kind: Kind) -> Self {
|
||||
Self {
|
||||
program,
|
||||
id: Id::new(),
|
||||
commit_counter: CommitCounter::default(),
|
||||
area: Rectangle::default(),
|
||||
opaque_regions: vec![],
|
||||
alpha: 1.,
|
||||
additional_uniforms: vec![],
|
||||
textures: HashMap::new(),
|
||||
kind,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn damage_all(&mut self) {
|
||||
self.commit_counter.increment();
|
||||
}
|
||||
|
||||
pub fn update(
|
||||
&mut self,
|
||||
size: Size<i32, Logical>,
|
||||
opaque_regions: Option<Vec<Rectangle<i32, Logical>>>,
|
||||
uniforms: Vec<Uniform<'_>>,
|
||||
textures: HashMap<String, GlesTexture>,
|
||||
) {
|
||||
self.area.size = size;
|
||||
self.opaque_regions = opaque_regions.unwrap_or_default();
|
||||
self.additional_uniforms = uniforms.into_iter().map(|u| u.into_owned()).collect();
|
||||
self.textures = textures;
|
||||
|
||||
self.commit_counter.increment();
|
||||
}
|
||||
|
||||
pub fn with_location(mut self, location: Point<i32, Logical>) -> Self {
|
||||
self.area.loc = location;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Element for ShaderRenderElement {
|
||||
fn id(&self) -> &Id {
|
||||
&self.id
|
||||
}
|
||||
|
||||
fn current_commit(&self) -> CommitCounter {
|
||||
self.commit_counter
|
||||
}
|
||||
|
||||
fn src(&self) -> Rectangle<f64, Buffer> {
|
||||
Rectangle::from_loc_and_size((0., 0.), (1., 1.))
|
||||
}
|
||||
|
||||
fn geometry(&self, scale: Scale<f64>) -> Rectangle<i32, Physical> {
|
||||
self.area.to_physical_precise_round(scale)
|
||||
}
|
||||
|
||||
fn opaque_regions(&self, scale: Scale<f64>) -> OpaqueRegions<i32, Physical> {
|
||||
self.opaque_regions
|
||||
.iter()
|
||||
.map(|region| region.to_physical_precise_round(scale))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn alpha(&self) -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
fn kind(&self) -> Kind {
|
||||
self.kind
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderElement<GlesRenderer> for ShaderRenderElement {
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut GlesFrame<'_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dest: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), GlesError> {
|
||||
let frame = frame.as_gles_frame();
|
||||
|
||||
let Some(shader) = Shaders::get_from_frame(frame).program(self.program) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let Some(resources) = Resources::get(frame) else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut resources = resources.borrow_mut();
|
||||
|
||||
let supports_instancing = frame.capabilities().contains(&Capability::Instancing);
|
||||
|
||||
// prepare the vertices
|
||||
resources.vertices.clear();
|
||||
if supports_instancing {
|
||||
resources.vertices.extend(damage.iter().flat_map(|rect| {
|
||||
let dest_size = dest.size;
|
||||
|
||||
let rect_constrained_loc = rect
|
||||
.loc
|
||||
.constrain(Rectangle::from_extemities((0, 0), dest_size.to_point()));
|
||||
let rect_clamped_size = rect.size.clamp(
|
||||
(0, 0),
|
||||
(dest_size.to_point() - rect_constrained_loc).to_size(),
|
||||
);
|
||||
|
||||
let rect = Rectangle::from_loc_and_size(rect_constrained_loc, rect_clamped_size);
|
||||
[
|
||||
rect.loc.x as f32,
|
||||
rect.loc.y as f32,
|
||||
rect.size.w as f32,
|
||||
rect.size.h as f32,
|
||||
]
|
||||
}));
|
||||
} else {
|
||||
resources.vertices.extend(damage.iter().flat_map(|rect| {
|
||||
let dest_size = dest.size;
|
||||
|
||||
let rect_constrained_loc = rect
|
||||
.loc
|
||||
.constrain(Rectangle::from_extemities((0, 0), dest_size.to_point()));
|
||||
let rect_clamped_size = rect.size.clamp(
|
||||
(0, 0),
|
||||
(dest_size.to_point() - rect_constrained_loc).to_size(),
|
||||
);
|
||||
|
||||
let rect = Rectangle::from_loc_and_size(rect_constrained_loc, rect_clamped_size);
|
||||
// Add the 4 f32s per damage rectangle for each of the 6 vertices.
|
||||
(0..6).flat_map(move |_| {
|
||||
[
|
||||
rect.loc.x as f32,
|
||||
rect.loc.y as f32,
|
||||
rect.size.w as f32,
|
||||
rect.size.h as f32,
|
||||
]
|
||||
})
|
||||
}));
|
||||
}
|
||||
|
||||
if resources.vertices.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// dest position and scale
|
||||
let mut matrix = Mat3::from_translation(Vec2::new(dest.loc.x as f32, dest.loc.y as f32));
|
||||
|
||||
let scale = src.size.to_f64() / dest.size.to_f64();
|
||||
let tex_matrix = Mat3::from_scale(Vec2::new(scale.x as f32, scale.y as f32));
|
||||
let tex_matrix =
|
||||
Mat3::from_translation(Vec2::new(src.loc.x as f32, src.loc.y as f32)) * tex_matrix;
|
||||
|
||||
//apply output transformation
|
||||
matrix = Mat3::from_cols_array(frame.projection()) * matrix;
|
||||
|
||||
let has_debug = !frame.debug_flags().is_empty();
|
||||
let has_tint = frame.debug_flags().contains(DebugFlags::TINT);
|
||||
|
||||
// render
|
||||
frame.with_context(move |gl| -> Result<(), GlesError> {
|
||||
let program = if has_debug {
|
||||
&shader.0.debug
|
||||
} else {
|
||||
&shader.0.normal
|
||||
};
|
||||
|
||||
unsafe {
|
||||
for (i, texture) in self.textures.values().enumerate() {
|
||||
gl.ActiveTexture(ffi::TEXTURE0 + i as u32);
|
||||
gl.BindTexture(ffi::TEXTURE_2D, texture.tex_id());
|
||||
gl.TexParameteri(ffi::TEXTURE_2D, ffi::TEXTURE_MIN_FILTER, ffi::LINEAR as i32);
|
||||
gl.TexParameteri(ffi::TEXTURE_2D, ffi::TEXTURE_MAG_FILTER, ffi::LINEAR as i32);
|
||||
gl.TexParameteri(
|
||||
ffi::TEXTURE_2D,
|
||||
ffi::TEXTURE_WRAP_S,
|
||||
ffi::CLAMP_TO_BORDER as i32,
|
||||
);
|
||||
gl.TexParameteri(
|
||||
ffi::TEXTURE_2D,
|
||||
ffi::TEXTURE_WRAP_T,
|
||||
ffi::CLAMP_TO_BORDER as i32,
|
||||
);
|
||||
}
|
||||
|
||||
gl.UseProgram(program.program);
|
||||
|
||||
for (i, name) in self.textures.keys().enumerate() {
|
||||
gl.Uniform1i(program.texture_uniforms[name], i as i32);
|
||||
}
|
||||
|
||||
gl.UniformMatrix3fv(
|
||||
program.uniform_matrix,
|
||||
1,
|
||||
ffi::FALSE,
|
||||
matrix.as_ref().as_ptr(),
|
||||
);
|
||||
gl.UniformMatrix3fv(
|
||||
program.uniform_tex_matrix,
|
||||
1,
|
||||
ffi::FALSE,
|
||||
tex_matrix.as_ref().as_ptr(),
|
||||
);
|
||||
gl.Uniform2f(program.uniform_size, dest.size.w as f32, dest.size.h as f32);
|
||||
gl.Uniform1f(program.uniform_alpha, self.alpha);
|
||||
|
||||
let tint = if has_tint { 1.0f32 } else { 0.0f32 };
|
||||
if has_debug {
|
||||
gl.Uniform1f(shader.0.uniform_tint, tint);
|
||||
}
|
||||
|
||||
for uniform in &self.additional_uniforms {
|
||||
let desc =
|
||||
program
|
||||
.additional_uniforms
|
||||
.get(&*uniform.name)
|
||||
.ok_or_else(|| {
|
||||
GlesError::UnknownUniform(uniform.name.clone().into_owned())
|
||||
})?;
|
||||
uniform.value.set(gl, desc)?;
|
||||
}
|
||||
|
||||
gl.EnableVertexAttribArray(program.attrib_vert as u32);
|
||||
gl.BindBuffer(ffi::ARRAY_BUFFER, resources.vbos[0]);
|
||||
gl.VertexAttribPointer(
|
||||
program.attrib_vert as u32,
|
||||
2,
|
||||
ffi::FLOAT,
|
||||
ffi::FALSE,
|
||||
0,
|
||||
std::ptr::null(),
|
||||
);
|
||||
|
||||
// vert_position
|
||||
gl.EnableVertexAttribArray(program.attrib_vert_position as u32);
|
||||
gl.BindBuffer(ffi::ARRAY_BUFFER, resources.vbos[1]);
|
||||
gl.BufferData(
|
||||
ffi::ARRAY_BUFFER,
|
||||
(std::mem::size_of::<ffi::types::GLfloat>() * resources.vertices.len())
|
||||
as isize,
|
||||
resources.vertices.as_ptr() as *const _,
|
||||
ffi::STREAM_DRAW,
|
||||
);
|
||||
|
||||
gl.VertexAttribPointer(
|
||||
program.attrib_vert_position as u32,
|
||||
4,
|
||||
ffi::FLOAT,
|
||||
ffi::FALSE,
|
||||
0,
|
||||
std::ptr::null(),
|
||||
);
|
||||
|
||||
let damage_len = damage.len() as i32;
|
||||
if supports_instancing {
|
||||
gl.VertexAttribDivisor(program.attrib_vert as u32, 0);
|
||||
gl.VertexAttribDivisor(program.attrib_vert_position as u32, 1);
|
||||
gl.DrawArraysInstanced(ffi::TRIANGLE_STRIP, 0, 4, damage_len);
|
||||
} else {
|
||||
// When we have more than 10 rectangles, draw them in batches of 10.
|
||||
for i in 0..(damage_len - 1) / 10 {
|
||||
gl.DrawArrays(ffi::TRIANGLES, 0, 6);
|
||||
|
||||
// Set damage pointer to the next 10 rectangles.
|
||||
let offset =
|
||||
(i + 1) as usize * 6 * 4 * std::mem::size_of::<ffi::types::GLfloat>();
|
||||
gl.VertexAttribPointer(
|
||||
program.attrib_vert_position as u32,
|
||||
4,
|
||||
ffi::FLOAT,
|
||||
ffi::FALSE,
|
||||
0,
|
||||
offset as *const _,
|
||||
);
|
||||
}
|
||||
|
||||
// Draw the up to 10 remaining rectangles.
|
||||
let count = ((damage_len - 1) % 10 + 1) * 6;
|
||||
gl.DrawArrays(ffi::TRIANGLES, 0, count);
|
||||
}
|
||||
|
||||
gl.BindBuffer(ffi::ARRAY_BUFFER, 0);
|
||||
gl.BindTexture(ffi::TEXTURE_2D, 0);
|
||||
gl.ActiveTexture(ffi::TEXTURE0);
|
||||
gl.BindTexture(ffi::TEXTURE_2D, 0);
|
||||
gl.DisableVertexAttribArray(program.attrib_vert as u32);
|
||||
gl.DisableVertexAttribArray(program.attrib_vert_position as u32);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})??;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn underlying_storage(&self, _renderer: &mut GlesRenderer) -> Option<UnderlyingStorage> {
|
||||
// If scanout for things other than Wayland buffers is implemented, this will need to take
|
||||
// the target GPU into account.
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<'render> RenderElement<TtyRenderer<'render>> for ShaderRenderElement {
|
||||
fn draw(
|
||||
&self,
|
||||
frame: &mut TtyFrame<'_, '_>,
|
||||
src: Rectangle<f64, Buffer>,
|
||||
dst: Rectangle<i32, Physical>,
|
||||
damage: &[Rectangle<i32, Physical>],
|
||||
) -> Result<(), TtyRendererError<'render>> {
|
||||
let frame = frame.as_gles_frame();
|
||||
|
||||
RenderElement::<GlesRenderer>::draw(self, frame, src, dst, damage)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn underlying_storage(
|
||||
&self,
|
||||
_renderer: &mut TtyRenderer<'render>,
|
||||
) -> Option<UnderlyingStorage> {
|
||||
// If scanout for things other than Wayland buffers is implemented, this will need to take
|
||||
// the target GPU into account.
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
precision mediump float;
|
||||
|
||||
#if defined(DEBUG_FLAGS)
|
||||
uniform float niri_tint;
|
||||
#endif
|
||||
|
||||
uniform float niri_alpha;
|
||||
|
||||
uniform vec2 niri_size;
|
||||
varying vec2 niri_v_coords;
|
||||
|
||||
uniform vec4 color_from;
|
||||
uniform vec4 color_to;
|
||||
uniform vec2 grad_offset;
|
||||
uniform float grad_width;
|
||||
uniform vec2 grad_vec;
|
||||
|
||||
uniform mat3 input_to_geo;
|
||||
uniform vec2 geo_size;
|
||||
uniform vec4 outer_radius;
|
||||
uniform float border_width;
|
||||
|
||||
vec4 gradient_color(vec2 coords) {
|
||||
coords = coords + grad_offset;
|
||||
|
||||
if ((grad_vec.x < 0.0 && 0.0 <= grad_vec.y) || (0.0 <= grad_vec.x && grad_vec.y < 0.0))
|
||||
coords.x -= grad_width;
|
||||
|
||||
float frac = dot(coords, grad_vec) / dot(grad_vec, grad_vec);
|
||||
|
||||
if (grad_vec.y < 0.0)
|
||||
frac += 1.0;
|
||||
|
||||
frac = clamp(frac, 0.0, 1.0);
|
||||
return mix(color_from, color_to, frac);
|
||||
}
|
||||
|
||||
float rounding_alpha(vec2 coords, vec2 size, vec4 corner_radius) {
|
||||
vec2 center;
|
||||
float radius;
|
||||
|
||||
if (coords.x < corner_radius.x && coords.y < corner_radius.x) {
|
||||
radius = corner_radius.x;
|
||||
center = vec2(radius, radius);
|
||||
} else if (size.x - corner_radius.y < coords.x && coords.y < corner_radius.y) {
|
||||
radius = corner_radius.y;
|
||||
center = vec2(size.x - radius, radius);
|
||||
} else if (size.x - corner_radius.z < coords.x && size.y - corner_radius.z < coords.y) {
|
||||
radius = corner_radius.z;
|
||||
center = vec2(size.x - radius, size.y - radius);
|
||||
} else if (coords.x < corner_radius.w && size.y - corner_radius.w < coords.y) {
|
||||
radius = corner_radius.w;
|
||||
center = vec2(radius, size.y - radius);
|
||||
} else {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
float dist = distance(coords, center);
|
||||
return 1.0 - smoothstep(radius - 0.5, radius + 0.5, dist);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 coords_geo = input_to_geo * vec3(niri_v_coords, 1.0);
|
||||
vec4 color = gradient_color(coords_geo.xy);
|
||||
color = color * rounding_alpha(coords_geo.xy, geo_size, outer_radius);
|
||||
|
||||
if (border_width > 0.0) {
|
||||
coords_geo -= vec3(border_width);
|
||||
vec2 inner_geo_size = geo_size - vec2(border_width * 2.0);
|
||||
if (0.0 <= coords_geo.x && coords_geo.x <= inner_geo_size.x
|
||||
&& 0.0 <= coords_geo.y && coords_geo.y <= inner_geo_size.y)
|
||||
{
|
||||
vec4 inner_radius = max(outer_radius - vec4(border_width), 0.0);
|
||||
color = color * (1.0 - rounding_alpha(coords_geo.xy, inner_geo_size, inner_radius));
|
||||
}
|
||||
}
|
||||
|
||||
color = color * niri_alpha;
|
||||
|
||||
#if defined(DEBUG_FLAGS)
|
||||
if (niri_tint == 1.0)
|
||||
color = vec4(0.0, 0.2, 0.0, 0.2) + color * 0.8;
|
||||
#endif
|
||||
|
||||
gl_FragColor = color;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
#version 100
|
||||
|
||||
//_DEFINES_
|
||||
|
||||
#if defined(EXTERNAL)
|
||||
#extension GL_OES_EGL_image_external : require
|
||||
#endif
|
||||
|
||||
precision mediump float;
|
||||
#if defined(EXTERNAL)
|
||||
uniform samplerExternalOES tex;
|
||||
#else
|
||||
uniform sampler2D tex;
|
||||
#endif
|
||||
|
||||
uniform float alpha;
|
||||
varying vec2 v_coords;
|
||||
|
||||
#if defined(DEBUG_FLAGS)
|
||||
uniform float tint;
|
||||
#endif
|
||||
|
||||
uniform vec2 geo_size;
|
||||
uniform vec4 corner_radius;
|
||||
uniform mat3 input_to_geo;
|
||||
|
||||
float rounding_alpha(vec2 coords, vec2 size) {
|
||||
vec2 center;
|
||||
float radius;
|
||||
|
||||
if (coords.x < corner_radius.x && coords.y < corner_radius.x) {
|
||||
radius = corner_radius.x;
|
||||
center = vec2(radius, radius);
|
||||
} else if (size.x - corner_radius.y < coords.x && coords.y < corner_radius.y) {
|
||||
radius = corner_radius.y;
|
||||
center = vec2(size.x - radius, radius);
|
||||
} else if (size.x - corner_radius.z < coords.x && size.y - corner_radius.z < coords.y) {
|
||||
radius = corner_radius.z;
|
||||
center = vec2(size.x - radius, size.y - radius);
|
||||
} else if (coords.x < corner_radius.w && size.y - corner_radius.w < coords.y) {
|
||||
radius = corner_radius.w;
|
||||
center = vec2(radius, size.y - radius);
|
||||
} else {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
float dist = distance(coords, center);
|
||||
return 1.0 - smoothstep(radius - 0.5, radius + 0.5, dist);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 coords_geo = input_to_geo * vec3(v_coords, 1.0);
|
||||
|
||||
// Sample the texture.
|
||||
vec4 color = texture2D(tex, v_coords);
|
||||
#if defined(NO_ALPHA)
|
||||
color = vec4(color.rgb, 1.0);
|
||||
#endif
|
||||
|
||||
if (coords_geo.x < 0.0 || 1.0 < coords_geo.x || coords_geo.y < 0.0 || 1.0 < coords_geo.y) {
|
||||
// Clip outside geometry.
|
||||
color = vec4(0.0);
|
||||
} else {
|
||||
// Apply corner rounding inside geometry.
|
||||
color = color * rounding_alpha(coords_geo.xy * geo_size, geo_size);
|
||||
}
|
||||
|
||||
// Apply final alpha and tint.
|
||||
color = color * alpha;
|
||||
|
||||
#if defined(DEBUG_FLAGS)
|
||||
if (tint == 1.0)
|
||||
color = vec4(0.0, 0.2, 0.0, 0.2) + color * 0.8;
|
||||
#endif
|
||||
|
||||
gl_FragColor = color;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
void main() {
|
||||
vec3 coords_geo = niri_input_to_geo * vec3(niri_v_coords, 1.0);
|
||||
vec3 size_geo = vec3(niri_geo_size, 1.0);
|
||||
|
||||
vec4 color = close_color(coords_geo, size_geo);
|
||||
|
||||
color = color * niri_alpha;
|
||||
|
||||
#if defined(DEBUG_FLAGS)
|
||||
if (niri_tint == 1.0)
|
||||
color = vec4(0.0, 0.2, 0.0, 0.2) + color * 0.8;
|
||||
#endif
|
||||
|
||||
gl_FragColor = color;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
precision mediump float;
|
||||
|
||||
#if defined(DEBUG_FLAGS)
|
||||
uniform float niri_tint;
|
||||
#endif
|
||||
|
||||
varying vec2 niri_v_coords;
|
||||
uniform vec2 niri_size;
|
||||
|
||||
uniform mat3 niri_input_to_geo;
|
||||
uniform vec2 niri_geo_size;
|
||||
|
||||
uniform sampler2D niri_tex;
|
||||
uniform mat3 niri_geo_to_tex;
|
||||
|
||||
uniform float niri_progress;
|
||||
uniform float niri_clamped_progress;
|
||||
uniform float niri_random_seed;
|
||||
|
||||
uniform float niri_alpha;
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
use std::cell::RefCell;
|
||||
|
||||
use glam::Mat3;
|
||||
use smithay::backend::renderer::gles::{
|
||||
GlesError, GlesFrame, GlesRenderer, GlesTexProgram, Uniform, UniformName, UniformType,
|
||||
UniformValue,
|
||||
};
|
||||
|
||||
use super::renderer::NiriRenderer;
|
||||
use super::shader_element::ShaderProgram;
|
||||
|
||||
pub struct Shaders {
|
||||
pub border: Option<ShaderProgram>,
|
||||
pub clipped_surface: Option<GlesTexProgram>,
|
||||
pub resize: Option<ShaderProgram>,
|
||||
pub custom_resize: RefCell<Option<ShaderProgram>>,
|
||||
pub custom_close: RefCell<Option<ShaderProgram>>,
|
||||
pub custom_open: RefCell<Option<ShaderProgram>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum ProgramType {
|
||||
Border,
|
||||
Resize,
|
||||
Close,
|
||||
Open,
|
||||
}
|
||||
|
||||
impl Shaders {
|
||||
fn compile(renderer: &mut GlesRenderer) -> Self {
|
||||
let _span = tracy_client::span!("Shaders::compile");
|
||||
|
||||
let border = ShaderProgram::compile(
|
||||
renderer,
|
||||
include_str!("border.frag"),
|
||||
&[
|
||||
UniformName::new("color_from", UniformType::_4f),
|
||||
UniformName::new("color_to", UniformType::_4f),
|
||||
UniformName::new("grad_offset", UniformType::_2f),
|
||||
UniformName::new("grad_width", UniformType::_1f),
|
||||
UniformName::new("grad_vec", UniformType::_2f),
|
||||
UniformName::new("input_to_geo", UniformType::Matrix3x3),
|
||||
UniformName::new("geo_size", UniformType::_2f),
|
||||
UniformName::new("outer_radius", UniformType::_4f),
|
||||
UniformName::new("border_width", UniformType::_1f),
|
||||
],
|
||||
&[],
|
||||
)
|
||||
.map_err(|err| {
|
||||
warn!("error compiling border shader: {err:?}");
|
||||
})
|
||||
.ok();
|
||||
|
||||
let clipped_surface = renderer
|
||||
.compile_custom_texture_shader(
|
||||
include_str!("clipped_surface.frag"),
|
||||
&[
|
||||
UniformName::new("geo_size", UniformType::_2f),
|
||||
UniformName::new("corner_radius", UniformType::_4f),
|
||||
UniformName::new("input_to_geo", UniformType::Matrix3x3),
|
||||
],
|
||||
)
|
||||
.map_err(|err| {
|
||||
warn!("error compiling clipped surface shader: {err:?}");
|
||||
})
|
||||
.ok();
|
||||
|
||||
let resize = compile_resize_program(renderer, include_str!("resize.frag"))
|
||||
.map_err(|err| {
|
||||
warn!("error compiling resize shader: {err:?}");
|
||||
})
|
||||
.ok();
|
||||
|
||||
Self {
|
||||
border,
|
||||
clipped_surface,
|
||||
resize,
|
||||
custom_resize: RefCell::new(None),
|
||||
custom_close: RefCell::new(None),
|
||||
custom_open: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_from_frame<'a>(frame: &'a mut GlesFrame<'_>) -> &'a Self {
|
||||
let data = frame.egl_context().user_data();
|
||||
data.get()
|
||||
.expect("shaders::init() must be called when creating the renderer")
|
||||
}
|
||||
|
||||
pub fn get(renderer: &mut impl NiriRenderer) -> &Self {
|
||||
let renderer = renderer.as_gles_renderer();
|
||||
let data = renderer.egl_context().user_data();
|
||||
data.get()
|
||||
.expect("shaders::init() must be called when creating the renderer")
|
||||
}
|
||||
|
||||
pub fn replace_custom_resize_program(
|
||||
&self,
|
||||
program: Option<ShaderProgram>,
|
||||
) -> Option<ShaderProgram> {
|
||||
self.custom_resize.replace(program)
|
||||
}
|
||||
|
||||
pub fn replace_custom_close_program(
|
||||
&self,
|
||||
program: Option<ShaderProgram>,
|
||||
) -> Option<ShaderProgram> {
|
||||
self.custom_close.replace(program)
|
||||
}
|
||||
|
||||
pub fn replace_custom_open_program(
|
||||
&self,
|
||||
program: Option<ShaderProgram>,
|
||||
) -> Option<ShaderProgram> {
|
||||
self.custom_open.replace(program)
|
||||
}
|
||||
|
||||
pub fn program(&self, program: ProgramType) -> Option<ShaderProgram> {
|
||||
match program {
|
||||
ProgramType::Border => self.border.clone(),
|
||||
ProgramType::Resize => self
|
||||
.custom_resize
|
||||
.borrow()
|
||||
.clone()
|
||||
.or_else(|| self.resize.clone()),
|
||||
ProgramType::Close => self.custom_close.borrow().clone(),
|
||||
ProgramType::Open => self.custom_open.borrow().clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(renderer: &mut GlesRenderer) {
|
||||
let shaders = Shaders::compile(renderer);
|
||||
let data = renderer.egl_context().user_data();
|
||||
if !data.insert_if_missing(|| shaders) {
|
||||
error!("shaders were already compiled");
|
||||
}
|
||||
}
|
||||
|
||||
fn compile_resize_program(
|
||||
renderer: &mut GlesRenderer,
|
||||
src: &str,
|
||||
) -> Result<ShaderProgram, GlesError> {
|
||||
let mut program = include_str!("resize_prelude.frag").to_string();
|
||||
program.push_str(src);
|
||||
program.push_str(include_str!("resize_epilogue.frag"));
|
||||
|
||||
ShaderProgram::compile(
|
||||
renderer,
|
||||
&program,
|
||||
&[
|
||||
UniformName::new("niri_input_to_curr_geo", UniformType::Matrix3x3),
|
||||
UniformName::new("niri_curr_geo_to_prev_geo", UniformType::Matrix3x3),
|
||||
UniformName::new("niri_curr_geo_to_next_geo", UniformType::Matrix3x3),
|
||||
UniformName::new("niri_curr_geo_size", UniformType::_2f),
|
||||
UniformName::new("niri_geo_to_tex_prev", UniformType::Matrix3x3),
|
||||
UniformName::new("niri_geo_to_tex_next", UniformType::Matrix3x3),
|
||||
UniformName::new("niri_progress", UniformType::_1f),
|
||||
UniformName::new("niri_clamped_progress", UniformType::_1f),
|
||||
UniformName::new("niri_corner_radius", UniformType::_4f),
|
||||
UniformName::new("niri_clip_to_geometry", UniformType::_1f),
|
||||
],
|
||||
&["niri_tex_prev", "niri_tex_next"],
|
||||
)
|
||||
}
|
||||
|
||||
pub fn set_custom_resize_program(renderer: &mut GlesRenderer, src: Option<&str>) {
|
||||
let program = if let Some(src) = src {
|
||||
match compile_resize_program(renderer, src) {
|
||||
Ok(program) => Some(program),
|
||||
Err(err) => {
|
||||
warn!("error compiling custom resize shader: {err:?}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(prev) = Shaders::get(renderer).replace_custom_resize_program(program) {
|
||||
if let Err(err) = prev.destroy(renderer) {
|
||||
warn!("error destroying previous custom resize shader: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compile_close_program(
|
||||
renderer: &mut GlesRenderer,
|
||||
src: &str,
|
||||
) -> Result<ShaderProgram, GlesError> {
|
||||
let mut program = include_str!("close_prelude.frag").to_string();
|
||||
program.push_str(src);
|
||||
program.push_str(include_str!("close_epilogue.frag"));
|
||||
|
||||
ShaderProgram::compile(
|
||||
renderer,
|
||||
&program,
|
||||
&[
|
||||
UniformName::new("niri_input_to_geo", UniformType::Matrix3x3),
|
||||
UniformName::new("niri_geo_size", UniformType::_2f),
|
||||
UniformName::new("niri_geo_to_tex", UniformType::Matrix3x3),
|
||||
UniformName::new("niri_progress", UniformType::_1f),
|
||||
UniformName::new("niri_clamped_progress", UniformType::_1f),
|
||||
UniformName::new("niri_random_seed", UniformType::_1f),
|
||||
],
|
||||
&["niri_tex"],
|
||||
)
|
||||
}
|
||||
|
||||
pub fn set_custom_close_program(renderer: &mut GlesRenderer, src: Option<&str>) {
|
||||
let program = if let Some(src) = src {
|
||||
match compile_close_program(renderer, src) {
|
||||
Ok(program) => Some(program),
|
||||
Err(err) => {
|
||||
warn!("error compiling custom close shader: {err:?}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(prev) = Shaders::get(renderer).replace_custom_close_program(program) {
|
||||
if let Err(err) = prev.destroy(renderer) {
|
||||
warn!("error destroying previous custom close shader: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compile_open_program(
|
||||
renderer: &mut GlesRenderer,
|
||||
src: &str,
|
||||
) -> Result<ShaderProgram, GlesError> {
|
||||
let mut program = include_str!("open_prelude.frag").to_string();
|
||||
program.push_str(src);
|
||||
program.push_str(include_str!("open_epilogue.frag"));
|
||||
|
||||
ShaderProgram::compile(
|
||||
renderer,
|
||||
&program,
|
||||
&[
|
||||
UniformName::new("niri_input_to_geo", UniformType::Matrix3x3),
|
||||
UniformName::new("niri_geo_size", UniformType::_2f),
|
||||
UniformName::new("niri_geo_to_tex", UniformType::Matrix3x3),
|
||||
UniformName::new("niri_progress", UniformType::_1f),
|
||||
UniformName::new("niri_clamped_progress", UniformType::_1f),
|
||||
UniformName::new("niri_random_seed", UniformType::_1f),
|
||||
],
|
||||
&["niri_tex"],
|
||||
)
|
||||
}
|
||||
|
||||
pub fn set_custom_open_program(renderer: &mut GlesRenderer, src: Option<&str>) {
|
||||
let program = if let Some(src) = src {
|
||||
match compile_open_program(renderer, src) {
|
||||
Ok(program) => Some(program),
|
||||
Err(err) => {
|
||||
warn!("error compiling custom open shader: {err:?}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(prev) = Shaders::get(renderer).replace_custom_open_program(program) {
|
||||
if let Err(err) = prev.destroy(renderer) {
|
||||
warn!("error destroying previous custom open shader: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mat3_uniform(name: &str, mat: Mat3) -> Uniform {
|
||||
Uniform::new(
|
||||
name,
|
||||
UniformValue::Matrix3x3 {
|
||||
matrices: vec![mat.to_cols_array()],
|
||||
transpose: false,
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
void main() {
|
||||
vec3 coords_geo = niri_input_to_geo * vec3(niri_v_coords, 1.0);
|
||||
vec3 size_geo = vec3(niri_geo_size, 1.0);
|
||||
|
||||
vec4 color = open_color(coords_geo, size_geo);
|
||||
|
||||
color = color * niri_alpha;
|
||||
|
||||
#if defined(DEBUG_FLAGS)
|
||||
if (niri_tint == 1.0)
|
||||
color = vec4(0.0, 0.2, 0.0, 0.2) + color * 0.8;
|
||||
#endif
|
||||
|
||||
gl_FragColor = color;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
precision mediump float;
|
||||
|
||||
#if defined(DEBUG_FLAGS)
|
||||
uniform float niri_tint;
|
||||
#endif
|
||||
|
||||
varying vec2 niri_v_coords;
|
||||
uniform vec2 niri_size;
|
||||
|
||||
uniform mat3 niri_input_to_geo;
|
||||
uniform vec2 niri_geo_size;
|
||||
|
||||
uniform sampler2D niri_tex;
|
||||
uniform mat3 niri_geo_to_tex;
|
||||
|
||||
uniform float niri_progress;
|
||||
uniform float niri_clamped_progress;
|
||||
uniform float niri_random_seed;
|
||||
|
||||
uniform float niri_alpha;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
vec4 resize_color(vec3 coords_curr_geo, vec3 size_curr_geo) {
|
||||
vec3 coords_tex_prev = niri_geo_to_tex_prev * coords_curr_geo;
|
||||
vec4 color_prev = texture2D(niri_tex_prev, coords_tex_prev.st);
|
||||
|
||||
vec3 coords_tex_next = niri_geo_to_tex_next * coords_curr_geo;
|
||||
vec4 color_next = texture2D(niri_tex_next, coords_tex_next.st);
|
||||
|
||||
vec4 color = mix(color_prev, color_next, niri_clamped_progress);
|
||||
return color;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
|
||||
void main() {
|
||||
vec3 coords_curr_geo = niri_input_to_curr_geo * vec3(niri_v_coords, 1.0);
|
||||
vec3 size_curr_geo = vec3(niri_curr_geo_size, 1.0);
|
||||
|
||||
vec4 color = resize_color(coords_curr_geo, size_curr_geo);
|
||||
|
||||
if (niri_clip_to_geometry == 1.0) {
|
||||
if (coords_curr_geo.x < 0.0 || 1.0 < coords_curr_geo.x
|
||||
|| coords_curr_geo.y < 0.0 || 1.0 < coords_curr_geo.y) {
|
||||
// Clip outside geometry.
|
||||
color = vec4(0.0);
|
||||
} else {
|
||||
// Apply corner rounding inside geometry.
|
||||
color = color * niri_rounding_alpha(coords_curr_geo.xy * size_curr_geo.xy, size_curr_geo.xy);
|
||||
}
|
||||
}
|
||||
|
||||
color = color * niri_alpha;
|
||||
|
||||
#if defined(DEBUG_FLAGS)
|
||||
if (niri_tint == 1.0)
|
||||
color = vec4(0.0, 0.2, 0.0, 0.2) + color * 0.8;
|
||||
#endif
|
||||
|
||||
gl_FragColor = color;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
precision mediump float;
|
||||
|
||||
#if defined(DEBUG_FLAGS)
|
||||
uniform float niri_tint;
|
||||
#endif
|
||||
|
||||
varying vec2 niri_v_coords;
|
||||
uniform vec2 niri_size;
|
||||
|
||||
uniform mat3 niri_input_to_curr_geo;
|
||||
uniform mat3 niri_curr_geo_to_prev_geo;
|
||||
uniform mat3 niri_curr_geo_to_next_geo;
|
||||
uniform vec2 niri_curr_geo_size;
|
||||
|
||||
uniform sampler2D niri_tex_prev;
|
||||
uniform mat3 niri_geo_to_tex_prev;
|
||||
|
||||
uniform sampler2D niri_tex_next;
|
||||
uniform mat3 niri_geo_to_tex_next;
|
||||
|
||||
uniform float niri_progress;
|
||||
uniform float niri_clamped_progress;
|
||||
|
||||
uniform vec4 niri_corner_radius;
|
||||
uniform float niri_clip_to_geometry;
|
||||
|
||||
uniform float niri_alpha;
|
||||
|
||||
float niri_rounding_alpha(vec2 coords, vec2 size) {
|
||||
vec2 center;
|
||||
float radius;
|
||||
|
||||
if (coords.x < niri_corner_radius.x && coords.y < niri_corner_radius.x) {
|
||||
radius = niri_corner_radius.x;
|
||||
center = vec2(radius, radius);
|
||||
} else if (size.x - niri_corner_radius.y < coords.x && coords.y < niri_corner_radius.y) {
|
||||
radius = niri_corner_radius.y;
|
||||
center = vec2(size.x - radius, radius);
|
||||
} else if (size.x - niri_corner_radius.z < coords.x && size.y - niri_corner_radius.z < coords.y) {
|
||||
radius = niri_corner_radius.z;
|
||||
center = vec2(size.x - radius, size.y - radius);
|
||||
} else if (coords.x < niri_corner_radius.w && size.y - niri_corner_radius.w < coords.y) {
|
||||
radius = niri_corner_radius.w;
|
||||
center = vec2(radius, size.y - radius);
|
||||
} else {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
float dist = distance(coords, center);
|
||||
return 1.0 - smoothstep(radius - 0.5, radius + 0.5, dist);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#version 100
|
||||
|
||||
uniform mat3 matrix;
|
||||
uniform mat3 tex_matrix;
|
||||
|
||||
attribute vec2 vert;
|
||||
attribute vec4 vert_position;
|
||||
|
||||
varying vec2 niri_v_coords;
|
||||
|
||||
mat2 scale(vec2 scale_vec){
|
||||
return mat2(
|
||||
scale_vec.x, 0.0,
|
||||
0.0, scale_vec.y
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec2 vert_transform_translation = vert_position.xy;
|
||||
vec2 vert_transform_scale = vert_position.zw;
|
||||
vec3 position = vec3(vert * scale(vert_transform_scale) + vert_transform_translation, 1.0);
|
||||
niri_v_coords = (tex_matrix * position).xy;
|
||||
gl_Position = vec4(matrix * position, 1.0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
use std::cell::OnceCell;
|
||||
|
||||
use niri_config::BlockOutFrom;
|
||||
use smithay::backend::allocator::Fourcc;
|
||||
use smithay::backend::renderer::element::{Kind, RenderElement};
|
||||
use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
|
||||
use smithay::utils::{Logical, Physical, Point, Rectangle, Scale, Size, Transform};
|
||||
|
||||
use super::{render_to_encompassing_texture, RenderTarget, ToRenderElement};
|
||||
|
||||
/// Snapshot of a render.
|
||||
#[derive(Debug)]
|
||||
pub struct RenderSnapshot<C, B> {
|
||||
/// Contents for a normal render.
|
||||
///
|
||||
/// Relative to the geometry.
|
||||
pub contents: Vec<C>,
|
||||
|
||||
/// Blocked-out contents.
|
||||
///
|
||||
/// Relative to the geometry.
|
||||
pub blocked_out_contents: Vec<B>,
|
||||
|
||||
/// Where the contents were blocked out from at the time of the snapshot.
|
||||
pub block_out_from: Option<BlockOutFrom>,
|
||||
|
||||
/// Visual size of the element at the point of the snapshot.
|
||||
pub size: Size<i32, Logical>,
|
||||
|
||||
/// Contents rendered into a texture (lazily).
|
||||
pub texture: OnceCell<Option<(GlesTexture, Rectangle<i32, Physical>)>>,
|
||||
|
||||
/// Blocked-out contents rendered into a texture (lazily).
|
||||
pub blocked_out_texture: OnceCell<Option<(GlesTexture, Rectangle<i32, Physical>)>>,
|
||||
}
|
||||
|
||||
impl<C, B, EC, EB> RenderSnapshot<C, B>
|
||||
where
|
||||
C: ToRenderElement<RenderElement = EC>,
|
||||
B: ToRenderElement<RenderElement = EB>,
|
||||
EC: RenderElement<GlesRenderer>,
|
||||
EB: RenderElement<GlesRenderer>,
|
||||
{
|
||||
pub fn texture(
|
||||
&self,
|
||||
renderer: &mut GlesRenderer,
|
||||
scale: Scale<f64>,
|
||||
target: RenderTarget,
|
||||
) -> Option<&(GlesTexture, Rectangle<i32, Physical>)> {
|
||||
if target.should_block_out(self.block_out_from) {
|
||||
self.blocked_out_texture.get_or_init(|| {
|
||||
let _span = tracy_client::span!("RenderSnapshot::Texture");
|
||||
|
||||
let elements: Vec<_> = self
|
||||
.blocked_out_contents
|
||||
.iter()
|
||||
.map(|baked| {
|
||||
baked.to_render_element(Point::from((0, 0)), scale, 1., Kind::Unspecified)
|
||||
})
|
||||
.collect();
|
||||
|
||||
match render_to_encompassing_texture(
|
||||
renderer,
|
||||
scale,
|
||||
Transform::Normal,
|
||||
Fourcc::Abgr8888,
|
||||
&elements,
|
||||
) {
|
||||
Ok((texture, _sync_point, geo)) => Some((texture, geo)),
|
||||
Err(err) => {
|
||||
warn!("error rendering blocked-out contents to texture: {err:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
self.texture.get_or_init(|| {
|
||||
let _span = tracy_client::span!("RenderSnapshot::Texture");
|
||||
|
||||
let elements: Vec<_> = self
|
||||
.contents
|
||||
.iter()
|
||||
.map(|baked| {
|
||||
baked.to_render_element(Point::from((0, 0)), scale, 1., Kind::Unspecified)
|
||||
})
|
||||
.collect();
|
||||
|
||||
match render_to_encompassing_texture(
|
||||
renderer,
|
||||
scale,
|
||||
Transform::Normal,
|
||||
Fourcc::Abgr8888,
|
||||
&elements,
|
||||
) {
|
||||
Ok((texture, _sync_point, geo)) => Some((texture, geo)),
|
||||
Err(err) => {
|
||||
warn!("error rendering contents to texture: {err:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
.as_ref()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
use smithay::backend::renderer::element::texture::TextureBuffer;
|
||||
use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
|
||||
use smithay::backend::renderer::utils::{import_surface, RendererSurfaceStateUserData};
|
||||
use smithay::backend::renderer::Renderer as _;
|
||||
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
|
||||
use smithay::utils::{Logical, Point};
|
||||
use smithay::wayland::compositor::{with_surface_tree_downward, TraversalAction};
|
||||
|
||||
use super::BakedBuffer;
|
||||
|
||||
/// Renders elements from a surface tree as textures into `storage`.
|
||||
pub fn render_snapshot_from_surface_tree(
|
||||
renderer: &mut GlesRenderer,
|
||||
surface: &WlSurface,
|
||||
location: Point<i32, Logical>,
|
||||
storage: &mut Vec<BakedBuffer<TextureBuffer<GlesTexture>>>,
|
||||
) {
|
||||
let _span = tracy_client::span!("render_snapshot_from_surface_tree");
|
||||
|
||||
with_surface_tree_downward(
|
||||
surface,
|
||||
location,
|
||||
|_, states, location| {
|
||||
let mut location = *location;
|
||||
let data = states.data_map.get::<RendererSurfaceStateUserData>();
|
||||
|
||||
if let Some(data) = data {
|
||||
let data = &*data.borrow();
|
||||
|
||||
if let Some(view) = data.view() {
|
||||
location += view.offset;
|
||||
TraversalAction::DoChildren(location)
|
||||
} else {
|
||||
TraversalAction::SkipChildren
|
||||
}
|
||||
} else {
|
||||
TraversalAction::SkipChildren
|
||||
}
|
||||
},
|
||||
|_, states, location| {
|
||||
let mut location = *location;
|
||||
let data = states.data_map.get::<RendererSurfaceStateUserData>();
|
||||
|
||||
if let Some(data) = data {
|
||||
if let Some(view) = data.borrow().view() {
|
||||
location += view.offset;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(err) = import_surface(renderer, states) {
|
||||
warn!("failed to import surface: {err:?}");
|
||||
return;
|
||||
}
|
||||
|
||||
let data = data.borrow();
|
||||
let view = data.view().unwrap();
|
||||
let Some(texture) = data.texture::<GlesRenderer>(renderer.id()) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let buffer = TextureBuffer::from_texture(
|
||||
renderer,
|
||||
texture.clone(),
|
||||
data.buffer_scale(),
|
||||
data.buffer_transform(),
|
||||
None,
|
||||
);
|
||||
|
||||
let baked = BakedBuffer {
|
||||
buffer,
|
||||
location,
|
||||
src: Some(view.src),
|
||||
dst: Some(view.dst),
|
||||
};
|
||||
|
||||
storage.push(baked);
|
||||
}
|
||||
},
|
||||
|_, _, _| true,
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user