├── .gitignore ├── .gitlab-ci.yml ├── .mailmap ├── LICENSE ├── LICENSE.0BSD ├── LICENSE.GPL-3.0-only ├── Makefile ├── README.md ├── contrib ├── apparmor.in ├── polkit.in └── udev.in ├── doc └── man │ └── brillo.1.md ├── src ├── burno.h ├── common.h ├── ctrl.c ├── ctrl.h ├── exec.c ├── exec.h ├── file.c ├── file.h ├── info.c ├── info.h ├── init.c ├── init.h ├── light.c ├── light.h ├── main.c ├── parse.c ├── parse.h ├── path.c ├── path.h ├── value.c ├── value.h ├── vlog.c └── vlog.h └── test.sh /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.o 3 | /build 4 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | image: 2 | name: cameronnemo/gitlab-ci-brillo-musl 3 | entrypoint: [""] 4 | 5 | stages: 6 | - lint 7 | - build 8 | 9 | cppcheck: 10 | stage: lint 11 | script: cppcheck --inline-suppr --error-exitcode=3 . 12 | 13 | make: 14 | stage: build 15 | script: make 16 | 17 | make-glibc: 18 | stage: build 19 | image: 20 | name: cameronnemo/gitlab-ci-brillo 21 | entrypoint: [""] 22 | script: make 23 | -------------------------------------------------------------------------------- /.mailmap: -------------------------------------------------------------------------------- 1 | Cameron Nemo Cameron Nemo 2 | Cameron Nemo Cameron Nemo 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | LICENSE.GPL-3.0-only -------------------------------------------------------------------------------- /LICENSE.0BSD: -------------------------------------------------------------------------------- 1 | Copyright (C) 2018-2019 by Cameron Nemo 2 | 3 | Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. 4 | 5 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 6 | -------------------------------------------------------------------------------- /LICENSE.GPL-3.0-only: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PROG := brillo 2 | DESC := Control the brightness of backlight and keyboard LED devices 3 | VENDOR := com.gitlab.CameronNemo 4 | VERSION := 1.4.11 5 | 6 | GOMD2MAN ?= go-md2man 7 | GROUP ?= video 8 | 9 | SYSCONFDIR ?= /etc 10 | AADIR ?= $(SYSCONFDIR)/apparmor.d 11 | PREFIX ?= /usr 12 | BINDIR ?= $(PREFIX)/bin 13 | MANDIR ?= $(PREFIX)/share/man/man1 14 | PKEDIR ?= $(PREFIX)/share/polkit-1/actions 15 | UDEVRULESDIR ?= $(PREFIX)/lib/udev/rules.d 16 | 17 | ifeq ($(UBSAN),1) 18 | override CFLAGS += \ 19 | -fsanitize=undefined \ 20 | -fsanitize=shift \ 21 | -fsanitize=unreachable \ 22 | -fsanitize=vla-bound \ 23 | -fsanitize=null \ 24 | -fsanitize=return \ 25 | -fsanitize=signed-integer-overflow \ 26 | -fsanitize=integer-divide-by-zero \ 27 | -fsanitize=float-divide-by-zero \ 28 | -fsanitize=float-cast-overflow \ 29 | -fsanitize=bounds \ 30 | -fsanitize=alignment \ 31 | -fsanitize=object-size \ 32 | -fsanitize=vptr 33 | endif 34 | 35 | override CFLAGS += \ 36 | -std=c99 -D_XOPEN_SOURCE=700 \ 37 | -DPROG='"$(PROG)"' -DVERSION='"$(VERSION)"' 38 | 39 | ifeq ($(WERROR),1) 40 | override CFLAGS += -pedantic -Wall -Werror -Wextra 41 | endif 42 | 43 | override LDLIBS += -lm 44 | 45 | SRC = \ 46 | src/vlog.c \ 47 | src/value.c \ 48 | src/light.c \ 49 | src/file.c \ 50 | src/parse.c \ 51 | src/path.c \ 52 | src/ctrl.c \ 53 | src/info.c \ 54 | src/init.c \ 55 | src/exec.c \ 56 | src/main.c 57 | 58 | OBJ = $(SRC:.c=.o) 59 | 60 | build/$(PROG): $(OBJ) 61 | mkdir -p build 62 | $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS) 63 | 64 | install.bin: build/$(PROG) 65 | install -Dm 0755 -t $(DESTDIR)$(BINDIR) $^ 66 | 67 | build/$(VENDOR).$(PROG): contrib/apparmor.in 68 | sed -e 's|@vendor@|$(VENDOR)|g' -e 's|@prog@|$(PROG)|g' $^ > $@ 69 | 70 | install.apparmor: build/$(VENDOR).$(PROG) 71 | install -d $(DESTDIR)$(AADIR) 72 | install -m 0640 -t $(DESTDIR)$(AADIR) $^ 73 | 74 | build/$(PROG).1: doc/man/brillo.1.md 75 | $(GOMD2MAN) -in $^ -out $@ 76 | 77 | install.man: build/$(PROG).1 78 | install -d $(DESTDIR)$(MANDIR) 79 | install -m 0644 -t $(DESTDIR)$(MANDIR) $^ 80 | 81 | build/92-$(VENDOR).$(PROG).rules: contrib/udev.in 82 | sed -e 's|@group@|$(GROUP)|g' $^ > $@ 83 | 84 | install.udev: build/92-$(VENDOR).$(PROG).rules 85 | install -d $(DESTDIR)$(UDEVRULESDIR) 86 | install -m 00644 -t $(DESTDIR)$(UDEVRULESDIR) $^ 87 | 88 | install.common: install.man install.udev 89 | 90 | install: install.bin install.common 91 | 92 | install.bin.setgid: build/$(PROG) 93 | install -d $(DESTDIR)$(BINDIR) 94 | install -m 2755 -g $(GROUP) -t $(DESTDIR)$(BINDIR) $^ 95 | 96 | install.setgid: install.bin.setgid install.common 97 | 98 | build/$(VENDOR).$(PROG).policy: contrib/polkit.in 99 | sed -e 's|@bindir@|$(BINDIR)|g' \ 100 | -e 's|@prog@|$(PROG)|g' \ 101 | -e 's|@vendor@|$(VENDOR)|g' \ 102 | -e 's|@desc@|$(DESC)|g' \ 103 | $^ > $@ 104 | 105 | install.polkit: build/$(VENDOR).$(PROG).policy 106 | install -d $(DESTDIR)$(PKEDIR) 107 | install -m 0644 -t $(DESTDIR)$(PKEDIR) $^ 108 | 109 | dist: 110 | 111 | install-dist: install.bin install.common install.polkit 112 | 113 | clean: 114 | rm -rfv -- *~ $(OBJ) build 115 | 116 | .PHONY: install.bin install.apparmor install.man install.udev install.common install install.setgid install.polkit dist install-dist clean 117 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Introduction 2 | ------------ 3 | 4 | `brillo` controls the brightness of backlight and LED devices on Linux. 5 | 6 | Notable features include: 7 | 8 | * Automatic best controller detection 9 | * Smooth transitions and natural brightness adjustments 10 | * Ability to save and restore brightness across boots 11 | * Directly using `sysfs` to set brightness without relying on X 12 | * Unprivileged access with no new setuid binaries 13 | * Containment with AppArmor 14 | 15 | For detailed usage, please refer to the [man page](doc/man/brillo.1.md). 16 | 17 | Installation 18 | ------------ 19 | 20 | [![Packaging status](https://repology.org/badge/vertical-allrepos/brillo.svg)](https://repology.org/project/brillo/versions) 21 | 22 | ### From source 23 | 24 | Building the manpage requires `go-md2man`. 25 | 26 | To build and install the binary, manpage, and udev rule: 27 | 28 | ``` 29 | $ make 30 | # make install 31 | ``` 32 | 33 | Users in the configured group (`video` by default) will be able to adjust 34 | the brightness. 35 | An alternative group can be configured using the `GROUP` variable: 36 | 37 | ``` 38 | # make install GROUP=_brillo 39 | ``` 40 | 41 | If you would prefer to allow any user, regardless of group, to change the 42 | brightness, you may install the binary as `setgid`: 43 | 44 | ``` 45 | # make install.setgid GROUP=_brillo 46 | ``` 47 | 48 | To additionally install the apparmor profile: 49 | 50 | ``` 51 | # make install.apparmor 52 | ``` 53 | 54 | To additionally install the polkit rule: 55 | 56 | ``` 57 | # make install.polkit 58 | ``` 59 | 60 | > Note: the `install*` targets use the `PREFIX` and `DESTDIR` variables to 61 | > compose the installation path and generate configuration files. 62 | 63 | Unprivileged Access 64 | ------------------- 65 | 66 | ### polkit 67 | 68 | Active sessions can invoke `brillo` via `pkexec` to escalate priveleges. 69 | 70 | Examples: 71 | 72 | ``` 73 | $ pkexec /usr/bin/brillo -O 74 | $ pkexec /usr/bin/brillo -A 5 75 | ``` 76 | 77 | > Note: this requires polkitd and (e)logind or ConsoleKit. 78 | 79 | ### udev 80 | 81 | `brillo`'s udev rule grants necessary permissions to the `video` group for 82 | backlight and keyboard LED devices. 83 | 84 | Users in these groups can modify values directly. 85 | Alternately, the binary may be installed as `setgid` so that any user may 86 | change the brightness. 87 | 88 | > Note: in this mode, stored brightness and minimum cap files will be in 89 | > the user's cache home (typically "~/.cache"). 90 | 91 | See Also 92 | -------- 93 | 94 | [clight](https://github.com/FedeDP/Clight): provides dimming based on ambient 95 | light and color correction based on location. 96 | 97 | [ddcci-driver-linux](https://gitlab.com/ddcci-driver-linux/ddcci-driver-linux): 98 | exposes external monitor brightness in sysfs, so `brillo` can access them. 99 | 100 | [ddcutil](http://www.ddcutil.com/): designed to control brightness and color 101 | correction for external monitors. 102 | 103 | Copyright 104 | --------- 105 | 106 | Copyright (C) 2018-2019 Cameron Nemo, 2014 Fredrik Haikarainen 107 | 108 | This is free software, see the source for copying conditions. There is NO 109 | warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE 110 | -------------------------------------------------------------------------------- /contrib/apparmor.in: -------------------------------------------------------------------------------- 1 | # vim:syntax=apparmor 2 | 3 | abi , 4 | 5 | include 6 | 7 | profile @vendor@.@prog@ /{,usr/}{,local/}bin/@prog@ { 8 | include 9 | 10 | capability dac_override, 11 | capability dac_read_search, 12 | 13 | /{,usr/}{,local/}bin/@prog@ mixr, 14 | /var/cache/@prog@ rw, 15 | /var/cache/@prog@/** rwk, 16 | 17 | # unpriveleged mode 18 | owner @{HOME}/.cache/@prog@ rw, 19 | owner @{HOME}/.cache/@prog@/** rwk, 20 | 21 | /sys/class/{backlight,leds}/ r, 22 | /sys/devices/**/brightness rwk, 23 | /sys/devices/**/max_brightness r, 24 | 25 | # Site-specific additions and overrides. See local/README for details. 26 | include if exists 27 | } 28 | -------------------------------------------------------------------------------- /contrib/polkit.in: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | @vendor@ 7 | https://gitlab.com/CameronNemo/@prog@ 8 | 9 | @desc@ 10 | 11 | no 12 | no 13 | yes 14 | 15 | @bindir@/@prog@ 16 | 17 | 18 | -------------------------------------------------------------------------------- /contrib/udev.in: -------------------------------------------------------------------------------- 1 | ACTION=="add", SUBSYSTEM=="backlight", RUN+="/bin/chgrp @group@ /sys/class/backlight/%k/brightness" 2 | ACTION=="add", SUBSYSTEM=="backlight", RUN+="/bin/chmod g+w /sys/class/backlight/%k/brightness" 3 | ACTION=="add", SUBSYSTEM=="leds", RUN+="/bin/chgrp @group@ /sys/class/leds/%k/brightness" 4 | ACTION=="add", SUBSYSTEM=="leds", RUN+="/bin/chmod g+w /sys/class/leds/%k/brightness" 5 | -------------------------------------------------------------------------------- /doc/man/brillo.1.md: -------------------------------------------------------------------------------- 1 | % brillo(1) 2 | % Cameron Nemo 3 | % OCTOBER 2018 4 | # NAME 5 | brillo - control the brightness of backlight and keyboard LED devices 6 | 7 | # SYNOPSIS 8 | **brillo** [**operation** [*value*]] [**-k**] [**-q**|**-r**] [**-m**|**-c**] [**-e**|**-s** *ctrl*] [**-u** *usecs*] [**-v** *loglevel*] 9 | 10 | # DESCRIPTION 11 | 12 | **brillo** is a tool for controlling the brightness of backlight 13 | and LED devices on Linux. Notable features include: 14 | 15 | * Automatic best controller detection 16 | * Smooth transitions and exponential (natural) adjustments 17 | * Ability to save and restore brightness across boots 18 | * Directly using **sysfs** to set brightness without relying on X 19 | * Unprivileged access with no new setuid binaries 20 | * Containment with AppArmor 21 | 22 | # OPTIONS 23 | 24 | *Operations* 25 | 26 | * **-G**: Get brightness value (default) 27 | * **-S** *VALUE*: Set brightness to value 28 | * **-A** *VALUE*: Increment brightness by given value 29 | * **-U** *VALUE*: Decrement brightness by given value 30 | * **-O**: Store the current brightness 31 | * **-I**: Restore cached brightness 32 | * **-L**: List available devices 33 | * **-H**: Show a short help output 34 | * **-V**: Report the version 35 | 36 | *Controllers* 37 | 38 | The default controller is automatically selected to maximize precision. 39 | To select every controller available, use the **-e** option. 40 | To select a specific controller, use the **-s** option. 41 | 42 | * **-a**: Automatic controller selection (default) 43 | * **-e**: Operate on every controller available 44 | * **-s** *CONTROLLER*: Manual controller selection 45 | 46 | The list operation (**-L**) can be used to discover available controllers. 47 | 48 | *Targets* 49 | 50 | By default, **brillo** acts on the display devices, but the **-k** option 51 | can be used to adjust keyboard backlights instead. In either case, it may be 52 | necessary to specify an alternative controller. 53 | 54 | * **-l**: Act on display backlight (default) 55 | * **-k**: Act on keyboard backlight and LEDs 56 | 57 | *Fields* 58 | 59 | By default, **brillo** acts on the brightness property. With these options, 60 | the maximum brightness of a controller can be retrieved. In addition, it is 61 | possible to set (or retrieve) a minimum cap, which is used to prevent 62 | lowering the brightness beyond a certain threshold. This is especially 63 | useful for devices that become pitch black when the brightness is set to 0. 64 | 65 | * **-b**: Current brightness (default) 66 | * **-m**: Maximum brightness 67 | * **-c**: Minimum brightness 68 | 69 | *Value modes* 70 | 71 | Values may be given, or presented, in percent or raw mode. 72 | 73 | The default value mode is linear percentages, however the **-q** option 74 | can be used for exponential percentages. Exponential mode offers a more 75 | natural and gradual brightness scale. 76 | 77 | Raw mode will use the same format and range given by the device driver; 78 | this mode is most useful when a high degree of precision is required, 79 | such as for keyboard controllers. 80 | 81 | * **-p**: Linear percentages (default) 82 | * **-q**: Exponential percentages 83 | * **-r**: Raw values 84 | 85 | *Smooth adjustment* 86 | 87 | **brillo** is capable of gradually adjusting the brightness over a specified 88 | time period. Use the **-u** *microseconds* option to specify how long the operation 89 | should take. This flag is silently ignored when not setting the brightness. 90 | 91 | * **-u** *microseconds*: time used to space the operation out 92 | 93 | *Verbosity* 94 | 95 | By default, **brillo** outputs only warnings or more severe messages. 96 | To enable more verbose logs on **stderr**, use the verbosity argument: 97 | **-v** *loglevel*. 98 | The loglevel is a value between 0 and 8 (corresponding to syslog severities). 99 | 100 | # EXAMPLES 101 | 102 | Get the current brightness in percent: 103 | 104 | brillo [-G] 105 | 106 | Increase brightness by 5 percent: 107 | 108 | brillo -A 5 109 | 110 | Specify the controller to use: 111 | 112 | brillo -s intel_backlight -A 5 113 | 114 | Set the brightness to 50% for every controller: 115 | 116 | brillo -e -S 50 117 | 118 | Retrieve or increase the brightness using an exponential scale: 119 | 120 | brillo -q 121 | brillo -q -A 5 122 | 123 | Decrease the brightness and smooth the operation over 1500 microseconds: 124 | 125 | brillo -u 150000 -U 5 126 | 127 | Get the raw maximum brightness value: 128 | 129 | brillo -rm 130 | 131 | Set the minimum cap for the *acpi_video0* controller to a raw value of 2: 132 | 133 | brillo -rc -s acpi_video0 -S 2 134 | 135 | *Note*: subsequent attempts to set the controller's brightness to a raw value less than 2 will then be raised to this minimum threshold. 136 | 137 | List keyboard controllers: 138 | 139 | brillo -Lk 140 | 141 | Activate a specific controller LED: 142 | 143 | brillo -k -s "input15::scrolllock" -S 100 144 | 145 | *Note*: LEDs often only take 0 or 1 in raw value (i.e. for off/on). In these cases, you can use any non-zero value instead of 100. 146 | 147 | # COPYRIGHT 148 | 149 | Copyright (C) 2018-2019 Cameron Nemo, 2014 Fredrik Haikarainen 150 | 151 | This is free software, see the source for copying conditions. There is NO 152 | warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE 153 | -------------------------------------------------------------------------------- /src/burno.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: 0BSD */ 2 | 3 | #ifndef BURN_H 4 | #define BURN_H 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | static inline void burn__o(void *o) 13 | { 14 | free(*(void **)o); 15 | } 16 | 17 | static inline void burn__fd(int *fd) 18 | { 19 | close(*fd); 20 | } 21 | 22 | static inline void burn__file(FILE **file) 23 | { 24 | if (*file) 25 | fclose(*file); 26 | } 27 | 28 | static inline void burn__dir(DIR **dir) 29 | { 30 | if (*dir) 31 | closedir(*dir); 32 | } 33 | 34 | #define burn_o __attribute__((cleanup(burn__o))) 35 | #define burn_fd __attribute__((cleanup(burn__fd))) int 36 | #define burn_dir __attribute__((cleanup(burn__dir))) DIR * 37 | #define burn_file __attribute__((cleanup(burn__file))) FILE * 38 | 39 | #endif /* BURN_H */ 40 | -------------------------------------------------------------------------------- /src/common.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | -------------------------------------------------------------------------------- /src/ctrl.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #include 4 | 5 | #include "common.h" 6 | 7 | #include "burno.h" 8 | #include "vlog.h" 9 | #include "light.h" 10 | #include "exec.h" 11 | #include "ctrl.h" 12 | 13 | /** 14 | * ctrl_iter_next: 15 | * @dir: opened directory to iterate over 16 | * 17 | * Iterates over the directory given by dir. 18 | * 19 | * WARNING: will allocate a string and return it, 20 | * this string should be freed after use 21 | * 22 | * Returns: name of the next controller, NULL on end of dir or failure 23 | **/ 24 | char *ctrl_iter_next(DIR * dir) 25 | { 26 | struct dirent *file; 27 | 28 | if (!dir) { 29 | vlog_err("directory uninitialized"); 30 | return NULL; 31 | } 32 | 33 | while ((file = readdir(dir))) { 34 | if (file->d_name[0] != '.') 35 | return strdup(file->d_name); 36 | } 37 | 38 | return NULL; 39 | } 40 | 41 | /** 42 | * ctrl_auto: 43 | * @conf: configuration object to work on 44 | * 45 | * Iterates over the appropriate directory and finds the 46 | * controller with the highest max brightness. Stores the 47 | * name of the controller and the max brightness value in 48 | * the configuration object 49 | * 50 | * WARNING: will return an allocated string, which 51 | * should be freed after use 52 | * 53 | * Returns: best controller, or NULL if no suitable controller is found 54 | **/ 55 | bool ctrl_auto(struct light_conf *conf) 56 | { 57 | char *next, *prev; 58 | burn_dir dir = opendir(conf->sys_prefix); 59 | 60 | if (!dir) { 61 | vlog_err("opendir: %m"); 62 | return false; 63 | } 64 | 65 | while ((next = ctrl_iter_next(dir))) { 66 | int64_t max = 0; 67 | prev = conf->ctrl; 68 | conf->ctrl = next; 69 | 70 | if ((max = light_fetch(conf, LIGHT_MAX_BRIGHTNESS)) > 0) { 71 | if (max > conf->cached_max) { 72 | vlog_debug("found (better) controller '%s'", next); 73 | conf->cached_max = max; 74 | if (prev) 75 | free(prev); 76 | continue; 77 | } else { 78 | vlog_notice("found worse controller '%s'", next); 79 | conf->ctrl = prev; 80 | } 81 | } else { 82 | vlog_warning("found inaccessible controller '%s'", next); 83 | conf->ctrl = prev; 84 | } 85 | 86 | free(next); 87 | } 88 | 89 | if (conf->ctrl) { 90 | vlog_notice("automatically chose controller: '%s'", conf->ctrl); 91 | return true; 92 | } 93 | 94 | vlog_err("could not find an accessible controller"); 95 | return false; 96 | } 97 | -------------------------------------------------------------------------------- /src/ctrl.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #ifndef CTRL_H 4 | #define CTRL_H 5 | 6 | #include 7 | 8 | #include "light.h" 9 | 10 | char *ctrl_iter_next(DIR * dir) 11 | __attribute__ ((warn_unused_result)); 12 | bool ctrl_auto(struct light_conf *conf) 13 | __attribute__ ((warn_unused_result)); 14 | 15 | #endif /* CTRL_H */ 16 | -------------------------------------------------------------------------------- /src/exec.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #include 4 | 5 | #include "common.h" 6 | 7 | #include "burno.h" 8 | #include "vlog.h" 9 | #include "path.h" 10 | #include "info.h" 11 | #include "ctrl.h" 12 | #include "light.h" 13 | #include "value.h" 14 | #include "file.h" 15 | #include "exec.h" 16 | 17 | static int64_t exec_get_min(struct light_conf *conf); 18 | static bool exec_write(struct light_conf *conf, LIGHT_FIELD field, int64_t val_old, int64_t val_new); 19 | static bool exec_restore(struct light_conf *conf); 20 | 21 | /** 22 | * exec_get_max: 23 | * 24 | * Determines max value from cache, or by fetching it. 25 | * 26 | * Returns: negative value on failure, raw max value on success 27 | **/ 28 | static int64_t exec_get_max(struct light_conf *conf) 29 | { 30 | if (conf->cached_max != 0) 31 | return conf->cached_max; 32 | return light_fetch(conf, LIGHT_MAX_BRIGHTNESS); 33 | } 34 | 35 | /** 36 | * exec_open: 37 | * @conf: configuration object 38 | * @field: field to access 39 | * @flags: flags to pass to open 40 | * 41 | * Opens a given field with the flags specified. 42 | * 43 | * Returns: an fd on success, negative value on failure 44 | **/ 45 | static int exec_open(struct light_conf *conf, LIGHT_FIELD field, int flags) 46 | { 47 | burn_o char *path = light_path_new(conf, field); 48 | return path ? file_open(path, flags) : -1; 49 | } 50 | 51 | /** 52 | * exec_get: 53 | * @conf: configuration object 54 | * @max: maximum raw value 55 | * 56 | * Executes the get operation, printing the appropriate field to standard out. 57 | * 58 | * Returns: true on success, false on failure 59 | **/ 60 | static bool exec_get(struct light_conf *conf) 61 | { 62 | int64_t raw_val, val, max; 63 | 64 | if ((max = exec_get_max(conf)) < 0) 65 | return false; 66 | 67 | switch (conf->field) { 68 | case LIGHT_BRIGHTNESS: 69 | raw_val = light_fetch(conf, LIGHT_BRIGHTNESS); 70 | break; 71 | case LIGHT_MAX_BRIGHTNESS: 72 | raw_val = max; 73 | break; 74 | case LIGHT_MIN_CAP: 75 | raw_val = exec_get_min(conf); 76 | break; 77 | case LIGHT_SAVERESTORE: 78 | return true; 79 | default: 80 | return false; 81 | } 82 | 83 | if (raw_val < 0) 84 | return false; 85 | 86 | val = value_from_raw(conf->val_mode, raw_val, max); 87 | 88 | if (conf->val_mode == LIGHT_RAW) 89 | printf("%" PRId64 "\n", val); 90 | else 91 | printf("%.2f\n", ((double) val / 100.00)); 92 | 93 | return true; 94 | } 95 | 96 | /** 97 | * exec_set: 98 | * @conf: configuration object to operate on 99 | * 100 | * Sets the minimum cap or brightness value. 101 | * 102 | * Returns: true on success, false on failure 103 | **/ 104 | static bool exec_set(struct light_conf *conf) 105 | { 106 | int64_t new_value, curr_value, new_raw, max, curr_raw = -1, mincap = 0; 107 | burn_fd fd = exec_open(conf, conf->field, O_WRONLY); 108 | 109 | if (fd < 0) 110 | return false; 111 | 112 | if (conf->field == LIGHT_MIN_CAP) 113 | curr_raw = exec_get_min(conf); 114 | else 115 | mincap = exec_get_min(conf); 116 | 117 | if (conf->field != LIGHT_MIN_CAP) 118 | curr_raw = light_fetch(conf, conf->field); 119 | 120 | if (curr_raw < 0) 121 | return false; 122 | 123 | if ((max = exec_get_max(conf)) < 0) 124 | return false; 125 | 126 | new_value = conf->value; 127 | curr_value = value_from_raw(conf->val_mode, curr_raw, max); 128 | vlog_notice("specified value: %" PRId64, new_value); 129 | vlog_notice("current value: %" PRId64, curr_value); 130 | 131 | if (conf->field == LIGHT_BRIGHTNESS) { 132 | switch (conf->op_mode) { 133 | case LIGHT_SUB: 134 | /* val is unsigned so we need to get back to >= 0 */ 135 | if (new_value > curr_value) 136 | new_value = -curr_value; 137 | else 138 | new_value = -new_value; 139 | /* FALLTHRU */ 140 | case LIGHT_ADD: 141 | new_value += curr_value; 142 | break; 143 | case LIGHT_SET: 144 | break; 145 | default: 146 | return false; 147 | } 148 | } else if (conf->field != LIGHT_MIN_CAP) { 149 | return false; 150 | } 151 | 152 | new_raw = value_to_raw(conf->val_mode, new_value, max); 153 | 154 | /* Force any increment to result in some change, however small */ 155 | if (conf->op_mode == LIGHT_ADD && new_raw <= curr_raw) 156 | new_raw += 1; 157 | 158 | new_raw = value_clamp(new_raw, mincap, max); 159 | 160 | return file_write(fd, curr_raw, new_raw, conf->usec); 161 | } 162 | 163 | /** 164 | * exec_all: 165 | * @conf: configuration object to operate on 166 | * 167 | * Iterates through available controllers and executes 168 | * the requested operation for each one. 169 | * 170 | * Returns: true on success, false on failure 171 | **/ 172 | bool exec_all(struct light_conf *conf) 173 | { 174 | bool ret = true; 175 | burn_dir dir = opendir(conf->sys_prefix); 176 | 177 | if (!dir) { 178 | vlog_err("opendir: %m"); 179 | return false; 180 | } 181 | 182 | /* Change the controller mode so exec_op() does its thing */ 183 | conf->ctrl_mode = LIGHT_CTRL_SPECIFY; 184 | 185 | while ((conf->ctrl = ctrl_iter_next(dir))) { 186 | if (conf->op_mode == LIGHT_GET) 187 | fprintf(stdout, "%s\t", conf->ctrl); 188 | if (!exec_op(conf)) 189 | ret = false; 190 | free(conf->ctrl); 191 | } 192 | 193 | return ret; 194 | } 195 | 196 | /** 197 | * exec_save: 198 | * @conf: configuration object 199 | * 200 | * Saves current value to the cache file. 201 | **/ 202 | static bool exec_save(struct light_conf *conf) 203 | { 204 | int64_t curr = light_fetch(conf, LIGHT_BRIGHTNESS); 205 | if (curr < 0) 206 | return false; 207 | return exec_write(conf, LIGHT_SAVERESTORE, curr, curr); 208 | } 209 | 210 | /** 211 | * exec_op: 212 | * @conf: configuration object to operate on 213 | * 214 | * Executes the requested operation. 215 | * 216 | * Returns: true on success, false on failure 217 | **/ 218 | bool exec_op(struct light_conf *conf) 219 | { 220 | if (info_print(conf->op_mode, conf->sys_prefix, false)) 221 | return info_print(conf->op_mode, conf->sys_prefix, true); 222 | 223 | if (conf->ctrl_mode == LIGHT_CTRL_ALL) 224 | return exec_all(conf); 225 | 226 | vlog_notice("executing light on '%s' controller", conf->ctrl); 227 | 228 | switch (conf->op_mode) { 229 | case LIGHT_SAVE: 230 | return exec_save(conf); 231 | case LIGHT_GET: 232 | return exec_get(conf); 233 | case LIGHT_RESTORE: 234 | return exec_restore(conf); 235 | case LIGHT_SET: 236 | case LIGHT_SUB: 237 | case LIGHT_ADD: 238 | return exec_set(conf); 239 | default: 240 | /* Should not be reached */ 241 | fprintf(stderr, 242 | "Controller: %s\nValue: %" PRId64 "\nOpMode: %u\nValMode: %u\nField: %u\n\n", 243 | conf->ctrl, conf->value, conf->op_mode, 244 | conf->val_mode, conf->field); 245 | fprintf(stderr, 246 | "Invalid combination of commandline arguments.\n"); 247 | return info_help(); 248 | } 249 | } 250 | 251 | /** 252 | * light_path_new: 253 | * @conf: configuration object to generate path from 254 | * @type: field being accessed 255 | * 256 | * Generates a path in /sys or /etc for a given operation and 257 | * stores it in the string pointed to by buffer. 258 | * 259 | * WARNING: this function allocates memory, but does not free it. 260 | * free the data pointed to by the return value after use. 261 | * 262 | * Returns: the generated path, or NULL on failure 263 | **/ 264 | char *light_path_new(struct light_conf *conf, LIGHT_FIELD type) 265 | { 266 | char *p; 267 | const char *fmt, *prefix; 268 | 269 | if (!path_component(conf->ctrl)) 270 | return NULL; 271 | 272 | if (type == LIGHT_BRIGHTNESS || type == LIGHT_MAX_BRIGHTNESS) 273 | prefix = conf->sys_prefix; 274 | else if (type == LIGHT_MIN_CAP || type == LIGHT_SAVERESTORE) 275 | prefix = conf->cache_prefix; 276 | else 277 | return NULL; 278 | 279 | switch (type) { 280 | case LIGHT_BRIGHTNESS: 281 | fmt = "%s/%s/brightness"; 282 | break; 283 | case LIGHT_MAX_BRIGHTNESS: 284 | fmt = "%s/%s/max_brightness"; 285 | break; 286 | case LIGHT_MIN_CAP: 287 | fmt = "%s.%s.mincap"; 288 | break; 289 | case LIGHT_SAVERESTORE: 290 | fmt = "%s.%s.brightness"; 291 | break; 292 | default: 293 | return NULL; 294 | } 295 | 296 | if (!(p = path_new())) 297 | return NULL; 298 | 299 | return path_append(p, fmt, prefix, conf->ctrl); 300 | } 301 | 302 | /** 303 | * light_fetch: 304 | * @conf: configuration object to fetch from 305 | * @field: field to fetch value from 306 | * 307 | * Fetches value from the appropriate path. 308 | * 309 | * Returns: value on success, -errno on failure 310 | **/ 311 | int64_t light_fetch(struct light_conf *conf, LIGHT_FIELD field) 312 | { 313 | burn_o char *path = light_path_new(conf, field); 314 | return path ? file_read(path) : -ENOMEM; 315 | } 316 | 317 | /** 318 | * exec_write: 319 | * @conf: configuration object to operate on 320 | * @field: field to write value into 321 | * @val_old: old value 322 | * @val_new: new value 323 | * 324 | * Writes a value for a given controller and field. 325 | * 326 | * Returns: true if write was successful, otherwise false 327 | **/ 328 | static bool exec_write(struct light_conf *conf, LIGHT_FIELD field, 329 | int64_t val_old, int64_t val_new) 330 | { 331 | burn_fd fd = exec_open(conf, field, O_WRONLY); 332 | return fd > 0 ? file_write(fd, val_old, val_new, conf->usec) : false; 333 | } 334 | 335 | /** 336 | * exec_get_min: 337 | * @conf: configuration object to operate on 338 | * 339 | * Returns: the mincap if it is available, otherwise 0 340 | **/ 341 | static int64_t exec_get_min(struct light_conf *conf) 342 | { 343 | int64_t mincap = light_fetch(conf, LIGHT_MIN_CAP); 344 | if (mincap == -ENOENT) 345 | mincap = 1; 346 | if (mincap >= 0) 347 | return mincap; 348 | vlog_err("fetching mincap value: %m"); 349 | return 0; 350 | } 351 | 352 | /** 353 | * exec_restore: 354 | * @conf: configuration object to operate on 355 | * 356 | * Restores the brightness value for a given controller. 357 | * 358 | * Returns: true if write was successful, otherwise false 359 | **/ 360 | static bool exec_restore(struct light_conf *conf) 361 | { 362 | int64_t val = light_fetch(conf, LIGHT_SAVERESTORE); 363 | 364 | conf->value = val; 365 | conf->val_mode = LIGHT_RAW; 366 | conf->op_mode = LIGHT_SET; 367 | 368 | return val >= 0 ? exec_set(conf) : false; 369 | } 370 | -------------------------------------------------------------------------------- /src/exec.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #ifndef EXEC_H 4 | #define EXEC_H 5 | 6 | #include 7 | 8 | #include "light.h" 9 | 10 | bool exec_op(struct light_conf *conf); 11 | char *light_path_new(struct light_conf *conf, LIGHT_FIELD type) 12 | __attribute__ ((warn_unused_result)); 13 | int64_t light_fetch(struct light_conf *conf, LIGHT_FIELD field); 14 | 15 | #endif /* EXEC_H */ 16 | -------------------------------------------------------------------------------- /src/file.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: 0BSD */ 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "burno.h" 13 | #include "vlog.h" 14 | #include "file.h" 15 | 16 | #define FILE_MODE_DEFAULT (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) 17 | 18 | #define SMOOTH_WRITES_PER_SECOND 50 19 | #define SMOOTH_ITER_DURATION 1e9 / SMOOTH_WRITES_PER_SECOND 20 | 21 | /** 22 | * file_write_sleep: 23 | * @nsec: nanoseconds to sleep for 24 | * @t0: initial time spec to compare to 25 | * 26 | * Sleeps for nsec nanoseconds, subtracted by how much time 27 | * has passed since the time stored in t0. 28 | * 29 | * Returns: true on success, false on failure 30 | **/ 31 | static bool file_write_sleep(long nsec, struct timespec t0) 32 | { 33 | struct timespec t_sleep, t1; 34 | 35 | t_sleep.tv_sec = 0; 36 | t_sleep.tv_nsec = nsec; 37 | 38 | /* get current time so that we can compare to t0 */ 39 | if (clock_gettime(CLOCK_MONOTONIC_RAW, &t1) < 0) { 40 | vlog_err("clock_gettime: %m"); 41 | return false; 42 | } 43 | 44 | if ((t1.tv_sec - t0.tv_sec) > 1) { 45 | vlog_warning("time diff greater than 1 second, skipping sleep"); 46 | return true; 47 | } 48 | 49 | if ((t1.tv_nsec - t0.tv_nsec) < 0) 50 | t_sleep.tv_nsec -= (t1.tv_nsec - t0.tv_nsec + 1e9); 51 | else 52 | t_sleep.tv_nsec -= (t1.tv_nsec - t0.tv_nsec); 53 | 54 | if (t_sleep.tv_nsec <= 0) 55 | return true; 56 | 57 | /* don't overload nanosleep() */ 58 | if (t_sleep.tv_nsec >= 1e9) 59 | t_sleep.tv_nsec = 1e9 - 1; 60 | 61 | if (nanosleep(&t_sleep, NULL) < 0) { 62 | vlog_err("nanosleep: %m"); 63 | return false; 64 | } 65 | 66 | return true; 67 | } 68 | 69 | /** 70 | * file_rewrite: 71 | * @fd: file descriptor to write to 72 | * @val: value to write into file 73 | * 74 | * Truncates the file described by fd and prints val into it. 75 | * 76 | * Returns: true on success, false on failure 77 | **/ 78 | static bool file_rewrite(int fd, int64_t val) 79 | { 80 | if (val < 0) 81 | val = 0; 82 | 83 | if (ftruncate(fd, 0) < 0) { 84 | vlog_err("ftruncate: %m"); 85 | return false; 86 | } 87 | 88 | if (dprintf(fd, "%" PRId64, val) < 0) { 89 | vlog_err("dprintf: %" PRId64, val); 90 | return false; 91 | } 92 | 93 | /* flush all data to disk so the change takes effect */ 94 | if (fsync(fd) != 0) { 95 | vlog_err("fsync: %m"); 96 | return false; 97 | } 98 | 99 | return true; 100 | } 101 | 102 | /** 103 | * file_write: 104 | * @fd: file descriptor to write to 105 | * @start: starting value 106 | * @end: value to eventually write 107 | * @usec: time used to smooth the write 108 | * 109 | * Writes to the file pointed to by fd, optionally smoothing 110 | * the operation over usec microseconds. 111 | * 112 | * Returns: true on success, false on failure. 113 | **/ 114 | bool file_write(int fd, int64_t start, int64_t end, int64_t usec) 115 | { 116 | struct timespec t0; 117 | 118 | vlog_notice("Writing (raw) value: %" PRId64, end); 119 | 120 | int64_t num_writes = usec * SMOOTH_WRITES_PER_SECOND / 1e6; 121 | 122 | for (int64_t i = 0; i <= num_writes; i++) { 123 | int64_t next_value; 124 | 125 | /* save current time to account for the time 126 | * taken to perform the write operation */ 127 | clock_gettime(CLOCK_MONOTONIC_RAW, &t0); 128 | 129 | if (usec == 0 || i == num_writes) 130 | next_value = end; 131 | else 132 | next_value = ((start * num_writes) + ((end - start) * i)) / num_writes; 133 | 134 | if (!file_rewrite(fd, next_value)) 135 | return false; 136 | 137 | if (!file_write_sleep(SMOOTH_ITER_DURATION, t0)) 138 | return false; 139 | } 140 | 141 | return true; 142 | } 143 | 144 | /** 145 | * file_open: 146 | * @path: path to open 147 | * @mode: access mode to pass to open() 148 | * 149 | * Opens a given path and obtains a lock for the file. 150 | * 151 | * Returns: an fd for the path on success, -1 on failure 152 | **/ 153 | int file_open(const char *const path, int mode) 154 | { 155 | int fd; 156 | 157 | if ((fd = open(path, mode | O_TRUNC | O_CREAT | O_SYNC, FILE_MODE_DEFAULT)) < 0) { 158 | vlog_err("open '%s': %m", path); 159 | return -1; 160 | } 161 | 162 | if (lockf(fd, F_LOCK, 0) < 0) { 163 | vlog_err("lockf '%s': %m", path); 164 | close(fd); 165 | return -1; 166 | } 167 | 168 | return fd; 169 | } 170 | 171 | /** 172 | * file_read: 173 | * @path: path to read value from 174 | * 175 | * Returns: value, or -errno on error 176 | */ 177 | int64_t file_read(const char *const path) 178 | { 179 | int64_t value; 180 | 181 | burn_file file = fopen(path, "r"); 182 | 183 | if (!file) 184 | return -errno; 185 | 186 | errno = 0; 187 | if (fscanf(file, "%" SCNd64, &value) != 1) { 188 | if (errno == 0) 189 | /* cppcheck-suppress resourceLeak */ 190 | return -EINVAL; 191 | /* cppcheck-suppress resourceLeak */ 192 | return -errno; 193 | } 194 | 195 | /* cppcheck-suppress resourceLeak */ 196 | return value; 197 | } 198 | -------------------------------------------------------------------------------- /src/file.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: 0BSD */ 2 | 3 | #ifndef FILE_H 4 | #define FILE_H 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | bool file_write(int fd, int64_t start, int64_t end, int64_t usec); 11 | int file_open(char const *path, int mode); 12 | int64_t file_read(char const *path); 13 | 14 | #endif /* FILE_H */ 15 | -------------------------------------------------------------------------------- /src/info.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #include "common.h" 4 | 5 | #include "burno.h" 6 | #include "vlog.h" 7 | #include "ctrl.h" 8 | #include "light.h" 9 | #include "info.h" 10 | 11 | /** 12 | * info_list: 13 | * @prefix: sysfs prefix to walk through 14 | * 15 | * Prints controller names in the specified prefix. 16 | * 17 | * Returns: false if could not list controllers or no 18 | * controllers found, otherwise true 19 | **/ 20 | bool info_list(char *prefix) 21 | { 22 | burn_dir dir = opendir(prefix); 23 | 24 | if (!dir) { 25 | vlog_err("opendir: %m"); 26 | return false; 27 | } 28 | 29 | for (char *c; (c = ctrl_iter_next(dir)); free(c)) 30 | printf("%s\n", c); 31 | 32 | return true; 33 | } 34 | 35 | /** 36 | * info_help: 37 | * 38 | * Prints help dialog to standard output. 39 | * 40 | * Returns: false 41 | **/ 42 | bool info_help(void) 43 | { 44 | printf("Usage: %s [options] [operation [value]]\n", PROG); 45 | return false; 46 | } 47 | 48 | /** 49 | * info_print: 50 | * @op: operation mode to use 51 | * @prefix: sysfs prefix to hand to list controllers 52 | * @exec: whether or not to take action 53 | * 54 | * If exec is true, prints information 55 | * according to the operation mode. 56 | * 57 | * Returns: true if op_mode is an info mode, otherwise false 58 | **/ 59 | bool info_print(LIGHT_OP_MODE op, char *prefix, bool exec) 60 | { 61 | switch (op) { 62 | case LIGHT_PRINT_HELP: 63 | if (exec) 64 | info_help(); 65 | break; 66 | case LIGHT_PRINT_VERSION: 67 | if (exec) 68 | printf("%s %s\n", PROG, VERSION);; 69 | break; 70 | case LIGHT_LIST_CTRL: 71 | if (exec) 72 | info_list(prefix); 73 | break; 74 | default: 75 | return false; 76 | } 77 | 78 | return true; 79 | } 80 | -------------------------------------------------------------------------------- /src/info.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #ifndef INFO_H 4 | #define INFO_H 5 | 6 | #include "light.h" 7 | 8 | bool info_help(void); 9 | bool info_print(LIGHT_OP_MODE op, char *prefix, bool exec); 10 | 11 | #endif /* INFO_H */ 12 | -------------------------------------------------------------------------------- /src/init.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #include 4 | #include 5 | 6 | #include "common.h" 7 | #include "vlog.h" 8 | #include "path.h" 9 | #include "info.h" 10 | #include "ctrl.h" 11 | #include "light.h" 12 | 13 | /** 14 | * init_sys: 15 | * @tgt: either "leds" or "backlight" 16 | * 17 | * Initializes the sysfs prefix string. 18 | * 19 | * Returns: pointer to allocated prefix, or NULL on failure 20 | **/ 21 | static char *init_sys(const char *tgt) 22 | { 23 | char *s; 24 | 25 | if (!(s = path_new())) 26 | return NULL; 27 | 28 | return path_append(s, "/sys/class/%s", tgt); 29 | } 30 | 31 | /** 32 | * init_cache: 33 | * @tgt: either "leds" or "backlight" 34 | * 35 | * Initializes the cache prefix string, 36 | * attempts to create the directory. 37 | * 38 | * Returns: pointer to allocated prefix, or NULL on failure 39 | **/ 40 | static char *init_cache(const char * const tgt) 41 | { 42 | char *s; 43 | const char *env, *dirfmt; 44 | int r; 45 | 46 | if ((geteuid() == 0 && (env = "/var/cache")) || 47 | (env = getenv("XDG_CACHE_HOME"))) 48 | dirfmt = "%s/" PROG; 49 | else if ((env = getenv("HOME"))) 50 | dirfmt = "%s/.cache/" PROG; 51 | 52 | if (!env) { 53 | vlog_err("XDG/HOME env vars not set, failed to init cache"); 54 | return NULL; 55 | } 56 | 57 | if (!(s = path_new())) 58 | return NULL; 59 | 60 | if (!(s = path_append(s, dirfmt, env))) 61 | return NULL; 62 | 63 | /* make the cache dir */ 64 | r = mkdir(s, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 65 | 66 | /* warn now, the exec will fail later if necessary */ 67 | if (r != 0 && errno != EEXIST) 68 | vlog_warning("mkdir: %m"); 69 | 70 | return path_append(s, "/%s", tgt); 71 | } 72 | 73 | /** 74 | * init_strings: 75 | * @conf: light configuration object to initialize 76 | * 77 | * Initializes sys/cache prefixes and controller string. 78 | * 79 | * Returns: true on success, false on failure 80 | **/ 81 | bool init_strings(struct light_conf *conf) 82 | { 83 | const char *tgt; 84 | 85 | if (conf->target == LIGHT_BACKLIGHT) 86 | tgt = "backlight"; 87 | else if (conf->target == LIGHT_KEYBOARD) 88 | tgt = "leds"; 89 | else 90 | return false; 91 | 92 | if (!(conf->sys_prefix = init_sys(tgt))) 93 | return false; 94 | 95 | /* info mode needs no more initialization */ 96 | if (info_print(conf->op_mode, conf->sys_prefix, false)) 97 | return true; 98 | 99 | if (!(conf->cache_prefix = init_cache(tgt))) 100 | return false; 101 | 102 | /* Make sure we have a valid controller before we proceed */ 103 | if ((conf->ctrl_mode == LIGHT_CTRL_ALL) || conf->ctrl || ctrl_auto(conf)) 104 | return true; 105 | 106 | return false; 107 | } 108 | -------------------------------------------------------------------------------- /src/init.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #ifndef INIT_H 4 | #define INIT_H 5 | 6 | #include 7 | 8 | bool init_strings(struct light_conf *conf); 9 | 10 | #endif /* INIT_H */ 11 | -------------------------------------------------------------------------------- /src/light.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #include 4 | #include 5 | 6 | #include "light.h" 7 | #include "vlog.h" 8 | 9 | /** 10 | * light_new: 11 | * 12 | * Creates a new light configuration object and initializes its values. 13 | * 14 | * Returns: light configuration object, or NULL on memory error 15 | **/ 16 | struct light_conf *light_new(void) 17 | { 18 | struct light_conf *conf = NULL; 19 | 20 | if (!(conf = malloc(sizeof(struct light_conf)))) { 21 | vlog_err("malloc: %m"); 22 | return NULL; 23 | } 24 | 25 | conf->ctrl = NULL; 26 | conf->sys_prefix = NULL; 27 | conf->cache_prefix = NULL; 28 | conf->ctrl_mode = LIGHT_CTRL_UNSET; 29 | conf->op_mode = LIGHT_OP_UNSET; 30 | conf->val_mode = LIGHT_VAL_UNSET; 31 | conf->target = LIGHT_TARGET_UNSET; 32 | conf->field = LIGHT_FIELD_UNSET; 33 | conf->value = 0; 34 | conf->usec = 0; 35 | conf->cached_max = 0; 36 | 37 | return conf; 38 | } 39 | 40 | /** 41 | * light_defaults: 42 | * @conf: configuration object to populate 43 | * 44 | * Populate a light configuration object with default values 45 | * for all struct members that have not been set. 46 | * 47 | * Returns: void 48 | **/ 49 | void light_defaults(struct light_conf *conf) 50 | { 51 | if (conf->ctrl_mode == 0) 52 | conf->ctrl_mode = LIGHT_CTRL_AUTO; 53 | 54 | if (conf->op_mode == 0) 55 | conf->op_mode = LIGHT_GET; 56 | 57 | if (conf->val_mode == 0) 58 | conf->val_mode = LIGHT_PERCENT; 59 | 60 | if (conf->target == 0) 61 | conf->target = LIGHT_BACKLIGHT; 62 | 63 | if (conf->field == 0) 64 | conf->field = LIGHT_BRIGHTNESS; 65 | } 66 | -------------------------------------------------------------------------------- /src/light.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #ifndef LIGHT_H 4 | #define LIGHT_H 5 | 6 | #include 7 | #include 8 | 9 | typedef enum LIGHT_FIELD { 10 | LIGHT_FIELD_UNSET = 0, 11 | LIGHT_BRIGHTNESS, 12 | LIGHT_MAX_BRIGHTNESS, 13 | LIGHT_MIN_CAP, 14 | LIGHT_SAVERESTORE 15 | } LIGHT_FIELD; 16 | 17 | typedef enum LIGHT_TARGET { 18 | LIGHT_TARGET_UNSET = 0, 19 | LIGHT_BACKLIGHT, 20 | LIGHT_KEYBOARD 21 | } LIGHT_TARGET; 22 | 23 | typedef enum LIGHT_CTRL_MODE { 24 | LIGHT_CTRL_UNSET = 0, 25 | LIGHT_CTRL_AUTO, 26 | LIGHT_CTRL_ALL, 27 | LIGHT_CTRL_SPECIFY 28 | } LIGHT_CTRL_MODE; 29 | 30 | typedef enum LIGHT_OP_MODE { 31 | LIGHT_OP_UNSET = 0, 32 | LIGHT_GET, 33 | LIGHT_SET, 34 | LIGHT_ADD, 35 | LIGHT_SUB, 36 | LIGHT_PRINT_HELP, /* Prints help and exits */ 37 | LIGHT_PRINT_VERSION, /* Prints version info and exits */ 38 | LIGHT_LIST_CTRL, 39 | LIGHT_RESTORE, 40 | LIGHT_SAVE 41 | } LIGHT_OP_MODE; 42 | 43 | typedef enum LIGHT_VAL_MODE { 44 | LIGHT_VAL_UNSET = 0, 45 | LIGHT_RAW, 46 | LIGHT_PERCENT, 47 | LIGHT_PERCENT_EXPONENTIAL 48 | } LIGHT_VAL_MODE; 49 | 50 | struct light_conf { 51 | char *sys_prefix; 52 | char *cache_prefix; 53 | char *ctrl; 54 | LIGHT_CTRL_MODE ctrl_mode; 55 | LIGHT_OP_MODE op_mode; 56 | LIGHT_VAL_MODE val_mode; 57 | LIGHT_TARGET target; 58 | LIGHT_FIELD field; 59 | int64_t value; 60 | int64_t usec; 61 | int64_t cached_max; 62 | }; 63 | 64 | static inline void light_free(struct light_conf **conf) 65 | { 66 | if (!(*conf)) 67 | return; 68 | free((*conf)->ctrl); 69 | free((*conf)->sys_prefix); 70 | free((*conf)->cache_prefix); 71 | free(*conf); 72 | } 73 | 74 | #define light_t __attribute__((cleanup(light_free))) struct light_conf * 75 | 76 | struct light_conf *light_new(void); 77 | void light_defaults(struct light_conf *conf); 78 | 79 | #endif /* LIGHT_H */ 80 | -------------------------------------------------------------------------------- /src/main.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #include 4 | #include 5 | 6 | #include "light.h" 7 | #include "vlog.h" 8 | #include "parse.h" 9 | #include "init.h" 10 | #include "exec.h" 11 | 12 | int main(int argc, char **argv) 13 | { 14 | light_t ctx = light_new(); 15 | 16 | if (!ctx) 17 | return EXIT_FAILURE; 18 | 19 | if (!(parse_args(argc, argv, ctx))) { 20 | vlog_err("arguments parsing failed"); 21 | return 2; 22 | } 23 | 24 | if (!(init_strings(ctx))) { 25 | vlog_err("initialization failed"); 26 | return EXIT_FAILURE; 27 | } 28 | 29 | if (!exec_op(ctx)) { 30 | vlog_err("execution failed"); 31 | return EXIT_FAILURE; 32 | } 33 | 34 | return EXIT_SUCCESS; 35 | } 36 | -------------------------------------------------------------------------------- /src/parse.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #include 4 | #include 5 | 6 | #include "common.h" 7 | #include "vlog.h" 8 | #include "path.h" 9 | #include "info.h" 10 | #include "ctrl.h" 11 | #include "value.h" 12 | #include "light.h" 13 | 14 | #define PARSE_SET(str, box, item) \ 15 | if (box != 0) { \ 16 | fprintf(stderr, "%s arguments can not be used in conjunction.\n", str); \ 17 | return info_help(); \ 18 | } else { \ 19 | box = item; \ 20 | } 21 | 22 | #define PARSE_SET_OP(new) PARSE_SET("Operation", ctx->op_mode, new) 23 | #define PARSE_SET_TARGET(new) PARSE_SET("Target", ctx->target, new) 24 | #define PARSE_SET_FIELD(new) PARSE_SET("Field", ctx->field, new) 25 | #define PARSE_SET_CTRL(new) PARSE_SET("Controller", ctx->ctrl_mode, new) 26 | #define PARSE_SET_VAL(new) PARSE_SET("Value", ctx->val_mode, new) 27 | 28 | /** 29 | * parse_check: 30 | * @op: operation being done 31 | * @field: field being accessed 32 | * 33 | * Ensure that the operation is valid for the field. 34 | * 35 | * Returns: false if an invalid operation mode is used, otherwise true. 36 | **/ 37 | static bool parse_check(LIGHT_OP_MODE op, LIGHT_FIELD field) 38 | { 39 | /* Nothing to check if we just print info */ 40 | if (op == LIGHT_PRINT_HELP || 41 | op == LIGHT_PRINT_VERSION || 42 | op == LIGHT_LIST_CTRL) 43 | return true; 44 | 45 | switch (field) { 46 | case LIGHT_MAX_BRIGHTNESS: 47 | if (op == LIGHT_GET) 48 | return true; 49 | vlog_err("only use -G with the max brightness field"); 50 | return false; 51 | case LIGHT_MIN_CAP: 52 | if (op == LIGHT_GET || op == LIGHT_SET) 53 | return true; 54 | vlog_err("only use -G or -S with the min cap field"); 55 | return false; 56 | default: 57 | return true; 58 | } 59 | } 60 | 61 | /** 62 | * parse_args: 63 | * @argc argument count 64 | * @argv argument array 65 | * 66 | * WARNING: may allocate a string in ctx->ctrl, 67 | * but will not free it 68 | * 69 | * Returns: a valid conf object on success, NULL on failure 70 | **/ 71 | bool parse_args(int argc, char **argv, struct light_conf *ctx) 72 | { 73 | int opt, level; 74 | char *value = NULL, *ctrl = NULL; 75 | 76 | level = -1; 77 | 78 | while ((opt = getopt(argc, argv, "HhVGS:A:U:LIObmclkaes:pqrv:u:")) != -1) { 79 | switch (opt) { 80 | /* -- Operations -- */ 81 | case 'H': 82 | case 'h': 83 | PARSE_SET_OP(LIGHT_PRINT_HELP); 84 | break; 85 | case 'V': 86 | PARSE_SET_OP(LIGHT_PRINT_VERSION); 87 | break; 88 | case 'G': 89 | PARSE_SET_OP(LIGHT_GET); 90 | break; 91 | case 'S': 92 | PARSE_SET_OP(LIGHT_SET); 93 | value = optarg; 94 | break; 95 | case 'A': 96 | PARSE_SET_OP(LIGHT_ADD); 97 | value = optarg; 98 | break; 99 | case 'U': 100 | PARSE_SET_OP(LIGHT_SUB); 101 | value = optarg; 102 | break; 103 | case 'L': 104 | PARSE_SET_OP(LIGHT_LIST_CTRL); 105 | break; 106 | case 'I': 107 | PARSE_SET_OP(LIGHT_RESTORE); 108 | break; 109 | case 'O': 110 | PARSE_SET_OP(LIGHT_SAVE); 111 | break; 112 | 113 | /* -- Targets -- */ 114 | case 'l': 115 | PARSE_SET_TARGET(LIGHT_BACKLIGHT); 116 | break; 117 | case 'k': 118 | PARSE_SET_TARGET(LIGHT_KEYBOARD); 119 | break; 120 | 121 | /* -- Fields -- */ 122 | case 'b': 123 | PARSE_SET_FIELD(LIGHT_BRIGHTNESS); 124 | break; 125 | case 'm': 126 | PARSE_SET_FIELD(LIGHT_MAX_BRIGHTNESS); 127 | break; 128 | case 'c': 129 | PARSE_SET_FIELD(LIGHT_MIN_CAP); 130 | break; 131 | 132 | /* -- Controller selection -- */ 133 | case 'a': 134 | PARSE_SET_CTRL(LIGHT_CTRL_AUTO); 135 | break; 136 | case 'e': 137 | PARSE_SET_CTRL(LIGHT_CTRL_ALL); 138 | break; 139 | case 's': 140 | PARSE_SET_CTRL(LIGHT_CTRL_SPECIFY); 141 | ctrl = optarg; 142 | break; 143 | /* -- Value modes -- */ 144 | case 'p': 145 | PARSE_SET_VAL(LIGHT_PERCENT); 146 | break; 147 | case 'q': 148 | PARSE_SET_VAL(LIGHT_PERCENT_EXPONENTIAL); 149 | break; 150 | case 'r': 151 | PARSE_SET_VAL(LIGHT_RAW); 152 | break; 153 | 154 | /* -- Other -- */ 155 | case 'v': 156 | if (sscanf(optarg, "%i", &level) != 1) { 157 | vlog_err("verbosity not recognizable"); 158 | return info_help(); 159 | } 160 | if (level < 0 || level > 8) { 161 | vlog_err("verbosity must be in range 0-8"); 162 | return info_help(); 163 | } 164 | break; 165 | case 'u': 166 | if (sscanf(optarg, "%" SCNd64, &ctx->usec) != 1) { 167 | vlog_err("usecs not recognizable"); 168 | return info_help(); 169 | } 170 | break; 171 | default: 172 | return info_help(); 173 | } 174 | } 175 | 176 | if (level >= 0) 177 | vlog_lvl_set((vlog_lvl_t) level); 178 | 179 | light_defaults(ctx); 180 | 181 | if (!parse_check(ctx->op_mode, ctx->field)) 182 | return info_help(); 183 | 184 | if (ctx->field != LIGHT_BRIGHTNESS && ctx->usec != 0) { 185 | vlog_warning("Resetting time to zero for non-brightness field"); 186 | ctx->usec = 0; 187 | } 188 | 189 | if (value && 190 | (ctx->value = value_from_string(ctx->val_mode, value)) < 0) { 191 | vlog_err("value not recognizable"); 192 | return info_help(); 193 | } 194 | 195 | if (ctrl && (!path_component(ctrl) || !(ctx->ctrl = strdup(ctrl)))) { 196 | vlog_err("can't handle controller: '%s'", ctrl); 197 | return info_help(); 198 | } 199 | 200 | return true; 201 | } 202 | -------------------------------------------------------------------------------- /src/parse.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-only */ 2 | 3 | #ifndef PARSE_H 4 | #define PARSE_H 5 | 6 | #include "light.h" 7 | 8 | bool parse_args(int argc, char **argv, struct light_conf *ctx); 9 | 10 | #endif /* PARSE_H */ 11 | -------------------------------------------------------------------------------- /src/path.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: 0BSD */ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include "common.h" 8 | #include "vlog.h" 9 | 10 | /** 11 | * path_component: 12 | * @c: component to verify 13 | * 14 | * Returns: true if c is a valid path component, otherwise false 15 | **/ 16 | bool path_component(const char *c) { 17 | if (!c || strnlen(c, NAME_MAX + 1) > NAME_MAX || strchr(c, '/') != NULL) 18 | return false; 19 | return true; 20 | } 21 | 22 | /** 23 | * path_new: 24 | * 25 | * Returns: pointer to initialized path string, or NULL on failure 26 | **/ 27 | char *path_new(void) 28 | { 29 | char *p; 30 | 31 | if (!(p = malloc(PATH_MAX))) { 32 | vlog_err("malloc: %m"); 33 | return NULL; 34 | } 35 | 36 | *p = '\0'; 37 | 38 | return p; 39 | } 40 | 41 | /** 42 | * path_append: 43 | * @str: string to append to 44 | * @fmt: format string to append 45 | * @args: variadic arguments to pass to printf 46 | * 47 | * Appends the format and arguments to the 48 | * supplied string, freeing str on error. 49 | * 50 | * Returns: str, or NULL on error 51 | **/ 52 | char *path_append(char * const str, const char *fmt, ...) 53 | { 54 | int r; 55 | va_list ap; 56 | 57 | va_start(ap, fmt); 58 | 59 | r = vsnprintf(str + strlen(str), PATH_MAX - strlen(str), fmt, ap); 60 | 61 | if (r < 0 || (size_t)r >= (PATH_MAX - strlen(str))) { 62 | vlog_err("snprintf"); 63 | free(str); 64 | va_end(ap); 65 | return NULL; 66 | } 67 | 68 | va_end(ap); 69 | return str; 70 | } 71 | -------------------------------------------------------------------------------- /src/path.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: 0BSD */ 2 | 3 | #ifndef PATH_H 4 | #define PATH_H 5 | 6 | #include 7 | #include 8 | 9 | bool path_component(const char *c); 10 | char *path_append(char * const str, const char *fmt, ...); 11 | char *path_new(void); 12 | 13 | #endif /* PATH_H */ 14 | -------------------------------------------------------------------------------- /src/value.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: 0BSD */ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include "value.h" 8 | #include "vlog.h" 9 | 10 | /** 11 | * value_clamp: 12 | * @val: value to clamp 13 | * @min: minimum value to use 14 | * @max: maximum value to use 15 | * 16 | * Returns: clamped value 17 | **/ 18 | int64_t value_clamp(int64_t val, int64_t min, int64_t max) 19 | { 20 | if (val < min) { 21 | vlog_notice("Raising value '%" PRId64 "' to '%" PRId64 "'", val, min); 22 | return min; 23 | } else if (val > max) { 24 | vlog_notice("Lowering value '%" PRId64 "' to '%" PRId64 "'", val, max); 25 | return max; 26 | } else { 27 | return val; 28 | } 29 | } 30 | 31 | /** 32 | * value_log_pct: 33 | * @raw: raw value to convert 34 | * @max: raw maximum value 35 | * 36 | * Converts a raw value to a logarithmic percentage. 37 | * 38 | * Returns: the percentage. 39 | **/ 40 | static int64_t value_log_pct(int64_t raw, int64_t max) 41 | { 42 | return (int64_t) ((log((double) raw) / log((double) max)) * VALUE_PCT_MAX); 43 | } 44 | 45 | /** 46 | * value_from_raw: 47 | * @mode: mode used to calculate value 48 | * @raw: raw value to use in calculation 49 | * @max: raw maximum value to use 50 | * 51 | * Calculates a linear or exponential percentage. 52 | * 53 | * Returns: the percentage, or a negative value on error 54 | **/ 55 | int64_t value_from_raw(LIGHT_VAL_MODE mode, int64_t raw, int64_t max) 56 | { 57 | if (mode == LIGHT_RAW) { 58 | return raw; 59 | } else if (mode == LIGHT_PERCENT) { 60 | return VALUE_CLAMP_PCT((raw * VALUE_PCT_MAX) / max); 61 | } else if (mode == LIGHT_PERCENT_EXPONENTIAL) { 62 | return value_log_pct(raw, max); 63 | } else { 64 | return -1; 65 | } 66 | } 67 | 68 | /** 69 | * value_exp_raw: 70 | * @val: logarithmic percentage to convert 71 | * @max: raw maximum value 72 | * 73 | * Returns: a raw value from a logarithmic percentage. 74 | **/ 75 | static int64_t value_exp_raw(int64_t val, int64_t max) 76 | { 77 | return (int64_t) (exp((double) val * log((double) max) / VALUE_PCT_MAX)); 78 | } 79 | 80 | /** 81 | * value_to_raw: 82 | * @mode: value mode used to calculate raw value 83 | * @val: value to convert to raw value 84 | * @max: raw maximum value to use 85 | * 86 | * Calculates a raw value based on the value mode. 87 | * 88 | * Returns: the raw value 89 | **/ 90 | int64_t value_to_raw(LIGHT_VAL_MODE mode, int64_t val, int64_t max) 91 | { 92 | if (mode == LIGHT_RAW) { 93 | return val; 94 | } else if (mode == LIGHT_PERCENT) { 95 | return ((val * max) / VALUE_PCT_MAX); 96 | } else if (mode == LIGHT_PERCENT_EXPONENTIAL) { 97 | int64_t value = value_exp_raw(val, max); 98 | /* Protect against getting stuck in the sunken place -- 99 | * if the brightness is too low, future increments may not 100 | * be enough to increase the percentage above zero. */ 101 | if (value_from_raw(mode, value, max) == 0) 102 | return value_to_raw(mode, val + (VALUE_PCT_MAX / 200), max); 103 | else 104 | return value; 105 | } else { 106 | return -1; 107 | } 108 | } 109 | 110 | /** 111 | * value_from_string: 112 | * @mode: mode to use to convert value 113 | * @str: string that the value is stored in 114 | * 115 | * Returns: the value, or -1 on failure 116 | **/ 117 | int64_t value_from_string(LIGHT_VAL_MODE mode, const char* str) 118 | { 119 | int ret; 120 | int64_t value = -1; 121 | double value_pct = -1; 122 | 123 | if (mode == LIGHT_RAW) 124 | ret = sscanf(str, "%" SCNd64, &value); 125 | else 126 | ret = sscanf(str, "%lf", &value_pct); 127 | 128 | if (ret != 1) 129 | return -1; 130 | 131 | if (mode == LIGHT_RAW) 132 | return value; 133 | else 134 | return VALUE_CLAMP_PCT((int64_t) (value_pct * (VALUE_PCT_MAX / 100))); 135 | } 136 | -------------------------------------------------------------------------------- /src/value.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: 0BSD */ 2 | 3 | #ifndef VALUE_H 4 | #define VALUE_H 5 | 6 | #include 7 | 8 | #include "light.h" 9 | 10 | #define VALUE_PCT_MAX 10000 11 | 12 | int64_t value_clamp(int64_t val, int64_t min, int64_t max); 13 | int64_t value_from_raw(LIGHT_VAL_MODE mode, int64_t raw, int64_t max); 14 | int64_t value_to_raw(LIGHT_VAL_MODE mode, int64_t val, int64_t max); 15 | int64_t value_from_string(LIGHT_VAL_MODE mode, const char *str); 16 | 17 | #define VALUE_CLAMP_PCT(val) value_clamp(val, 0, VALUE_PCT_MAX) 18 | 19 | #endif /* VALUE_H */ 20 | -------------------------------------------------------------------------------- /src/vlog.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: 0BSD */ 2 | 3 | #include 4 | #include 5 | 6 | #include "vlog.h" 7 | 8 | static vlog_lvl_t vlog_lvl = VLOG_LVL_DEFAULT; 9 | static const char *vlog_lvl_to_string(vlog_lvl_t lvl); 10 | 11 | void vlog(vlog_lvl_t lvl, const char *fmt, ...) 12 | { 13 | if (lvl > vlog_lvl) 14 | return; 15 | fprintf(stderr, "%s: ", vlog_lvl_to_string(lvl)); 16 | va_list ap; 17 | va_start(ap, fmt); 18 | vfprintf(stderr, fmt, ap); 19 | va_end(ap); 20 | fprintf(stderr, "\n"); 21 | } 22 | 23 | vlog_lvl_t vlog_lvl_set(vlog_lvl_t lvl) 24 | { 25 | return (vlog_lvl = lvl); 26 | } 27 | 28 | vlog_lvl_t vlog_lvl_get(void) 29 | { 30 | return vlog_lvl; 31 | } 32 | 33 | static const char *vlog_lvl_to_string(vlog_lvl_t lvl) 34 | { 35 | switch (lvl) { 36 | case VLOG_LVL_EMERGENCY: return "Emergency"; 37 | case VLOG_LVL_ALERT: return "Alert"; 38 | case VLOG_LVL_CRITICAL: return "Critical"; 39 | case VLOG_LVL_ERROR: return "Error"; 40 | case VLOG_LVL_WARNING: return "Warning"; 41 | case VLOG_LVL_NOTICE: return "Notice"; 42 | case VLOG_LVL_INFORMATIONAL: return "Informational"; 43 | case VLOG_LVL_DEBUG: return "Debug"; 44 | default: return "Unknown"; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/vlog.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: 0BSD */ 2 | 3 | #ifndef VLOG_H 4 | #define VLOG_H 5 | 6 | typedef enum { 7 | VLOG_LVL_EMERGENCY = 0, 8 | VLOG_LVL_ALERT, 9 | VLOG_LVL_CRITICAL, 10 | VLOG_LVL_ERROR, 11 | VLOG_LVL_WARNING, 12 | VLOG_LVL_NOTICE, 13 | VLOG_LVL_INFORMATIONAL, 14 | VLOG_LVL_DEBUG 15 | } vlog_lvl_t; 16 | 17 | #ifndef VLOG_LVL_DEFAULT 18 | #define VLOG_LVL_DEFAULT VLOG_LVL_WARNING 19 | #endif 20 | 21 | void vlog(vlog_lvl_t lvl, const char* fmt, ...); 22 | 23 | #define vlog_emerg(...) vlog(VLOG_LVL_EMERGENCY, __VA_ARGS__) 24 | #define vlog_alert(...) vlog(VLOG_LVL_ALERT, __VA_ARGS__) 25 | #define vlog_crit(...) vlog(VLOG_LVL_CRITICAL, __VA_ARGS__) 26 | #define vlog_err(...) vlog(VLOG_LVL_ERROR, __VA_ARGS__) 27 | #define vlog_warning(...) vlog(VLOG_LVL_WARNING, __VA_ARGS__) 28 | #define vlog_notice(...) vlog(VLOG_LVL_NOTICE, __VA_ARGS__) 29 | #define vlog_info(...) vlog(VLOG_LVL_INFORMATIONAL, __VA_ARGS__) 30 | #define vlog_debug(...) vlog(VLOG_LVL_DEBUG, __VA_ARGS__) 31 | 32 | vlog_lvl_t vlog_lvl_set(vlog_lvl_t lvl); 33 | vlog_lvl_t vlog_lvl_get(void); 34 | 35 | #endif /* VLOG_H */ 36 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -eu 4 | 5 | : ${BRILLO_BIN:=./brillo} 6 | : ${BRILLO_VALGRIND:=valgrind --leak-check=full --show-leak-kinds=all} 7 | 8 | _ckvg() { 9 | local id="$1" 10 | 11 | shift 12 | 13 | local out="$(${BRILLO_VALGRIND} "$BRILLO_BIN" $@ 2>&1)" 14 | 15 | printf '%s' "${out}" | grep -q "${ckstr}" || { 16 | printf 'Valgrind reported errors for test: %s\n' "${id}" 17 | printf '%s\n' "${out}" 18 | ret=1 19 | } 20 | } 21 | 22 | ret=0 23 | ckstr='ERROR SUMMARY: 0 errors from 0 context' 24 | 25 | _ckvg "opmode=help" -h 26 | _ckvg "opmode=version" -V 27 | 28 | test ! -d /sys/class/backlight || { 29 | _ckvg "opmode=get" 30 | _ckvg "opmode=list" -L 31 | } 32 | 33 | test ! -d /sys/class/leds || { 34 | _ckvg "opmode=get target=keyboard" -k 35 | _ckvg "opmode=list target=keyboard" -Lk 36 | } 37 | 38 | exit "${ret}" 39 | --------------------------------------------------------------------------------