├── .github ├── FUNDING.yml └── workflows │ ├── ci.yaml │ └── release.yaml ├── .gitignore ├── .pre-commit-config.yaml ├── Cargo.lock ├── Cargo.toml ├── Cross.toml ├── LICENSE ├── Readme.md ├── Release.md ├── assets └── logo.png ├── flake.lock ├── flake.nix ├── package.nix └── src ├── app.rs ├── bluetooth.rs ├── config.rs ├── confirmation.rs ├── event.rs ├── handler.rs ├── help.rs ├── lib.rs ├── main.rs ├── notification.rs ├── rfkill.rs ├── spinner.rs ├── tui.rs └── ui.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: pythops 4 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | name: CI 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - "*" 8 | jobs: 9 | test: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: dtolnay/rust-toolchain@stable 14 | with: 15 | toolchain: stable 16 | components: clippy rustfmt 17 | 18 | - name: Setup the build env 19 | run: | 20 | sudo apt update 21 | sudo apt install -y libdbus-1-dev pkg-config 22 | 23 | - name: Linting 24 | run: | 25 | cargo clippy --workspace --all-features -- -D warnings 26 | cargo fmt --all -- --check 27 | 28 | - name: Debug builds 29 | run: cargo build 30 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Release 3 | on: 4 | push: 5 | tags: 6 | - "v*" 7 | jobs: 8 | build: 9 | permissions: 10 | contents: write 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: cargo-bins/cargo-binstall@main 15 | - uses: dtolnay/rust-toolchain@stable 16 | with: 17 | toolchain: stable 18 | 19 | - name: Setup the build env 20 | run: | 21 | sudo apt-get update && \ 22 | sudo apt-get install -y \ 23 | podman \ 24 | qemu-user-static\ 25 | pkg-config \ 26 | libdbus-1-dev && \ 27 | cargo binstall --no-confirm cross 28 | 29 | - name: Build for x86_64 linux gnu 30 | run: | 31 | cargo build --release 32 | cp target/release/bluetui bluetui-x86_64-linux-gnu 33 | 34 | - name: Build for aarch64 linux gnu 35 | run: | 36 | CROSS_CONTAINER_ENGINE=podman cross build --target aarch64-unknown-linux-gnu --release 37 | cp target/aarch64-unknown-linux-gnu/release/bluetui bluetui-aarch64-linux-gnu 38 | 39 | - name: Release 40 | uses: softprops/action-gh-release@v1 41 | with: 42 | body: | 43 | [Release.md](${{ github.server_url }}/${{ github.repository }}/blob/master/Release.md) 44 | files: "bluetui*" 45 | env: 46 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 47 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | fail_fast: true 3 | repos: 4 | - repo: local 5 | hooks: 6 | - id: cargo-fmt 7 | name: cargo fmt 8 | entry: cargo fmt --all -- 9 | language: system 10 | types: [rust] 11 | - id: clippy 12 | name: clippy 13 | entry: | 14 | cargo clippy --workspace --all-targets --all-features -- -D warnings 15 | language: system 16 | pass_filenames: false 17 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bluetui" 3 | version = "0.6.0" 4 | authors = ["Badr Badri "] 5 | license = "GPL-3.0" 6 | edition = "2024" 7 | description = "TUI for managing bluetooth on Linux" 8 | readme = "Readme.md" 9 | homepage = "https://github.com/pythops/bluetui" 10 | repository = "https://github.com/pythops/bluetui" 11 | 12 | [dependencies] 13 | async-channel = "2" 14 | bluer = { version = "0.17", features = ["full"] } 15 | crossterm = { version = "0.28", features = ["event-stream"] } 16 | futures = "0.3" 17 | ratatui = "0.29" 18 | tokio = { version = "1", features = ["full"] } 19 | dirs = "6" 20 | toml = "0.8" 21 | serde = { version = "1", features = ["derive"] } 22 | clap = { version = "4", features = ["derive", "cargo"] } 23 | terminal-light = "1" 24 | tui-input = "0.12" 25 | 26 | [profile.release] 27 | strip = true 28 | codegen-units = 1 29 | lto = "fat" 30 | -------------------------------------------------------------------------------- /Cross.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | pre-build = [ 3 | "dpkg --add-architecture $CROSS_DEB_ARCH", 4 | "apt update && apt install -y libdbus-1-dev:$CROSS_DEB_ARCH pkg-config:$CROSS_DEB_ARCH ", 5 | ] 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | 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 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

TUI for managing bluetooth on Linux

4 | 5 |
6 | 7 | ## 💡 Prerequisites 8 | 9 | A Linux based OS with [bluez](https://www.bluez.org/) installed. 10 | 11 | > [!NOTE] 12 | > You might need to install [nerdfonts](https://www.nerdfonts.com/) for the icons to be displayed correctly. 13 | 14 | ## 🚀 Installation 15 | 16 | ### 📥 Binary release 17 | 18 | You can download the pre-built binaries from the release page [release page](https://github.com/pythops/bluetui/releases) 19 | 20 | ### 📦 crates.io 21 | 22 | You can install `bluetui` from [crates.io](https://crates.io/crates/bluetui) 23 | 24 | ```shell 25 | cargo install bluetui 26 | ``` 27 | 28 | ### 🐧 Arch Linux 29 | 30 | You can install `bluetui` from the [extra repository](https://archlinux.org/packages/extra/x86_64/bluetui/): 31 | 32 | ```shell 33 | pacman -S bluetui 34 | ``` 35 | 36 | ### 🐧 Gentoo 37 | 38 | You can install `bluetui` from the [lamdness Gentoo Overlay](https://gpo.zugaina.org/net-wireless/bluetui): 39 | ```sh 40 | sudo eselect repository enable lamdness 41 | sudo emaint -r lamdness sync 42 | sudo emerge -av net-wireless/bluetui 43 | ``` 44 | 45 | ### 🧰 X-CMD 46 | 47 | If you are a user of [x-cmd](https://x-cmd.com), you can run: 48 | 49 | ```shell 50 | x install bluetui 51 | ``` 52 | 53 | 54 | ### ⚒️ Build from source 55 | 56 | Run the following command: 57 | 58 | ```shell 59 | git clone https://github.com/pythops/bluetui 60 | cd bluetui 61 | cargo build --release 62 | ``` 63 | 64 | This will produce an executable file at `target/release/bluetui` that you can copy to a directory in your `$PATH`. 65 | 66 | ## 🪄 Usage 67 | 68 | ### Global 69 | 70 | `Tab`: Switch between different sections. 71 | 72 | `j` or `Down` : Scroll down. 73 | 74 | `k` or `Up`: Scroll up. 75 | 76 | `s`: Start/Stop scanning. 77 | 78 | `?`: Show help. 79 | 80 | `esc`: Dismiss the help pop-up. 81 | 82 | `ctrl+c` or `q`: Quit the app. 83 | 84 | ### Adapters 85 | 86 | `p`: Enable/Disable the pairing. 87 | 88 | `o`: Power on/off the adapter. 89 | 90 | `d`: Enable/Disable the discovery. 91 | 92 | ### Paired devices 93 | 94 | `u`: Unpair the device. 95 | 96 | `Space`: Connect/Disconnect the device. 97 | 98 | `t`: Trust/Untrust the device. 99 | 100 | `e`: Rename the device. 101 | 102 | ### New devices 103 | 104 | `p`: Pair the device. 105 | 106 | ## Custom keybindings 107 | 108 | Keybindings can be customized in the config file `$HOME/.config/bluetui/config.toml` 109 | 110 | ```toml 111 | toggle_scanning = "s" 112 | 113 | [adapter] 114 | toggle_pairing = "p" 115 | toggle_power = "o" 116 | toggle_discovery = "d" 117 | 118 | [paired_device] 119 | unpair = "u" 120 | toggle_connect = " " 121 | toggle_trust = "t" 122 | rename = "e" 123 | 124 | [new_device] 125 | pair = "p" 126 | ``` 127 | 128 | ## ⚖️ License 129 | 130 | GPLv3 131 | -------------------------------------------------------------------------------- /Release.md: -------------------------------------------------------------------------------- 1 | ## v0.6 - 2024-12-21 2 | 3 | ### Updated 4 | 5 | - The layout has been reorgonized to show paired devices section on the top 6 | 7 | ### Fix 8 | 9 | - fg color is fixed for light mode 10 | 11 | ## v0.5.1 - 29/07/2024 12 | 13 | ### Added 14 | 15 | - Detect when the device is soft/hard blocked 16 | - Add `q` to quit 17 | 18 | ## v0.5 - 11/07/2024 19 | 20 | ### Added 21 | 22 | - Rename paired devices 23 | - Support light background 24 | 25 | ## v0.4 - 15/03/2024 26 | 27 | ### Added 28 | 29 | - Add scrollbars by [@orhun](https://github.com/orhun/) 30 | - Custom keybindings 31 | 32 | ## v0.3 - 06/03/2024 33 | 34 | ### Added 35 | 36 | - Show battery percentage 37 | - Colorful layout 38 | 39 | ### Updated 40 | 41 | - Update the main layout 42 | 43 | ## v0.2 - 25/02/2024 44 | 45 | ### Added 46 | 47 | - Handle pairing confirmation request 48 | 49 | ### Updated 50 | 51 | - notification layout 52 | - notification ttl is set to 1 second 53 | 54 | ## v0.1 - 22/02/2024 55 | 56 | First release 🎉 57 | -------------------------------------------------------------------------------- /assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythops/bluetui/e9fa58e4ecd087cf53b8468b54c3d603ec69c04c/assets/logo.png -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "nixpkgs": { 4 | "locked": { 5 | "lastModified": 1742268799, 6 | "narHash": "sha256-IhnK4LhkBlf14/F8THvUy3xi/TxSQkp9hikfDZRD4Ic=", 7 | "owner": "nixos", 8 | "repo": "nixpkgs", 9 | "rev": "da044451c6a70518db5b730fe277b70f494188f1", 10 | "type": "github" 11 | }, 12 | "original": { 13 | "owner": "nixos", 14 | "ref": "nixos-24.11", 15 | "repo": "nixpkgs", 16 | "type": "github" 17 | } 18 | }, 19 | "root": { 20 | "inputs": { 21 | "nixpkgs": "nixpkgs" 22 | } 23 | } 24 | }, 25 | "root": "root", 26 | "version": 7 27 | } 28 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | inputs.nixpkgs.url = "github:nixos/nixpkgs/nixos-24.11"; 3 | 4 | outputs = 5 | { self, nixpkgs }: 6 | { 7 | packages = 8 | nixpkgs.lib.genAttrs 9 | [ 10 | "x86_64-linux" 11 | "aarch64-linux" 12 | ] 13 | (system: rec { 14 | bluetui = nixpkgs.legacyPackages.${system}.callPackage ./package.nix { }; 15 | default = bluetui; 16 | }); 17 | }; 18 | } 19 | -------------------------------------------------------------------------------- /package.nix: -------------------------------------------------------------------------------- 1 | { 2 | lib, 3 | rustPlatform, 4 | pkg-config, 5 | dbus, 6 | }: 7 | 8 | let 9 | cargo = (lib.importTOML ./Cargo.toml).package; 10 | in 11 | rustPlatform.buildRustPackage { 12 | pname = cargo.name; 13 | version = cargo.version; 14 | 15 | src = ./.; 16 | 17 | cargoLock = { 18 | lockFile = ./Cargo.lock; 19 | }; 20 | 21 | nativeBuildInputs = [ pkg-config ]; 22 | 23 | buildInputs = [ dbus ]; 24 | 25 | meta = { 26 | description = cargo.description; 27 | homepage = cargo.homepage; 28 | license = lib.licenses.gpl3Only; 29 | maintainers = with lib.maintainers; [ samuel-martineau ]; 30 | }; 31 | } 32 | -------------------------------------------------------------------------------- /src/app.rs: -------------------------------------------------------------------------------- 1 | use bluer::{ 2 | Session, 3 | agent::{Agent, AgentHandle}, 4 | }; 5 | use futures::FutureExt; 6 | use ratatui::{ 7 | Frame, 8 | layout::{Alignment, Constraint, Direction, Layout, Margin}, 9 | style::{Color, Modifier, Style, Stylize}, 10 | text::{Line, Span}, 11 | widgets::{ 12 | Block, BorderType, Borders, Cell, Clear, Padding, Paragraph, Row, Scrollbar, 13 | ScrollbarOrientation, ScrollbarState, Table, TableState, 14 | }, 15 | }; 16 | use tui_input::Input; 17 | 18 | use crate::{ 19 | bluetooth::{Controller, request_confirmation}, 20 | config::Config, 21 | confirmation::PairingConfirmation, 22 | help::Help, 23 | notification::Notification, 24 | spinner::Spinner, 25 | }; 26 | use std::{ 27 | error, 28 | sync::{Arc, atomic::Ordering}, 29 | }; 30 | 31 | pub type AppResult = std::result::Result>; 32 | 33 | #[derive(Debug, Clone, Copy, PartialEq)] 34 | pub enum FocusedBlock { 35 | Adapter, 36 | PairedDevices, 37 | NewDevices, 38 | Help, 39 | PassKeyConfirmation, 40 | SetDeviceAliasBox, 41 | } 42 | 43 | #[derive(Debug, Clone, Copy, PartialEq)] 44 | pub enum ColorMode { 45 | Dark, 46 | Light, 47 | } 48 | 49 | #[derive(Debug)] 50 | pub struct App { 51 | pub running: bool, 52 | pub session: Arc, 53 | pub agent: AgentHandle, 54 | pub help: Help, 55 | pub spinner: Spinner, 56 | pub notifications: Vec, 57 | pub controllers: Vec, 58 | pub controller_state: TableState, 59 | pub paired_devices_state: TableState, 60 | pub new_devices_state: TableState, 61 | pub focused_block: FocusedBlock, 62 | pub pairing_confirmation: PairingConfirmation, 63 | pub color_mode: ColorMode, 64 | pub new_alias: Input, 65 | } 66 | 67 | impl App { 68 | pub async fn new(config: Arc) -> AppResult { 69 | let color_mode = match terminal_light::luma() { 70 | Ok(luma) if luma > 0.6 => ColorMode::Light, 71 | Ok(_) => ColorMode::Dark, 72 | Err(_) => ColorMode::Dark, 73 | }; 74 | 75 | let session = Arc::new(bluer::Session::new().await?); 76 | 77 | let pairing_confirmation = PairingConfirmation::new(); 78 | 79 | let user_confirmation_receiver = pairing_confirmation.user_confirmation_receiver.clone(); 80 | 81 | let confirmation_message_sender = pairing_confirmation.confirmation_message_sender.clone(); 82 | 83 | let confirmation_display = pairing_confirmation.display.clone(); 84 | 85 | let agent = Agent { 86 | request_default: false, 87 | request_confirmation: Some(Box::new(move |req| { 88 | request_confirmation( 89 | req, 90 | confirmation_display.clone(), 91 | user_confirmation_receiver.clone(), 92 | confirmation_message_sender.clone(), 93 | ) 94 | .boxed() 95 | })), 96 | ..Default::default() 97 | }; 98 | 99 | let handle = session.register_agent(agent).await?; 100 | let controllers: Vec = Controller::get_all(session.clone()).await?; 101 | 102 | let mut controller_state = TableState::default(); 103 | if controllers.is_empty() { 104 | controller_state.select(None); 105 | } else { 106 | controller_state.select(Some(0)); 107 | } 108 | 109 | Ok(Self { 110 | running: true, 111 | session, 112 | agent: handle, 113 | help: Help::new(config), 114 | spinner: Spinner::default(), 115 | notifications: Vec::new(), 116 | controllers, 117 | controller_state, 118 | paired_devices_state: TableState::default(), 119 | new_devices_state: TableState::default(), 120 | focused_block: FocusedBlock::PairedDevices, 121 | pairing_confirmation, 122 | color_mode, 123 | new_alias: Input::default(), 124 | }) 125 | } 126 | 127 | pub fn reset_devices_state(&mut self) { 128 | if let Some(selected_controller) = self.controller_state.selected() { 129 | let controller = &self.controllers[selected_controller]; 130 | if !controller.paired_devices.is_empty() { 131 | self.paired_devices_state.select(Some(0)); 132 | } else { 133 | self.paired_devices_state.select(None); 134 | } 135 | 136 | if !controller.new_devices.is_empty() { 137 | self.new_devices_state.select(Some(0)); 138 | } else { 139 | self.new_devices_state.select(None); 140 | } 141 | } 142 | } 143 | 144 | pub fn render_set_alias(&mut self, frame: &mut Frame) { 145 | let area = Layout::default() 146 | .direction(Direction::Vertical) 147 | .constraints([ 148 | Constraint::Fill(1), 149 | Constraint::Length(6), 150 | Constraint::Fill(1), 151 | ]) 152 | .split(frame.area()); 153 | 154 | let area = Layout::default() 155 | .direction(Direction::Horizontal) 156 | .constraints([ 157 | Constraint::Fill(1), 158 | Constraint::Min(80), 159 | Constraint::Fill(1), 160 | ]) 161 | .split(area[1]); 162 | 163 | let area = area[1]; 164 | 165 | let (text_area, alias_area) = { 166 | let chunks = Layout::default() 167 | .direction(Direction::Vertical) 168 | .constraints( 169 | [ 170 | Constraint::Length(1), 171 | Constraint::Length(3), 172 | Constraint::Length(1), 173 | Constraint::Length(2), 174 | ] 175 | .as_ref(), 176 | ) 177 | .split(area); 178 | 179 | let area1 = Layout::default() 180 | .direction(Direction::Horizontal) 181 | .constraints( 182 | [ 183 | Constraint::Length(1), 184 | Constraint::Fill(1), 185 | Constraint::Length(1), 186 | ] 187 | .as_ref(), 188 | ) 189 | .split(chunks[1]); 190 | 191 | let area2 = Layout::default() 192 | .direction(Direction::Horizontal) 193 | .constraints( 194 | [ 195 | Constraint::Percentage(20), 196 | Constraint::Fill(1), 197 | Constraint::Percentage(20), 198 | ] 199 | .as_ref(), 200 | ) 201 | .split(chunks[2]); 202 | 203 | (area1[1], area2[1]) 204 | }; 205 | 206 | frame.render_widget(Clear, area); 207 | frame.render_widget( 208 | Block::new() 209 | .borders(Borders::ALL) 210 | .border_type(BorderType::Thick) 211 | .style(Style::default().green()) 212 | .border_style(Style::default().fg(Color::Green)), 213 | area, 214 | ); 215 | 216 | if let Some(selected_controller) = self.controller_state.selected() { 217 | let controller = &self.controllers[selected_controller]; 218 | if let Some(index) = self.paired_devices_state.selected() { 219 | let name = controller.paired_devices[index].alias.as_str(); 220 | 221 | let text = Line::from(vec![ 222 | Span::from("Enter the new name for "), 223 | Span::styled( 224 | name, 225 | Style::default().add_modifier(Modifier::BOLD | Modifier::ITALIC), 226 | ), 227 | ]); 228 | 229 | let msg = Paragraph::new(text) 230 | .alignment(Alignment::Center) 231 | .style(Style::default().fg(Color::White)) 232 | .block(Block::new().padding(Padding::horizontal(2))); 233 | 234 | let alias = Paragraph::new(self.new_alias.value()) 235 | .alignment(Alignment::Left) 236 | .style(Style::default().fg(Color::White)) 237 | .block( 238 | Block::new() 239 | .bg(Color::DarkGray) 240 | .padding(Padding::horizontal(2)), 241 | ); 242 | 243 | frame.render_widget(msg, text_area); 244 | frame.render_widget(alias, alias_area); 245 | } 246 | } 247 | } 248 | 249 | pub fn render(&mut self, frame: &mut Frame) { 250 | if let Some(selected_controller_index) = self.controller_state.selected() { 251 | let selected_controller = &self.controllers[selected_controller_index]; 252 | // Layout 253 | let render_new_devices = !selected_controller.new_devices.is_empty() 254 | | selected_controller.is_scanning.load(Ordering::Relaxed); 255 | 256 | let adapter_block_height = self.controllers.len() as u16 + 6; 257 | 258 | let paired_devices_block_height = selected_controller.paired_devices.len() as u16 + 4; 259 | 260 | let (paired_devices_block, new_devices_block, controller_block) = { 261 | let chunks = Layout::default() 262 | .direction(Direction::Vertical) 263 | .constraints(if render_new_devices { 264 | [ 265 | Constraint::Length(paired_devices_block_height), 266 | Constraint::Fill(1), 267 | Constraint::Length(adapter_block_height), 268 | ] 269 | } else { 270 | [ 271 | Constraint::Fill(1), 272 | Constraint::Length(0), 273 | Constraint::Length(adapter_block_height), 274 | ] 275 | }) 276 | .margin(1) 277 | .split(frame.area()); 278 | (chunks[0], chunks[1], chunks[2]) 279 | }; 280 | 281 | //Adapters 282 | let rows: Vec = self 283 | .controllers 284 | .iter() 285 | .map(|controller| { 286 | Row::new(vec![ 287 | controller.name.to_string(), 288 | controller.alias.to_string(), 289 | { 290 | if controller.is_powered { 291 | "On".to_string() 292 | } else { 293 | "Off".to_string() 294 | } 295 | }, 296 | controller.is_pairable.to_string(), 297 | controller.is_discoverable.to_string(), 298 | ]) 299 | }) 300 | .collect(); 301 | 302 | let widths = [ 303 | Constraint::Length(10), 304 | Constraint::Length(10), 305 | Constraint::Length(10), 306 | Constraint::Length(10), 307 | Constraint::Length(14), 308 | ]; 309 | 310 | let rows_len = rows.len(); 311 | 312 | let controller_table = Table::new(rows, widths) 313 | .header({ 314 | if self.focused_block == FocusedBlock::Adapter { 315 | Row::new(vec![ 316 | Cell::from("Name").style(Style::default().fg(Color::Yellow)), 317 | Cell::from("Alias").style(Style::default().fg(Color::Yellow)), 318 | Cell::from("Power").style(Style::default().fg(Color::Yellow)), 319 | Cell::from("Pairable").style(Style::default().fg(Color::Yellow)), 320 | Cell::from("Discoverable").style(Style::default().fg(Color::Yellow)), 321 | ]) 322 | .style(Style::new().bold()) 323 | .bottom_margin(1) 324 | } else { 325 | Row::new(vec![ 326 | Cell::from("Name").style(match self.color_mode { 327 | ColorMode::Dark => Style::default().fg(Color::White), 328 | ColorMode::Light => Style::default().fg(Color::Black), 329 | }), 330 | Cell::from("Alias").style(match self.color_mode { 331 | ColorMode::Dark => Style::default().fg(Color::White), 332 | ColorMode::Light => Style::default().fg(Color::Black), 333 | }), 334 | Cell::from("Power").style(match self.color_mode { 335 | ColorMode::Dark => Style::default().fg(Color::White), 336 | ColorMode::Light => Style::default().fg(Color::Black), 337 | }), 338 | Cell::from("Pairable").style(match self.color_mode { 339 | ColorMode::Dark => Style::default().fg(Color::White), 340 | ColorMode::Light => Style::default().fg(Color::Black), 341 | }), 342 | Cell::from("Discoverable").style(match self.color_mode { 343 | ColorMode::Dark => Style::default().fg(Color::White), 344 | ColorMode::Light => Style::default().fg(Color::Black), 345 | }), 346 | ]) 347 | .style(Style::new().bold()) 348 | .bottom_margin(1) 349 | } 350 | }) 351 | .block( 352 | Block::default() 353 | .title(" Adapter ") 354 | .title_style({ 355 | if self.focused_block == FocusedBlock::Adapter { 356 | Style::default().bold() 357 | } else { 358 | Style::default() 359 | } 360 | }) 361 | .borders(Borders::ALL) 362 | .border_style({ 363 | if self.focused_block == FocusedBlock::Adapter { 364 | Style::default().fg(Color::Green) 365 | } else { 366 | Style::default() 367 | } 368 | }) 369 | .border_type({ 370 | if self.focused_block == FocusedBlock::Adapter { 371 | BorderType::Thick 372 | } else { 373 | BorderType::default() 374 | } 375 | }), 376 | ) 377 | .style(match self.color_mode { 378 | ColorMode::Dark => Style::default().fg(Color::White), 379 | ColorMode::Light => Style::default().fg(Color::Black), 380 | }) 381 | .highlight_symbol(" ") 382 | .row_highlight_style(if self.focused_block == FocusedBlock::Adapter { 383 | Style::default().bg(Color::DarkGray).fg(Color::White) 384 | } else { 385 | Style::default() 386 | }); 387 | 388 | frame.render_stateful_widget( 389 | controller_table, 390 | controller_block, 391 | &mut self.controller_state.clone(), 392 | ); 393 | 394 | if rows_len > controller_block.height.saturating_sub(4) as usize { 395 | let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight) 396 | .begin_symbol(Some("↑")) 397 | .end_symbol(Some("↓")); 398 | let mut scrollbar_state = 399 | ScrollbarState::new(self.controllers.len()).position(selected_controller_index); 400 | frame.render_stateful_widget( 401 | scrollbar, 402 | controller_block.inner(Margin { 403 | vertical: 1, 404 | horizontal: 0, 405 | }), 406 | &mut scrollbar_state, 407 | ); 408 | } 409 | 410 | //Paired devices 411 | let rows: Vec = selected_controller 412 | .paired_devices 413 | .iter() 414 | .map(|d| { 415 | Row::new(vec![ 416 | { 417 | if let Some(icon) = &d.icon { 418 | format!("{} {}", icon, &d.alias) 419 | } else { 420 | d.alias.to_owned() 421 | } 422 | }, 423 | d.is_trusted.to_string(), 424 | d.is_connected.to_string(), 425 | { 426 | if let Some(battery_percentage) = d.battery_percentage { 427 | match battery_percentage { 428 | n if n >= 90 => { 429 | format!("{battery_percentage}% 󰥈 ") 430 | } 431 | n if (80..90).contains(&n) => { 432 | format!("{battery_percentage}% 󰥅 ") 433 | } 434 | n if (70..80).contains(&n) => { 435 | format!("{battery_percentage}% 󰥄 ") 436 | } 437 | n if (60..70).contains(&n) => { 438 | format!("{battery_percentage}% 󰥃 ") 439 | } 440 | n if (50..60).contains(&n) => { 441 | format!("{battery_percentage}% 󰥂 ") 442 | } 443 | n if (40..50).contains(&n) => { 444 | format!("{battery_percentage}% 󰥁 ") 445 | } 446 | n if (30..40).contains(&n) => { 447 | format!("{battery_percentage}% 󰥀 ") 448 | } 449 | n if (20..30).contains(&n) => { 450 | format!("{battery_percentage}% 󰤿 ") 451 | } 452 | n if (10..20).contains(&n) => { 453 | format!("{battery_percentage}% 󰤾 ") 454 | } 455 | _ => { 456 | format!("{battery_percentage}% 󰤾 ") 457 | } 458 | } 459 | } else { 460 | String::new() 461 | } 462 | }, 463 | ]) 464 | }) 465 | .collect(); 466 | let rows_len = rows.len(); 467 | 468 | if rows_len > 0 469 | && self.focused_block == FocusedBlock::PairedDevices 470 | && self.paired_devices_state.selected().is_none() 471 | { 472 | self.paired_devices_state.select(Some(0)); 473 | } 474 | 475 | let show_battery_column = selected_controller 476 | .paired_devices 477 | .iter() 478 | .any(|device| device.battery_percentage.is_some()); 479 | 480 | let mut widths = vec![ 481 | Constraint::Max(25), 482 | Constraint::Length(10), 483 | Constraint::Length(10), 484 | ]; 485 | 486 | if show_battery_column { 487 | widths.push(Constraint::Length(10)); 488 | } 489 | 490 | let paired_devices_table = Table::new(rows, widths) 491 | .header({ 492 | if show_battery_column { 493 | if self.focused_block == FocusedBlock::PairedDevices { 494 | Row::new(vec![ 495 | Cell::from("Name").style(Style::default().fg(Color::Yellow)), 496 | Cell::from("Trusted").style(Style::default().fg(Color::Yellow)), 497 | Cell::from("Connected").style(Style::default().fg(Color::Yellow)), 498 | Cell::from("Battery").style(Style::default().fg(Color::Yellow)), 499 | ]) 500 | .style(Style::new().bold()) 501 | .bottom_margin(1) 502 | } else { 503 | Row::new(vec![ 504 | Cell::from("Name").style(match self.color_mode { 505 | ColorMode::Dark => Style::default().fg(Color::White), 506 | ColorMode::Light => Style::default().fg(Color::Black), 507 | }), 508 | Cell::from("Trusted").style(match self.color_mode { 509 | ColorMode::Dark => Style::default().fg(Color::White), 510 | ColorMode::Light => Style::default().fg(Color::Black), 511 | }), 512 | Cell::from("Connected").style(match self.color_mode { 513 | ColorMode::Dark => Style::default().fg(Color::White), 514 | ColorMode::Light => Style::default().fg(Color::Black), 515 | }), 516 | Cell::from("Battery").style(match self.color_mode { 517 | ColorMode::Dark => Style::default().fg(Color::White), 518 | ColorMode::Light => Style::default().fg(Color::Black), 519 | }), 520 | ]) 521 | .style(Style::new().bold()) 522 | .bottom_margin(1) 523 | } 524 | } else if self.focused_block == FocusedBlock::PairedDevices { 525 | Row::new(vec![ 526 | Cell::from("Name").style(Style::default().fg(Color::Yellow)), 527 | Cell::from("Trusted").style(Style::default().fg(Color::Yellow)), 528 | Cell::from("Connected").style(Style::default().fg(Color::Yellow)), 529 | ]) 530 | .style(Style::new().bold()) 531 | .bottom_margin(1) 532 | } else { 533 | Row::new(vec![ 534 | Cell::from("Name").style(match self.color_mode { 535 | ColorMode::Dark => Style::default().fg(Color::White), 536 | ColorMode::Light => Style::default().fg(Color::Black), 537 | }), 538 | Cell::from("Trusted").style(match self.color_mode { 539 | ColorMode::Dark => Style::default().fg(Color::White), 540 | ColorMode::Light => Style::default().fg(Color::Black), 541 | }), 542 | Cell::from("Connected").style(match self.color_mode { 543 | ColorMode::Dark => Style::default().fg(Color::White), 544 | ColorMode::Light => Style::default().fg(Color::Black), 545 | }), 546 | ]) 547 | .style(Style::new().bold()) 548 | .bottom_margin(1) 549 | } 550 | }) 551 | .block( 552 | Block::default() 553 | .title(" Paired Devices ") 554 | .title_style({ 555 | if self.focused_block == FocusedBlock::PairedDevices { 556 | Style::default().bold() 557 | } else { 558 | Style::default() 559 | } 560 | }) 561 | .borders(Borders::ALL) 562 | .border_style({ 563 | if self.focused_block == FocusedBlock::PairedDevices { 564 | Style::default().fg(Color::Green) 565 | } else { 566 | Style::default() 567 | } 568 | }) 569 | .border_type({ 570 | if self.focused_block == FocusedBlock::PairedDevices { 571 | BorderType::Thick 572 | } else { 573 | BorderType::default() 574 | } 575 | }), 576 | ) 577 | .style(match self.color_mode { 578 | ColorMode::Dark => Style::default().fg(Color::White), 579 | ColorMode::Light => Style::default().fg(Color::Black), 580 | }) 581 | .highlight_symbol(" ") 582 | .row_highlight_style(if self.focused_block == FocusedBlock::PairedDevices { 583 | Style::default().bg(Color::DarkGray).fg(Color::White) 584 | } else { 585 | Style::default() 586 | }); 587 | 588 | frame.render_stateful_widget( 589 | paired_devices_table, 590 | paired_devices_block, 591 | &mut self.paired_devices_state.clone(), 592 | ); 593 | 594 | if rows_len > paired_devices_block.height.saturating_sub(4) as usize { 595 | let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight) 596 | .begin_symbol(Some("↑")) 597 | .end_symbol(Some("↓")); 598 | let mut scrollbar_state = ScrollbarState::new(rows_len) 599 | .position(self.paired_devices_state.selected().unwrap_or_default()); 600 | frame.render_stateful_widget( 601 | scrollbar, 602 | paired_devices_block.inner(Margin { 603 | vertical: 1, 604 | horizontal: 0, 605 | }), 606 | &mut scrollbar_state, 607 | ); 608 | } 609 | 610 | //New devices 611 | 612 | if render_new_devices { 613 | let rows: Vec = selected_controller 614 | .new_devices 615 | .iter() 616 | .map(|d| { 617 | Row::new(vec![d.addr.to_string(), { 618 | if let Some(icon) = &d.icon { 619 | format!("{} {}", icon, &d.alias) 620 | } else { 621 | d.alias.to_owned() 622 | } 623 | }]) 624 | }) 625 | .collect(); 626 | let rows_len = rows.len(); 627 | 628 | let widths = [Constraint::Length(25), Constraint::Length(20)]; 629 | 630 | let new_devices_table = Table::new(rows, widths) 631 | .header({ 632 | if self.focused_block == FocusedBlock::NewDevices { 633 | Row::new(vec![ 634 | Cell::from("Address").style(Style::default().fg(Color::Yellow)), 635 | Cell::from("Name").style(Style::default().fg(Color::Yellow)), 636 | ]) 637 | .style(Style::new().bold()) 638 | .bottom_margin(1) 639 | } else { 640 | Row::new(vec![ 641 | Cell::from("Address").style(match self.color_mode { 642 | ColorMode::Dark => Style::default().fg(Color::White), 643 | ColorMode::Light => Style::default().fg(Color::Black), 644 | }), 645 | Cell::from("Name").style(match self.color_mode { 646 | ColorMode::Dark => Style::default().fg(Color::White), 647 | ColorMode::Light => Style::default().fg(Color::Black), 648 | }), 649 | ]) 650 | .style(Style::new().bold()) 651 | .bottom_margin(1) 652 | } 653 | }) 654 | .block( 655 | Block::default() 656 | .title({ 657 | if selected_controller.is_scanning.load(Ordering::Relaxed) { 658 | format!(" Scanning {} ", self.spinner.draw()) 659 | } else { 660 | String::from(" Discovered devices ") 661 | } 662 | }) 663 | .title_style({ 664 | if self.focused_block == FocusedBlock::NewDevices { 665 | Style::default().bold() 666 | } else { 667 | Style::default() 668 | } 669 | }) 670 | .borders(Borders::ALL) 671 | .border_style({ 672 | if self.focused_block == FocusedBlock::NewDevices { 673 | Style::default().fg(Color::Green) 674 | } else { 675 | Style::default() 676 | } 677 | }) 678 | .border_type({ 679 | if self.focused_block == FocusedBlock::NewDevices { 680 | BorderType::Thick 681 | } else { 682 | BorderType::default() 683 | } 684 | }), 685 | ) 686 | .style(match self.color_mode { 687 | ColorMode::Dark => Style::default().fg(Color::White), 688 | ColorMode::Light => Style::default().fg(Color::Black), 689 | }) 690 | .highlight_symbol(" ") 691 | .row_highlight_style(if self.focused_block == FocusedBlock::NewDevices { 692 | Style::default().bg(Color::DarkGray).fg(Color::White) 693 | } else { 694 | Style::default() 695 | }); 696 | 697 | let mut state = self.new_devices_state.clone(); 698 | if self.focused_block == FocusedBlock::NewDevices && state.selected().is_none() { 699 | state.select(Some(0)); 700 | } 701 | 702 | frame.render_stateful_widget(new_devices_table, new_devices_block, &mut state); 703 | 704 | if rows_len > new_devices_block.height.saturating_sub(4) as usize { 705 | let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight) 706 | .begin_symbol(Some("↑")) 707 | .end_symbol(Some("↓")); 708 | let mut scrollbar_state = ScrollbarState::new(rows_len) 709 | .position(state.selected().unwrap_or_default()); 710 | frame.render_stateful_widget( 711 | scrollbar, 712 | new_devices_block.inner(Margin { 713 | vertical: 1, 714 | horizontal: 0, 715 | }), 716 | &mut scrollbar_state, 717 | ); 718 | } 719 | } 720 | 721 | // Pairing confirmation 722 | 723 | if self.pairing_confirmation.display.load(Ordering::Relaxed) { 724 | self.focused_block = FocusedBlock::PassKeyConfirmation; 725 | self.pairing_confirmation.render(frame); 726 | } 727 | } 728 | } 729 | 730 | pub async fn tick(&mut self) -> AppResult<()> { 731 | self.notifications.retain(|n| n.ttl > 0); 732 | self.notifications.iter_mut().for_each(|n| n.ttl -= 1); 733 | 734 | if self.spinner.active { 735 | self.spinner.update(); 736 | } 737 | self.refresh().await?; 738 | Ok(()) 739 | } 740 | 741 | pub async fn refresh(&mut self) -> AppResult<()> { 742 | if !self.pairing_confirmation.display.load(Ordering::Relaxed) 743 | & self.pairing_confirmation.message.is_some() 744 | { 745 | self.pairing_confirmation.message = None; 746 | } 747 | 748 | let refreshed_controllers = Controller::get_all(self.session.clone()).await?; 749 | 750 | let names = { 751 | let mut names: Vec = Vec::new(); 752 | 753 | for controller in self.controllers.iter() { 754 | if !refreshed_controllers 755 | .iter() 756 | .any(|c| c.name == controller.name) 757 | { 758 | names.push(controller.name.clone()); 759 | } 760 | } 761 | 762 | names 763 | }; 764 | 765 | // Remove unplugged adapters 766 | for name in names { 767 | self.controllers.retain(|c| c.name != name); 768 | 769 | if !self.controllers.is_empty() { 770 | let i = match self.controller_state.selected() { 771 | Some(i) => { 772 | if i > 0 { 773 | i - 1 774 | } else { 775 | 0 776 | } 777 | } 778 | None => 0, 779 | }; 780 | self.controller_state.select(Some(i)); 781 | } else { 782 | self.controller_state.select(None); 783 | } 784 | } 785 | 786 | for refreshed_controller in refreshed_controllers { 787 | if let Some(controller) = self 788 | .controllers 789 | .iter_mut() 790 | .find(|c| c.name == refreshed_controller.name) 791 | { 792 | // Update existing adapters 793 | controller.alias = refreshed_controller.alias; 794 | controller.is_powered = refreshed_controller.is_powered; 795 | controller.is_pairable = refreshed_controller.is_pairable; 796 | controller.is_discoverable = refreshed_controller.is_discoverable; 797 | controller.paired_devices = refreshed_controller.paired_devices; 798 | controller.new_devices = refreshed_controller.new_devices; 799 | } else { 800 | // Add new detected adapters 801 | self.controllers.push(refreshed_controller); 802 | } 803 | } 804 | 805 | Ok(()) 806 | } 807 | 808 | pub fn quit(&mut self) { 809 | self.running = false; 810 | } 811 | } 812 | -------------------------------------------------------------------------------- /src/bluetooth.rs: -------------------------------------------------------------------------------- 1 | use std::sync::{Arc, atomic::AtomicBool, mpsc::Sender}; 2 | 3 | use async_channel::Receiver; 4 | use bluer::{ 5 | Adapter, Address, Session, 6 | agent::{ReqError, ReqResult, RequestConfirmation}, 7 | }; 8 | 9 | use bluer::Device as BTDevice; 10 | 11 | use tokio::sync::oneshot; 12 | 13 | use crate::app::AppResult; 14 | 15 | #[derive(Debug, Clone)] 16 | pub struct Controller { 17 | pub adapter: Arc, 18 | pub name: String, 19 | pub alias: String, 20 | pub is_powered: bool, 21 | pub is_pairable: bool, 22 | pub is_discoverable: bool, 23 | pub is_scanning: Arc, 24 | pub paired_devices: Vec, 25 | pub new_devices: Vec, 26 | } 27 | 28 | #[derive(Debug, Clone)] 29 | pub struct Device { 30 | device: BTDevice, 31 | pub addr: Address, 32 | pub icon: Option, 33 | pub alias: String, 34 | pub is_paired: bool, 35 | pub is_trusted: bool, 36 | pub is_connected: bool, 37 | pub battery_percentage: Option, 38 | } 39 | 40 | impl Device { 41 | pub async fn set_alias(&self, alias: String) -> AppResult<()> { 42 | self.device.set_alias(alias).await?; 43 | Ok(()) 44 | } 45 | 46 | // https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html 47 | pub fn get_icon(name: &str) -> Option { 48 | match name { 49 | "audio-card" => Some(String::from("󰓃")), 50 | "audio-input-microphone" => Some(String::from("")), 51 | "audio-headphones" => Some(String::from("󰋋")), 52 | "battery" => Some(String::from("󰂀")), 53 | "camera-photo" => Some(String::from("󰻛")), 54 | "computer" => Some(String::from("")), 55 | "input-keyboard" => Some(String::from("󰌌")), 56 | "input-mouse" => Some(String::from("󰍽")), 57 | "phone" => Some(String::from("󰏲")), 58 | _ => None, 59 | } 60 | } 61 | } 62 | 63 | impl Controller { 64 | pub async fn get_all(session: Arc) -> AppResult> { 65 | let mut controllers: Vec = Vec::new(); 66 | 67 | // let session = bluer::Session::new().await?; 68 | let adapter_names = session.adapter_names().await?; 69 | for adapter_name in adapter_names { 70 | if let Ok(adapter) = session.adapter(&adapter_name) { 71 | let name = adapter.name().to_owned(); 72 | let alias = adapter.alias().await?; 73 | let is_powered = adapter.is_powered().await?; 74 | let is_pairable = adapter.is_pairable().await?; 75 | let is_discoverable = adapter.is_discoverable().await?; 76 | let is_scanning = adapter.is_discovering().await?; 77 | 78 | let (paired_devices, new_devices) = Controller::get_all_devices(&adapter).await?; 79 | 80 | let controller = Controller { 81 | adapter: Arc::new(adapter), 82 | name, 83 | alias, 84 | is_powered, 85 | is_pairable, 86 | is_discoverable, 87 | is_scanning: Arc::new(AtomicBool::new(is_scanning)), 88 | paired_devices, 89 | new_devices, 90 | }; 91 | 92 | controllers.push(controller); 93 | } 94 | } 95 | 96 | Ok(controllers) 97 | } 98 | 99 | pub async fn get_all_devices(adapter: &Adapter) -> AppResult<(Vec, Vec)> { 100 | let mut paired_devices: Vec = Vec::new(); 101 | let mut new_devices: Vec = Vec::new(); 102 | 103 | let connected_devices_addresses = adapter.device_addresses().await?; 104 | for addr in connected_devices_addresses { 105 | let device = adapter.device(addr)?; 106 | 107 | let alias = device.alias().await?; 108 | let icon = Device::get_icon(device.icon().await?.unwrap_or("-".to_string()).as_str()); 109 | let is_paired = device.is_paired().await?; 110 | let is_trusted = device.is_trusted().await?; 111 | let is_connected = device.is_connected().await?; 112 | let battery_percentage = device.battery_percentage().await?; 113 | 114 | let dev = Device { 115 | device, 116 | addr, 117 | alias, 118 | icon, 119 | is_paired, 120 | is_trusted, 121 | is_connected, 122 | battery_percentage, 123 | }; 124 | 125 | if dev.is_paired { 126 | paired_devices.push(dev); 127 | } else { 128 | new_devices.push(dev); 129 | } 130 | } 131 | 132 | paired_devices.sort_by_key(|i| i.addr); 133 | new_devices.sort_by_key(|i| i.addr); 134 | Ok((paired_devices, new_devices)) 135 | } 136 | } 137 | 138 | pub async fn request_confirmation( 139 | req: RequestConfirmation, 140 | display_confirmation_popup: Arc, 141 | rx: Receiver, 142 | sender: Sender, 143 | ) -> ReqResult<()> { 144 | display_confirmation_popup.store(true, std::sync::atomic::Ordering::Relaxed); 145 | 146 | sender 147 | .send(format!( 148 | "Is passkey \"{:06}\" correct for device {} on {}?", 149 | req.passkey, &req.device, &req.adapter 150 | )) 151 | .unwrap(); 152 | 153 | // request cancel 154 | let (_done_tx, done_rx) = oneshot::channel::<()>(); 155 | tokio::spawn(async move { 156 | if done_rx.await.is_err() { 157 | display_confirmation_popup.store(false, std::sync::atomic::Ordering::Relaxed); 158 | } 159 | }); 160 | match rx.recv().await { 161 | Ok(v) => { 162 | // false: reject the confirmation 163 | if !v { 164 | return Err(ReqError::Rejected); 165 | } 166 | } 167 | Err(_) => return Err(ReqError::Rejected), 168 | } 169 | 170 | Ok(()) 171 | } 172 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | use toml; 2 | 3 | use dirs; 4 | use serde::Deserialize; 5 | 6 | #[derive(Deserialize, Debug)] 7 | pub struct Config { 8 | #[serde(default = "default_toggle_scanning")] 9 | pub toggle_scanning: char, 10 | 11 | #[serde(default)] 12 | pub adapter: Adapter, 13 | 14 | #[serde(default)] 15 | pub paired_device: PairedDevice, 16 | 17 | #[serde(default)] 18 | pub new_device: NewDevice, 19 | } 20 | 21 | #[derive(Deserialize, Debug)] 22 | pub struct Adapter { 23 | #[serde(default = "default_toggle_adapter_pairing")] 24 | pub toggle_pairing: char, 25 | 26 | #[serde(default = "default_toggle_adapter_power")] 27 | pub toggle_power: char, 28 | 29 | #[serde(default = "default_toggle_adapter_discovery")] 30 | pub toggle_discovery: char, 31 | } 32 | 33 | impl Default for Adapter { 34 | fn default() -> Self { 35 | Self { 36 | toggle_pairing: 'p', 37 | toggle_power: 'o', 38 | toggle_discovery: 'd', 39 | } 40 | } 41 | } 42 | 43 | #[derive(Deserialize, Debug)] 44 | pub struct PairedDevice { 45 | #[serde(default = "default_unpair_device")] 46 | pub unpair: char, 47 | 48 | #[serde(default = "default_toggle_device_connection")] 49 | pub toggle_connect: char, 50 | 51 | #[serde(default = "default_toggle_device_trust")] 52 | pub toggle_trust: char, 53 | 54 | #[serde(default = "default_set_new_name")] 55 | pub rename: char, 56 | } 57 | 58 | impl Default for PairedDevice { 59 | fn default() -> Self { 60 | Self { 61 | unpair: 'u', 62 | toggle_connect: ' ', 63 | toggle_trust: 't', 64 | rename: 'e', 65 | } 66 | } 67 | } 68 | 69 | fn default_set_new_name() -> char { 70 | 'e' 71 | } 72 | 73 | #[derive(Deserialize, Debug)] 74 | pub struct NewDevice { 75 | #[serde(default = "default_pair_new_device")] 76 | pub pair: char, 77 | } 78 | 79 | impl Default for NewDevice { 80 | fn default() -> Self { 81 | Self { pair: 'p' } 82 | } 83 | } 84 | 85 | fn default_toggle_scanning() -> char { 86 | 's' 87 | } 88 | 89 | fn default_toggle_adapter_pairing() -> char { 90 | 'p' 91 | } 92 | 93 | fn default_toggle_adapter_power() -> char { 94 | 'o' 95 | } 96 | 97 | fn default_toggle_adapter_discovery() -> char { 98 | 'd' 99 | } 100 | 101 | fn default_unpair_device() -> char { 102 | 'u' 103 | } 104 | 105 | fn default_toggle_device_connection() -> char { 106 | ' ' 107 | } 108 | 109 | fn default_toggle_device_trust() -> char { 110 | 't' 111 | } 112 | 113 | fn default_pair_new_device() -> char { 114 | 'p' 115 | } 116 | 117 | impl Config { 118 | pub fn new() -> Self { 119 | let conf_path = dirs::config_dir() 120 | .unwrap() 121 | .join("bluetui") 122 | .join("config.toml"); 123 | 124 | let config = std::fs::read_to_string(conf_path).unwrap_or_default(); 125 | let app_config: Config = toml::from_str(&config).unwrap(); 126 | 127 | app_config 128 | } 129 | } 130 | 131 | impl Default for Config { 132 | fn default() -> Self { 133 | Self::new() 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/confirmation.rs: -------------------------------------------------------------------------------- 1 | use std::sync::mpsc::channel; 2 | use std::sync::{Arc, atomic::AtomicBool}; 3 | 4 | use ratatui::Frame; 5 | use ratatui::layout::{Alignment, Constraint, Direction, Layout}; 6 | use ratatui::style::{Color, Style}; 7 | use ratatui::text::{Span, Text}; 8 | use ratatui::widgets::{Block, BorderType, Borders, Clear}; 9 | 10 | #[derive(Debug)] 11 | pub struct PairingConfirmation { 12 | pub confirmed: bool, 13 | pub display: Arc, 14 | pub message: Option, 15 | pub user_confirmation_sender: async_channel::Sender, 16 | pub user_confirmation_receiver: async_channel::Receiver, 17 | pub confirmation_message_sender: std::sync::mpsc::Sender, 18 | pub confirmation_message_receiver: std::sync::mpsc::Receiver, 19 | } 20 | 21 | impl Default for PairingConfirmation { 22 | fn default() -> Self { 23 | Self::new() 24 | } 25 | } 26 | 27 | impl PairingConfirmation { 28 | pub fn new() -> Self { 29 | let (user_confirmation_sender, user_confirmation_receiver) = async_channel::unbounded(); 30 | 31 | let (confirmation_message_sender, confirmation_message_receiver) = channel::(); 32 | Self { 33 | confirmed: true, 34 | display: Arc::new(AtomicBool::new(false)), 35 | message: None, 36 | user_confirmation_sender, 37 | user_confirmation_receiver, 38 | confirmation_message_sender, 39 | confirmation_message_receiver, 40 | } 41 | } 42 | 43 | pub fn render(&mut self, frame: &mut Frame) { 44 | if self.message.is_none() { 45 | let msg = self.confirmation_message_receiver.recv().unwrap(); 46 | self.message = Some(msg); 47 | } 48 | 49 | let layout = Layout::default() 50 | .direction(Direction::Vertical) 51 | .constraints([ 52 | Constraint::Fill(1), 53 | Constraint::Length(5), 54 | Constraint::Fill(1), 55 | ]) 56 | .split(frame.area()); 57 | 58 | let block = Layout::default() 59 | .direction(Direction::Horizontal) 60 | .constraints([ 61 | Constraint::Fill(1), 62 | Constraint::Max(80), 63 | Constraint::Fill(1), 64 | ]) 65 | .split(layout[1])[1]; 66 | 67 | let (text_area, choices_area) = { 68 | let chunks = Layout::default() 69 | .direction(Direction::Vertical) 70 | .constraints( 71 | [ 72 | Constraint::Length(1), 73 | Constraint::Length(1), 74 | Constraint::Length(1), 75 | Constraint::Length(1), 76 | Constraint::Length(1), 77 | ] 78 | .as_ref(), 79 | ) 80 | .split(block); 81 | 82 | (chunks[1], chunks[3]) 83 | }; 84 | 85 | let (yes_area, no_area) = { 86 | let chunks = Layout::default() 87 | .direction(Direction::Horizontal) 88 | .constraints( 89 | [ 90 | Constraint::Percentage(30), 91 | Constraint::Length(5), 92 | Constraint::Min(1), 93 | Constraint::Length(5), 94 | Constraint::Percentage(30), 95 | ] 96 | .as_ref(), 97 | ) 98 | .split(choices_area); 99 | 100 | (chunks[1], chunks[3]) 101 | }; 102 | 103 | let text = Text::from(self.message.clone().unwrap_or_default()) 104 | .style(Style::default().fg(Color::White)); 105 | 106 | let (yes, no) = { 107 | if self.confirmed { 108 | let no = Span::from("[No]").style(Style::default()); 109 | let yes = Span::from("[Yes]").style(Style::default().bg(Color::DarkGray)); 110 | (yes, no) 111 | } else { 112 | let no = Span::from("[No]").style(Style::default().bg(Color::DarkGray)); 113 | let yes = Span::from("[Yes]").style(Style::default()); 114 | (yes, no) 115 | } 116 | }; 117 | 118 | frame.render_widget(Clear, block); 119 | 120 | frame.render_widget( 121 | Block::new() 122 | .borders(Borders::ALL) 123 | .border_type(BorderType::Thick) 124 | .border_style(Style::default().fg(Color::Green)), 125 | block, 126 | ); 127 | frame.render_widget(text.alignment(Alignment::Center), text_area); 128 | frame.render_widget(yes, yes_area); 129 | frame.render_widget(no, no_area); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/event.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | 3 | use crossterm::event::{Event as CrosstermEvent, KeyEvent, MouseEvent}; 4 | use futures::{FutureExt, StreamExt}; 5 | use tokio::sync::mpsc; 6 | 7 | use crate::{app::AppResult, notification::Notification}; 8 | 9 | #[derive(Clone, Debug)] 10 | pub enum Event { 11 | Tick, 12 | Key(KeyEvent), 13 | Mouse(MouseEvent), 14 | Resize(u16, u16), 15 | Notification(Notification), 16 | } 17 | 18 | #[allow(dead_code)] 19 | #[derive(Debug)] 20 | pub struct EventHandler { 21 | pub sender: mpsc::UnboundedSender, 22 | pub receiver: mpsc::UnboundedReceiver, 23 | handler: tokio::task::JoinHandle<()>, 24 | } 25 | 26 | impl EventHandler { 27 | pub fn new(tick_rate: u64) -> Self { 28 | let tick_rate = Duration::from_millis(tick_rate); 29 | let (sender, receiver) = mpsc::unbounded_channel(); 30 | let _sender = sender.clone(); 31 | let handler = tokio::spawn(async move { 32 | let mut reader = crossterm::event::EventStream::new(); 33 | let mut tick = tokio::time::interval(tick_rate); 34 | loop { 35 | let tick_delay = tick.tick(); 36 | let crossterm_event = reader.next().fuse(); 37 | tokio::select! { 38 | _ = tick_delay => { 39 | _sender.send(Event::Tick).unwrap(); 40 | } 41 | Some(Ok(evt)) = crossterm_event => { 42 | match evt { 43 | CrosstermEvent::Key(key) => { 44 | if key.kind == crossterm::event::KeyEventKind::Press { 45 | _sender.send(Event::Key(key)).unwrap(); 46 | } 47 | }, 48 | CrosstermEvent::Mouse(mouse) => { 49 | _sender.send(Event::Mouse(mouse)).unwrap(); 50 | }, 51 | CrosstermEvent::Resize(x, y) => { 52 | _sender.send(Event::Resize(x, y)).unwrap(); 53 | }, 54 | CrosstermEvent::FocusLost => { 55 | }, 56 | CrosstermEvent::FocusGained => { 57 | }, 58 | CrosstermEvent::Paste(_) => { 59 | }, 60 | } 61 | } 62 | }; 63 | } 64 | }); 65 | Self { 66 | sender, 67 | receiver, 68 | handler, 69 | } 70 | } 71 | 72 | pub async fn next(&mut self) -> AppResult { 73 | self.receiver 74 | .recv() 75 | .await 76 | .ok_or(Box::new(std::io::Error::other("This is an IO error"))) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/handler.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | use std::sync::atomic::Ordering; 3 | 4 | use crate::app::FocusedBlock; 5 | use crate::app::{App, AppResult}; 6 | use crate::config::Config; 7 | use crate::event::Event; 8 | use crate::notification::{Notification, NotificationLevel}; 9 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; 10 | use futures::StreamExt; 11 | use tokio::sync::mpsc::UnboundedSender; 12 | 13 | use tui_input::backend::crossterm::EventHandler; 14 | 15 | pub async fn handle_key_events( 16 | key_event: KeyEvent, 17 | app: &mut App, 18 | sender: UnboundedSender, 19 | config: Arc, 20 | ) -> AppResult<()> { 21 | match app.focused_block { 22 | FocusedBlock::SetDeviceAliasBox => match key_event.code { 23 | KeyCode::Enter => { 24 | if let Some(selected_controller) = app.controller_state.selected() { 25 | let controller = &app.controllers[selected_controller]; 26 | if let Some(index) = app.paired_devices_state.selected() { 27 | let device = &controller.paired_devices[index]; 28 | match device.set_alias(app.new_alias.value().to_string()).await { 29 | Ok(_) => { 30 | Notification::send( 31 | "Set New Alias".to_string(), 32 | NotificationLevel::Info, 33 | sender, 34 | )?; 35 | } 36 | Err(e) => { 37 | Notification::send( 38 | e.to_string(), 39 | NotificationLevel::Error, 40 | sender, 41 | )?; 42 | } 43 | } 44 | app.focused_block = FocusedBlock::PairedDevices; 45 | app.new_alias.reset(); 46 | } 47 | } 48 | } 49 | 50 | KeyCode::Esc => { 51 | app.focused_block = FocusedBlock::PairedDevices; 52 | app.new_alias.reset(); 53 | } 54 | _ => { 55 | app.new_alias 56 | .handle_event(&crossterm::event::Event::Key(key_event)); 57 | } 58 | }, 59 | _ => { 60 | match key_event.code { 61 | // Exit the app 62 | KeyCode::Char('c') if key_event.modifiers == KeyModifiers::CONTROL => { 63 | app.quit(); 64 | } 65 | 66 | KeyCode::Char('q') => { 67 | app.quit(); 68 | } 69 | 70 | // Show help 71 | KeyCode::Char('?') => { 72 | app.focused_block = FocusedBlock::Help; 73 | } 74 | 75 | // Discard help popup 76 | KeyCode::Esc => { 77 | if app.focused_block == FocusedBlock::Help { 78 | app.focused_block = FocusedBlock::Adapter; 79 | } 80 | } 81 | 82 | // Switch focus 83 | KeyCode::Tab => match app.focused_block { 84 | FocusedBlock::Adapter => { 85 | app.focused_block = FocusedBlock::PairedDevices; 86 | app.reset_devices_state(); 87 | } 88 | FocusedBlock::PairedDevices => { 89 | if let Some(selected_controller) = app.controller_state.selected() { 90 | let controller = &app.controllers[selected_controller]; 91 | if controller.new_devices.is_empty() { 92 | app.focused_block = FocusedBlock::Adapter; 93 | } else { 94 | app.focused_block = FocusedBlock::NewDevices; 95 | } 96 | } 97 | } 98 | FocusedBlock::NewDevices => app.focused_block = FocusedBlock::Adapter, 99 | _ => {} 100 | }, 101 | 102 | KeyCode::BackTab => match app.focused_block { 103 | FocusedBlock::Adapter => { 104 | if let Some(selected_controller) = app.controller_state.selected() { 105 | let controller = &app.controllers[selected_controller]; 106 | if controller.new_devices.is_empty() { 107 | app.focused_block = FocusedBlock::PairedDevices; 108 | } else { 109 | app.focused_block = FocusedBlock::NewDevices; 110 | } 111 | } 112 | } 113 | FocusedBlock::PairedDevices => { 114 | app.focused_block = FocusedBlock::Adapter; 115 | } 116 | FocusedBlock::NewDevices => { 117 | app.focused_block = FocusedBlock::PairedDevices; 118 | app.reset_devices_state(); 119 | } 120 | _ => {} 121 | }, 122 | 123 | // scroll down 124 | KeyCode::Char('j') | KeyCode::Down => match app.focused_block { 125 | FocusedBlock::Adapter => { 126 | if !app.controllers.is_empty() { 127 | let i = match app.controller_state.selected() { 128 | Some(i) => { 129 | if i < app.controllers.len() - 1 { 130 | i + 1 131 | } else { 132 | i 133 | } 134 | } 135 | None => 0, 136 | }; 137 | 138 | app.controller_state.select(Some(i)); 139 | } 140 | } 141 | 142 | FocusedBlock::PairedDevices => { 143 | if let Some(selected_controller) = app.controller_state.selected() { 144 | let controller = &mut app.controllers[selected_controller]; 145 | 146 | if !controller.paired_devices.is_empty() { 147 | let i = match app.paired_devices_state.selected() { 148 | Some(i) => { 149 | if i < controller.paired_devices.len() - 1 { 150 | i + 1 151 | } else { 152 | i 153 | } 154 | } 155 | None => 0, 156 | }; 157 | 158 | app.paired_devices_state.select(Some(i)); 159 | } 160 | } 161 | } 162 | 163 | FocusedBlock::NewDevices => { 164 | if let Some(selected_controller) = app.controller_state.selected() { 165 | let controller = &mut app.controllers[selected_controller]; 166 | 167 | if !controller.new_devices.is_empty() { 168 | let i = match app.new_devices_state.selected() { 169 | Some(i) => { 170 | if i < controller.new_devices.len() - 1 { 171 | i + 1 172 | } else { 173 | i 174 | } 175 | } 176 | None => 0, 177 | }; 178 | 179 | app.new_devices_state.select(Some(i)); 180 | } 181 | } 182 | } 183 | 184 | FocusedBlock::Help => { 185 | app.help.scroll_down(); 186 | } 187 | _ => {} 188 | }, 189 | 190 | // scroll up 191 | KeyCode::Char('k') | KeyCode::Up => match app.focused_block { 192 | FocusedBlock::Adapter => { 193 | if !app.controllers.is_empty() { 194 | let i = match app.controller_state.selected() { 195 | Some(i) => i.saturating_sub(1), 196 | None => 0, 197 | }; 198 | 199 | app.controller_state.select(Some(i)); 200 | } 201 | } 202 | 203 | FocusedBlock::PairedDevices => { 204 | if let Some(selected_controller) = app.controller_state.selected() { 205 | let controller = &mut app.controllers[selected_controller]; 206 | if !controller.paired_devices.is_empty() { 207 | let i = match app.paired_devices_state.selected() { 208 | Some(i) => i.saturating_sub(1), 209 | None => 0, 210 | }; 211 | app.paired_devices_state.select(Some(i)); 212 | } 213 | } 214 | } 215 | 216 | FocusedBlock::NewDevices => { 217 | if let Some(selected_controller) = app.controller_state.selected() { 218 | let controller = &mut app.controllers[selected_controller]; 219 | if !controller.new_devices.is_empty() { 220 | let i = match app.new_devices_state.selected() { 221 | Some(i) => i.saturating_sub(1), 222 | None => 0, 223 | }; 224 | app.new_devices_state.select(Some(i)); 225 | } 226 | } 227 | } 228 | FocusedBlock::Help => { 229 | app.help.scroll_up(); 230 | } 231 | _ => {} 232 | }, 233 | 234 | // Start/Stop Scan 235 | KeyCode::Char(c) if c == config.toggle_scanning => { 236 | if let Some(selected_controller) = app.controller_state.selected() { 237 | let controller = &app.controllers[selected_controller]; 238 | 239 | if controller.is_scanning.load(Ordering::Relaxed) { 240 | controller 241 | .is_scanning 242 | .store(false, std::sync::atomic::Ordering::Relaxed); 243 | 244 | Notification::send( 245 | "Scanning stopped".to_string(), 246 | NotificationLevel::Info, 247 | sender, 248 | )?; 249 | 250 | app.spinner.active = false; 251 | } else { 252 | controller 253 | .is_scanning 254 | .store(true, std::sync::atomic::Ordering::Relaxed); 255 | app.spinner.active = true; 256 | let adapter = controller.adapter.clone(); 257 | let is_scanning = controller.is_scanning.clone(); 258 | tokio::spawn(async move { 259 | let _ = Notification::send( 260 | "Scanning started".to_string(), 261 | NotificationLevel::Info, 262 | sender.clone(), 263 | ); 264 | 265 | match adapter.discover_devices().await { 266 | Ok(mut discover) => { 267 | while let Some(_evt) = discover.next().await { 268 | if !is_scanning.load(Ordering::Relaxed) { 269 | break; 270 | } 271 | } 272 | } 273 | Err(e) => { 274 | let _ = Notification::send( 275 | e.to_string(), 276 | NotificationLevel::Error, 277 | sender.clone(), 278 | ); 279 | } 280 | } 281 | }); 282 | } 283 | } 284 | } 285 | 286 | _ => { 287 | match app.focused_block { 288 | FocusedBlock::PairedDevices => { 289 | match key_event.code { 290 | // Unpair 291 | KeyCode::Char(c) if c == config.paired_device.unpair => { 292 | if let Some(selected_controller) = 293 | app.controller_state.selected() 294 | { 295 | let controller = &app.controllers[selected_controller]; 296 | if let Some(index) = app.paired_devices_state.selected() { 297 | let addr = controller.paired_devices[index].addr; 298 | match controller.adapter.remove_device(addr).await { 299 | Ok(_) => { 300 | let _ = Notification::send( 301 | "Device unpaired".to_string(), 302 | NotificationLevel::Info, 303 | sender.clone(), 304 | ); 305 | } 306 | Err(e) => { 307 | let _ = Notification::send( 308 | e.to_string(), 309 | NotificationLevel::Error, 310 | sender.clone(), 311 | ); 312 | } 313 | } 314 | } 315 | } 316 | } 317 | 318 | // Connect / Disconnect 319 | KeyCode::Char(c) if c == config.paired_device.toggle_connect => { 320 | if let Some(selected_controller) = 321 | app.controller_state.selected() 322 | { 323 | let controller = &app.controllers[selected_controller]; 324 | if let Some(index) = app.paired_devices_state.selected() { 325 | let addr = controller.paired_devices[index].addr; 326 | match controller.adapter.device(addr) { 327 | Ok(device) => { 328 | tokio::spawn(async move { 329 | match device.is_connected().await { 330 | Ok(is_connected) => { 331 | if is_connected { 332 | match device.disconnect().await 333 | { 334 | Ok(_) => { 335 | let _ = Notification::send( 336 | "Device disconnected" 337 | .to_string(), 338 | NotificationLevel::Info, 339 | sender.clone(), 340 | ); 341 | } 342 | Err(e) => { 343 | let _ = Notification::send( 344 | e.to_string(), 345 | NotificationLevel::Error, 346 | sender.clone(), 347 | ); 348 | } 349 | } 350 | } else { 351 | match device.connect().await { 352 | Ok(_) => { 353 | let _ = Notification::send( 354 | "Device connected" 355 | .to_string(), 356 | NotificationLevel::Info, 357 | sender.clone(), 358 | ); 359 | } 360 | Err(e) => { 361 | let _ = Notification::send( 362 | e.to_string(), 363 | NotificationLevel::Error, 364 | sender.clone(), 365 | ); 366 | } 367 | } 368 | } 369 | } 370 | Err(e) => { 371 | let _ = Notification::send( 372 | e.to_string(), 373 | NotificationLevel::Error, 374 | sender.clone(), 375 | ); 376 | } 377 | } 378 | }); 379 | } 380 | Err(e) => { 381 | let _ = Notification::send( 382 | e.to_string(), 383 | NotificationLevel::Error, 384 | sender.clone(), 385 | ); 386 | } 387 | } 388 | } 389 | } 390 | } 391 | 392 | // Trust / Untrust 393 | KeyCode::Char(c) if c == config.paired_device.toggle_trust => { 394 | if let Some(selected_controller) = 395 | app.controller_state.selected() 396 | { 397 | let controller = &app.controllers[selected_controller]; 398 | if let Some(index) = app.paired_devices_state.selected() { 399 | let addr = controller.paired_devices[index].addr; 400 | match controller.adapter.device(addr) { 401 | Ok(device) => { 402 | tokio::spawn(async move { 403 | match device.is_trusted().await { 404 | Ok(is_trusted) => { 405 | if is_trusted { 406 | match device 407 | .set_trusted(false) 408 | .await 409 | { 410 | Ok(_) => { 411 | let _ = Notification::send( 412 | "Device untrusted" 413 | .to_string(), 414 | NotificationLevel::Info, 415 | sender.clone(), 416 | ); 417 | } 418 | Err(e) => { 419 | let _ = Notification::send( 420 | e.to_string(), 421 | NotificationLevel::Error, 422 | sender.clone(), 423 | ); 424 | } 425 | } 426 | } else { 427 | match device 428 | .set_trusted(true) 429 | .await 430 | { 431 | Ok(_) => { 432 | let _ = Notification::send( 433 | "Device trusted" 434 | .to_string(), 435 | NotificationLevel::Info, 436 | sender.clone(), 437 | ); 438 | } 439 | 440 | Err(e) => { 441 | let _ = Notification::send( 442 | e.to_string(), 443 | NotificationLevel::Error, 444 | sender.clone(), 445 | ); 446 | } 447 | } 448 | } 449 | } 450 | Err(e) => { 451 | let _ = Notification::send( 452 | e.to_string(), 453 | NotificationLevel::Error, 454 | sender.clone(), 455 | ); 456 | } 457 | } 458 | }); 459 | } 460 | Err(e) => { 461 | let _ = Notification::send( 462 | e.to_string(), 463 | NotificationLevel::Error, 464 | sender.clone(), 465 | ); 466 | } 467 | } 468 | } 469 | } 470 | } 471 | 472 | KeyCode::Char(c) if c == config.paired_device.rename => { 473 | app.focused_block = FocusedBlock::SetDeviceAliasBox; 474 | } 475 | 476 | _ => {} 477 | } 478 | } 479 | 480 | FocusedBlock::Adapter => { 481 | match key_event.code { 482 | // toggle pairing 483 | KeyCode::Char(c) if c == config.adapter.toggle_pairing => { 484 | if let Some(selected_controller) = 485 | app.controller_state.selected() 486 | { 487 | let adapter = &app.controllers[selected_controller].adapter; 488 | tokio::spawn({ 489 | let adapter = adapter.clone(); 490 | async move { 491 | match adapter.is_pairable().await { 492 | Ok(is_pairable) => { 493 | if is_pairable { 494 | match adapter.set_pairable(false).await 495 | { 496 | Ok(_) => { 497 | let _ = Notification::send( 498 | "Adapter unpairable" 499 | .to_string(), 500 | NotificationLevel::Info, 501 | sender.clone(), 502 | ); 503 | } 504 | Err(e) => { 505 | let _ = Notification::send( 506 | e.to_string(), 507 | NotificationLevel::Error, 508 | sender.clone(), 509 | ); 510 | } 511 | } 512 | } else { 513 | match adapter.set_pairable(true).await { 514 | Ok(_) => { 515 | let _ = Notification::send( 516 | "Adapter pairable" 517 | .to_string(), 518 | NotificationLevel::Info, 519 | sender.clone(), 520 | ); 521 | } 522 | Err(e) => { 523 | let _ = Notification::send( 524 | e.to_string(), 525 | NotificationLevel::Error, 526 | sender.clone(), 527 | ); 528 | } 529 | } 530 | } 531 | } 532 | Err(e) => { 533 | let _ = Notification::send( 534 | e.to_string(), 535 | NotificationLevel::Error, 536 | sender.clone(), 537 | ); 538 | } 539 | } 540 | } 541 | }); 542 | } 543 | } 544 | 545 | // toggle power 546 | KeyCode::Char(c) if c == config.adapter.toggle_power => { 547 | if let Some(selected_controller) = 548 | app.controller_state.selected() 549 | { 550 | let adapter = &app.controllers[selected_controller].adapter; 551 | tokio::spawn({ 552 | let adapter = adapter.clone(); 553 | async move { 554 | match adapter.is_powered().await { 555 | Ok(is_powered) => { 556 | if is_powered { 557 | match adapter.set_powered(false).await { 558 | Ok(_) => { 559 | let _ = Notification::send( 560 | "Adapter powered off" 561 | .to_string(), 562 | NotificationLevel::Info, 563 | sender.clone(), 564 | ); 565 | } 566 | Err(e) => { 567 | let _ = Notification::send( 568 | e.to_string(), 569 | NotificationLevel::Error, 570 | sender.clone(), 571 | ); 572 | } 573 | } 574 | } else { 575 | match adapter.set_powered(true).await { 576 | Ok(_) => { 577 | let _ = Notification::send( 578 | "Adapter powered on" 579 | .to_string(), 580 | NotificationLevel::Info, 581 | sender.clone(), 582 | ); 583 | } 584 | Err(e) => { 585 | let _ = Notification::send( 586 | e.to_string(), 587 | NotificationLevel::Error, 588 | sender.clone(), 589 | ); 590 | } 591 | } 592 | } 593 | } 594 | Err(e) => { 595 | let _ = Notification::send( 596 | e.to_string(), 597 | NotificationLevel::Error, 598 | sender.clone(), 599 | ); 600 | } 601 | } 602 | } 603 | }); 604 | } 605 | } 606 | 607 | // toggle discovery 608 | KeyCode::Char(c) if c == config.adapter.toggle_discovery => { 609 | if let Some(selected_controller) = 610 | app.controller_state.selected() 611 | { 612 | let adapter = &app.controllers[selected_controller].adapter; 613 | tokio::spawn({ 614 | let adapter = adapter.clone(); 615 | async move { 616 | match adapter.is_discoverable().await { 617 | Ok(is_discoverable) => { 618 | if is_discoverable { 619 | match adapter 620 | .set_discoverable(false) 621 | .await 622 | { 623 | Ok(_) => { 624 | let _ = Notification::send( 625 | "Adapter undiscoverable" 626 | .to_string(), 627 | NotificationLevel::Info, 628 | sender.clone(), 629 | ); 630 | } 631 | Err(e) => { 632 | let _ = Notification::send( 633 | e.to_string(), 634 | NotificationLevel::Error, 635 | sender.clone(), 636 | ); 637 | } 638 | } 639 | } else { 640 | match adapter 641 | .set_discoverable(true) 642 | .await 643 | { 644 | Ok(_) => { 645 | let _ = Notification::send( 646 | "Adapter discoverable" 647 | .to_string(), 648 | NotificationLevel::Info, 649 | sender.clone(), 650 | ); 651 | } 652 | Err(e) => { 653 | let _ = Notification::send( 654 | e.to_string(), 655 | NotificationLevel::Error, 656 | sender.clone(), 657 | ); 658 | } 659 | } 660 | } 661 | } 662 | Err(e) => { 663 | let _ = Notification::send( 664 | e.to_string(), 665 | NotificationLevel::Error, 666 | sender.clone(), 667 | ); 668 | } 669 | } 670 | } 671 | }); 672 | } 673 | } 674 | 675 | _ => {} 676 | } 677 | } 678 | 679 | FocusedBlock::NewDevices => { 680 | // Pair new device 681 | if KeyCode::Char(config.new_device.pair) == key_event.code { 682 | if let Some(selected_controller) = app.controller_state.selected() { 683 | let controller = &app.controllers[selected_controller]; 684 | if let Some(index) = app.new_devices_state.selected() { 685 | let addr = controller.new_devices[index].addr; 686 | match controller.adapter.device(addr) { 687 | Ok(device) => match device.alias().await { 688 | Ok(device_name) => { 689 | let _ = Notification::send( 690 | format!( 691 | "Start pairing with the device\n `{device_name}`", 692 | ), 693 | NotificationLevel::Info, 694 | sender.clone(), 695 | ); 696 | 697 | tokio::spawn(async move { 698 | match device.pair().await { 699 | Ok(_) => { 700 | let _ = Notification::send( 701 | "Device paired".to_string(), 702 | NotificationLevel::Info, 703 | sender.clone(), 704 | ); 705 | } 706 | Err(e) => { 707 | let _ = Notification::send( 708 | e.to_string(), 709 | NotificationLevel::Error, 710 | sender.clone(), 711 | ); 712 | } 713 | } 714 | }); 715 | } 716 | Err(e) => { 717 | let _ = Notification::send( 718 | e.to_string(), 719 | NotificationLevel::Error, 720 | sender.clone(), 721 | ); 722 | } 723 | }, 724 | Err(e) => { 725 | let _ = Notification::send( 726 | e.to_string(), 727 | NotificationLevel::Error, 728 | sender.clone(), 729 | ); 730 | } 731 | } 732 | } 733 | } 734 | } 735 | } 736 | 737 | FocusedBlock::PassKeyConfirmation => match key_event.code { 738 | KeyCode::Left | KeyCode::Char('h') => { 739 | if !app.pairing_confirmation.confirmed { 740 | app.pairing_confirmation.confirmed = true; 741 | } 742 | } 743 | KeyCode::Right | KeyCode::Char('l') => { 744 | if app.pairing_confirmation.confirmed { 745 | app.pairing_confirmation.confirmed = false; 746 | } 747 | } 748 | 749 | KeyCode::Enter => { 750 | app.pairing_confirmation 751 | .user_confirmation_sender 752 | .send(app.pairing_confirmation.confirmed) 753 | .await?; 754 | app.pairing_confirmation 755 | .display 756 | .store(false, Ordering::Relaxed); 757 | app.focused_block = FocusedBlock::PairedDevices; 758 | app.pairing_confirmation.message = None; 759 | } 760 | 761 | _ => {} 762 | }, 763 | 764 | _ => {} 765 | } 766 | } 767 | } 768 | } 769 | } 770 | 771 | Ok(()) 772 | } 773 | -------------------------------------------------------------------------------- /src/help.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use ratatui::{ 4 | Frame, 5 | layout::{Alignment, Constraint, Direction, Layout, Margin}, 6 | style::{Color, Style, Stylize}, 7 | widgets::{ 8 | Block, BorderType, Borders, Cell, Clear, Padding, Row, Scrollbar, ScrollbarOrientation, 9 | ScrollbarState, Table, TableState, 10 | }, 11 | }; 12 | 13 | use crate::{app::ColorMode, config::Config}; 14 | 15 | #[derive(Debug)] 16 | pub struct Help { 17 | block_height: usize, 18 | state: TableState, 19 | keys: Vec<(Cell<'static>, &'static str)>, 20 | } 21 | 22 | impl Help { 23 | pub fn new(config: Arc) -> Self { 24 | let mut state = TableState::new().with_offset(0); 25 | state.select(Some(0)); 26 | 27 | Self { 28 | block_height: 0, 29 | state, 30 | keys: vec![ 31 | ( 32 | Cell::from("## Global").style(Style::new().bold().fg(Color::Yellow)), 33 | "", 34 | ), 35 | (Cell::from("Esc").bold(), "Dismiss different pop-ups"), 36 | ( 37 | Cell::from("Tab").bold(), 38 | "Switch between different sections", 39 | ), 40 | (Cell::from("j or Down").bold(), "Scroll down"), 41 | (Cell::from("k or Up").bold(), "Scroll up"), 42 | ( 43 | Cell::from(config.toggle_scanning.to_string()).bold(), 44 | "Start/Stop scanning", 45 | ), 46 | (Cell::from("?").bold(), "Show help"), 47 | (Cell::from("ctrl+c or q").bold(), "Quit"), 48 | (Cell::from(""), ""), 49 | ( 50 | Cell::from("## Adapters").style(Style::new().bold().fg(Color::Yellow)), 51 | "", 52 | ), 53 | ( 54 | Cell::from(config.adapter.toggle_pairing.to_string()).bold(), 55 | "Enable/Disable the pairing", 56 | ), 57 | ( 58 | Cell::from(config.adapter.toggle_power.to_string()).bold(), 59 | "Power on/off the adapter", 60 | ), 61 | ( 62 | Cell::from(config.adapter.toggle_discovery.to_string()).bold(), 63 | "Enable/Disable the discovery", 64 | ), 65 | (Cell::from(""), ""), 66 | ( 67 | Cell::from("## Paired devices").style(Style::new().bold().fg(Color::Yellow)), 68 | "", 69 | ), 70 | ( 71 | Cell::from(config.paired_device.unpair.to_string()).bold(), 72 | "Unpair the device", 73 | ), 74 | ( 75 | Cell::from({ 76 | if config.paired_device.toggle_connect == ' ' { 77 | "Space".to_string() 78 | } else { 79 | config.paired_device.toggle_connect.to_string() 80 | } 81 | }) 82 | .bold(), 83 | "Connect/Disconnect the device", 84 | ), 85 | ( 86 | Cell::from(config.paired_device.toggle_trust.to_string()).bold(), 87 | "Trust/Untrust the device", 88 | ), 89 | ( 90 | Cell::from(config.paired_device.rename.to_string()).bold(), 91 | "Rename the device", 92 | ), 93 | (Cell::from(""), ""), 94 | ( 95 | Cell::from("## New devices").style(Style::default().bold().fg(Color::Yellow)), 96 | "", 97 | ), 98 | ( 99 | Cell::from(config.new_device.pair.to_string()).bold(), 100 | "Pair the device", 101 | ), 102 | ], 103 | } 104 | } 105 | 106 | pub fn scroll_down(&mut self) { 107 | let i = match self.state.selected() { 108 | Some(i) => { 109 | if i >= self.keys.len().saturating_sub(self.block_height - 6) { 110 | i 111 | } else { 112 | i + 1 113 | } 114 | } 115 | None => 1, 116 | }; 117 | *self.state.offset_mut() = i; 118 | self.state.select(Some(i)); 119 | } 120 | pub fn scroll_up(&mut self) { 121 | let i = match self.state.selected() { 122 | Some(i) => i.saturating_sub(1), 123 | None => 1, 124 | }; 125 | *self.state.offset_mut() = i; 126 | self.state.select(Some(i)); 127 | } 128 | 129 | pub fn render(&mut self, frame: &mut Frame, color_mode: ColorMode) { 130 | let layout = Layout::default() 131 | .direction(Direction::Vertical) 132 | .constraints([ 133 | Constraint::Fill(1), 134 | Constraint::Length(28), 135 | Constraint::Fill(1), 136 | ]) 137 | .flex(ratatui::layout::Flex::SpaceBetween) 138 | .split(frame.area()); 139 | 140 | let block = Layout::default() 141 | .direction(Direction::Horizontal) 142 | .constraints([ 143 | Constraint::Fill(1), 144 | Constraint::Length(70), 145 | Constraint::Fill(1), 146 | ]) 147 | .flex(ratatui::layout::Flex::SpaceBetween) 148 | .split(layout[1])[1]; 149 | 150 | self.block_height = block.height as usize; 151 | 152 | let widths = [Constraint::Length(20), Constraint::Max(40)]; 153 | let rows: Vec = self 154 | .keys 155 | .iter() 156 | .map(|key| { 157 | Row::new(vec![key.0.to_owned(), key.1.into()]).style(match color_mode { 158 | ColorMode::Dark => Style::default().fg(Color::White), 159 | ColorMode::Light => Style::default().fg(Color::Black), 160 | }) 161 | }) 162 | .collect(); 163 | let rows_len = self.keys.len().saturating_sub(self.block_height - 6); 164 | 165 | let table = Table::new(rows, widths).block( 166 | Block::default() 167 | .padding(Padding::uniform(2)) 168 | .title(" Help ") 169 | .title_style(Style::default().bold().fg(Color::Green)) 170 | .title_alignment(Alignment::Center) 171 | .borders(Borders::ALL) 172 | .style(Style::default()) 173 | .border_type(BorderType::Thick) 174 | .border_style(Style::default().fg(Color::Green)), 175 | ); 176 | 177 | frame.render_widget(Clear, block); 178 | frame.render_stateful_widget(table, block, &mut self.state); 179 | 180 | let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight) 181 | .begin_symbol(Some("↑")) 182 | .end_symbol(Some("↓")); 183 | let mut scrollbar_state = 184 | ScrollbarState::new(rows_len).position(self.state.selected().unwrap_or_default()); 185 | frame.render_stateful_widget( 186 | scrollbar, 187 | block.inner(Margin { 188 | vertical: 1, 189 | horizontal: 0, 190 | }), 191 | &mut scrollbar_state, 192 | ); 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod app; 2 | 3 | pub mod event; 4 | 5 | pub mod ui; 6 | 7 | pub mod tui; 8 | 9 | pub mod handler; 10 | 11 | pub mod bluetooth; 12 | 13 | pub mod notification; 14 | 15 | pub mod spinner; 16 | 17 | pub mod help; 18 | 19 | pub mod config; 20 | 21 | pub mod rfkill; 22 | 23 | pub mod confirmation; 24 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use bluetui::{ 2 | app::{App, AppResult}, 3 | config::Config, 4 | event::{Event, EventHandler}, 5 | handler::handle_key_events, 6 | rfkill, 7 | tui::Tui, 8 | }; 9 | use clap::{Command, crate_version}; 10 | use ratatui::{Terminal, backend::CrosstermBackend}; 11 | use std::{io, sync::Arc}; 12 | 13 | #[tokio::main] 14 | async fn main() -> AppResult<()> { 15 | Command::new("bluetui") 16 | .version(crate_version!()) 17 | .get_matches(); 18 | 19 | rfkill::check()?; 20 | 21 | let config = Arc::new(Config::new()); 22 | let mut app = App::new(config.clone()).await?; 23 | let backend = CrosstermBackend::new(io::stdout()); 24 | let terminal = Terminal::new(backend)?; 25 | let events = EventHandler::new(1_000); 26 | let mut tui = Tui::new(terminal, events); 27 | tui.init()?; 28 | 29 | while app.running { 30 | tui.draw(&mut app)?; 31 | match tui.events.next().await? { 32 | Event::Tick => app.tick().await?, 33 | Event::Key(key_event) => { 34 | handle_key_events( 35 | key_event, 36 | &mut app, 37 | tui.events.sender.clone(), 38 | config.clone(), 39 | ) 40 | .await? 41 | } 42 | Event::Notification(notification) => { 43 | app.notifications.push(notification); 44 | } 45 | _ => {} 46 | } 47 | } 48 | 49 | tui.exit()?; 50 | Ok(()) 51 | } 52 | -------------------------------------------------------------------------------- /src/notification.rs: -------------------------------------------------------------------------------- 1 | use ratatui::{ 2 | Frame, 3 | layout::{Alignment, Constraint, Direction, Layout, Rect}, 4 | style::{Color, Modifier, Style}, 5 | text::{Line, Text}, 6 | widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, 7 | }; 8 | use tokio::sync::mpsc::UnboundedSender; 9 | 10 | use crate::{app::AppResult, event::Event}; 11 | 12 | #[derive(Debug, Clone)] 13 | pub struct Notification { 14 | pub message: String, 15 | pub level: NotificationLevel, 16 | pub ttl: u16, 17 | } 18 | 19 | #[derive(Debug, Clone)] 20 | pub enum NotificationLevel { 21 | Error, 22 | Warning, 23 | Info, 24 | } 25 | 26 | impl Notification { 27 | pub fn render(&self, index: usize, frame: &mut Frame) { 28 | let (color, title) = match self.level { 29 | NotificationLevel::Info => (Color::Green, "Info"), 30 | NotificationLevel::Warning => (Color::Yellow, "Warning"), 31 | NotificationLevel::Error => (Color::Red, "Error"), 32 | }; 33 | 34 | let mut text = Text::from(vec![ 35 | Line::from(title).style(Style::new().fg(color).add_modifier(Modifier::BOLD)), 36 | ]); 37 | 38 | text.extend(Text::from(self.message.as_str())); 39 | 40 | let notification_height = text.height() as u16 + 2; 41 | let notification_width = text.width() as u16 + 4; 42 | 43 | let block = Paragraph::new(text) 44 | .alignment(Alignment::Center) 45 | .wrap(Wrap { trim: false }) 46 | .block( 47 | Block::default() 48 | .borders(Borders::ALL) 49 | .style(Style::default()) 50 | .border_type(BorderType::Thick) 51 | .border_style(Style::default().fg(color)), 52 | ); 53 | 54 | let area = notification_rect( 55 | index as u16, 56 | notification_height, 57 | notification_width, 58 | frame.area(), 59 | ); 60 | 61 | frame.render_widget(Clear, area); 62 | frame.render_widget(block, area); 63 | } 64 | pub fn send( 65 | message: String, 66 | level: NotificationLevel, 67 | sender: UnboundedSender, 68 | ) -> AppResult<()> { 69 | let notif = Notification { 70 | message, 71 | level, 72 | ttl: 1, 73 | }; 74 | 75 | sender.send(Event::Notification(notif))?; 76 | 77 | Ok(()) 78 | } 79 | } 80 | 81 | pub fn notification_rect(offset: u16, height: u16, width: u16, r: Rect) -> Rect { 82 | let popup_layout = Layout::default() 83 | .direction(Direction::Vertical) 84 | .constraints( 85 | [ 86 | Constraint::Length(height * offset), 87 | Constraint::Length(height), 88 | Constraint::Min(1), 89 | ] 90 | .as_ref(), 91 | ) 92 | .split(r); 93 | 94 | Layout::default() 95 | .direction(Direction::Horizontal) 96 | .constraints( 97 | [ 98 | Constraint::Min(1), 99 | Constraint::Length(width), 100 | Constraint::Length(2), 101 | ] 102 | .as_ref(), 103 | ) 104 | .split(popup_layout[1])[1] 105 | } 106 | -------------------------------------------------------------------------------- /src/rfkill.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | 3 | use crate::app::AppResult; 4 | 5 | pub fn check() -> AppResult<()> { 6 | let entries = fs::read_dir("/sys/class/rfkill/")?; 7 | 8 | for entry in entries { 9 | let entry = entry?; 10 | let entry_path = entry.path(); 11 | 12 | if let Some(_file_name) = entry_path.file_name() { 13 | let name = fs::read_to_string(entry_path.join("type"))?; 14 | 15 | if name.trim() == "bluetooth" { 16 | let state_path = entry_path.join("state"); 17 | let state = fs::read_to_string(state_path)?.trim().parse::()?; 18 | 19 | // https://www.kernel.org/doc/Documentation/ABI/stable/sysfs-class-rfkill 20 | match state { 21 | 0 => { 22 | eprintln!( 23 | r#" 24 | The bluetooth device is soft blocked 25 | Run the following command to unblock it 26 | $ sudo rfkill unblock bluetooth 27 | "# 28 | ); 29 | std::process::exit(1); 30 | } 31 | 2 => { 32 | eprintln!("The bluetooth device is hard blocked"); 33 | std::process::exit(1); 34 | } 35 | _ => {} 36 | } 37 | break; 38 | } 39 | } 40 | } 41 | Ok(()) 42 | } 43 | -------------------------------------------------------------------------------- /src/spinner.rs: -------------------------------------------------------------------------------- 1 | static SPINNER_CHARS: &[char] = &['⦾', '⦿']; 2 | 3 | #[derive(Default, Clone, Copy, Debug)] 4 | pub struct Spinner { 5 | pub active: bool, 6 | pub index: usize, 7 | } 8 | 9 | impl Spinner { 10 | pub fn draw(&self) -> char { 11 | SPINNER_CHARS[self.index] 12 | } 13 | 14 | pub fn update(&mut self) { 15 | self.index += 1; 16 | self.index %= SPINNER_CHARS.len(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/tui.rs: -------------------------------------------------------------------------------- 1 | use crate::app::{App, AppResult}; 2 | use crate::event::EventHandler; 3 | use crate::ui; 4 | use crossterm::event::{DisableMouseCapture, EnableMouseCapture}; 5 | use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen}; 6 | use ratatui::Terminal; 7 | use ratatui::backend::Backend; 8 | use std::io; 9 | use std::panic; 10 | 11 | #[derive(Debug)] 12 | pub struct Tui { 13 | terminal: Terminal, 14 | pub events: EventHandler, 15 | } 16 | 17 | impl Tui { 18 | pub fn new(terminal: Terminal, events: EventHandler) -> Self { 19 | Self { terminal, events } 20 | } 21 | 22 | pub fn init(&mut self) -> AppResult<()> { 23 | terminal::enable_raw_mode()?; 24 | crossterm::execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)?; 25 | 26 | let panic_hook = panic::take_hook(); 27 | panic::set_hook(Box::new(move |panic| { 28 | Self::reset().expect("failed to reset the terminal"); 29 | panic_hook(panic); 30 | })); 31 | 32 | self.terminal.hide_cursor()?; 33 | self.terminal.clear()?; 34 | Ok(()) 35 | } 36 | 37 | pub fn draw(&mut self, app: &mut App) -> AppResult<()> { 38 | self.terminal.draw(|frame| ui::render(app, frame))?; 39 | Ok(()) 40 | } 41 | 42 | fn reset() -> AppResult<()> { 43 | terminal::disable_raw_mode()?; 44 | crossterm::execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture)?; 45 | Ok(()) 46 | } 47 | 48 | pub fn exit(&mut self) -> AppResult<()> { 49 | Self::reset()?; 50 | self.terminal.show_cursor()?; 51 | Ok(()) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/ui.rs: -------------------------------------------------------------------------------- 1 | use ratatui::Frame; 2 | 3 | use crate::app::{App, FocusedBlock}; 4 | 5 | pub fn render(app: &mut App, frame: &mut Frame) { 6 | // App 7 | app.render(frame); 8 | 9 | match app.focused_block { 10 | FocusedBlock::Help => app.help.render(frame, app.color_mode), 11 | FocusedBlock::SetDeviceAliasBox => app.render_set_alias(frame), 12 | _ => {} 13 | } 14 | 15 | // Notifications 16 | for (index, notification) in app.notifications.iter().enumerate() { 17 | notification.render(index, frame); 18 | } 19 | } 20 | --------------------------------------------------------------------------------