├── .cargo ├── config.default └── config.toml ├── .gitignore ├── .idea └── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE.md ├── README.md ├── build.rs ├── cosmic-notifications-config ├── Cargo.toml └── src │ └── lib.rs ├── cosmic-notifications-util ├── .gitignore ├── Cargo.toml └── src │ ├── image.rs │ └── lib.rs ├── data ├── com.system76.CosmicNotifications.desktop ├── com.system76.CosmicNotifications.metainfo.xml ├── icons │ ├── com.system76.CosmicNotifications.svg │ └── justfile └── justfile ├── debian ├── changelog ├── control ├── copyright ├── install ├── rules └── source │ ├── format │ └── options ├── flake.lock ├── flake.nix ├── hooks └── pre-commit.hook ├── i18n.toml ├── i18n ├── af │ └── cosmic_notifications.ftl ├── ar │ └── cosmic_notifications.ftl ├── be │ └── cosmic_notifications.ftl ├── bg │ └── cosmic_notifications.ftl ├── ca │ └── cosmic_notifications.ftl ├── cs │ └── cosmic_notifications.ftl ├── da │ └── cosmic_notifications.ftl ├── de │ └── cosmic_notifications.ftl ├── el │ └── cosmic_notifications.ftl ├── en-GB │ └── cosmic_notifications.ftl ├── en │ └── cosmic_notifications.ftl ├── eo │ └── cosmic_notifications.ftl ├── es-419 │ └── cosmic_notifications.ftl ├── es-MX │ └── cosmic_notifications.ftl ├── es │ └── cosmic_notifications.ftl ├── et │ └── cosmic_notifications.ftl ├── fa │ └── cosmic_notifications.ftl ├── fi │ └── cosmic_notifications.ftl ├── fr │ └── cosmic_notifications.ftl ├── fy │ └── cosmic_notifications.ftl ├── ga │ └── cosmic_notifications.ftl ├── gd │ └── cosmic_notifications.ftl ├── he │ └── cosmic_notifications.ftl ├── hi │ └── cosmic_notifications.ftl ├── hr │ └── cosmic_notifications.ftl ├── hu │ └── cosmic_notifications.ftl ├── id │ └── cosmic_notifications.ftl ├── ie │ └── cosmic_notifications.ftl ├── it │ └── cosmic_notifications.ftl ├── ja │ └── cosmic_notifications.ftl ├── jv │ └── cosmic_notifications.ftl ├── kn │ └── cosmic_notifications.ftl ├── ko │ └── cosmic_notifications.ftl ├── li │ └── cosmic_notifications.ftl ├── lt │ └── cosmic_notifications.ftl ├── nb-NO │ └── cosmic_notifications.ftl ├── nl │ └── cosmic_notifications.ftl ├── pl │ └── cosmic_notifications.ftl ├── pt-BR │ └── cosmic_notifications.ftl ├── pt │ └── cosmic_notifications.ftl ├── ro │ └── cosmic_notifications.ftl ├── ru │ └── cosmic_notifications.ftl ├── sk │ └── cosmic_notifications.ftl ├── sr-Cyrl │ └── cosmic_notifications.ftl ├── sr-Latn │ └── cosmic_notifications.ftl ├── sr │ └── cosmic_notifications.ftl ├── sv │ └── cosmic_notifications.ftl ├── ta │ └── cosmic_notifications.ftl ├── th │ └── cosmic_notifications.ftl ├── tr │ └── cosmic_notifications.ftl ├── uk │ └── cosmic_notifications.ftl ├── vi │ └── cosmic_notifications.ftl ├── zh-CN │ └── cosmic_notifications.ftl └── zh-TW │ └── cosmic_notifications.ftl ├── justfile ├── rust-toolchain.toml └── src ├── app.rs ├── config.rs ├── localize.rs ├── main.rs └── subscriptions ├── applet.rs ├── mod.rs └── notifications.rs /.cargo/config.default: -------------------------------------------------------------------------------- 1 | [build] 2 | rustflags = ["--cfg", "tokio_unstable"] 3 | rustdocflags = ["--cfg", "tokio_unstable"] 4 | -------------------------------------------------------------------------------- /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | rustflags = ["--cfg", "tokio_unstable"] 3 | rustdocflags = ["--cfg", "tokio_unstable"] 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | build/ 3 | _build/ 4 | builddir/ 5 | build-aux/app 6 | build-aux/.flatpak-builder/ 7 | *.ui.in~ 8 | *.ui~ 9 | .flatpak/ 10 | .flatpak-builder/ 11 | flatpak_app/ 12 | vendor 13 | vendor.tar 14 | /result 15 | 16 | debian/* 17 | !debian/*install 18 | !debian/*postinst 19 | !debian/changelog 20 | !debian/copyright 21 | !debian/control 22 | !debian/links 23 | !debian/rules 24 | !debian/source 25 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cosmic-notifications" 3 | version = "0.1.0" 4 | authors = ["Ashley Wulber "] 5 | edition = "2024" 6 | rust-version = "1.85" 7 | 8 | [dependencies] 9 | libcosmic = { git = "https://github.com/pop-os/libcosmic", default-features = false, features = [ 10 | "autosize", 11 | "dbus-config", 12 | "a11y", 13 | "winit", 14 | "multi-window", 15 | "wayland", 16 | "tokio", 17 | "dbus-config", 18 | ] } 19 | sctk = { package = "smithay-client-toolkit", version = "0.20.0" } 20 | anyhow = "1.0" 21 | i18n-embed = { version = "0.16", features = [ 22 | "fluent-system", 23 | "desktop-requester", 24 | ] } 25 | i18n-embed-fl = "0.10" 26 | color-backtrace = "0.7.1" 27 | cosmic-notifications-util = { path = "./cosmic-notifications-util" } 28 | cosmic-notifications-config = { path = "./cosmic-notifications-config" } 29 | cosmic-panel-config = { git = "https://github.com/pop-os/cosmic-panel" } 30 | cosmic-time = { git = "https://github.com/pop-os/cosmic-time", default-features = false} 31 | rust-embed = "8.7.2" 32 | rustix = "1.1.1" 33 | tokio = { version = "1.47.1", features = [ 34 | "sync", 35 | "rt", 36 | "tracing", 37 | "macros", 38 | "net", 39 | "io-util", 40 | ] } 41 | tracing = "0.1" 42 | tracing-subscriber = { version = "0.3.20", features = ["std", "env-filter"] } 43 | tracing-journald = { version = "0.3.1", optional = true } 44 | zbus = { version = "5.11.0", features = ["tokio", "p2p"] } 45 | 46 | [features] 47 | systemd = ["dep:tracing-journald"] 48 | default = ["systemd"] 49 | 50 | [workspace] 51 | members = ["cosmic-notifications-util", "cosmic-notifications-config"] 52 | 53 | [profile.release] 54 | opt-level = "s" 55 | lto = "thin" 56 | 57 | # cosmic-config = { git = "https://github.com/pop-os/libcosmic//" } 58 | # [patch.'https://github.com/pop-os/libcosmic'] 59 | # libcosmic = { path = "../libcosmic" } 60 | # cosmic-config = { path = "../libcosmic/cosmic-config" } 61 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU General Public License 2 | ========================== 3 | 4 | _Version 3, 29 June 2007_ 5 | _Copyright © 2007 Free Software Foundation, Inc. <>_ 6 | 7 | Everyone is permitted to copy and distribute verbatim copies of this license 8 | document, but changing it is not allowed. 9 | 10 | ## Preamble 11 | 12 | The GNU General Public License is a free, copyleft license for software and other 13 | kinds of works. 14 | 15 | The licenses for most software and other practical works are designed to take away 16 | your freedom to share and change the works. By contrast, the GNU General Public 17 | License is intended to guarantee your freedom to share and change all versions of a 18 | program--to make sure it remains free software for all its users. We, the Free 19 | Software Foundation, use the GNU General Public License for most of our software; it 20 | applies also to any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not price. Our General 24 | Public Licenses are designed to make sure that you have the freedom to distribute 25 | copies of free software (and charge for them if you wish), that you receive source 26 | code or can get it if you want it, that you can change the software or use pieces of 27 | it in new free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you these rights or 30 | asking you to surrender the rights. Therefore, you have certain responsibilities if 31 | you distribute copies of the software, or if you modify it: responsibilities to 32 | respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether gratis or for a fee, 35 | you must pass on to the recipients the same freedoms that you received. You must make 36 | sure that they, too, receive or can get the source code. And you must show them these 37 | terms so they know their rights. 38 | 39 | Developers that use the GNU GPL protect your rights with two steps: **(1)** assert 40 | copyright on the software, and **(2)** offer you this License giving you legal permission 41 | to copy, distribute and/or modify it. 42 | 43 | For the developers' and authors' protection, the GPL clearly explains that there is 44 | no warranty for this free software. For both users' and authors' sake, the GPL 45 | requires that modified versions be marked as changed, so that their problems will not 46 | be attributed erroneously to authors of previous versions. 47 | 48 | Some devices are designed to deny users access to install or run modified versions of 49 | the software inside them, although the manufacturer can do so. This is fundamentally 50 | incompatible with the aim of protecting users' freedom to change the software. The 51 | systematic pattern of such abuse occurs in the area of products for individuals to 52 | use, which is precisely where it is most unacceptable. Therefore, we have designed 53 | this version of the GPL to prohibit the practice for those products. If such problems 54 | arise substantially in other domains, we stand ready to extend this provision to 55 | those domains in future versions of the GPL, as needed to protect the freedom of 56 | users. 57 | 58 | Finally, every program is threatened constantly by software patents. States should 59 | not allow patents to restrict development and use of software on general-purpose 60 | computers, but in those that do, we wish to avoid the special danger that patents 61 | applied to a free program could make it effectively proprietary. To prevent this, the 62 | GPL assures that patents cannot be used to render the program non-free. 63 | 64 | The precise terms and conditions for copying, distribution and modification follow. 65 | 66 | ## TERMS AND CONDITIONS 67 | 68 | ### 0. Definitions 69 | 70 | “This License” refers to version 3 of the GNU General Public License. 71 | 72 | “Copyright” also means copyright-like laws that apply to other kinds of 73 | works, such as semiconductor masks. 74 | 75 | “The Program” refers to any copyrightable work licensed under this 76 | License. Each licensee is addressed as “you”. “Licensees” and 77 | “recipients” may be individuals or organizations. 78 | 79 | To “modify” a work means to copy from or adapt all or part of the work in 80 | a fashion requiring copyright permission, other than the making of an exact copy. The 81 | resulting work is called a “modified version” of the earlier work or a 82 | work “based on” the earlier work. 83 | 84 | A “covered work” means either the unmodified Program or a work based on 85 | the Program. 86 | 87 | To “propagate” a work means to do anything with it that, without 88 | permission, would make you directly or secondarily liable for infringement under 89 | applicable copyright law, except executing it on a computer or modifying a private 90 | copy. Propagation includes copying, distribution (with or without modification), 91 | making available to the public, and in some countries other activities as well. 92 | 93 | To “convey” a work means any kind of propagation that enables other 94 | parties to make or receive copies. Mere interaction with a user through a computer 95 | network, with no transfer of a copy, is not conveying. 96 | 97 | An interactive user interface displays “Appropriate Legal Notices” to the 98 | extent that it includes a convenient and prominently visible feature that **(1)** 99 | displays an appropriate copyright notice, and **(2)** tells the user that there is no 100 | warranty for the work (except to the extent that warranties are provided), that 101 | licensees may convey the work under this License, and how to view a copy of this 102 | License. If the interface presents a list of user commands or options, such as a 103 | menu, a prominent item in the list meets this criterion. 104 | 105 | ### 1. Source Code 106 | 107 | The “source code” for a work means the preferred form of the work for 108 | making modifications to it. “Object code” means any non-source form of a 109 | work. 110 | 111 | A “Standard Interface” means an interface that either is an official 112 | standard defined by a recognized standards body, or, in the case of interfaces 113 | specified for a particular programming language, one that is widely used among 114 | developers working in that language. 115 | 116 | The “System Libraries” of an executable work include anything, other than 117 | the work as a whole, that **(a)** is included in the normal form of packaging a Major 118 | Component, but which is not part of that Major Component, and **(b)** serves only to 119 | enable use of the work with that Major Component, or to implement a Standard 120 | Interface for which an implementation is available to the public in source code form. 121 | A “Major Component”, in this context, means a major essential component 122 | (kernel, window system, and so on) of the specific operating system (if any) on which 123 | the executable work runs, or a compiler used to produce the work, or an object code 124 | interpreter used to run it. 125 | 126 | The “Corresponding Source” for a work in object code form means all the 127 | source code needed to generate, install, and (for an executable work) run the object 128 | code and to modify the work, including scripts to control those activities. However, 129 | it does not include the work's System Libraries, or general-purpose tools or 130 | generally available free programs which are used unmodified in performing those 131 | activities but which are not part of the work. For example, Corresponding Source 132 | includes interface definition files associated with source files for the work, and 133 | the source code for shared libraries and dynamically linked subprograms that the work 134 | is specifically designed to require, such as by intimate data communication or 135 | control flow between those subprograms and other parts of the work. 136 | 137 | The Corresponding Source need not include anything that users can regenerate 138 | automatically from other parts of the Corresponding Source. 139 | 140 | The Corresponding Source for a work in source code form is that same work. 141 | 142 | ### 2. Basic Permissions 143 | 144 | All rights granted under this License are granted for the term of copyright on the 145 | Program, and are irrevocable provided the stated conditions are met. This License 146 | explicitly affirms your unlimited permission to run the unmodified Program. The 147 | output from running a covered work is covered by this License only if the output, 148 | given its content, constitutes a covered work. This License acknowledges your rights 149 | of fair use or other equivalent, as provided by copyright law. 150 | 151 | You may make, run and propagate covered works that you do not convey, without 152 | conditions so long as your license otherwise remains in force. You may convey covered 153 | works to others for the sole purpose of having them make modifications exclusively 154 | for you, or provide you with facilities for running those works, provided that you 155 | comply with the terms of this License in conveying all material for which you do not 156 | control copyright. Those thus making or running the covered works for you must do so 157 | exclusively on your behalf, under your direction and control, on terms that prohibit 158 | them from making any copies of your copyrighted material outside their relationship 159 | with you. 160 | 161 | Conveying under any other circumstances is permitted solely under the conditions 162 | stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 163 | 164 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law 165 | 166 | No covered work shall be deemed part of an effective technological measure under any 167 | applicable law fulfilling obligations under article 11 of the WIPO copyright treaty 168 | adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention 169 | of such measures. 170 | 171 | When you convey a covered work, you waive any legal power to forbid circumvention of 172 | technological measures to the extent such circumvention is effected by exercising 173 | rights under this License with respect to the covered work, and you disclaim any 174 | intention to limit operation or modification of the work as a means of enforcing, 175 | against the work's users, your or third parties' legal rights to forbid circumvention 176 | of technological measures. 177 | 178 | ### 4. Conveying Verbatim Copies 179 | 180 | You may convey verbatim copies of the Program's source code as you receive it, in any 181 | medium, provided that you conspicuously and appropriately publish on each copy an 182 | appropriate copyright notice; keep intact all notices stating that this License and 183 | any non-permissive terms added in accord with section 7 apply to the code; keep 184 | intact all notices of the absence of any warranty; and give all recipients a copy of 185 | this License along with the Program. 186 | 187 | You may charge any price or no price for each copy that you convey, and you may offer 188 | support or warranty protection for a fee. 189 | 190 | ### 5. Conveying Modified Source Versions 191 | 192 | You may convey a work based on the Program, or the modifications to produce it from 193 | the Program, in the form of source code under the terms of section 4, provided that 194 | you also meet all of these conditions: 195 | 196 | * **a)** The work must carry prominent notices stating that you modified it, and giving a 197 | relevant date. 198 | * **b)** The work must carry prominent notices stating that it is released under this 199 | License and any conditions added under section 7. This requirement modifies the 200 | requirement in section 4 to “keep intact all notices”. 201 | * **c)** You must license the entire work, as a whole, under this License to anyone who 202 | comes into possession of a copy. This License will therefore apply, along with any 203 | applicable section 7 additional terms, to the whole of the work, and all its parts, 204 | regardless of how they are packaged. This License gives no permission to license the 205 | work in any other way, but it does not invalidate such permission if you have 206 | separately received it. 207 | * **d)** If the work has interactive user interfaces, each must display Appropriate Legal 208 | Notices; however, if the Program has interactive interfaces that do not display 209 | Appropriate Legal Notices, your work need not make them do so. 210 | 211 | A compilation of a covered work with other separate and independent works, which are 212 | not by their nature extensions of the covered work, and which are not combined with 213 | it such as to form a larger program, in or on a volume of a storage or distribution 214 | medium, is called an “aggregate” if the compilation and its resulting 215 | copyright are not used to limit the access or legal rights of the compilation's users 216 | beyond what the individual works permit. Inclusion of a covered work in an aggregate 217 | does not cause this License to apply to the other parts of the aggregate. 218 | 219 | ### 6. Conveying Non-Source Forms 220 | 221 | You may convey a covered work in object code form under the terms of sections 4 and 222 | 5, provided that you also convey the machine-readable Corresponding Source under the 223 | terms of this License, in one of these ways: 224 | 225 | * **a)** Convey the object code in, or embodied in, a physical product (including a 226 | physical distribution medium), accompanied by the Corresponding Source fixed on a 227 | durable physical medium customarily used for software interchange. 228 | * **b)** Convey the object code in, or embodied in, a physical product (including a 229 | physical distribution medium), accompanied by a written offer, valid for at least 230 | three years and valid for as long as you offer spare parts or customer support for 231 | that product model, to give anyone who possesses the object code either **(1)** a copy of 232 | the Corresponding Source for all the software in the product that is covered by this 233 | License, on a durable physical medium customarily used for software interchange, for 234 | a price no more than your reasonable cost of physically performing this conveying of 235 | source, or **(2)** access to copy the Corresponding Source from a network server at no 236 | charge. 237 | * **c)** Convey individual copies of the object code with a copy of the written offer to 238 | provide the Corresponding Source. This alternative is allowed only occasionally and 239 | noncommercially, and only if you received the object code with such an offer, in 240 | accord with subsection 6b. 241 | * **d)** Convey the object code by offering access from a designated place (gratis or for 242 | a charge), and offer equivalent access to the Corresponding Source in the same way 243 | through the same place at no further charge. You need not require recipients to copy 244 | the Corresponding Source along with the object code. If the place to copy the object 245 | code is a network server, the Corresponding Source may be on a different server 246 | (operated by you or a third party) that supports equivalent copying facilities, 247 | provided you maintain clear directions next to the object code saying where to find 248 | the Corresponding Source. Regardless of what server hosts the Corresponding Source, 249 | you remain obligated to ensure that it is available for as long as needed to satisfy 250 | these requirements. 251 | * **e)** Convey the object code using peer-to-peer transmission, provided you inform 252 | other peers where the object code and Corresponding Source of the work are being 253 | offered to the general public at no charge under subsection 6d. 254 | 255 | A separable portion of the object code, whose source code is excluded from the 256 | Corresponding Source as a System Library, need not be included in conveying the 257 | object code work. 258 | 259 | A “User Product” is either **(1)** a “consumer product”, which 260 | means any tangible personal property which is normally used for personal, family, or 261 | household purposes, or **(2)** anything designed or sold for incorporation into a 262 | dwelling. In determining whether a product is a consumer product, doubtful cases 263 | shall be resolved in favor of coverage. For a particular product received by a 264 | particular user, “normally used” refers to a typical or common use of 265 | that class of product, regardless of the status of the particular user or of the way 266 | in which the particular user actually uses, or expects or is expected to use, the 267 | product. A product is a consumer product regardless of whether the product has 268 | substantial commercial, industrial or non-consumer uses, unless such uses represent 269 | the only significant mode of use of the product. 270 | 271 | “Installation Information” for a User Product means any methods, 272 | procedures, authorization keys, or other information required to install and execute 273 | modified versions of a covered work in that User Product from a modified version of 274 | its Corresponding Source. The information must suffice to ensure that the continued 275 | functioning of the modified object code is in no case prevented or interfered with 276 | solely because modification has been made. 277 | 278 | If you convey an object code work under this section in, or with, or specifically for 279 | use in, a User Product, and the conveying occurs as part of a transaction in which 280 | the right of possession and use of the User Product is transferred to the recipient 281 | in perpetuity or for a fixed term (regardless of how the transaction is 282 | characterized), the Corresponding Source conveyed under this section must be 283 | accompanied by the Installation Information. But this requirement does not apply if 284 | neither you nor any third party retains the ability to install modified object code 285 | on the User Product (for example, the work has been installed in ROM). 286 | 287 | The requirement to provide Installation Information does not include a requirement to 288 | continue to provide support service, warranty, or updates for a work that has been 289 | modified or installed by the recipient, or for the User Product in which it has been 290 | modified or installed. Access to a network may be denied when the modification itself 291 | materially and adversely affects the operation of the network or violates the rules 292 | and protocols for communication across the network. 293 | 294 | Corresponding Source conveyed, and Installation Information provided, in accord with 295 | this section must be in a format that is publicly documented (and with an 296 | implementation available to the public in source code form), and must require no 297 | special password or key for unpacking, reading or copying. 298 | 299 | ### 7. Additional Terms 300 | 301 | “Additional permissions” are terms that supplement the terms of this 302 | License by making exceptions from one or more of its conditions. Additional 303 | permissions that are applicable to the entire Program shall be treated as though they 304 | were included in this License, to the extent that they are valid under applicable 305 | law. If additional permissions apply only to part of the Program, that part may be 306 | used separately under those permissions, but the entire Program remains governed by 307 | this License without regard to the additional permissions. 308 | 309 | When you convey a copy of a covered work, you may at your option remove any 310 | additional permissions from that copy, or from any part of it. (Additional 311 | permissions may be written to require their own removal in certain cases when you 312 | modify the work.) You may place additional permissions on material, added by you to a 313 | covered work, for which you have or can give appropriate copyright permission. 314 | 315 | Notwithstanding any other provision of this License, for material you add to a 316 | covered work, you may (if authorized by the copyright holders of that material) 317 | supplement the terms of this License with terms: 318 | 319 | * **a)** Disclaiming warranty or limiting liability differently from the terms of 320 | sections 15 and 16 of this License; or 321 | * **b)** Requiring preservation of specified reasonable legal notices or author 322 | attributions in that material or in the Appropriate Legal Notices displayed by works 323 | containing it; or 324 | * **c)** Prohibiting misrepresentation of the origin of that material, or requiring that 325 | modified versions of such material be marked in reasonable ways as different from the 326 | original version; or 327 | * **d)** Limiting the use for publicity purposes of names of licensors or authors of the 328 | material; or 329 | * **e)** Declining to grant rights under trademark law for use of some trade names, 330 | trademarks, or service marks; or 331 | * **f)** Requiring indemnification of licensors and authors of that material by anyone 332 | who conveys the material (or modified versions of it) with contractual assumptions of 333 | liability to the recipient, for any liability that these contractual assumptions 334 | directly impose on those licensors and authors. 335 | 336 | All other non-permissive additional terms are considered “further 337 | restrictions” within the meaning of section 10. If the Program as you received 338 | it, or any part of it, contains a notice stating that it is governed by this License 339 | along with a term that is a further restriction, you may remove that term. If a 340 | license document contains a further restriction but permits relicensing or conveying 341 | under this License, you may add to a covered work material governed by the terms of 342 | that license document, provided that the further restriction does not survive such 343 | relicensing or conveying. 344 | 345 | If you add terms to a covered work in accord with this section, you must place, in 346 | the relevant source files, a statement of the additional terms that apply to those 347 | files, or a notice indicating where to find the applicable terms. 348 | 349 | Additional terms, permissive or non-permissive, may be stated in the form of a 350 | separately written license, or stated as exceptions; the above requirements apply 351 | either way. 352 | 353 | ### 8. Termination 354 | 355 | You may not propagate or modify a covered work except as expressly provided under 356 | this License. Any attempt otherwise to propagate or modify it is void, and will 357 | automatically terminate your rights under this License (including any patent licenses 358 | granted under the third paragraph of section 11). 359 | 360 | However, if you cease all violation of this License, then your license from a 361 | particular copyright holder is reinstated **(a)** provisionally, unless and until the 362 | copyright holder explicitly and finally terminates your license, and **(b)** permanently, 363 | if the copyright holder fails to notify you of the violation by some reasonable means 364 | prior to 60 days after the cessation. 365 | 366 | Moreover, your license from a particular copyright holder is reinstated permanently 367 | if the copyright holder notifies you of the violation by some reasonable means, this 368 | is the first time you have received notice of violation of this License (for any 369 | work) from that copyright holder, and you cure the violation prior to 30 days after 370 | your receipt of the notice. 371 | 372 | Termination of your rights under this section does not terminate the licenses of 373 | parties who have received copies or rights from you under this License. If your 374 | rights have been terminated and not permanently reinstated, you do not qualify to 375 | receive new licenses for the same material under section 10. 376 | 377 | ### 9. Acceptance Not Required for Having Copies 378 | 379 | You are not required to accept this License in order to receive or run a copy of the 380 | Program. Ancillary propagation of a covered work occurring solely as a consequence of 381 | using peer-to-peer transmission to receive a copy likewise does not require 382 | acceptance. However, nothing other than this License grants you permission to 383 | propagate or modify any covered work. These actions infringe copyright if you do not 384 | accept this License. Therefore, by modifying or propagating a covered work, you 385 | indicate your acceptance of this License to do so. 386 | 387 | ### 10. Automatic Licensing of Downstream Recipients 388 | 389 | Each time you convey a covered work, the recipient automatically receives a license 390 | from the original licensors, to run, modify and propagate that work, subject to this 391 | License. You are not responsible for enforcing compliance by third parties with this 392 | License. 393 | 394 | An “entity transaction” is a transaction transferring control of an 395 | organization, or substantially all assets of one, or subdividing an organization, or 396 | merging organizations. If propagation of a covered work results from an entity 397 | transaction, each party to that transaction who receives a copy of the work also 398 | receives whatever licenses to the work the party's predecessor in interest had or 399 | could give under the previous paragraph, plus a right to possession of the 400 | Corresponding Source of the work from the predecessor in interest, if the predecessor 401 | has it or can get it with reasonable efforts. 402 | 403 | You may not impose any further restrictions on the exercise of the rights granted or 404 | affirmed under this License. For example, you may not impose a license fee, royalty, 405 | or other charge for exercise of rights granted under this License, and you may not 406 | initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging 407 | that any patent claim is infringed by making, using, selling, offering for sale, or 408 | importing the Program or any portion of it. 409 | 410 | ### 11. Patents 411 | 412 | A “contributor” is a copyright holder who authorizes use under this 413 | License of the Program or a work on which the Program is based. The work thus 414 | licensed is called the contributor's “contributor version”. 415 | 416 | A contributor's “essential patent claims” are all patent claims owned or 417 | controlled by the contributor, whether already acquired or hereafter acquired, that 418 | would be infringed by some manner, permitted by this License, of making, using, or 419 | selling its contributor version, but do not include claims that would be infringed 420 | only as a consequence of further modification of the contributor version. For 421 | purposes of this definition, “control” includes the right to grant patent 422 | sublicenses in a manner consistent with the requirements of this License. 423 | 424 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license 425 | under the contributor's essential patent claims, to make, use, sell, offer for sale, 426 | import and otherwise run, modify and propagate the contents of its contributor 427 | version. 428 | 429 | In the following three paragraphs, a “patent license” is any express 430 | agreement or commitment, however denominated, not to enforce a patent (such as an 431 | express permission to practice a patent or covenant not to sue for patent 432 | infringement). To “grant” such a patent license to a party means to make 433 | such an agreement or commitment not to enforce a patent against the party. 434 | 435 | If you convey a covered work, knowingly relying on a patent license, and the 436 | Corresponding Source of the work is not available for anyone to copy, free of charge 437 | and under the terms of this License, through a publicly available network server or 438 | other readily accessible means, then you must either **(1)** cause the Corresponding 439 | Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the 440 | patent license for this particular work, or **(3)** arrange, in a manner consistent with 441 | the requirements of this License, to extend the patent license to downstream 442 | recipients. “Knowingly relying” means you have actual knowledge that, but 443 | for the patent license, your conveying the covered work in a country, or your 444 | recipient's use of the covered work in a country, would infringe one or more 445 | identifiable patents in that country that you have reason to believe are valid. 446 | 447 | If, pursuant to or in connection with a single transaction or arrangement, you 448 | convey, or propagate by procuring conveyance of, a covered work, and grant a patent 449 | license to some of the parties receiving the covered work authorizing them to use, 450 | propagate, modify or convey a specific copy of the covered work, then the patent 451 | license you grant is automatically extended to all recipients of the covered work and 452 | works based on it. 453 | 454 | A patent license is “discriminatory” if it does not include within the 455 | scope of its coverage, prohibits the exercise of, or is conditioned on the 456 | non-exercise of one or more of the rights that are specifically granted under this 457 | License. You may not convey a covered work if you are a party to an arrangement with 458 | a third party that is in the business of distributing software, under which you make 459 | payment to the third party based on the extent of your activity of conveying the 460 | work, and under which the third party grants, to any of the parties who would receive 461 | the covered work from you, a discriminatory patent license **(a)** in connection with 462 | copies of the covered work conveyed by you (or copies made from those copies), or **(b)** 463 | primarily for and in connection with specific products or compilations that contain 464 | the covered work, unless you entered into that arrangement, or that patent license 465 | was granted, prior to 28 March 2007. 466 | 467 | Nothing in this License shall be construed as excluding or limiting any implied 468 | license or other defenses to infringement that may otherwise be available to you 469 | under applicable patent law. 470 | 471 | ### 12. No Surrender of Others' Freedom 472 | 473 | If conditions are imposed on you (whether by court order, agreement or otherwise) 474 | that contradict the conditions of this License, they do not excuse you from the 475 | conditions of this License. If you cannot convey a covered work so as to satisfy 476 | simultaneously your obligations under this License and any other pertinent 477 | obligations, then as a consequence you may not convey it at all. For example, if you 478 | agree to terms that obligate you to collect a royalty for further conveying from 479 | those to whom you convey the Program, the only way you could satisfy both those terms 480 | and this License would be to refrain entirely from conveying the Program. 481 | 482 | ### 13. Use with the GNU Affero General Public License 483 | 484 | Notwithstanding any other provision of this License, you have permission to link or 485 | combine any covered work with a work licensed under version 3 of the GNU Affero 486 | General Public License into a single combined work, and to convey the resulting work. 487 | The terms of this License will continue to apply to the part which is the covered 488 | work, but the special requirements of the GNU Affero General Public License, section 489 | 13, concerning interaction through a network will apply to the combination as such. 490 | 491 | ### 14. Revised Versions of this License 492 | 493 | The Free Software Foundation may publish revised and/or new versions of the GNU 494 | General Public License from time to time. Such new versions will be similar in spirit 495 | to the present version, but may differ in detail to address new problems or concerns. 496 | 497 | Each version is given a distinguishing version number. If the Program specifies that 498 | a certain numbered version of the GNU General Public License “or any later 499 | version” applies to it, you have the option of following the terms and 500 | conditions either of that numbered version or of any later version published by the 501 | Free Software Foundation. If the Program does not specify a version number of the GNU 502 | General Public License, you may choose any version ever published by the Free 503 | Software Foundation. 504 | 505 | If the Program specifies that a proxy can decide which future versions of the GNU 506 | General Public License can be used, that proxy's public statement of acceptance of a 507 | version permanently authorizes you to choose that version for the Program. 508 | 509 | Later license versions may give you additional or different permissions. However, no 510 | additional obligations are imposed on any author or copyright holder as a result of 511 | your choosing to follow a later version. 512 | 513 | ### 15. Disclaimer of Warranty 514 | 515 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 516 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 517 | PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER 518 | EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 519 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE 520 | QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 521 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 522 | 523 | ### 16. Limitation of Liability 524 | 525 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY 526 | COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS 527 | PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, 528 | INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 529 | PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE 530 | OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE 531 | WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 532 | POSSIBILITY OF SUCH DAMAGES. 533 | 534 | ### 17. Interpretation of Sections 15 and 16 535 | 536 | If the disclaimer of warranty and limitation of liability provided above cannot be 537 | given local legal effect according to their terms, reviewing courts shall apply local 538 | law that most closely approximates an absolute waiver of all civil liability in 539 | connection with the Program, unless a warranty or assumption of liability accompanies 540 | a copy of the Program in return for a fee. 541 | 542 | _END OF TERMS AND CONDITIONS_ 543 | 544 | ## How to Apply These Terms to Your New Programs 545 | 546 | If you develop a new program, and you want it to be of the greatest possible use to 547 | the public, the best way to achieve this is to make it free software which everyone 548 | can redistribute and change under these terms. 549 | 550 | To do so, attach the following notices to the program. It is safest to attach them 551 | to the start of each source file to most effectively state the exclusion of warranty; 552 | and each file should have at least the “copyright” line and a pointer to 553 | where the full notice is found. 554 | 555 | 556 | Copyright (C) 557 | 558 | This program is free software: you can redistribute it and/or modify 559 | it under the terms of the GNU General Public License as published by 560 | the Free Software Foundation, either version 3 of the License, or 561 | (at your option) any later version. 562 | 563 | This program is distributed in the hope that it will be useful, 564 | but WITHOUT ANY WARRANTY; without even the implied warranty of 565 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 566 | GNU General Public License for more details. 567 | 568 | You should have received a copy of the GNU General Public License 569 | along with this program. If not, see . 570 | 571 | Also add information on how to contact you by electronic and paper mail. 572 | 573 | If the program does terminal interaction, make it output a short notice like this 574 | when it starts in an interactive mode: 575 | 576 | Copyright (C) 577 | This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. 578 | This is free software, and you are welcome to redistribute it 579 | under certain conditions; type 'show c' for details. 580 | 581 | The hypothetical commands `show w` and `show c` should show the appropriate parts of 582 | the General Public License. Of course, your program's commands might be different; 583 | for a GUI interface, you would use an “about box”. 584 | 585 | You should also get your employer (if you work as a programmer) or school, if any, to 586 | sign a “copyright disclaimer” for the program, if necessary. For more 587 | information on this, and how to apply and follow the GNU GPL, see 588 | <>. 589 | 590 | The GNU General Public License does not permit incorporating your program into 591 | proprietary programs. If your program is a subroutine library, you may consider it 592 | more useful to permit linking proprietary applications with the library. If this is 593 | what you want to do, use the GNU Lesser General Public License instead of this 594 | License. But first, please read 595 | <>. 596 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cosmic Notifications 2 | 3 | Layer Shell notifications daemon which integrates with COSMIC. 4 | 5 | # Building 6 | 7 | Cosmic Notifications is set up to build a deb and a Nix flake, but it can be built using just. 8 | 9 | Some Build Dependencies: 10 | ``` 11 | cargo, 12 | just, 13 | intltool, 14 | appstream-util, 15 | desktop-file-utils, 16 | libxkbcommon-dev, 17 | pkg-config, 18 | desktop-file-utils, 19 | ``` 20 | 21 | ## Build Commands 22 | 23 | For a typical install from source, use `just` followed with `sudo just install`. 24 | ```sh 25 | just 26 | sudo just install 27 | ``` 28 | 29 | If you are packaging, run `just vendor` outside of your build chroot, then use `just build-vendored` inside the build-chroot. Then you can specify a custom root directory and prefix. 30 | ```sh 31 | # Outside build chroot 32 | just clean-dist 33 | just vendor 34 | 35 | # Inside build chroot 36 | just build-vendored 37 | sudo just rootdir=debian/cosmic-notifications prefix=/usr install 38 | ``` 39 | 40 | # Translators 41 | 42 | Translation files may be found in the i18n directory. New translations may copy the English (en) localization of the project and rename `en` to the desired [ISO 639-1 language code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). Translations may be submitted through GitHub as an issue or pull request. Submissions by email or other means are also acceptable; with the preferred name and email to associate with the changes. 43 | 44 | # Debugging & Profiling 45 | 46 | ## Profiling async tasks with tokio-console 47 | 48 | To debug issues with asynchronous code, install [tokio-console](https://github.com/tokio-rs/console) and run it within a separate terminal. Then kill the **cosmic-notifications** process a couple times in quick succession to prevent **cosmic-session** from spawning it again. Then you can start **cosmic-notifications** with **tokio-console** support either by running `just tokio-console` from this repository to test code changes, or `env TOKIO_CONSOLE=1 cosmic-notifications` to enable it with the installed version of **cosmic-notifications**. -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /cosmic-notifications-config/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cosmic-notifications-config" 3 | version = "0.1.0" 4 | edition = "2024" 5 | rust-version = "1.85" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | serde = { version = "1.0", features = ["derive"] } 11 | cosmic-config = { git = "https://github.com/pop-os/libcosmic" } 12 | # cosmic-config = { path = "../../libcosmic/cosmic-config" } 13 | -------------------------------------------------------------------------------- /cosmic-notifications-config/src/lib.rs: -------------------------------------------------------------------------------- 1 | use cosmic_config::{CosmicConfigEntry, cosmic_config_derive::CosmicConfigEntry}; 2 | 3 | pub const ID: &str = "com.system76.CosmicNotifications"; 4 | 5 | #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] 6 | pub enum Anchor { 7 | #[default] 8 | Top, 9 | Bottom, 10 | Right, 11 | Left, 12 | TopLeft, 13 | TopRight, 14 | BottomLeft, 15 | BottomRight, 16 | } 17 | 18 | #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, CosmicConfigEntry)] 19 | #[version = 1] 20 | pub struct NotificationsConfig { 21 | pub do_not_disturb: bool, 22 | pub anchor: Anchor, 23 | /// The maximum number of notifications that can be displayed at once. 24 | pub max_notifications: u32, 25 | /// The maximum number of notifications that can be displayed per app if not urgent and constrained by `max_notifications`. 26 | pub max_per_app: u32, 27 | /// Max time in milliseconds a critical notification can be displayed before being removed. 28 | pub max_timeout_urgent: Option, 29 | /// Max time in milliseconds a normal notification can be displayed before being removed. 30 | pub max_timeout_normal: Option, 31 | /// Max time in milliseconds a low priority notification can be displayed before being removed. 32 | pub max_timeout_low: Option, 33 | } 34 | 35 | impl Default for NotificationsConfig { 36 | fn default() -> Self { 37 | Self { 38 | do_not_disturb: false, 39 | anchor: Anchor::default(), 40 | max_notifications: 3, 41 | max_per_app: 2, 42 | max_timeout_urgent: None, 43 | max_timeout_normal: Some(5000), 44 | max_timeout_low: Some(3000), 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /cosmic-notifications-util/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /cosmic-notifications-util/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cosmic-notifications-util" 3 | version = "0.1.0" 4 | edition = "2024" 5 | rust-version = "1.85" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | [features] 9 | default = ["zbus_notifications"] 10 | zbus_notifications = ["image", "zbus"] 11 | image = ["fast_image_resize"] 12 | 13 | [dependencies] 14 | libcosmic = { git = "https://github.com/pop-os/libcosmic", default-features = false } 15 | serde = { version = "1.0", features = ["derive"] } 16 | zbus = { version = "5.11.0", optional = true } 17 | fast_image_resize = { version = "5.1.4", optional = true } 18 | tracing = "0.1.41" 19 | url = "2.5.7" 20 | -------------------------------------------------------------------------------- /cosmic-notifications-util/src/image.rs: -------------------------------------------------------------------------------- 1 | use fast_image_resize as fr; 2 | use std::str::FromStr; 3 | use zbus::zvariant::{Signature, Structure}; 4 | pub struct ImageData { 5 | pub width: u32, 6 | pub height: u32, 7 | pub rowstride: i32, 8 | pub has_alpha: bool, 9 | pub bits_per_sample: i32, 10 | pub channels: i32, 11 | pub data: Vec, 12 | } 13 | 14 | impl ImageData { 15 | pub fn into_rgba(self) -> Self { 16 | let rgba = if self.has_alpha { 17 | self 18 | } else { 19 | let mut data = self.data; 20 | let mut new_data = Vec::with_capacity(data.len() / self.channels as usize * 4); 21 | 22 | for chunk in data.chunks_exact_mut(self.channels as usize) { 23 | new_data.extend_from_slice(chunk); 24 | new_data.push(0xFF); 25 | } 26 | 27 | Self { 28 | has_alpha: true, 29 | data: new_data, 30 | channels: 4, 31 | rowstride: self.width as i32 * 4, 32 | ..self 33 | } 34 | }; 35 | 36 | if rgba.width <= 16 && rgba.height <= 16 { 37 | return rgba; 38 | } 39 | let mut src = 40 | fr::images::Image::from_vec_u8(rgba.width, rgba.height, rgba.data, fr::PixelType::U8x4) 41 | .unwrap(); 42 | 43 | let mut dst = 44 | fr::images::Image::new(rgba.width.min(16), rgba.height.min(16), fr::PixelType::U8x4); 45 | 46 | // Multiple RGB channels of source image by alpha channel 47 | // (not required for the Nearest algorithm) 48 | fr::MulDiv::default() 49 | .multiply_alpha_inplace(&mut src) 50 | .unwrap(); 51 | 52 | fr::Resizer::new() 53 | .resize(&src, &mut dst, Some(&fr::ResizeOptions::default())) 54 | .unwrap(); 55 | 56 | fr::MulDiv::default() 57 | .divide_alpha_inplace(&mut dst) 58 | .unwrap(); 59 | 60 | Self { 61 | width: dst.width(), 62 | height: dst.height(), 63 | data: dst.into_vec(), 64 | ..rgba 65 | } 66 | } 67 | } 68 | 69 | impl<'a> TryFrom> for ImageData { 70 | type Error = zbus::Error; 71 | 72 | fn try_from(value: Structure<'a>) -> zbus::Result { 73 | if Ok(value.signature()) != Signature::from_str("(iiibiiay)").as_ref() { 74 | return Err(zbus::Error::Failure(format!( 75 | "Invalid ImageData: invalid signature {}", 76 | value.signature().to_string() 77 | ))); 78 | } 79 | 80 | let mut fields = value.into_fields(); 81 | 82 | if fields.len() != 7 { 83 | return Err(zbus::Error::Failure( 84 | "Invalid ImageData: missing fields".to_owned(), 85 | )); 86 | } 87 | 88 | let data = Vec::::try_from(fields.remove(6)) 89 | .map_err(|e| zbus::Error::Failure(format!("data: {}", e)))?; 90 | let channels = i32::try_from(fields.remove(5)) 91 | .map_err(|e| zbus::Error::Failure(format!("channels: {}", e)))?; 92 | let bits_per_sample = i32::try_from(fields.remove(4)) 93 | .map_err(|e| zbus::Error::Failure(format!("bits_per_sample: {}", e)))?; 94 | let has_alpha = bool::try_from(fields.remove(3)) 95 | .map_err(|e| zbus::Error::Failure(format!("has_alpha: {}", e)))?; 96 | let rowstride = i32::try_from(fields.remove(2)) 97 | .map_err(|e| zbus::Error::Failure(format!("rowstride: {}", e)))?; 98 | let height = i32::try_from(fields.remove(1)) 99 | .map_err(|e| zbus::Error::Failure(format!("height: {}", e)))?; 100 | let width = i32::try_from(fields.remove(0)) 101 | .map_err(|e| zbus::Error::Failure(format!("width: {}", e)))?; 102 | 103 | if width <= 0 { 104 | return Err(zbus::Error::Failure( 105 | "Invalid ImageData: width is not positive".to_string(), 106 | )); 107 | } 108 | 109 | if height <= 0 { 110 | return Err(zbus::Error::Failure( 111 | "Invalid ImageData: height is not positive".to_string(), 112 | )); 113 | } 114 | 115 | if bits_per_sample != 8 { 116 | return Err(zbus::Error::Failure( 117 | "Invalid ImageData: bits_per_sample is not 8".to_string(), 118 | )); 119 | } 120 | 121 | if has_alpha && channels != 4 { 122 | return Err(zbus::Error::Failure( 123 | "Invalid ImageData: has_alpha is true but channels is not 4".to_string(), 124 | )); 125 | } 126 | 127 | if (width * height * channels) as usize != data.len() { 128 | return Err(zbus::Error::Failure( 129 | "Invalid ImageData: data length does not match width * height * channels" 130 | .to_string(), 131 | )); 132 | } 133 | 134 | if data.len() != (rowstride * height) as usize { 135 | return Err(zbus::Error::Failure( 136 | "Invalid ImageData: data length does not match rowstride * height".to_string(), 137 | )); 138 | } 139 | 140 | Ok(Self { 141 | width: width as u32, 142 | height: height as u32, 143 | rowstride, 144 | has_alpha, 145 | bits_per_sample, 146 | channels, 147 | data, 148 | }) 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /cosmic-notifications-util/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "image")] 2 | pub mod image; 3 | #[cfg(feature = "image")] 4 | pub use image::*; 5 | 6 | use cosmic::widget::{Icon, icon}; 7 | use serde::{Deserialize, Serialize}; 8 | use std::{ 9 | collections::HashMap, convert::Infallible, fmt, path::PathBuf, str::FromStr, time::SystemTime, 10 | }; 11 | 12 | #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] 13 | pub struct Notification { 14 | pub id: u32, 15 | pub app_name: String, 16 | pub app_icon: String, 17 | pub summary: String, 18 | pub body: String, 19 | pub actions: Vec<(ActionId, String)>, 20 | pub hints: Vec, 21 | pub expire_timeout: i32, 22 | pub time: SystemTime, 23 | } 24 | 25 | impl Notification { 26 | #[allow(clippy::too_many_arguments)] 27 | #[cfg(feature = "zbus_notifications")] 28 | pub fn new( 29 | app_name: &str, 30 | id: u32, 31 | app_icon: &str, 32 | summary: &str, 33 | body: &str, 34 | actions: Vec<&str>, 35 | hints: HashMap<&str, zbus::zvariant::Value<'_>>, 36 | expire_timeout: i32, 37 | ) -> Self { 38 | let actions = actions 39 | .chunks_exact(2) 40 | .map(|a| (a[0].parse().unwrap(), a[1].to_string())) 41 | .collect(); 42 | 43 | let hints = hints 44 | .into_iter() 45 | .filter_map(|(k, v)| match k { 46 | "action-icons" => bool::try_from(v).map(Hint::ActionIcons).ok(), 47 | "category" => String::try_from(v).map(Hint::Category).ok(), 48 | "desktop-entry" => String::try_from(v).map(Hint::DesktopEntry).ok(), 49 | "resident" => bool::try_from(v).map(Hint::Resident).ok(), 50 | "sound-file" => String::try_from(v) 51 | .map(|s| Hint::SoundFile(PathBuf::from(s))) 52 | .ok(), 53 | "sound-name" => String::try_from(v).map(Hint::SoundName).ok(), 54 | "suppress-sound" => bool::try_from(v).map(Hint::SuppressSound).ok(), 55 | "transient" => bool::try_from(v).map(Hint::Transient).ok(), 56 | "x" => i32::try_from(v).map(Hint::X).ok(), 57 | "y" => i32::try_from(v).map(Hint::Y).ok(), 58 | "urgency" => u8::try_from(v).map(Hint::Urgency).ok(), 59 | "image-path" | "image_path" => String::try_from(v).ok().map(|s| { 60 | Hint::Image( 61 | url::Url::parse(&s) 62 | .ok() 63 | .and_then(|u| u.to_file_path().ok()) 64 | .map_or(Image::Name(s), Image::File), 65 | ) 66 | }), 67 | "image-data" | "image_data" | "icon_data" => match v { 68 | zbus::zvariant::Value::Structure(v) => match ImageData::try_from(v) { 69 | Ok(mut image) => Some({ 70 | image = image.into_rgba(); 71 | Hint::Image(Image::Data { 72 | width: image.width, 73 | height: image.height, 74 | data: image.data, 75 | }) 76 | }), 77 | Err(err) => { 78 | tracing::warn!("Invalid image data: {}", err); 79 | None 80 | } 81 | }, 82 | _ => { 83 | tracing::warn!("Invalid value for hint: {}", k); 84 | None 85 | } 86 | }, 87 | _ => { 88 | tracing::warn!("Unknown hint: {}", k); 89 | None 90 | } 91 | }) 92 | .collect(); 93 | 94 | Notification { 95 | id, 96 | app_name: app_name.to_string(), 97 | app_icon: app_icon.to_string(), 98 | summary: summary.to_string(), 99 | body: body.to_string(), 100 | actions, 101 | hints, 102 | expire_timeout, 103 | time: SystemTime::now(), 104 | } 105 | } 106 | 107 | pub fn transient(&self) -> bool { 108 | self.hints.iter().any(|h| *h == Hint::Transient(true)) 109 | } 110 | 111 | pub fn category(&self) -> Option<&str> { 112 | self.hints.iter().find_map(|h| match h { 113 | Hint::Category(s) => Some(s.as_str()), 114 | _ => None, 115 | }) 116 | } 117 | 118 | pub fn desktop_entry(&self) -> Option<&str> { 119 | self.hints.iter().find_map(|h| match h { 120 | Hint::DesktopEntry(s) => Some(s.as_str()), 121 | _ => None, 122 | }) 123 | } 124 | 125 | pub fn urgency(&self) -> u8 { 126 | self.hints 127 | .iter() 128 | .find_map(|h| match h { 129 | Hint::Urgency(u) => Some(*u), 130 | _ => None, 131 | }) 132 | .unwrap_or(1) 133 | } 134 | 135 | pub fn image(&self) -> Option<&Image> { 136 | self.hints.iter().find_map(|h| match h { 137 | Hint::Image(i) => Some(i), 138 | _ => None, 139 | }) 140 | } 141 | 142 | pub fn notification_icon(&self) -> Option { 143 | match self.image() { 144 | Some(Image::File(path)) => Some(icon::from_path(PathBuf::from(path)).icon()), 145 | Some(Image::Name(name)) => Some(icon::from_name(name.as_str()).icon()), 146 | Some(Image::Data { 147 | width, 148 | height, 149 | data, 150 | }) => Some(icon::from_raster_pixels(*width, *height, data.clone()).icon()), 151 | None => { 152 | (!self.app_icon.is_empty()).then(|| icon::from_name(self.app_icon.as_str()).icon()) 153 | } 154 | } 155 | } 156 | 157 | pub fn duration_since(&self) -> Option { 158 | SystemTime::now().duration_since(self.time).ok() 159 | } 160 | } 161 | 162 | #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] 163 | pub enum ActionId { 164 | Default, 165 | Custom(String), 166 | } 167 | 168 | impl fmt::Display for ActionId { 169 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 170 | match self { 171 | ActionId::Default => write!(f, "default"), 172 | ActionId::Custom(value) => write!(f, "{}", value), 173 | } 174 | } 175 | } 176 | 177 | impl FromStr for ActionId { 178 | type Err = Infallible; 179 | 180 | fn from_str(s: &str) -> Result { 181 | Ok(match s { 182 | "default" => ActionId::Default, 183 | s => ActionId::Custom(s.to_string()), 184 | }) 185 | } 186 | } 187 | 188 | #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] 189 | pub enum Hint { 190 | ActionIcons(bool), 191 | Category(String), 192 | DesktopEntry(String), 193 | Image(Image), 194 | IconData(Vec), 195 | Resident(bool), 196 | SoundFile(PathBuf), 197 | SoundName(String), 198 | SuppressSound(bool), 199 | Transient(bool), 200 | Urgency(u8), 201 | X(i32), 202 | Y(i32), 203 | } 204 | 205 | #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] 206 | 207 | pub enum Image { 208 | Name(String), 209 | File(PathBuf), 210 | /// RGBA 211 | Data { 212 | width: u32, 213 | height: u32, 214 | data: Vec, 215 | }, 216 | } 217 | 218 | #[repr(u32)] 219 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] 220 | pub enum CloseReason { 221 | Expired = 1, 222 | Dismissed = 2, 223 | CloseNotification = 3, 224 | Undefined = 4, 225 | } 226 | 227 | pub const PANEL_NOTIFICATIONS_FD: &str = "PANEL_NOTIFICATIONS_FD"; 228 | pub const DAEMON_NOTIFICATIONS_FD: &str = "DAEMON_NOTIFICATIONS_FD"; 229 | -------------------------------------------------------------------------------- /data/com.system76.CosmicNotifications.desktop: -------------------------------------------------------------------------------- 1 | [Desktop Entry] 2 | Name=COSMIC Notifications 3 | Name[ar]=إشعارات COSMIC 4 | Name[cs]=Oznámení COSMIC 5 | Name[hu]=COSMIC Értesítések 6 | Name[pt]=Notificações 7 | Name[zh_CN]=COSMIC 通知 8 | Comment=COSMIC Notifications 9 | Comment[ar]=إشعارات COSMIC 10 | Comment[cs]=Oznámení pro COSMIC 11 | Comment[hu]=COSMIC Értesítések 12 | Comment[pt]=Notificações do COSMIC 13 | Comment[zh_CN]=COSMIC 通知 14 | Type=Application 15 | Exec=cosmic-notifications 16 | Terminal=false 17 | Categories=GNOME;GTK; 18 | Keywords=Gnome;GTK; 19 | Keywords[ar]=جنوم;جي‌تي‌كي; 20 | Icon=com.system76.CosmicNotifications 21 | StartupNotify=true 22 | NoDisplay=true 23 | X-HostWaylandDisplay=true 24 | -------------------------------------------------------------------------------- /data/com.system76.CosmicNotifications.metainfo.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | com.system76.CosmicNotifications 5 | CC0 6 | GPL-3.0-only 7 | COSMIC Notifications 8 | إشعارات COSMIC 9 | Oznámení COSMIC 10 | Powiadomienia COSMIC 11 | Notificações 12 | Notificações 13 | COSMIC Notifications Daemon 14 | ناطر إشعارات COSMIC 15 | Daemon pro oznámení COSMIC 16 | Usługa powiadomień COSMIC 17 | Daemon de notificações do COSMIC 18 | 19 |

The COSMIC Notifications Daemon

20 |

ناطر إشعارات COSMIC

21 |

Daemon pro oznámení COSMIC

22 |

Usługa powiadomień COSMIC

23 |

O daemon de notificações do COSMIC

24 |

O daemon de notificações do COSMIC

25 |
26 | https://github.com/pop-os/cosmic-notifications 27 | https://github.com/pop-os/cosmic-notifications/issues 28 | 29 | 30 | 31 | 32 | 33 | ModernToolkit 34 | HiDpiIcon 35 | 36 | Ashley Wulber 37 | ashley@system76.com 38 | cosmic-notifications 39 | com.system76.CosmicNotifications.desktop 40 |
41 | -------------------------------------------------------------------------------- /data/icons/com.system76.CosmicNotifications.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /data/icons/justfile: -------------------------------------------------------------------------------- 1 | appid := env_var('APPID') 2 | install-dir := env_var('INSTALL_DIR') 3 | 4 | scalable-src := appid + '.svg' 5 | scalable-dst := install-dir / 'icons' / 'hicolor' / 'scalable' / 'apps' / scalable-src 6 | 7 | install: 8 | install -Dm0644 {{scalable-src}} {{scalable-dst}} 9 | 10 | uninstall: 11 | rm {{scalable-dst}} 12 | -------------------------------------------------------------------------------- /data/justfile: -------------------------------------------------------------------------------- 1 | appid := env_var('APPID') 2 | install-dir := env_var('INSTALL_DIR') 3 | 4 | desktop-src := appid + '.desktop' 5 | desktop-dst := install-dir / 'applications' / desktop-src 6 | 7 | metainfo-src := appid + '.metainfo.xml' 8 | metainfo-dst := install-dir / 'metainfo' / metainfo-src 9 | 10 | install: 11 | install -Dm0644 {{desktop-src}} {{desktop-dst}} 12 | install -Dm0644 {{metainfo-src}} {{metainfo-dst}} 13 | 14 | uninstall: 15 | rm {{desktop-dst}} {{metainfo-dst}} 16 | -------------------------------------------------------------------------------- /debian/changelog: -------------------------------------------------------------------------------- 1 | cosmic-notifications (0.1.0) UNRELEASED; urgency=medium 2 | 3 | * Initial release. 4 | 5 | -- Ashley Wulber Thu, 07 Apr 2022 09:39:19 -0700 6 | -------------------------------------------------------------------------------- /debian/control: -------------------------------------------------------------------------------- 1 | Source: cosmic-notifications 2 | Section: admin 3 | Priority: optional 4 | Maintainer: Ashley Wulber 5 | Build-Depends: 6 | debhelper (>= 11), 7 | debhelper-compat (= 11), 8 | rustc (>=1.63), 9 | cargo, 10 | just, 11 | intltool, 12 | libxkbcommon-dev, 13 | libwayland-dev, 14 | pkg-config, 15 | Standards-Version: 4.3.0 16 | Homepage: https://github.com/pop-os/cosmic-notifications 17 | 18 | Package: cosmic-notifications 19 | Architecture: amd64 arm64 20 | Depends: 21 | ${misc:Depends}, 22 | ${shlibs:Depends} 23 | Description: Cosmic Notifications 24 | -------------------------------------------------------------------------------- /debian/copyright: -------------------------------------------------------------------------------- 1 | Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ 2 | Upstream-Name: cosmic-notifications 3 | Source: https://github.com/pop-os/cosmic-notifications 4 | 5 | Files: * 6 | Copyright: Copyright 2022 System76 7 | License: GPL-3.0 8 | -------------------------------------------------------------------------------- /debian/install: -------------------------------------------------------------------------------- 1 | /usr/bin/cosmic-notifications 2 | /usr/share/applications/com.system76.CosmicNotifications.desktop 3 | /usr/share/icons/hicolor/scalable/apps/com.system76.CosmicNotifications.svg 4 | /usr/share/metainfo/com.system76.CosmicNotifications.metainfo.xml 5 | -------------------------------------------------------------------------------- /debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | 3 | DESTDIR = debian/cosmic-notifications 4 | CLEAN ?= 1 5 | VENDOR ?= 1 6 | 7 | %: 8 | dh $@ 9 | 10 | override_dh_shlibdeps: 11 | dh_shlibdeps --dpkg-shlibdeps-params=--ignore-missing-info 12 | 13 | override_dh_auto_clean: 14 | if test "${CLEAN}" = "1"; then \ 15 | cargo clean; \ 16 | fi 17 | 18 | if ! ischroot && test "${VENDOR}" = "1"; then \ 19 | cp .cargo/config.default .cargo/config.toml; \ 20 | cargo vendor --sync Cargo.toml | head -n -1 >> .cargo/config.toml; \ 21 | echo 'directory = "vendor"' >> .cargo/config.toml; \ 22 | rm -rf vendor/winapi*gnu*/lib/*.a; \ 23 | tar pcf vendor.tar vendor; \ 24 | rm -rf vendor; \ 25 | fi 26 | 27 | override_dh_auto_build: 28 | just build-vendored 29 | 30 | override_dh_install: 31 | just rootdir=$(DESTDIR) install 32 | -------------------------------------------------------------------------------- /debian/source/format: -------------------------------------------------------------------------------- 1 | 3.0 (native) 2 | -------------------------------------------------------------------------------- /debian/source/options: -------------------------------------------------------------------------------- 1 | tar-ignore=target 2 | tar-ignore=vendor 3 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "crane": { 4 | "inputs": { 5 | "flake-compat": "flake-compat", 6 | "flake-utils": "flake-utils", 7 | "nixpkgs": [ 8 | "nixpkgs" 9 | ], 10 | "rust-overlay": "rust-overlay" 11 | }, 12 | "locked": { 13 | "lastModified": 1687310026, 14 | "narHash": "sha256-20RHFbrnC+hsG4Hyeg/58LvQAK7JWfFItTPFAFamu8E=", 15 | "owner": "ipetkov", 16 | "repo": "crane", 17 | "rev": "116b32c30b5ff28e49f4fcbeeb1bbe3544593204", 18 | "type": "github" 19 | }, 20 | "original": { 21 | "owner": "ipetkov", 22 | "repo": "crane", 23 | "type": "github" 24 | } 25 | }, 26 | "fenix": { 27 | "inputs": { 28 | "nixpkgs": [ 29 | "nixpkgs" 30 | ], 31 | "rust-analyzer-src": "rust-analyzer-src" 32 | }, 33 | "locked": { 34 | "lastModified": 1687760804, 35 | "narHash": "sha256-4aJlNuAI+AjrUid9hmjdqwJxT7y/HCHptC2dtDmuEWU=", 36 | "owner": "nix-community", 37 | "repo": "fenix", 38 | "rev": "2102665784dba3f11314e37b4027794ccd324f1d", 39 | "type": "github" 40 | }, 41 | "original": { 42 | "owner": "nix-community", 43 | "repo": "fenix", 44 | "type": "github" 45 | } 46 | }, 47 | "flake-compat": { 48 | "flake": false, 49 | "locked": { 50 | "lastModified": 1673956053, 51 | "narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=", 52 | "owner": "edolstra", 53 | "repo": "flake-compat", 54 | "rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9", 55 | "type": "github" 56 | }, 57 | "original": { 58 | "owner": "edolstra", 59 | "repo": "flake-compat", 60 | "type": "github" 61 | } 62 | }, 63 | "flake-utils": { 64 | "inputs": { 65 | "systems": "systems" 66 | }, 67 | "locked": { 68 | "lastModified": 1685518550, 69 | "narHash": "sha256-o2d0KcvaXzTrPRIo0kOLV0/QXHhDQ5DTi+OxcjO8xqY=", 70 | "owner": "numtide", 71 | "repo": "flake-utils", 72 | "rev": "a1720a10a6cfe8234c0e93907ffe81be440f4cef", 73 | "type": "github" 74 | }, 75 | "original": { 76 | "owner": "numtide", 77 | "repo": "flake-utils", 78 | "type": "github" 79 | } 80 | }, 81 | "flake-utils_2": { 82 | "inputs": { 83 | "systems": "systems_2" 84 | }, 85 | "locked": { 86 | "lastModified": 1687709756, 87 | "narHash": "sha256-Y5wKlQSkgEK2weWdOu4J3riRd+kV/VCgHsqLNTTWQ/0=", 88 | "owner": "numtide", 89 | "repo": "flake-utils", 90 | "rev": "dbabf0ca0c0c4bce6ea5eaf65af5cb694d2082c7", 91 | "type": "github" 92 | }, 93 | "original": { 94 | "owner": "numtide", 95 | "repo": "flake-utils", 96 | "type": "github" 97 | } 98 | }, 99 | "nix-filter": { 100 | "locked": { 101 | "lastModified": 1687178632, 102 | "narHash": "sha256-HS7YR5erss0JCaUijPeyg2XrisEb959FIct3n2TMGbE=", 103 | "owner": "numtide", 104 | "repo": "nix-filter", 105 | "rev": "d90c75e8319d0dd9be67d933d8eb9d0894ec9174", 106 | "type": "github" 107 | }, 108 | "original": { 109 | "owner": "numtide", 110 | "repo": "nix-filter", 111 | "type": "github" 112 | } 113 | }, 114 | "nixpkgs": { 115 | "locked": { 116 | "lastModified": 1687793116, 117 | "narHash": "sha256-6xRgZ2E9r/BNam87vMkHJ/0EPTTKzeNwhw3abKilEE4=", 118 | "owner": "NixOS", 119 | "repo": "nixpkgs", 120 | "rev": "9e4e0807d2142d17f463b26a8b796b3fe20a3011", 121 | "type": "github" 122 | }, 123 | "original": { 124 | "owner": "NixOS", 125 | "ref": "nixpkgs-unstable", 126 | "repo": "nixpkgs", 127 | "type": "github" 128 | } 129 | }, 130 | "root": { 131 | "inputs": { 132 | "crane": "crane", 133 | "fenix": "fenix", 134 | "flake-utils": "flake-utils_2", 135 | "nix-filter": "nix-filter", 136 | "nixpkgs": "nixpkgs" 137 | } 138 | }, 139 | "rust-analyzer-src": { 140 | "flake": false, 141 | "locked": { 142 | "lastModified": 1687732103, 143 | "narHash": "sha256-5Jn/Nj/xgcjTT289Itng55GLUBTEIULPndl/XrGkUwQ=", 144 | "owner": "rust-lang", 145 | "repo": "rust-analyzer", 146 | "rev": "4a2ceeff0fb53de168691b0f55d9808d221b867e", 147 | "type": "github" 148 | }, 149 | "original": { 150 | "owner": "rust-lang", 151 | "ref": "nightly", 152 | "repo": "rust-analyzer", 153 | "type": "github" 154 | } 155 | }, 156 | "rust-overlay": { 157 | "inputs": { 158 | "flake-utils": [ 159 | "crane", 160 | "flake-utils" 161 | ], 162 | "nixpkgs": [ 163 | "crane", 164 | "nixpkgs" 165 | ] 166 | }, 167 | "locked": { 168 | "lastModified": 1685759304, 169 | "narHash": "sha256-I3YBH6MS3G5kGzNuc1G0f9uYfTcNY9NYoRc3QsykLk4=", 170 | "owner": "oxalica", 171 | "repo": "rust-overlay", 172 | "rev": "c535b4f3327910c96dcf21851bbdd074d0760290", 173 | "type": "github" 174 | }, 175 | "original": { 176 | "owner": "oxalica", 177 | "repo": "rust-overlay", 178 | "type": "github" 179 | } 180 | }, 181 | "systems": { 182 | "locked": { 183 | "lastModified": 1681028828, 184 | "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", 185 | "owner": "nix-systems", 186 | "repo": "default", 187 | "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", 188 | "type": "github" 189 | }, 190 | "original": { 191 | "owner": "nix-systems", 192 | "repo": "default", 193 | "type": "github" 194 | } 195 | }, 196 | "systems_2": { 197 | "locked": { 198 | "lastModified": 1681028828, 199 | "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", 200 | "owner": "nix-systems", 201 | "repo": "default", 202 | "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", 203 | "type": "github" 204 | }, 205 | "original": { 206 | "owner": "nix-systems", 207 | "repo": "default", 208 | "type": "github" 209 | } 210 | } 211 | }, 212 | "root": "root", 213 | "version": 7 214 | } 215 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | description = "Launcher for the COSMIC desktop environment"; 3 | 4 | inputs = { 5 | nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; 6 | flake-utils.url = "github:numtide/flake-utils"; 7 | nix-filter.url = "github:numtide/nix-filter"; 8 | crane = { 9 | url = "github:ipetkov/crane"; 10 | inputs.nixpkgs.follows = "nixpkgs"; 11 | }; 12 | fenix = { 13 | url = "github:nix-community/fenix"; 14 | inputs.nixpkgs.follows = "nixpkgs"; 15 | }; 16 | }; 17 | 18 | outputs = { self, nixpkgs, flake-utils, nix-filter, crane, fenix }: 19 | flake-utils.lib.eachSystem [ "x86_64-linux" "aarch64-linux" ] (system: 20 | let 21 | pkgs = nixpkgs.legacyPackages.${system}; 22 | craneLib = crane.lib.${system}.overrideToolchain fenix.packages.${system}.stable.toolchain; 23 | pkgDef = { 24 | src = nix-filter.lib.filter { 25 | root = ./.; 26 | exclude = [ 27 | ./.gitignore 28 | ./flake.nix 29 | ./flake.lock 30 | ./LICENSE 31 | ./debian 32 | ]; 33 | }; 34 | nativeBuildInputs = with pkgs; [ 35 | just 36 | pkg-config 37 | autoPatchelfHook 38 | ]; 39 | buildInputs = with pkgs; [ 40 | libxkbcommon 41 | wayland 42 | freetype 43 | fontconfig 44 | expat 45 | lld 46 | desktop-file-utils 47 | stdenv.cc.cc.lib 48 | desktop-file-utils 49 | ]; 50 | runtimeDependencies = with pkgs; [ 51 | wayland 52 | ]; 53 | }; 54 | 55 | cargoArtifacts = craneLib.buildDepsOnly pkgDef; 56 | cosmic-notifications-daemon= craneLib.buildPackage (pkgDef // { 57 | inherit cargoArtifacts; 58 | }); 59 | in { 60 | checks = { 61 | inherit cosmic-notifications-daemon; 62 | }; 63 | 64 | packages.default = cosmic-notifications-daemon.overrideAttrs (oldAttrs: rec { 65 | buildPhase= '' 66 | just prefix=$out build-release 67 | ''; 68 | installPhase = '' 69 | just prefix=$out install 70 | ''; 71 | }); 72 | 73 | apps.default = flake-utils.lib.mkApp { 74 | drv = cosmic-notifications-daemon; 75 | }; 76 | 77 | devShells.default = pkgs.mkShell rec { 78 | inputsFrom = builtins.attrValues self.checks.${system}; 79 | LD_LIBRARY_PATH = pkgs.lib.strings.makeLibraryPath (builtins.concatMap (d: d.runtimeDependencies) inputsFrom); 80 | }; 81 | }); 82 | 83 | nixConfig = { 84 | # Cache for the Rust toolchain in fenix 85 | extra-substituters = [ "https://nix-community.cachix.org" ]; 86 | extra-trusted-public-keys = [ "nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=" ]; 87 | }; 88 | } 89 | -------------------------------------------------------------------------------- /hooks/pre-commit.hook: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Source: https://gitlab.gnome.org/GNOME/fractal/blob/master/hooks/pre-commit.hook 3 | 4 | install_rustfmt() { 5 | if ! which rustup &> /dev/null; then 6 | curl https://sh.rustup.rs -sSf | sh -s -- -y 7 | export PATH=$PATH:$HOME/.cargo/bin 8 | if ! which rustup &> /dev/null; then 9 | echo "Failed to install rustup. Performing the commit without style checking." 10 | exit 0 11 | fi 12 | fi 13 | 14 | if ! rustup component list|grep rustfmt &> /dev/null; then 15 | echo "Installing rustfmt…" 16 | rustup component add rustfmt 17 | fi 18 | } 19 | 20 | if ! which cargo >/dev/null 2>&1 || ! cargo fmt --help >/dev/null 2>&1; then 21 | echo "Unable to check the project’s code style, because rustfmt could not be run." 22 | 23 | if [ ! -t 1 ]; then 24 | # No input is possible 25 | echo "Performing commit." 26 | exit 0 27 | fi 28 | 29 | echo "" 30 | echo "y: Install rustfmt via rustup" 31 | echo "n: Don't install rustfmt and perform the commit" 32 | echo "Q: Don't install rustfmt and abort the commit" 33 | 34 | echo "" 35 | while true 36 | do 37 | echo -n "Install rustfmt via rustup? [y/n/Q]: "; read yn < /dev/tty 38 | case $yn in 39 | [Yy]* ) install_rustfmt; break;; 40 | [Nn]* ) echo "Performing commit."; exit 0;; 41 | [Qq]* | "" ) echo "Aborting commit."; exit -1 >/dev/null 2>&1;; 42 | * ) echo "Invalid input";; 43 | esac 44 | done 45 | 46 | fi 47 | 48 | echo "--Checking style--" 49 | cargo fmt --all -- --check 50 | if test $? != 0; then 51 | echo "--Checking style fail--" 52 | echo "Please fix the above issues, either manually or by running: cargo fmt --all" 53 | 54 | exit -1 55 | else 56 | echo "--Checking style pass--" 57 | fi 58 | -------------------------------------------------------------------------------- /i18n.toml: -------------------------------------------------------------------------------- 1 | fallback_language = "en" 2 | 3 | [fluent] 4 | assets_dir = "i18n" -------------------------------------------------------------------------------- /i18n/af/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/af/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/ar/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = إشعارات COSMIC 2 | -------------------------------------------------------------------------------- /i18n/be/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/be/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/bg/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Известия на COSMIC 2 | -------------------------------------------------------------------------------- /i18n/ca/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/ca/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/cs/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Oznámení COSMIC 2 | -------------------------------------------------------------------------------- /i18n/da/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/da/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/de/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC Benachrichtigungen 2 | -------------------------------------------------------------------------------- /i18n/el/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/el/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/en-GB/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/en-GB/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/en/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC Notifications 2 | -------------------------------------------------------------------------------- /i18n/eo/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/eo/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/es-419/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Notificaciones de Cosmic 2 | -------------------------------------------------------------------------------- /i18n/es-MX/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/es-MX/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/es/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/es/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/et/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMICu teavitused 2 | -------------------------------------------------------------------------------- /i18n/fa/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/fa/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/fi/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC Ilmoitukset 2 | -------------------------------------------------------------------------------- /i18n/fr/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Notifications Cosmic -------------------------------------------------------------------------------- /i18n/fy/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/fy/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/ga/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Fógraí COSMIC 2 | -------------------------------------------------------------------------------- /i18n/gd/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/gd/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/he/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/he/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/hi/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/hi/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/hr/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/hr/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/hu/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC Értesítések -------------------------------------------------------------------------------- /i18n/id/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/id/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/ie/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/ie/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/it/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Notifiche di COSMIC 2 | -------------------------------------------------------------------------------- /i18n/ja/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/ja/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/jv/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/jv/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/kn/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/kn/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/ko/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/ko/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/li/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/li/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/lt/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/lt/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/nb-NO/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC Varsler 2 | -------------------------------------------------------------------------------- /i18n/nl/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC Meldingen 2 | -------------------------------------------------------------------------------- /i18n/pl/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Powiadomienia COSMIC 2 | -------------------------------------------------------------------------------- /i18n/pt-BR/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Notificações 2 | -------------------------------------------------------------------------------- /i18n/pt/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Notificações COSMIC 2 | -------------------------------------------------------------------------------- /i18n/ro/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Notificări COSMIC -------------------------------------------------------------------------------- /i18n/ru/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Уведомления COSMIC 2 | -------------------------------------------------------------------------------- /i18n/sk/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/sk/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/sr-Cyrl/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC обавештења 2 | -------------------------------------------------------------------------------- /i18n/sr-Latn/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC obaveštenja 2 | -------------------------------------------------------------------------------- /i18n/sr/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/sr/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/sv/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC Aviseringar 2 | -------------------------------------------------------------------------------- /i18n/ta/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/ta/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/th/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/th/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/tr/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC Bildirimler 2 | -------------------------------------------------------------------------------- /i18n/uk/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = Сповіщення COSMIC 2 | -------------------------------------------------------------------------------- /i18n/vi/cosmic_notifications.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pop-os/cosmic-notifications/81b636c069c0d931ba4d1d3823eba70ed8e54ba2/i18n/vi/cosmic_notifications.ftl -------------------------------------------------------------------------------- /i18n/zh-CN/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC 通知 2 | -------------------------------------------------------------------------------- /i18n/zh-TW/cosmic_notifications.ftl: -------------------------------------------------------------------------------- 1 | app-name = COSMIC 通知 2 | -------------------------------------------------------------------------------- /justfile: -------------------------------------------------------------------------------- 1 | name := 'cosmic-notifications' 2 | export APPID := 'com.system76.CosmicNotifications' 3 | 4 | rootdir := '' 5 | prefix := '/usr' 6 | 7 | base-dir := absolute_path(clean(rootdir / prefix)) 8 | 9 | export INSTALL_DIR := base-dir / 'share' 10 | 11 | cargo-target-dir := env('CARGO_TARGET_DIR', 'target') 12 | bin-src := cargo-target-dir / 'release' / name 13 | bin-dst := base-dir / 'bin' / name 14 | 15 | # Use lld linker if available 16 | ld-args := if `which lld || true` != '' { 17 | '-C link-arg=-fuse-ld=lld -C link-arg=-Wl,--build-id=sha1 -Clink-arg=-Wl,--no-rosegment' 18 | } else { 19 | '' 20 | } 21 | 22 | export RUSTFLAGS := env_var_or_default('RUSTFLAGS', '') + ' --cfg tokio_unstable ' + ld-args 23 | 24 | # Default recipe which runs `just build-release` 25 | default: build-release 26 | 27 | # Runs `cargo clean` 28 | clean: 29 | cargo clean 30 | 31 | # `cargo clean` and removes vendored dependencies 32 | clean-dist: clean 33 | rm -rf vendor vendor.tar 34 | 35 | # Compiles with debug profile 36 | build-debug *args: 37 | cargo build {{args}} 38 | 39 | # Compiles with release profile 40 | build-release *args: (build-debug '--release' args) 41 | 42 | # Compiles release profile with vendored dependencies 43 | build-vendored *args: vendor-extract (build-release '--frozen --offline' args) 44 | 45 | # Runs a clippy check 46 | check *args: 47 | cargo clippy --all-features {{args}} -- -W clippy::pedantic 48 | 49 | # Runs a clippy check with JSON message format 50 | check-json: (check '--message-format=json') 51 | 52 | # Runs after compiling a release build 53 | run: build-release 54 | {{cargo-target-dir}}/release/cosmic-notifications 55 | 56 | # Build and run with tokio-console enabled 57 | tokio-console: build-release 58 | env TOKIO_CONSOLE=1 {{cargo-target-dir}}/release/cosmic-notifications 59 | 60 | # Installs files 61 | install: 62 | install -Dm0755 {{bin-src}} {{bin-dst}} 63 | @just data/install 64 | @just data/icons/install 65 | 66 | # Uninstalls installed files 67 | uninstall: 68 | rm {{bin-dst}} 69 | @just data/uninstall 70 | @just data/icons/uninstall 71 | 72 | # Vendor dependencies locally 73 | vendor: 74 | cp .cargo/config.default .cargo/config.toml 75 | cargo vendor --sync Cargo.toml \ 76 | | head -n -1 >> .cargo/config.toml 77 | echo 'directory = "vendor"' >> .cargo/config.toml 78 | rm -rf vendor/winapi*gnu*/lib/*.a; \ 79 | tar pcf vendor.tar vendor 80 | rm -rf vendor 81 | 82 | # Extracts vendored dependencies 83 | vendor-extract: 84 | #!/usr/bin/env sh 85 | rm -rf vendor 86 | tar pxf vendor.tar 87 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "1.85.1" 3 | components = ["clippy", "rustfmt"] 4 | -------------------------------------------------------------------------------- /src/app.rs: -------------------------------------------------------------------------------- 1 | use crate::subscriptions::notifications; 2 | use cosmic::app::{Core, Settings}; 3 | use cosmic::cosmic_config::{Config, CosmicConfigEntry}; 4 | use cosmic::iced::platform_specific::runtime::wayland::layer_surface::{ 5 | IcedMargin, IcedOutput, SctkLayerSurfaceSettings, 6 | }; 7 | use cosmic::iced::platform_specific::shell::wayland::commands::{ 8 | activation, 9 | layer_surface::{Anchor, KeyboardInteractivity, destroy_layer_surface, get_layer_surface}, 10 | }; 11 | use cosmic::iced::{self, Length, Limits, Subscription}; 12 | use cosmic::iced_runtime::core::window::Id as SurfaceId; 13 | use cosmic::iced_widget::{column, row, vertical_space}; 14 | use cosmic::surface; 15 | use cosmic::widget::{autosize, button, container, icon, text}; 16 | use cosmic::{Application, Element, app::Task}; 17 | use cosmic_notifications_config::NotificationsConfig; 18 | use cosmic_notifications_util::{ActionId, CloseReason, Notification}; 19 | use cosmic_panel_config::{CosmicPanelConfig, CosmicPanelOuput, PanelAnchor}; 20 | use cosmic_time::{Instant, Timeline, anim, id}; 21 | use iced::Alignment; 22 | use std::borrow::Cow; 23 | use std::time::Duration; 24 | use tokio::sync::mpsc; 25 | 26 | static NOTIFICATIONS_APPLET: &str = "com.system76.CosmicAppletNotifications"; 27 | 28 | pub fn run() -> cosmic::iced::Result { 29 | cosmic::app::run::( 30 | Settings::default() 31 | .antialiasing(true) 32 | .client_decorations(true) 33 | .debug(false) 34 | .default_text_size(16.0) 35 | .scale_factor(1.0) 36 | .no_main_window(true) 37 | .exit_on_close(false), 38 | (), 39 | )?; 40 | Ok(()) 41 | } 42 | 43 | struct CosmicNotifications { 44 | core: Core, 45 | active_surface: bool, 46 | autosize_id: iced::id::Id, 47 | window_id: SurfaceId, 48 | cards: Vec, 49 | notifications_id: id::Cards, 50 | notifications_tx: Option>, 51 | config: NotificationsConfig, 52 | dock_config: CosmicPanelConfig, 53 | panel_config: CosmicPanelConfig, 54 | anchor: Option<(Anchor, Option)>, 55 | timeline: Timeline, 56 | } 57 | 58 | #[derive(Debug, Clone)] 59 | enum Message { 60 | ActivateNotification(u32), 61 | ActivationToken(Option, u32, Option), 62 | Dismissed(u32), 63 | Notification(notifications::Event), 64 | Timeout(u32), 65 | Config(NotificationsConfig), 66 | PanelConfig(CosmicPanelConfig), 67 | DockConfig(CosmicPanelConfig), 68 | Frame(Instant), 69 | Ignore, 70 | Surface(surface::Action), 71 | } 72 | 73 | impl CosmicNotifications { 74 | fn close(&mut self, i: u32, reason: CloseReason) -> Option> { 75 | let (c_pos, _) = self.cards.iter().enumerate().find(|(_, n)| n.id == i)?; 76 | 77 | let notification = self.cards.remove(c_pos); 78 | 79 | if self.cards.is_empty() { 80 | self.cards.shrink_to(50); 81 | } 82 | 83 | self.sort_notifications(); 84 | self.group_notifications(); 85 | if let Some(sender) = &self.notifications_tx { 86 | if !matches!(reason, CloseReason::Expired) { 87 | let id = notification.id; 88 | let sender = sender.clone(); 89 | tokio::spawn(async move { 90 | _ = sender.send(notifications::Input::Closed(id, reason)); 91 | }); 92 | } 93 | } 94 | 95 | if let Some(sender) = &self.notifications_tx { 96 | if !matches!(reason, CloseReason::Expired) { 97 | let sender = sender.clone(); 98 | let id = notification.id; 99 | tokio::spawn(async move { sender.send(notifications::Input::Dismissed(id)).await }); 100 | } 101 | } 102 | 103 | if self.cards.is_empty() && self.active_surface { 104 | self.active_surface = false; 105 | Some(destroy_layer_surface(self.window_id)) 106 | } else { 107 | Some(Task::none()) 108 | } 109 | } 110 | 111 | fn anchor_for_notification_applet(&self) -> (Anchor, Option) { 112 | self.panel_config 113 | .plugins_left() 114 | .iter() 115 | .find_map(|p| { 116 | if p.iter().any(|s| s == NOTIFICATIONS_APPLET) { 117 | return Some(( 118 | match self.panel_config.anchor { 119 | PanelAnchor::Top => Anchor::TOP.union(Anchor::LEFT), 120 | PanelAnchor::Bottom => Anchor::BOTTOM.union(Anchor::LEFT), 121 | PanelAnchor::Left => Anchor::LEFT.union(Anchor::TOP), 122 | PanelAnchor::Right => Anchor::RIGHT.union(Anchor::TOP), 123 | }, 124 | match self.panel_config.output { 125 | CosmicPanelOuput::Name(ref n) => Some(n.clone()), 126 | _ => None, 127 | }, 128 | )); 129 | } 130 | None 131 | }) 132 | .or_else(|| { 133 | self.panel_config.plugins_right().iter().find_map(|p| { 134 | if p.iter().any(|s| s == NOTIFICATIONS_APPLET) { 135 | return Some(( 136 | match self.panel_config.anchor { 137 | PanelAnchor::Top => Anchor::TOP.union(Anchor::RIGHT), 138 | PanelAnchor::Bottom => Anchor::BOTTOM.union(Anchor::RIGHT), 139 | PanelAnchor::Left => Anchor::LEFT.union(Anchor::BOTTOM), 140 | PanelAnchor::Right => Anchor::RIGHT.union(Anchor::BOTTOM), 141 | }, 142 | match self.panel_config.output { 143 | CosmicPanelOuput::Name(ref n) => Some(n.clone()), 144 | _ => None, 145 | }, 146 | )); 147 | } 148 | None 149 | }) 150 | }) 151 | .or_else(|| { 152 | self.panel_config.plugins_center().iter().find_map(|p| { 153 | if p.iter().any(|s| s == NOTIFICATIONS_APPLET) { 154 | return Some(( 155 | match self.panel_config.anchor { 156 | PanelAnchor::Top => Anchor::TOP, 157 | PanelAnchor::Bottom => Anchor::BOTTOM, 158 | PanelAnchor::Left => Anchor::LEFT, 159 | PanelAnchor::Right => Anchor::RIGHT, 160 | }, 161 | match self.panel_config.output { 162 | CosmicPanelOuput::Name(ref n) => Some(n.clone()), 163 | _ => None, 164 | }, 165 | )); 166 | } 167 | None 168 | }) 169 | }) 170 | .or_else(|| { 171 | self.dock_config.plugins_left().iter().find_map(|p| { 172 | if p.iter().any(|s| s == NOTIFICATIONS_APPLET) { 173 | return Some(( 174 | match self.dock_config.anchor { 175 | PanelAnchor::Top => Anchor::TOP.union(Anchor::LEFT), 176 | PanelAnchor::Bottom => Anchor::BOTTOM.union(Anchor::LEFT), 177 | PanelAnchor::Left => Anchor::LEFT.union(Anchor::TOP), 178 | PanelAnchor::Right => Anchor::RIGHT.union(Anchor::TOP), 179 | }, 180 | match self.dock_config.output { 181 | CosmicPanelOuput::Name(ref n) => Some(n.clone()), 182 | _ => None, 183 | }, 184 | )); 185 | } 186 | None 187 | }) 188 | }) 189 | .or_else(|| { 190 | self.dock_config.plugins_right().iter().find_map(|p| { 191 | if p.iter().any(|s| s == NOTIFICATIONS_APPLET) { 192 | return Some(( 193 | match self.dock_config.anchor { 194 | PanelAnchor::Top => Anchor::TOP.union(Anchor::RIGHT), 195 | PanelAnchor::Bottom => Anchor::BOTTOM.union(Anchor::RIGHT), 196 | PanelAnchor::Left => Anchor::TOP.union(Anchor::BOTTOM), 197 | PanelAnchor::Right => Anchor::RIGHT.union(Anchor::BOTTOM), 198 | }, 199 | match self.dock_config.output { 200 | CosmicPanelOuput::Name(ref n) => Some(n.clone()), 201 | _ => None, 202 | }, 203 | )); 204 | } 205 | None 206 | }) 207 | }) 208 | .or_else(|| { 209 | self.dock_config.plugins_center().iter().find_map(|p| { 210 | if p.iter().any(|s| s == NOTIFICATIONS_APPLET) { 211 | return Some(( 212 | match self.dock_config.anchor { 213 | PanelAnchor::Top => Anchor::TOP, 214 | PanelAnchor::Bottom => Anchor::BOTTOM, 215 | PanelAnchor::Left => Anchor::LEFT, 216 | PanelAnchor::Right => Anchor::RIGHT, 217 | }, 218 | match self.dock_config.output { 219 | CosmicPanelOuput::Name(ref n) => Some(n.clone()), 220 | _ => None, 221 | }, 222 | )); 223 | } 224 | None 225 | }) 226 | }) 227 | .unwrap_or((Anchor::TOP, None)) 228 | } 229 | 230 | fn push_notification( 231 | &mut self, 232 | notification: Notification, 233 | ) -> Task<::Message> { 234 | let mut timeout = u32::try_from(notification.expire_timeout).unwrap_or(3000); 235 | let max_timeout = if notification.urgency() == 2 { 236 | self.config.max_timeout_urgent 237 | } else if notification.urgency() == 1 { 238 | self.config.max_timeout_normal 239 | } else { 240 | self.config.max_timeout_low 241 | } 242 | .unwrap_or(u32::try_from(notification.expire_timeout).unwrap_or(3000)); 243 | timeout = timeout.min(max_timeout); 244 | 245 | let mut tasks = vec![if timeout > 0 { 246 | iced::Task::perform( 247 | tokio::time::sleep(Duration::from_millis(timeout as u64)), 248 | move |_| cosmic::action::app(Message::Timeout(notification.id)), 249 | ) 250 | } else { 251 | iced::Task::none() 252 | }]; 253 | 254 | if self.cards.is_empty() && !self.config.do_not_disturb { 255 | let (anchor, _output) = self.anchor.clone().unwrap_or((Anchor::TOP, None)); 256 | self.active_surface = true; 257 | tasks.push(get_layer_surface(SctkLayerSurfaceSettings { 258 | id: self.window_id, 259 | anchor, 260 | exclusive_zone: 0, 261 | keyboard_interactivity: KeyboardInteractivity::None, 262 | namespace: "notifications".to_string(), 263 | margin: IcedMargin { 264 | top: 8, 265 | right: 8, 266 | bottom: 8, 267 | left: 8, 268 | }, 269 | size: Some((Some(300), Some(1))), 270 | output: IcedOutput::Active, // TODO should we only create the notification on the output the applet is on? 271 | size_limits: Limits::NONE 272 | .min_width(300.0) 273 | .min_height(1.0) 274 | .max_height(1920.0) 275 | .max_width(300.0), 276 | ..Default::default() 277 | })); 278 | }; 279 | 280 | self.sort_notifications(); 281 | 282 | let mut insert_sorted = 283 | |notification: Notification| match self.cards.binary_search_by(|a| { 284 | match a.urgency().cmp(¬ification.urgency()) { 285 | std::cmp::Ordering::Equal => a.time.cmp(¬ification.time), 286 | other => other, 287 | } 288 | }) { 289 | Ok(pos) => { 290 | self.cards[pos] = notification; 291 | } 292 | Err(pos) => { 293 | self.cards.insert(pos, notification); 294 | } 295 | }; 296 | insert_sorted(notification); 297 | self.group_notifications(); 298 | 299 | iced::Task::batch(tasks) 300 | } 301 | 302 | fn group_notifications(&mut self) { 303 | if self.config.max_per_app == 0 { 304 | return; 305 | } 306 | 307 | let mut extra_per_app = Vec::new(); 308 | let mut cur_count = 0; 309 | let Some(mut cur_id) = self.cards.first().map(|n| n.app_name.clone()) else { 310 | return; 311 | }; 312 | self.cards = self 313 | .cards 314 | .drain(..) 315 | .filter(|n| { 316 | if n.app_name == cur_id { 317 | cur_count += 1; 318 | } else { 319 | cur_count = 1; 320 | cur_id = n.app_name.clone(); 321 | } 322 | if cur_count > self.config.max_per_app { 323 | extra_per_app.push(n.clone()); 324 | false 325 | } else { 326 | true 327 | } 328 | }) 329 | .collect(); 330 | 331 | for n in extra_per_app { 332 | if self.cards.len() < self.config.max_notifications as usize { 333 | self.insert_sorted(n); 334 | } else { 335 | self.cards.push(n); 336 | } 337 | } 338 | } 339 | 340 | fn insert_sorted(&mut self, notification: Notification) { 341 | match self 342 | .cards 343 | .binary_search_by(|a| match notification.urgency().cmp(&a.urgency()) { 344 | std::cmp::Ordering::Equal => notification.time.cmp(&a.time), 345 | other => other, 346 | }) { 347 | Ok(pos) => { 348 | self.cards[pos] = notification; 349 | } 350 | Err(pos) => { 351 | self.cards.insert(pos, notification); 352 | } 353 | } 354 | } 355 | 356 | fn sort_notifications(&mut self) { 357 | self.cards 358 | .sort_by(|a, b| match a.urgency().cmp(&b.urgency()) { 359 | std::cmp::Ordering::Equal => a.time.cmp(&b.time), 360 | other => other, 361 | }); 362 | } 363 | 364 | fn replace_notification(&mut self, notification: Notification) -> Task { 365 | if let Some(notif) = self.cards.iter_mut().find(|n| n.id == notification.id) { 366 | *notif = notification; 367 | Task::none() 368 | } else { 369 | tracing::error!("Notification not found... pushing instead"); 370 | self.push_notification(notification) 371 | } 372 | } 373 | 374 | fn request_activation(&mut self, i: u32, action: Option) -> Task { 375 | activation::request_token(Some(String::from(Self::APP_ID)), Some(self.window_id)).map( 376 | move |token| cosmic::Action::App(Message::ActivationToken(token, i, action.clone())), 377 | ) 378 | } 379 | 380 | fn activate_notification( 381 | &mut self, 382 | token: String, 383 | id: u32, 384 | action: Option, 385 | ) -> Option> { 386 | if let Some(tx) = self.notifications_tx.as_ref() { 387 | let (c_pos, _) = self.cards.iter().enumerate().find(|(_, n)| n.id == id)?; 388 | 389 | let notification = self.cards.get(c_pos).unwrap(); 390 | 391 | let maybe_action = if action 392 | .as_ref() 393 | .is_some_and(|a| notification.actions.iter().any(|(b, _)| b == a)) 394 | { 395 | action.clone().map(|a| a.to_string()) 396 | } else if notification 397 | .actions 398 | .iter() 399 | .any(|a| matches!(a.0, ActionId::Default)) 400 | { 401 | Some(ActionId::Default.to_string()) 402 | } else { 403 | notification.actions.first().map(|a| a.0.to_string()) 404 | }; 405 | 406 | let Some(action) = maybe_action else { 407 | return self.close(id, CloseReason::Dismissed); 408 | }; 409 | let tx = tx.clone(); 410 | tracing::trace!("action for {id} {action}"); 411 | tokio::spawn(async move { 412 | _ = tx 413 | .send(notifications::Input::Activated { token, id, action }) 414 | .await; 415 | tracing::trace!("sent action to sub"); 416 | }); 417 | self.close(id, CloseReason::Dismissed) 418 | } else { 419 | tracing::error!("Failed to activate notification. No channel."); 420 | None 421 | } 422 | } 423 | } 424 | 425 | impl cosmic::Application for CosmicNotifications { 426 | type Message = Message; 427 | type Executor = cosmic::executor::single::Executor; 428 | type Flags = (); 429 | const APP_ID: &'static str = "com.system76.CosmicNotifications"; 430 | 431 | fn init(core: Core, _flags: ()) -> (Self, Task) { 432 | let helper = Config::new( 433 | cosmic_notifications_config::ID, 434 | NotificationsConfig::VERSION, 435 | ) 436 | .ok(); 437 | 438 | let config: NotificationsConfig = helper 439 | .as_ref() 440 | .map(|helper| { 441 | NotificationsConfig::get_entry(helper).unwrap_or_else(|(errors, config)| { 442 | for err in errors { 443 | if err.is_err() { 444 | tracing::error!("{:?}", err); 445 | } 446 | } 447 | config 448 | }) 449 | }) 450 | .unwrap_or_default(); 451 | ( 452 | CosmicNotifications { 453 | core, 454 | active_surface: false, 455 | autosize_id: iced::id::Id::new("autosize"), 456 | window_id: SurfaceId::unique(), 457 | anchor: None, 458 | config, 459 | dock_config: CosmicPanelConfig::default(), 460 | panel_config: CosmicPanelConfig::default(), 461 | notifications_id: id::Cards::new("Notifications"), 462 | notifications_tx: None, 463 | timeline: Timeline::new(), 464 | cards: Vec::with_capacity(50), 465 | }, 466 | Task::none(), 467 | ) 468 | } 469 | 470 | fn core(&self) -> &Core { 471 | &self.core 472 | } 473 | 474 | fn core_mut(&mut self) -> &mut Core { 475 | &mut self.core 476 | } 477 | 478 | fn view(&self) -> Element { 479 | unimplemented!(); 480 | } 481 | 482 | #[allow(clippy::too_many_lines)] 483 | fn update(&mut self, message: Message) -> Task { 484 | match message { 485 | Message::ActivateNotification(id) => { 486 | tracing::trace!("requesting token for {id}"); 487 | return self.request_activation(id, None); 488 | } 489 | Message::ActivationToken(token, id, action) => { 490 | tracing::trace!("token for {id}"); 491 | if let Some(token) = token { 492 | return self 493 | .activate_notification(token, id, action) 494 | .unwrap_or(Task::none()); 495 | } else { 496 | tracing::error!("Failed to get activation token for clicked notification."); 497 | } 498 | } 499 | Message::Notification(e) => match e { 500 | notifications::Event::Notification(n) => { 501 | return self.push_notification(n); 502 | } 503 | notifications::Event::Replace(n) => { 504 | return self.replace_notification(n); 505 | } 506 | notifications::Event::CloseNotification(id) => { 507 | if let Some(c) = self.close(id, CloseReason::CloseNotification) { 508 | return c; 509 | } 510 | } 511 | notifications::Event::Ready(tx) => { 512 | self.notifications_tx = Some(tx); 513 | } 514 | notifications::Event::AppletActivated { id, action } => { 515 | tracing::trace!("requesting token for {id}"); 516 | return self.request_activation(id, Some(action)); 517 | } 518 | }, 519 | Message::Dismissed(id) => { 520 | if let Some(c) = self.close(id, CloseReason::Dismissed) { 521 | return c; 522 | } 523 | } 524 | Message::Timeout(id) => { 525 | if let Some(c) = self.close(id, CloseReason::Expired) { 526 | return c; 527 | } 528 | } 529 | Message::Config(config) => { 530 | self.config = config; 531 | } 532 | Message::PanelConfig(c) => { 533 | self.panel_config = c; 534 | self.anchor = Some(self.anchor_for_notification_applet()); 535 | } 536 | Message::DockConfig(c) => { 537 | self.dock_config = c; 538 | self.anchor = Some(self.anchor_for_notification_applet()); 539 | } 540 | Message::Frame(now) => { 541 | self.timeline.now(now); 542 | } 543 | Message::Ignore => {} 544 | Message::Surface(a) => { 545 | return cosmic::task::message(cosmic::Action::Cosmic( 546 | cosmic::app::Action::Surface(a), 547 | )); 548 | } 549 | } 550 | Task::none() 551 | } 552 | 553 | #[allow(clippy::too_many_lines)] 554 | fn view_window(&self, _: SurfaceId) -> Element { 555 | if self.cards.is_empty() { 556 | return container(vertical_space().height(Length::Fixed(1.0))) 557 | .center_x(Length::Fixed(1.0)) 558 | .center_y(Length::Fixed(1.0)) 559 | .into(); 560 | } 561 | 562 | let (ids, notif_elems): (Vec<_>, Vec<_>) = self 563 | .cards 564 | .iter() 565 | .rev() 566 | .map(|n| { 567 | let app_name = text::caption(if n.app_name.len() > 24 { 568 | Cow::from(format!( 569 | "{:.26}...", 570 | n.app_name.lines().next().unwrap_or_default() 571 | )) 572 | } else { 573 | Cow::from(&n.app_name) 574 | }) 575 | .width(Length::Fill); 576 | 577 | let close_notif = button::custom( 578 | icon::from_name("window-close-symbolic") 579 | .size(16) 580 | .symbolic(true), 581 | ) 582 | .on_press(Message::Dismissed(n.id)) 583 | .class(cosmic::theme::Button::Text); 584 | let e = Element::from( 585 | column!( 586 | if let Some(icon) = n.notification_icon() { 587 | row![icon.size(16), app_name, close_notif] 588 | .spacing(8) 589 | .align_y(Alignment::Center) 590 | } else { 591 | row![app_name, close_notif] 592 | .spacing(8) 593 | .align_y(Alignment::Center) 594 | }, 595 | column![ 596 | text::body(n.summary.lines().next().unwrap_or_default()) 597 | .width(Length::Fill), 598 | text::caption(n.body.lines().next().unwrap_or_default()) 599 | .width(Length::Fill) 600 | ] 601 | ) 602 | .width(Length::Fill), 603 | ); 604 | (n.id, e) 605 | }) 606 | .take(self.config.max_notifications as usize) 607 | .unzip(); 608 | 609 | let card_list = anim!( 610 | //cards 611 | self.notifications_id.clone(), 612 | &self.timeline, 613 | notif_elems, 614 | Message::Ignore, 615 | None:: Message>, 616 | Some(move |id| Message::ActivateNotification(ids[id])), 617 | "", 618 | "", 619 | "", 620 | None, 621 | true, 622 | ) 623 | .width(Length::Fixed(300.)); 624 | 625 | autosize::autosize(card_list, self.autosize_id.clone()) 626 | .min_width(200.) 627 | .min_height(100.) 628 | .max_width(300.) 629 | .max_height(1920.) 630 | .into() 631 | } 632 | 633 | fn subscription(&self) -> Subscription { 634 | Subscription::batch(vec![ 635 | self.core 636 | .watch_config(cosmic_notifications_config::ID) 637 | .map(|u| { 638 | for why in u 639 | .errors 640 | .into_iter() 641 | .filter(cosmic::cosmic_config::Error::is_err) 642 | { 643 | tracing::error!(?why, "config load error"); 644 | } 645 | Message::Config(u.config) 646 | }), 647 | self.core 648 | .watch_config("com.system76.CosmicPanel.Panel") 649 | .map(|u| { 650 | for why in u 651 | .errors 652 | .into_iter() 653 | .filter(cosmic::cosmic_config::Error::is_err) 654 | { 655 | tracing::error!(?why, "panel config load error"); 656 | } 657 | Message::PanelConfig(u.config) 658 | }), 659 | self.core 660 | .watch_config("com.system76.CosmicPanel.Dock") 661 | .map(|u| { 662 | for why in u 663 | .errors 664 | .into_iter() 665 | .filter(cosmic::cosmic_config::Error::is_err) 666 | { 667 | tracing::error!(?why, "dock config load error"); 668 | } 669 | Message::DockConfig(u.config) 670 | }), 671 | self.timeline 672 | .as_subscription() 673 | .map(|(_, now)| Message::Frame(now)), 674 | notifications::notifications().map(Message::Notification), 675 | ]) 676 | } 677 | } 678 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | pub const APP_ID: &str = "com.system76.CosmicNotifications"; 2 | pub const VERSION: &str = env!("CARGO_PKG_VERSION"); 3 | 4 | pub fn profile() -> &'static str { 5 | std::env!("OUT_DIR") 6 | .split(std::path::MAIN_SEPARATOR) 7 | .nth_back(3) 8 | .unwrap_or("unknown") 9 | } 10 | -------------------------------------------------------------------------------- /src/localize.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2023 System76 2 | // SPDX-License-Identifier: GPL-3.0-only 3 | use i18n_embed::{ 4 | DefaultLocalizer, LanguageLoader, Localizer, 5 | fluent::{FluentLanguageLoader, fluent_language_loader}, 6 | }; 7 | use rust_embed::RustEmbed; 8 | use std::sync::LazyLock; 9 | 10 | #[derive(RustEmbed)] 11 | #[folder = "i18n/"] 12 | struct Localizations; 13 | 14 | pub static LANGUAGE_LOADER: LazyLock = LazyLock::new(|| { 15 | let loader: FluentLanguageLoader = fluent_language_loader!(); 16 | 17 | loader 18 | .load_fallback_language(&Localizations) 19 | .expect("Error while loading fallback language"); 20 | 21 | loader 22 | }); 23 | 24 | #[macro_export] 25 | macro_rules! fl { 26 | ($message_id:literal) => {{ 27 | i18n_embed_fl::fl!($crate::localize::LANGUAGE_LOADER, $message_id) 28 | }}; 29 | 30 | ($message_id:literal, $($args:expr),*) => {{ 31 | i18n_embed_fl::fl!($crate::localize::LANGUAGE_LOADER, $message_id, $($args), *) 32 | }}; 33 | } 34 | 35 | // Get the `Localizer` to be used for localizing this library. 36 | pub fn localizer() -> Box { 37 | Box::from(DefaultLocalizer::new(&*LANGUAGE_LOADER, &Localizations)) 38 | } 39 | 40 | pub fn localize() { 41 | let localizer = localizer(); 42 | let requested_languages = i18n_embed::DesktopLanguageRequester::requested_languages(); 43 | 44 | if let Err(error) = localizer.select(&requested_languages) { 45 | eprintln!("Error while loading language for Notifications {error}"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | mod app; 2 | mod config; 3 | mod localize; 4 | mod subscriptions; 5 | 6 | use config::APP_ID; 7 | use tracing::{info, metadata::LevelFilter}; 8 | use tracing_subscriber::{EnvFilter, fmt, prelude::*}; 9 | 10 | use localize::localize; 11 | 12 | use crate::config::VERSION; 13 | 14 | fn main() -> anyhow::Result<()> { 15 | color_backtrace::install(); 16 | let trace = tracing_subscriber::registry(); 17 | 18 | let env_filter = EnvFilter::builder() 19 | .with_default_directive(LevelFilter::WARN.into()) 20 | .from_env_lossy(); 21 | #[cfg(feature = "systemd")] 22 | if let Ok(journald) = tracing_journald::layer() { 23 | trace 24 | .with(journald) 25 | .with(fmt::layer()) 26 | .with(env_filter) 27 | .try_init()?; 28 | } else { 29 | trace.with(fmt::layer()).with(env_filter).try_init()?; 30 | tracing::warn!("Failed to connect to journald") 31 | } 32 | 33 | #[cfg(not(feature = "systemd"))] 34 | trace.with(fmt::layer()).with(env_filter).try_init()?; 35 | 36 | info!("cosmic-notifications ({})", APP_ID); 37 | info!("Version: {} ({})", VERSION, config::profile()); 38 | 39 | // Prepare i18n 40 | localize(); 41 | 42 | app::run()?; 43 | Ok(()) 44 | } 45 | -------------------------------------------------------------------------------- /src/subscriptions/applet.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::HashMap, 3 | os::fd::{BorrowedFd, IntoRawFd, RawFd}, 4 | }; 5 | use tokio::{net::UnixStream, sync::mpsc::Sender}; 6 | use tracing::{error, info}; 7 | use zbus::{ 8 | Connection, Guid, connection::Builder, interface, object_server::SignalEmitter, 9 | zvariant::OwnedFd, 10 | }; 11 | 12 | use super::notifications::Input; 13 | 14 | use anyhow::{Result, bail}; 15 | use cosmic_notifications_util::DAEMON_NOTIFICATIONS_FD; 16 | use std::os::unix::io::FromRawFd; 17 | 18 | pub async fn setup_panel_conn(tx: Sender) -> Result { 19 | let socket = setup_panel_socket()?; 20 | let guid = Guid::generate(); 21 | let conn = tokio::time::timeout( 22 | tokio::time::Duration::from_secs(1), 23 | Builder::socket(socket) 24 | .p2p() 25 | .server(guid) 26 | .unwrap() 27 | .serve_at( 28 | "/com/system76/NotificationsSocket", 29 | NotificationsSocket { tx }, 30 | )? 31 | .build(), 32 | ) 33 | .await??; 34 | 35 | Ok(conn) 36 | } 37 | 38 | /// Creates a non-blocking [`UnixStream`] for communicating with the panel. 39 | /// 40 | /// # Safety 41 | /// 42 | /// It is assumed that `DAEMON_NOTIFICATIONS_FD` was set to a valid raw file descriptor ID. 43 | pub fn setup_panel_socket() -> Result { 44 | let Ok(raw_fd_env_var) = std::env::var(DAEMON_NOTIFICATIONS_FD) else { 45 | bail!("DAEMON_NOTIFICATIONS_FD is not set."); 46 | }; 47 | 48 | let Ok(raw_fd) = raw_fd_env_var.parse::() else { 49 | bail!("DAEMON_NOTIFICATIONS_FD is not a valid RawFd."); 50 | }; 51 | 52 | let fd = unsafe { BorrowedFd::borrow_raw(raw_fd).try_clone_to_owned().unwrap() }; 53 | info!("Connecting to daemon on fd {}", raw_fd); 54 | 55 | rustix::io::fcntl_setfd( 56 | &fd, 57 | rustix::io::fcntl_getfd(&fd)? | rustix::io::FdFlags::CLOEXEC, 58 | )?; 59 | 60 | let unix_stream = std::os::unix::net::UnixStream::from(fd); 61 | unix_stream.set_nonblocking(true)?; 62 | 63 | Ok(UnixStream::from_std(unix_stream)?) 64 | } 65 | 66 | pub struct NotificationsSocket { 67 | pub tx: Sender, 68 | } 69 | 70 | #[interface(name = "com.system76.NotificationsSocket")] 71 | impl NotificationsSocket { 72 | #[zbus(out_args("fd"))] 73 | async fn get_fd(&self) -> zbus::fdo::Result { 74 | let (mine, theirs) = std::os::unix::net::UnixStream::pair() 75 | .map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?; 76 | mine.set_nonblocking(true) 77 | .map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?; 78 | theirs 79 | .set_nonblocking(true) 80 | .map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?; 81 | let mine: UnixStream = 82 | UnixStream::from_std(mine).map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?; 83 | 84 | let guid = Guid::generate(); 85 | 86 | let tx_clone = self.tx.clone(); 87 | tokio::spawn(async move { 88 | let conn = match Builder::socket(mine).p2p().server(guid).unwrap().serve_at( 89 | "/com/system76/NotificationsApplet", 90 | NotificationsApplet { 91 | tx: tx_clone.clone(), 92 | }, 93 | ) { 94 | Ok(conn) => conn, 95 | Err(err) => { 96 | error!("Failed to create applet connection {}", err); 97 | return; 98 | } 99 | }; 100 | 101 | info!("Creating applet connection"); 102 | let conn = match conn.build().await { 103 | Ok(conn) => conn, 104 | Err(err) => { 105 | error!("Failed to create applet connection {}", err); 106 | return; 107 | } 108 | }; 109 | info!("Created applet connection"); 110 | 111 | if let Err(err) = tx_clone.send(Input::AppletConn(conn)).await { 112 | error!("Failed to send applet connection {}", err); 113 | return; 114 | } 115 | info!("Sent applet connection"); 116 | }); 117 | 118 | let raw = theirs.into_raw_fd(); 119 | info!("Sending fd to applet"); 120 | 121 | Ok(unsafe { zbus::zvariant::OwnedFd::from(std::os::fd::OwnedFd::from_raw_fd(raw)) }) 122 | } 123 | } 124 | 125 | pub struct NotificationsApplet { 126 | tx: Sender, 127 | } 128 | 129 | #[allow(clippy::too_many_arguments)] 130 | #[interface(name = "com.system76.NotificationsApplet")] 131 | impl NotificationsApplet { 132 | #[zbus(signal)] 133 | pub async fn notify( 134 | signal_ctxt: &SignalEmitter<'_>, 135 | app_name: &str, 136 | replaces_id: u32, 137 | app_icon: &str, 138 | summary: &str, 139 | body: &str, 140 | actions: Vec<&str>, 141 | hints: HashMap<&str, zbus::zvariant::Value<'_>>, 142 | expire_timeout: i32, 143 | ) -> zbus::Result<()>; 144 | 145 | pub async fn invoke_action(&self, id: u32, action: &str) -> zbus::fdo::Result<()> { 146 | tracing::trace!("Received action from applet {id} {action}"); 147 | let res = self 148 | .tx 149 | .send(Input::AppletActivated { 150 | id, 151 | action: action.parse().unwrap(), 152 | }) 153 | .await; 154 | if let Err(err) = res { 155 | tracing::error!("Failed to send action invoke message to channel. {id}"); 156 | return Err(zbus::fdo::Error::Failed(err.to_string())); 157 | } 158 | Ok(()) 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /src/subscriptions/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod applet; 2 | pub mod notifications; 3 | -------------------------------------------------------------------------------- /src/subscriptions/notifications.rs: -------------------------------------------------------------------------------- 1 | use crate::{config::VERSION, subscriptions::applet}; 2 | use cosmic::{ 3 | iced::{ 4 | futures::{self, SinkExt}, 5 | stream, 6 | }, 7 | iced_futures::Subscription, 8 | }; 9 | use cosmic_notifications_util::{ActionId, CloseReason, Notification}; 10 | use futures::channel::mpsc; 11 | use std::{collections::HashMap, fmt::Debug, num::NonZeroU32}; 12 | use tokio::{ 13 | sync::mpsc::{Receiver, Sender, channel}, 14 | task::JoinHandle, 15 | }; 16 | use tracing::error; 17 | 18 | use zbus::{ 19 | Connection, connection::Builder as ConnectionBuilder, interface, object_server::SignalEmitter, 20 | }; 21 | 22 | use super::applet::NotificationsApplet; 23 | 24 | #[derive(Debug)] 25 | pub struct Conns { 26 | notifications: Connection, 27 | pub tx: Sender, 28 | rx: Receiver, 29 | _panel: Option, 30 | } 31 | 32 | impl Conns { 33 | pub async fn new() -> zbus::Result { 34 | let (tx, rx) = channel(100); 35 | let panel = match applet::setup_panel_conn(tx.clone()).await { 36 | Ok(conn) => Some(conn), 37 | Err(err) => { 38 | error!("Failed to setup panel dbus server {}", err.to_string()); 39 | None 40 | } 41 | }; 42 | 43 | for _ in 0..5 { 44 | if let Some(conn) = ConnectionBuilder::session() 45 | .ok() 46 | .and_then(|conn| conn.name("org.freedesktop.Notifications").ok()) 47 | .and_then(|conn| { 48 | conn.serve_at( 49 | "/org/freedesktop/Notifications", 50 | Notifications(tx.clone(), NonZeroU32::new(1).unwrap(), Vec::new()), 51 | ) 52 | .ok() 53 | }) 54 | .map(ConnectionBuilder::build) 55 | { 56 | if let Ok(conn) = conn.await { 57 | return Ok(Self { 58 | tx, 59 | notifications: conn, 60 | rx, 61 | _panel: panel, 62 | }); 63 | } 64 | } else { 65 | error!("Failed to create connection at /org/freedesktop/Notifications"); 66 | tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; 67 | } 68 | } 69 | 70 | Err(zbus::Error::Failure( 71 | "Failed to create the dbus server".to_string(), 72 | )) 73 | } 74 | } 75 | 76 | struct Start; 77 | struct Waiting; 78 | 79 | struct Machine { 80 | conns: Option, 81 | output: mpsc::Sender, 82 | marker: core::marker::PhantomData, 83 | } 84 | 85 | impl Machine { 86 | pub fn new(conns: Option, output: mpsc::Sender) -> Self { 87 | Self { 88 | conns, 89 | output, 90 | marker: core::marker::PhantomData, 91 | } 92 | } 93 | 94 | pub fn transition(self) -> Machine { 95 | Machine:: { 96 | conns: self.conns, 97 | output: self.output, 98 | marker: core::marker::PhantomData, 99 | } 100 | } 101 | } 102 | 103 | impl Machine { 104 | pub async fn exec(mut self) -> Result<(Machine, Conns), ()> { 105 | let handle: JoinHandle> = tokio::spawn(async move { 106 | let conns = Conns::new().await?; 107 | Ok(conns) 108 | }); 109 | 110 | match handle.await { 111 | Ok(Ok(conns)) => { 112 | _ = self.output.send(Event::Ready(conns.tx.clone())).await; 113 | Ok((self.transition::(), conns)) 114 | } 115 | Ok(Err(err)) => { 116 | error!("Failed to create connection {}", err); 117 | Err(()) 118 | } 119 | Err(err) => { 120 | error!("Failed to create connection {}", err); 121 | Err(()) 122 | } 123 | } 124 | } 125 | } 126 | 127 | impl Machine { 128 | pub async fn exec(mut self, mut conns: Conns) { 129 | loop { 130 | if let Some(next) = conns.rx.recv().await { 131 | match next { 132 | Input::Activated { token, id, action } => { 133 | let object_server = conns.notifications.object_server(); 134 | let Ok(iface_ref) = object_server 135 | .interface::<_, Notifications>("/org/freedesktop/Notifications") 136 | .await 137 | else { 138 | continue; 139 | }; 140 | 141 | if let Err(err) = 142 | Notifications::activation_token(iface_ref.signal_emitter(), id, &token) 143 | .await 144 | { 145 | error!("Failed to signal notification with token {}", err); 146 | } 147 | 148 | if let Err(err) = 149 | Notifications::action_invoked(iface_ref.signal_emitter(), id, &action) 150 | .await 151 | { 152 | error!("Failed to signal activated notification {}", err); 153 | } 154 | tracing::trace!("Activated application"); 155 | } 156 | Input::Closed(id, reason) => { 157 | let object_server = conns.notifications.object_server(); 158 | if let Ok(iface_ref) = object_server 159 | .interface::<_, Notifications>("/org/freedesktop/Notifications") 160 | .await 161 | { 162 | _ = Notifications::notification_closed( 163 | iface_ref.signal_emitter(), 164 | id, 165 | reason as u32, 166 | ) 167 | .await; 168 | } 169 | } 170 | Input::Notification(notification) => { 171 | _ = self.output.send(Event::Notification(notification)).await; 172 | } 173 | Input::Replace(notification) => { 174 | _ = self.output.send(Event::Replace(notification)).await; 175 | } 176 | Input::CloseNotification(id) => { 177 | _ = self.output.send(Event::CloseNotification(id)).await; 178 | 179 | let object_server = conns.notifications.object_server(); 180 | let Ok(iface_ref) = object_server 181 | .interface::<_, Notifications>("/org/freedesktop/Notifications") 182 | .await 183 | else { 184 | continue; 185 | }; 186 | if let Err(err) = 187 | Notifications::notification_closed(iface_ref.signal_emitter(), id, 3) 188 | .await 189 | { 190 | error!("Failed to signal close notification {}", err); 191 | } 192 | } 193 | Input::Dismissed(id) => { 194 | let object_server = conns.notifications.object_server(); 195 | let Ok(iface_ref) = object_server 196 | .interface::<_, Notifications>("/org/freedesktop/Notifications") 197 | .await 198 | else { 199 | continue; 200 | }; 201 | if let Err(err) = 202 | Notifications::notification_closed(iface_ref.signal_emitter(), id, 2) 203 | .await 204 | { 205 | error!("Failed to signal dismissed notification {}", err); 206 | } 207 | } 208 | Input::AppletConn(c) => { 209 | let object_server = conns.notifications.object_server(); 210 | let Ok(iface_ref) = object_server 211 | .interface::<_, Notifications>("/org/freedesktop/Notifications") 212 | .await 213 | else { 214 | continue; 215 | }; 216 | let mut iface = iface_ref.get_mut().await; 217 | iface.2.push(c); 218 | } 219 | Input::AppletActivated { id, action } => { 220 | if let Err(err) = self 221 | .output 222 | .send(Event::AppletActivated { id, action }) 223 | .await 224 | { 225 | tracing::error!( 226 | "Failed to send activation action for {id} to subscription channel {err}" 227 | ); 228 | } 229 | } 230 | } 231 | } else { 232 | // The channel was closed, so we are done 233 | return; 234 | } 235 | } 236 | } 237 | } 238 | 239 | #[derive(Debug, Clone)] 240 | pub enum Input { 241 | Activated { 242 | token: String, 243 | id: u32, 244 | action: String, 245 | }, 246 | AppletActivated { 247 | id: u32, 248 | action: ActionId, 249 | }, 250 | Notification(Notification), 251 | Replace(Notification), 252 | CloseNotification(u32), 253 | Closed(u32, CloseReason), 254 | Dismissed(u32), 255 | AppletConn(Connection), 256 | } 257 | 258 | #[derive(Debug, Clone)] 259 | pub enum Event { 260 | Ready(Sender), 261 | Notification(Notification), 262 | Replace(Notification), 263 | CloseNotification(u32), 264 | AppletActivated { id: u32, action: ActionId }, 265 | } 266 | 267 | pub fn notifications() -> Subscription { 268 | struct SomeWorker; 269 | 270 | Subscription::run_with_id( 271 | std::any::TypeId::of::(), 272 | stream::channel(100, |output| async move { 273 | let machine = Machine::::new(None, output); 274 | 275 | if let Ok((waiting, conns)) = machine.exec().await { 276 | waiting.exec(conns).await; 277 | }; 278 | 279 | futures::pending!(); 280 | }), 281 | ) 282 | } 283 | 284 | pub struct Notifications(Sender, NonZeroU32, Vec); 285 | 286 | #[interface(name = "org.freedesktop.Notifications")] 287 | impl Notifications { 288 | async fn close_notification(&self, id: u32) { 289 | if let Err(err) = self.0.send(Input::CloseNotification(id)).await { 290 | tracing::error!("Failed to send close notification: {}", err); 291 | } 292 | } 293 | 294 | /// "action-icons" Supports using icons instead of text for displaying actions. Using icons for actions must be enabled on a per-notification basis using the "action-icons" hint. 295 | /// "actions" The server will provide the specified actions to the user. Even if this cap is missing, actions may still be specified by the client, however the server is free to ignore them. 296 | /// "body" Supports body text. Some implementations may only show the summary (for instance, onscreen displays, marquee/scrollers) 297 | /// "body-hyperlinks" The server supports hyperlinks in the notifications. 298 | /// "body-images" The server supports images in the notifications. 299 | /// "body-markup" Supports markup in the body text. If marked up text is sent to a server that does not give this cap, the markup will show through as regular text so must be stripped clientside. 300 | /// "icon-multi" The server will render an animation of all the frames in a given image array. The client may still specify multiple frames even if this cap and/or "icon-static" is missing, however the server is free to ignore them and use only the primary frame. 301 | /// "icon-static" Supports display of exactly 1 frame of any given image array. This value is mutually exclusive with "icon-multi", it is a protocol error for the server to specify both. 302 | /// "persistence" The server supports persistence of notifications. Notifications will be retained until they are acknowledged or removed by the user or recalled by the sender. The presence of this capability allows clients to depend on the server to ensure a notification is seen and eliminate the need for the client to display a reminding function (such as a status icon) of its own. 303 | /// "sound" The server supports sounds on notifications. If returned, the server must support the "sound-file" and "suppress-sound" hints. 304 | async fn get_capabilities(&self) -> Vec<&'static str> { 305 | vec![ 306 | "body", 307 | "icon-static", 308 | "persistence", 309 | "actions", 310 | // TODO support these 311 | "action-icons", 312 | "body-markup", 313 | "body-hyperlinks", 314 | "sound", 315 | ] 316 | } 317 | 318 | #[zbus(out_args("name", "vendor", "version", "spec_version"))] 319 | async fn get_server_information( 320 | &self, 321 | ) -> (&'static str, &'static str, &'static str, &'static str) { 322 | ("cosmic-notifications", "System76", VERSION, "1.2") 323 | } 324 | 325 | /// 326 | /// app_name STRING The optional name of the application sending the notification. Can be blank. 327 | /// 328 | /// replaces_id UINT32 The optional notification ID that this notification replaces. The server must atomically (ie with no flicker or other visual cues) replace the given notification with this one. This allows clients to effectively modify the notification while it's active. A value of value of 0 means that this notification won't replace any existing notifications. 329 | /// 330 | /// app_icon STRING The optional program icon of the calling application. See Icons and Images. Can be an empty string, indicating no icon. 331 | /// 332 | /// summary STRING The summary text briefly describing the notification. 333 | /// 334 | /// body STRING The optional detailed body text. Can be empty. 335 | /// 336 | /// actions as Actions are sent over as a list of pairs. Each even element in the list (starting at index 0) represents the identifier for the action. Each odd element in the list is the localized string that will be displayed to the user. 337 | /// 338 | /// hints a{sv} Optional hints that can be passed to the server from the client program. Although clients and servers should never assume each other supports any specific hints, they can be used to pass along information, such as the process PID or window ID, that the server may be able to make use of. See Hints. Can be empty. 339 | /// expire_timeout INT32 340 | /// 341 | /// The timeout time in milliseconds since the display of the notification at which the notification should automatically close. 342 | /// If -1, the notification's expiration time is dependent on the notification server's settings, and may vary for the type of notification. If 0, never expire. 343 | #[allow(clippy::too_many_arguments)] 344 | async fn notify( 345 | &mut self, 346 | app_name: &str, 347 | replaces_id: u32, 348 | app_icon: &str, 349 | summary: &str, 350 | body: &str, 351 | actions: Vec<&str>, 352 | hints: HashMap<&str, zbus::zvariant::Value<'_>>, 353 | expire_timeout: i32, 354 | ) -> u32 { 355 | let id = if replaces_id == 0 { 356 | let id = self.1; 357 | self.1 = match self.1.checked_add(1) { 358 | Some(id) => id, 359 | None => { 360 | tracing::warn!("Notification ID overflowed"); 361 | NonZeroU32::new(1).unwrap() 362 | } 363 | }; 364 | id.get() 365 | } else { 366 | replaces_id 367 | }; 368 | let hints_clone = hints 369 | .iter() 370 | .filter_map(|(k, v)| Some((*k, v.try_clone().ok()?))) 371 | .collect(); 372 | let n = Notification::new( 373 | app_name, 374 | id, 375 | app_icon, 376 | summary, 377 | body, 378 | actions.clone(), 379 | hints_clone, 380 | expire_timeout, 381 | ); 382 | 383 | if !n.transient() { 384 | let mut new_conns = Vec::with_capacity(self.2.len()); 385 | for c in self.2.drain(..) { 386 | let object_server = c.object_server(); 387 | let Ok(Ok(iface_ref)) = tokio::time::timeout( 388 | tokio::time::Duration::from_millis(100), 389 | object_server 390 | .interface::<_, NotificationsApplet>("/com/system76/NotificationsApplet"), 391 | ) 392 | .await 393 | else { 394 | continue; 395 | }; 396 | let hints_clone = hints 397 | .iter() 398 | .filter_map(|(k, v)| Some((*k, v.try_clone().ok()?))) 399 | .collect(); 400 | match tokio::time::timeout( 401 | tokio::time::Duration::from_millis(500), 402 | NotificationsApplet::notify( 403 | iface_ref.signal_emitter(), 404 | app_name, 405 | id, 406 | app_icon, 407 | summary, 408 | body, 409 | actions.clone(), 410 | hints_clone, 411 | expire_timeout, 412 | ), 413 | ) 414 | .await 415 | { 416 | Ok(Err(err)) => error!("Failed to notify applet of notification {}", err), 417 | Err(err) => error!("Failed to notify applet of notification {}", err), 418 | Ok(_) => {} 419 | } 420 | new_conns.push(c); 421 | } 422 | self.2 = new_conns; 423 | } 424 | 425 | if let Err(err) = self 426 | .0 427 | .send(if replaces_id == 0 { 428 | Input::Notification(n) 429 | } else { 430 | Input::Replace(n) 431 | }) 432 | .await 433 | { 434 | tracing::error!("Failed to send notification: {}", err); 435 | } 436 | 437 | id 438 | } 439 | 440 | #[zbus(signal)] 441 | async fn action_invoked( 442 | signal_ctxt: &SignalEmitter<'_>, 443 | id: u32, 444 | action_key: &str, 445 | ) -> zbus::Result<()>; 446 | 447 | #[zbus(signal)] 448 | async fn activation_token( 449 | signal_ctxt: &SignalEmitter<'_>, 450 | id: u32, 451 | activation_token: &str, 452 | ) -> zbus::Result<()>; 453 | 454 | /// id UINT32 The ID of the notification that was closed. 455 | /// reason UINT32 456 | /// 457 | /// The reason the notification was closed. 458 | /// 459 | /// 1 - The notification expired. 460 | /// 461 | /// 2 - The notification was dismissed by the user. 462 | /// 463 | /// 3 - The notification was closed by a call to CloseNotification. 464 | /// 465 | /// 4 - Undefined/reserved reasons. 466 | #[zbus(signal)] 467 | async fn notification_closed( 468 | signal_ctxt: &SignalEmitter<'_>, 469 | id: u32, 470 | reason: u32, 471 | ) -> zbus::Result<()>; 472 | } 473 | --------------------------------------------------------------------------------