pax_global_header00006660000000000000000000000064135243503210014510gustar00rootroot0000000000000052 comment=3417602a2d8322bc866861297f535e1ef80b8cb0 i3blocks-1.5/000077500000000000000000000000001352435032100130665ustar00rootroot00000000000000i3blocks-1.5/.gitignore000066400000000000000000000002171352435032100150560ustar00rootroot00000000000000*.o i3blocks .deps/ Makefile Makefile.in aclocal.m4 autom4te.cache/ build-aux/ config.log config.status configure i3blocks-config.h* stamp-h1 i3blocks-1.5/COPYING000066400000000000000000001045131352435032100141250ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . i3blocks-1.5/Makefile.am000066400000000000000000000012101352435032100151140ustar00rootroot00000000000000DEFS += \ -DSYSCONFDIR=\"$(sysconfdir)\" bin_PROGRAMS = i3blocks i3blocks_SOURCES = \ bar.c \ bar.h \ block.c \ block.h \ config.c \ config.h \ i3bar.c \ ini.c \ ini.h \ json.c \ json.h \ line.c \ line.h \ log.h \ main.c \ map.c \ map.h \ sys.c \ sys.h \ term.h dist_man1_MANS = \ docs/i3blocks.1 dist_sysconf_DATA = \ i3blocks.conf if ENABLE_BASH_COMPLETION bashcompletiondir = $(BASH_COMPLETION_DIR) bashcompletion_DATA = bash-completion install-data-local: ( cd '$(DESTDIR)$(BASH_COMPLETION_DIR)' && mv bash-completion i3blocks ) uninstall-local: ( cd '$(DESTDIR)$(BASH_COMPLETION_DIR)' && rm -rf i3blocks ) endif i3blocks-1.5/autogen.sh000077500000000000000000000000331352435032100150630ustar00rootroot00000000000000#! /bin/sh autoreconf -fiv i3blocks-1.5/bar.c000066400000000000000000000203441352435032100140010ustar00rootroot00000000000000/* * bar.c - status line handling functions * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include "bar.h" #include "block.h" #include "config.h" #include "json.h" #include "line.h" #include "log.h" #include "map.h" #include "sched.h" #include "sys.h" #include "term.h" static void bar_read(struct bar *bar) { int err; err = i3bar_click(bar); if (err) bar_error(bar, "failed to read bar"); } static void bar_print(struct bar *bar) { int err; err = i3bar_print(bar); if (err) fatal("failed to print bar!"); } static int bar_start(struct bar *bar) { int err; err = i3bar_start(bar); if (err) return err; debug("bar started"); return 0; } static void bar_stop(struct bar *bar) { i3bar_stop(bar); debug("bar stopped"); } static void bar_poll_timed(struct bar *bar) { struct block *block = bar->blocks; while (block) { /* spawn unless it is only meant for click or signal */ if (block->interval != 0) { block_spawn(block); block_touch(block); } block = block->next; } } static void bar_poll_expired(struct bar *bar) { struct block *block = bar->blocks; while (block) { if (block->interval > 0) { const unsigned long next_update = block->timestamp + block->interval; unsigned long now; int err; err = sys_gettime(&now); if (err) return; if (((long) (next_update - now)) <= 0) { block_debug(block, "expired"); block_spawn(block); block_touch(block); } } block = block->next; } } static void bar_poll_signaled(struct bar *bar, int sig) { struct block *block = bar->blocks; while (block) { if (block->signal == sig) { block_debug(block, "signaled"); block_spawn(block); block_touch(block); } block = block->next; } } static void bar_poll_exited(struct bar *bar) { struct block *block; pid_t pid; int err; for (;;) { err = sys_waitid(&pid); if (err) break; /* Find the dead process */ block = bar->blocks; while (block) { if (block->pid == pid) break; block = block->next; } if (block) { block_debug(block, "exited"); block_reap(block); if (block->interval == INTERVAL_PERSIST) { block_debug(block, "unexpected exit?"); } else { block_update(block); } block_close(block); if (block->interval == INTERVAL_REPEAT) { block_spawn(block); block_touch(block); } } else { error("unknown child process %d", pid); err = sys_waitpid(pid, NULL); if (err) break; } } } static void bar_poll_readable(struct bar *bar, const int fd) { struct block *block = bar->blocks; while (block) { if (block->out[0] == fd) { block_debug(block, "readable"); block_update(block); break; } block = block->next; } } static int gcd(int a, int b) { while (b != 0) a %= b, a ^= b, b ^= a, a ^= b; return a; } static int bar_setup(struct bar *bar) { struct block *block = bar->blocks; sigset_t *set = &bar->sigset; unsigned long sleeptime = 0; int sig; int err; while (block) { err = block_setup(block); if (err) return err; /* The maximum sleep time is actually the GCD * between all positive block intervals. */ if (block->interval > 0) { if (sleeptime > 0) sleeptime = gcd(sleeptime, block->interval); else sleeptime = block->interval; } block = block->next; } err = sys_sigemptyset(set); if (err) return err; /* Control signals */ err = sys_sigaddset(set, SIGTERM); if (err) return err; err = sys_sigaddset(set, SIGINT); if (err) return err; /* Timer signal */ err = sys_sigaddset(set, SIGALRM); if (err) return err; /* Block updates (forks) */ err = sys_sigaddset(set, SIGCHLD); if (err) return err; /* Deprecated signals */ err = sys_sigaddset(set, SIGUSR1); if (err) return err; err = sys_sigaddset(set, SIGUSR2); if (err) return err; /* Click signal */ err = sys_sigaddset(set, SIGIO); if (err) return err; /* I/O Possible signal for persistent blocks */ err = sys_sigaddset(set, SIGRTMIN); if (err) return err; /* Real-time signals for blocks */ for (sig = SIGRTMIN + 1; sig <= SIGRTMAX; sig++) { err = sys_sigaddset(set, sig); if (err) return err; } /* Block signals for which we are interested in waiting */ err = sys_sigsetmask(set); if (err) return err; if (sleeptime) { err = sys_setitimer(sleeptime); if (err) return err; } err = sys_cloexec(STDIN_FILENO); if (err) return err; /* Setup event I/O for stdin (clicks) */ err = sys_async(STDIN_FILENO, SIGIO); if (err) return err; debug("bar set up"); return 0; } static void bar_teardown(struct bar *bar) { struct block *block = bar->blocks; int err; /* Disable event I/O for blocks (persistent) */ while (block) { if (block->interval == INTERVAL_PERSIST) { err = sys_async(block->out[0], 0); if (err) block_error(block, "failed to disable event I/O"); } block = block->next; } /* Disable event I/O for stdin (clicks) */ err = sys_async(STDIN_FILENO, 0); if (err) error("failed to disable event I/O on stdin"); /* * Unblock signals (so subsequent syscall can be interrupted) * and wait for child processes termination. */ err = sys_sigunblock(&bar->sigset); if (err) error("failed to unblock signals"); err = sys_waitanychild(); if (err) error("failed to wait for any child"); debug("bar tear down"); } static int bar_poll(struct bar *bar) { int sig, fd; int err; err = bar_setup(bar); if (err) return err; /* Initial display (for static blocks and loading labels) */ bar_print(bar); /* First forks (for commands with an interval) */ bar_poll_timed(bar); while (1) { err = sys_sigwaitinfo(&bar->sigset, &sig, &fd); if (err) { /* Hiding the bar may interrupt this system call */ if (err == -EINTR) continue; break; } if (sig == SIGTERM || sig == SIGINT) break; if (sig == SIGALRM) { bar_poll_expired(bar); continue; } if (sig == SIGCHLD) { bar_poll_exited(bar); bar_print(bar); continue; } if (sig == SIGIO) { bar_read(bar); continue; } if (sig == SIGRTMIN) { bar_poll_readable(bar, fd); bar_print(bar); continue; } if (sig > SIGRTMIN && sig <= SIGRTMAX) { bar_poll_signaled(bar, sig - SIGRTMIN); continue; } if (sig == SIGUSR1 || sig == SIGUSR2) { error("SIGUSR{1,2} are deprecated, ignoring."); continue; } debug("unhandled signal %d", sig); } bar_teardown(bar); return err; } static void bar_destroy(struct bar *bar) { struct block *block = bar->blocks; struct block *next; bar_stop(bar); while (block) { next = block->next; block_destroy(block); block = next; } free(bar); } static struct bar *bar_create(bool term) { struct bar *bar; int err; bar = calloc(1, sizeof(struct bar)); if (!bar) return NULL; bar->blocks = block_create(bar, NULL); if (!bar->blocks) { bar_destroy(bar); return NULL; } bar->term = term; err = bar_start(bar); if (err) { bar_destroy(bar); return NULL; } return bar; } static int bar_config_cb(struct map *map, void *data) { struct bar *bar = data; struct block *block = bar->blocks; while (block->next) block = block->next; block->next = block_create(bar, map); map_destroy(map); if (!block->next) return -ENOMEM; return 0; } static void bar_load(struct bar *bar, const char *path) { int err; err = config_load(path, bar_config_cb, bar); if (err) bar_fatal(bar, "Failed to load configuration file %s", path); } int bar_init(bool term, const char *path) { struct bar *bar; int err; bar = bar_create(term); if (!bar) return -ENOMEM; bar_load(bar, path); err = bar_poll(bar); bar_destroy(bar); return err; } i3blocks-1.5/bar.h000066400000000000000000000040221352435032100140010ustar00rootroot00000000000000/* * bar.h - definition of a status line handling functions * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef BAR_H #define BAR_H #include #include "block.h" #include "sys.h" struct bar { struct block *blocks; sigset_t sigset; bool term; }; #define bar_printf(bar, lvl, fmt, ...) \ block_printf(bar->blocks, lvl, "%s" fmt, bar->term ? "TTY " : "", ##__VA_ARGS__) #define bar_fatal(bar, fmt, ...) \ do { \ fatal(fmt, ##__VA_ARGS__); \ bar_printf(bar, LOG_FATAL, "Oops! " fmt ". Increase log level for details.", ##__VA_ARGS__); \ } while (0) #define bar_error(bar, fmt, ...) \ do { \ error(fmt, ##__VA_ARGS__); \ bar_printf(bar, LOG_ERROR, "Error: " fmt, ##__VA_ARGS__); \ } while (0) #define bar_trace(bar, fmt, ...) \ do { \ trace(fmt, ##__VA_ARGS__); \ bar_printf(bar, LOG_TRACE, "Trace: " fmt, ##__VA_ARGS__); \ } while (0) #define bar_debug(bar, fmt, ...) \ do { \ debug(fmt, ##__VA_ARGS__); \ bar_printf(bar, LOG_DEBUG, "Debug: " fmt, ##__VA_ARGS__); \ } while (0) int bar_init(bool term, const char *path); struct map; /* i3bar.c */ int i3bar_read(int fd, size_t count, struct map *map); int i3bar_click(struct bar *bar); int i3bar_print(const struct bar *bar); int i3bar_printf(struct block *block, int lvl, const char *msg); int i3bar_setup(struct block *block); int i3bar_start(struct bar *bar); void i3bar_stop(struct bar *bar); #endif /* BAR_H */ i3blocks-1.5/bash-completion000066400000000000000000000020011352435032100160660ustar00rootroot00000000000000# # bash-completion - bash completion script for i3blocks # Copyright (C) 2019 Gaël Portay # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # _i3blocks() { local cur prev words cword _init_completion || return case $prev in -c) _filedir return ;; -o) COMPREPLY=( $( compgen -W "term" -- "$cur" ) ) return ;; esac COMPREPLY=( $( compgen -W "-c -o -v -h -V" -- "$cur" ) ) return } && complete -F _i3blocks i3blocks i3blocks-1.5/block.c000066400000000000000000000254151352435032100143330ustar00rootroot00000000000000/* * block.c - update of a single status line block * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include "bar.h" #include "block.h" #include "json.h" #include "line.h" #include "log.h" #include "sys.h" const char *block_get(const struct block *block, const char *key) { return map_get(block->env, key); } int block_set(struct block *block, const char *key, const char *value) { return map_set(block->env, key, value); } int block_reset(struct block *block) { map_clear(block->env); return map_copy(block->env, block->config); } int block_for_each(const struct block *block, int (*func)(const char *key, const char *value, void *data), void *data) { return map_for_each(block->env, func, data); } static bool block_is_spawned(struct block *block) { return block->pid > 0; } static int block_setenv(const char *name, const char *value, void *data) { int err; if (!value) value = ""; err = sys_setenv(name, value); if (err) return err; /* Legacy env variables */ if (strcmp(name, "name") == 0) return sys_setenv("BLOCK_NAME", value); if (strcmp(name, "instance") == 0) return sys_setenv("BLOCK_INSTANCE", value); if (strcmp(name, "interval") == 0) return sys_setenv("BLOCK_INTERVAL", value); if (strcmp(name, "button") == 0) return sys_setenv("BLOCK_BUTTON", value); if (strcmp(name, "x") == 0) return sys_setenv("BLOCK_X", value); if (strcmp(name, "y") == 0) return sys_setenv("BLOCK_Y", value); return 0; } static int block_child_env(struct block *block) { return block_for_each(block, block_setenv, NULL); } static int block_stdout(struct block *block) { const char *label, *full_text; int out = block->out[0]; char buf[BUFSIZ]; size_t count; int err; if (block->interval == INTERVAL_PERSIST) count = 1; else count = -1; /* SIZE_MAX */ if (block->format == FORMAT_JSON) err = json_read(out, count, block->env); else err = i3bar_read(out, count, block->env); if (err && err != -EAGAIN) return err; /* Deprecated label */ label = block_get(block, "label"); full_text = block_get(block, "full_text"); if (label && full_text) { snprintf(buf, sizeof(buf), "%s%s", label, full_text); err = block_set(block, "full_text", buf); if (err) return err; } return 0; } int block_update(struct block *block) { int err; /* Reset properties to default before updating from output */ err = block_reset(block); if (err) return err; err = block_stdout(block); if (err) return err; /* Exit code takes precedence over the output */ if (block->code == EXIT_URGENT) { err = block_set(block, "urgent", "true"); if (err) return err; } block_debug(block, "updated successfully"); return 0; } static int block_send_key(const char *key, const char *value, void *data) { struct block *block = data; char buf[BUFSIZ]; int err; if (!json_is_valid(value)) { err = json_escape(value, buf, sizeof(buf)); if (err) return err; value = buf; } dprintf(block->in[1], ",\"%s\":%s", key, value); return 0; } static int block_send_json(struct block *block) { int err; dprintf(block->in[1], "{\"\":\"\""); err = block_for_each(block, block_send_key, block); dprintf(block->in[1], "}\n"); return err; } /* Push data to forked process through the open stdin pipe */ static int block_send(struct block *block) { const char *button = block_get(block, "button"); if (!button) { block_error(block, "no click data to send"); return -EINVAL; } if (!block_is_spawned(block)) { block_error(block, "persistent block not spawned"); return 0; } if (block->format == FORMAT_JSON) return block_send_json(block); dprintf(block->in[1], "%s\n", button); return 0; } int block_click(struct block *block) { block_debug(block, "clicked"); if (block->interval == INTERVAL_PERSIST) return block_send(block); return block_spawn(block); } void block_touch(struct block *block) { unsigned long now; int err; err = sys_gettime(&now); if (err) { block_error(block, "failed to touch block"); return; } if (block->timestamp == now) { block_debug(block, "looping too fast"); return; } block->timestamp = now; } static int block_child_sig(struct block *block) { sigset_t set; int err; /* It'd be safe to assume that all signals are unblocked by default */ err = sys_sigfillset(&set); if (err) return err; return sys_sigunblock(&set); } static int block_child_stdin(struct block *block) { int err; if (block->interval == INTERVAL_PERSIST) { err = sys_close(block->in[1]); if (err) return err; } else { err = sys_open("/dev/null", &block->in[0]); if (err) return err; } err = sys_dup(block->in[0], STDIN_FILENO); if (err) return err; return sys_close(block->in[0]); } static int block_child_stdout(struct block *block) { int err; err = sys_close(block->out[0]); if (err) return err; err = sys_dup(block->out[1], STDOUT_FILENO); if (err) return err; return sys_close(block->out[1]); } static int block_child_exec(struct block *block) { return sys_execsh(block->command); } static int block_child(struct block *block) { int err; err = block_child_env(block); if (err) return err; err = block_child_sig(block); if (err) return err; err = block_child_stdin(block); if (err) return err; err = block_child_stdout(block); if (err) return err; return block_child_exec(block); } static int block_parent_stdin(struct block *block) { /* Close read end of stdin pipe */ if (block->interval == INTERVAL_PERSIST) return sys_close(block->in[0]); return 0; } static int block_parent_stdout(struct block *block) { int err; /* Close write end of stdout pipe */ err = sys_close(block->out[1]); if (err) return err; if (block->interval == INTERVAL_PERSIST) return sys_async(block->out[0], SIGRTMIN); return 0; } static int block_parent(struct block *block) { int err; err = block_parent_stdin(block); if (err) return err; err = block_parent_stdout(block); if (err) return err; block_debug(block, "forked child %d", block->pid); return 0; } static int block_fork(struct block *block) { int err; err = sys_fork(&block->pid); if (err) return err; if (block->pid == 0) { err = block_child(block); if (err) sys_exit(EXIT_ERR_INTERNAL); } return block_parent(block); } static int block_open(struct block *block) { int err; err = sys_pipe(block->out); if (err) return err; if (block->interval == INTERVAL_PERSIST) return sys_pipe(block->in); return 0; } int block_spawn(struct block *block) { int err; if (!block->command) { block_debug(block, "no command, skipping"); return 0; } if (block_is_spawned(block)) { block_debug(block, "process already spawned"); return 0; } err = block_open(block); if (err) return err; return block_fork(block); } static int block_wait(struct block *block) { int err; if (block->pid <= 0) { block_debug(block, "not spawned yet"); return -EAGAIN; } err = sys_waitpid(block->pid, &block->code); if (err) return err; block_debug(block, "process %d exited with %d", block->pid, block->code); /* Process successfully reaped, reset the block PID */ block->pid = 0; if (block->code == EXIT_ERR_INTERNAL) return -ECHILD; return 0; } void block_close(struct block *block) { int err; /* Invalidate descriptors to avoid misdetection after reassignment */ if (block->interval == INTERVAL_PERSIST) { err = sys_close(block->in[1]); if (err) block_error(block, "failed to close stdin"); block->in[1] = -1; } err = sys_close(block->out[0]); if (err) block_error(block, "failed to close stdout"); block->out[0] = -1; } int block_reap(struct block *block) { int err; err = block_wait(block); if (err) { if (err == -EAGAIN) return 0; block_error(block, "Internal error"); return err; } switch (block->code) { case 0: case EXIT_URGENT: break; case 126: block_error(block, "Command '%s' not executable", block->command); break; case 127: block_error(block, "Command '%s' not found or missing dependency", block->command); break; default: block_error(block, "Command '%s' exited unexpectedly with code %d", block->command, block->code); break; } return 0; } static int i3blocks_setup(struct block *block) { const char *value; value = map_get(block->config, "command"); if (value && *value != '\0') block->command = value; value = map_get(block->config, "interval"); if (!value) block->interval = 0; else if (strcmp(value, "once") == 0) block->interval = INTERVAL_ONCE; else if (strcmp(value, "repeat") == 0) block->interval = INTERVAL_REPEAT; else if (strcmp(value, "persist") == 0) block->interval = INTERVAL_PERSIST; else block->interval = atoi(value); value = map_get(block->config, "format"); if (value && strcmp(value, "json") == 0) block->format = FORMAT_JSON; else block->format = FORMAT_RAW; value = map_get(block->config, "signal"); if (!value) block->signal = 0; else block->signal = atoi(value); return 0; } int block_setup(struct block *block) { int err; err = i3bar_setup(block); if (err) return err; err = i3blocks_setup(block); if (err) return err; err = block_reset(block); if (err) return err; block_debug(block, "new block"); return 0; } void block_destroy(struct block *block) { map_destroy(block->config); map_destroy(block->env); free(block->name); free(block); } struct block *block_create(struct bar *bar, const struct map *config) { struct block *block; int err; block = calloc(1, sizeof(struct block)); if (!block) return NULL; block->bar = bar; block->config = map_create(); if (!block->config) { block_destroy(block); return NULL; } if (config) { err = map_copy(block->config, config); if (err) { block_destroy(block); return NULL; } } block->env = map_create(); if (!block->env) { block_destroy(block); return NULL; } return block; } void block_printf(struct block *block, int lvl, const char *fmt, ...) { char buf[BUFSIZ]; va_list ap; int err; if (lvl > log_level) return; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); err = i3bar_printf(block, lvl, buf); if (err) fatal("failed to format message for block %s: %s", block->name, buf); } i3blocks-1.5/block.h000066400000000000000000000055211352435032100143340ustar00rootroot00000000000000/* * block.h - definition of a block * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef BLOCK_H #define BLOCK_H #include #include "bar.h" #include "log.h" #include "map.h" #define INTERVAL_ONCE -1 #define INTERVAL_REPEAT -2 #define INTERVAL_PERSIST -3 #define FORMAT_RAW 0 #define FORMAT_JSON 1 /* Block command exit codes */ #define EXIT_URGENT '!' /* 33 */ #define EXIT_ERR_INTERNAL 66 struct block { const struct bar *bar; struct map *config; struct map *env; bool tainted; /* Pretty name for log messages */ char *name; /* Shortcuts */ const char *command; int interval; int signal; unsigned format; /* Runtime info */ unsigned long timestamp; int in[2]; int out[2]; int code; pid_t pid; struct block *next; }; struct block *block_create(struct bar *bar, const struct map *config); void block_destroy(struct block *block); int block_reset(struct block *block); const char *block_get(const struct block *block, const char *key); int block_set(struct block *block, const char *key, const char *value); int block_for_each(const struct block *block, int (*func)(const char *key, const char *value, void *data), void *data); void block_printf(struct block *block, int lvl, const char *fmt, ...); #define block_fatal(block, fmt, ...) \ do { \ fatal("[%s] " fmt, block->name, ##__VA_ARGS__); \ block_printf(block, LOG_FATAL, "Oops! " fmt, ##__VA_ARGS__); \ } while (0) #define block_error(block, fmt, ...) \ do { \ error("[%s] " fmt, block->name, ##__VA_ARGS__); \ block_printf(block, LOG_ERROR, "Error: " fmt, ##__VA_ARGS__); \ } while (0) #define block_trace(block, fmt, ...) \ do { \ trace("[%s] " fmt, block->name, ##__VA_ARGS__); \ block_printf(block, LOG_TRACE, fmt, ##__VA_ARGS__); \ } while (0) #define block_debug(block, fmt, ...) \ do { \ debug("[%s] " fmt, block->name, ##__VA_ARGS__); \ block_printf(block, LOG_DEBUG, fmt, ##__VA_ARGS__); \ } while (0) int block_setup(struct block *block); int block_click(struct block *block); int block_spawn(struct block *block); void block_touch(struct block *block); int block_reap(struct block *block); int block_update(struct block *block); void block_close(struct block *block); #endif /* BLOCK_H */ i3blocks-1.5/config.c000066400000000000000000000076541352435032100145130ustar00rootroot00000000000000/* * config.c - parsing of the configuration file * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include "config.h" #include "ini.h" #include "log.h" #include "map.h" #include "sys.h" #ifndef SYSCONFDIR #define SYSCONFDIR "/etc" #endif struct config { struct map *section; struct map *global; config_cb_t *cb; void *data; }; static int config_finalize(struct config *conf) { int err; if (conf->section) { if (conf->cb) { err = conf->cb(conf->section, conf->data); if (err) return err; } conf->section = NULL; } return 0; } static int config_reset(struct config *conf) { conf->section = map_create(); if (!conf->section) return -ENOMEM; if (conf->global) return map_copy(conf->section, conf->global); return 0; } static int config_set(struct config *conf, const char *key, const char *value) { struct map *map = conf->section; if (!map) { if (!conf->global) { conf->global = map_create(); if (!conf->global) return -ENOMEM; } map = conf->global; } return map_set(map, key, value); } static int config_ini_section_cb(char *section, void *data) { int err; err = config_finalize(data); if (err) return err; err = config_reset(data); if (err) return err; return config_set(data, "name", section); } static int config_ini_property_cb(char *key, char *value, void *data) { return config_set(data, key, value); } static int config_read(struct config *conf, int fd) { int err; err = ini_read(fd, -1, config_ini_section_cb, config_ini_property_cb, conf); if (err && err != -EAGAIN) return err; return config_finalize(conf); } static int config_open(struct config *conf, const char *path) { size_t plen = strlen(path); char pname[plen + 1]; char *dname; int err; int fd; debug("try file %s", path); err = sys_open(path, &fd); if (err) return err; strcpy(pname, path); dname = dirname(pname); err = sys_chdir(dname); if (err) { error("failed to change directory to %s", dname); return err; } debug("changed directory to %s", dname); err = config_read(conf, fd); sys_close(fd); if (conf->global) map_destroy(conf->global); return err; } int config_load(const char *path, config_cb_t *cb, void *data) { const char * const home = sys_getenv("HOME"); const char * const xdg_home = sys_getenv("XDG_CONFIG_HOME"); const char * const xdg_dirs = sys_getenv("XDG_CONFIG_DIRS"); struct config conf = { .data = data, .cb = cb, }; char buf[PATH_MAX]; int err; /* command line config file? */ if (path) return config_open(&conf, path); /* user config file? */ if (home) { if (xdg_home) snprintf(buf, sizeof(buf), "%s/i3blocks/config", xdg_home); else snprintf(buf, sizeof(buf), "%s/.config/i3blocks/config", home); err = config_open(&conf, buf); if (err != -ENOENT) return err; snprintf(buf, sizeof(buf), "%s/.i3blocks.conf", home); err = config_open(&conf, buf); if (err != -ENOENT) return err; } /* system config file? */ if (xdg_dirs) snprintf(buf, sizeof(buf), "%s/i3blocks/config", xdg_dirs); else snprintf(buf, sizeof(buf), "%s/xdg/i3blocks/config", SYSCONFDIR); err = config_open(&conf, buf); if (err != -ENOENT) return err; snprintf(buf, sizeof(buf), "%s/i3blocks.conf", SYSCONFDIR); return config_open(&conf, buf); } i3blocks-1.5/config.h000066400000000000000000000016461352435032100145130ustar00rootroot00000000000000/* * config.h - configuration file header * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef CONFIG_H #define CONFIG_H #include "map.h" typedef int config_cb_t(struct map *map, void *data); int config_load(const char *path, config_cb_t *cb, void *data); #endif /* CONFIG_H */ i3blocks-1.5/configure.ac000066400000000000000000000007571352435032100153650ustar00rootroot00000000000000AC_INIT([i3blocks], 1.5) AC_CONFIG_AUX_DIR([build-aux]) AM_INIT_AUTOMAKE(foreign) AC_PROG_CC AC_CONFIG_HEADERS([i3blocks-config.h]) PKG_CHECK_MODULES([BASH_COMPLETION], [bash-completion >= 2.0], [BASH_COMPLETION_DIR="$(pkg-config --variable=completionsdir bash-completion)"], [BASH_COMPLETION_DIR="$datadir/bash-completion/completions"] ) AC_SUBST([BASH_COMPLETION_DIR]) AM_CONDITIONAL([ENABLE_BASH_COMPLETION],[test "xBASH_COMPLETION_DIR" != "x"]) AC_CONFIG_FILES([ Makefile ]) AC_OUTPUT i3blocks-1.5/docs/000077500000000000000000000000001352435032100140165ustar00rootroot00000000000000i3blocks-1.5/docs/README.adoc000066400000000000000000000343351352435032100156130ustar00rootroot00000000000000:progname: i3blocks :toc: = {progname} A feed generator for text based status bars {progname} executes your command lines and generates a status line from their output. Commands are scheduled at configured time intervals, upon signal reception or on clicks. The generated line is meant to be displayed by the link:https://i3wm.org[i3] window manager through its i3bar component, as an alternative to i3status. {progname} is meant to be highly flexible but intuitive. No library package is required, just output what your status bar expects, from your favorite programming language and your preferred format. == Example [source,ini] ---- [click] full_text=Click me! command=echo "Got clicked with button $button" color=#F79494 # Guess the weather hourly [weather] command=curl -Ss 'https://wttr.in?0&T&Q' | cut -c 16- | head -2 | xargs echo interval=3600 color=#A4C2F4 # Query my default IP address only on startup [ip] command=hostname -i | awk '{ print "IP:" $1 }' interval=once color=#91E78B # Update time every 5 seconds [time] command=date +%T interval=5 ---- == Installation {progname} is already packaged for: * Archlinux: link:https://www.archlinux.org/packages/community/x86_64/i3blocks[i3blocks] in the community repository and link:https://aur.archlinux.org/packages/i3blocks-git[i3blocks-git] in the AUR * Gentoo: link:https://packages.gentoo.org/packages/x11-misc/i3blocks[x11-misc/i3blocks] * Debian: link:https://packages.debian.org/i3blocks[i3blocks] * Ubuntu: link:http://packages.ubuntu.com/i3blocks[i3blocks] * Fedora (COPR): link:https://copr.fedorainfracloud.org/coprs/wyvie/i3blocks[i3blocks] * Void Linux: link:https://github.com/void-linux/void-packages/tree/master/srcpkgs/i3blocks[i3blocks] Or can be installed from source with: [source] ---- git clone https://github.com/vivien/i3blocks cd i3blocks ./autogen.sh ./configure make make install ---- == Getting started In your i3 configuration file, define {progname} as the link:https://i3wm.org/docs/userguide.html#status_command[status line command] of a new bar block: [source] ---- bar { status_command i3blocks } ---- IMPORTANT: The project's repository does not include default scripts anymore. For the lazy, you can start from link:https://github.com/vivien/i3blocks-contrib[our collection of scripts]: [source] ---- git clone https://github.com/vivien/i3blocks-contrib ~/.config/i3blocks cd !$ cp config.example config ---- For the picky, you can start a configuration file in one of the following preferred paths: * `$XDG_CONFIG_HOME/i3blocks/config` (or `~/.config/i3blocks/config`); * `~/.i3blocks.conf`; * `$XDG_CONFIG_DIRS/i3blocks/config` (or `/etc/xdg/i3blocks/config`); * `/etc/i3blocks.conf`; * or any other path that you will specify using the `-c` option. NOTE: By default `/etc` is prefixed by `/usr/local` when you installed from source. Use the example above or dig in the configuration details below. Now restart i3 with `i3-msg restart` to apply your changes. == Blocks The configuration file uses a simplified INI file format: [source,ini] ---- # Properties not preceded by a section are considered global # and merged into every section declarations. foo=bar [block1] baz=qux # This is a comment [block2] quux= quuz ---- In this example, _block2_ contains a _foo_ property equal to _"bar"_ and a _quux_ property equal to _" quuz"_ (including the leading space). Everything after the equal sign will be part of the value, thus inline comments won't be stripped out. At runtime, these properties are simply variables, that are passed along to the status bar program when printing is necessary. However on startup, {progname} checks some optional properties to eventually setup the scheduling of a command. If a block specifies a command, then all of its properties are passed as environment variables at execution, which means that the _foo=bar_ property will be available from a shell script with `$foo`. The output of the command is used to update the values of these variables. The values are reset to default (as defined in the configuration file) before the update, so that blocks get a consistent behavior at each execution. == i3bar properties In order to use {progname} with i3, its status bar command _i3bar_ expects specific keys. To know how to customize the blocks of your status line, you must refer to the link:https://i3wm.org/docs/i3bar-protocol.html#_blocks_in_detail[i3bar protocol]. NOTE: _full_text_ is the only mandatory key, the block will be skipped if this key is absent or empty. Unless overriden, the section name of the block defines the _name_ key. Below are examples of static blocks interacting with _i3bar_. [source,ini] ---- [simple] full_text=This is a looong white on red text short_text=Short white on red text background=#FF0000 color=#FFFFFF # Block with a fixed width [aligned] full_text=Here. min_width=100 align=center # Fancy text with multiple colors and shapes [funky] full_text=Roses and violets! markup=pango ---- == {progname} properties These are some special properties checked by {progname} on startup. These will be considered as simple variables at runtime. === command The optional _command_ property specifies a command line to be executed with `sh -c`. The command can be relative to the configuration file where it is defined. If the command outputs some text, it is used to update the block. An exit code of 0 means success. A special exit code of _33_ will set the _urgent_ i3bar key to true. Any other exit code will raise an error. [source,ini] ---- [pacman] full_text=c · command=echo "· ${full_text~~}" color=#FFFF00 ---- === interval The optional _interval_ property specifies when the command must be scheduled. A positive value represents the number of seconds to wait between exectutions. [source,ini] ---- # Print seconds since 1970-01-01 [epoch] command=date +%s interval=1 ---- A value of _0_ (or undefined) means the command is not timed whatsoever and will not be executed on startup. This is useful to trigger the command only on user input (e.g. signal or click), not before. [source,ini] ---- # Restart i3 on click [restart] full_text=Restart command=i3-msg -q restart #interval=0 ---- The interval value _once_ (or _-1_) will schedule the command only on startup. This tells {progname} not to schedule the command again on a time basis. But events such as signals and clicks will execute the command again of course. [source,ini] ---- # Fetch the public IP address only on startup [public-ip] command=wget -qO - icanhazip.com interval=once ---- The interval value _repeat_ (or _-2_) will respawn the command as soon as it terminates. This is convenient for blocking programs which exit as soon as the awaited event arises. NOTE: clicks are not supported with this value, since such commands are unlikely to expect data on their standard input. [source,ini] ---- # Print the last command entered in Bash [history] command=inotifywait -qq -e close_write ~/.bash_history; tail -1 ~/.bash_history interval=repeat ---- The interval value _persist_ (or _-3_) expects the command to be an infinite loop. Each line of the output will trigger an update of the block. [source,ini] ---- [window] command=xtitle -s interval=persist ---- === signal Blocks can be scheduled upon reception of a real-time signal (think prioritized and queueable). The range of available signal numbers is _1_ to _N_, where _SIGRTMIN+N = SIGRTMAX_. (Note: there are 31 real-time signals in Linux.) [source,ini] ---- [caps-lock] command=xset -q | grep Caps | awk '{ print $2, $3, $4 }' interval=once signal=10 ---- This example block above will be scheduled once {progname} handles the _SIGRTMIN+10_ signal. This can be sent directly from an i3 binding on Caps Lock release with the following configuration: [source] ---- bindsym --release Caps_Lock exec pkill -SIGRTMIN+10 i3blocks ---- === format There are several formats supported to specify which variables {progname} must update. Some favor simplicity over flexibility but thus can be limited. When undefined, a raw format is assumed. Each line of the output corresponds to an i3bar key, in the order of definition found in the link:https://i3wm.org/docs/i3bar-protocol.html#_blocks_in_detail[i3bar protocol]: * the 1st line updates the _full_text_; * the 2nd line updates the _short_text_; * the 3rd line updates the _color_; * the 4th line updates the _background_. Excess lines are considered an error. Below is an example of a simple battery script. .battery.sh [source,sh] ---- #!/bin/bash BAT=$(acpi -b | grep -E -o '[0-9][0-9]?%') # Full and short texts echo "Battery: $BAT" echo "BAT: $BAT" # Set urgent flag below 5% or use orange below 20% [ ${BAT%?} -le 5 ] && exit 33 [ ${BAT%?} -le 20 ] && echo "#FF8000" exit 0 ---- [source,ini] ---- [battery] command=battery.sh interval=10 ---- The _json_ format can update any variable. [source,ini] ---- [counter] _count=0 command=printf '{"full_text":"Counter: %s", "_count":%d}\n' $_count $((_count + 1)) format=json interval=1 ---- == Click When you click on a block, data such as the button number and coordinates are merged into the block variables. NOTE: _name_ and _instance_ are the two keys used by i3bar to identify a block. The data sent on click is detailed in the link:https://i3wm.org/docs/i3bar-protocol.html#_click_events[i3bar protocol]. If the block command isn't already spawned, it is executed again. [source,ini] ---- # Print click data [clickme] align=center full_text=Click me! min_width=Button=? x=? y=? command=echo "Button=$button x=$x y=$y" ---- If the value of the block's interval is _persist_, then the data is written on the command standard input, one line per click. What gets written depends on the block's format. The raw format only gets the click button. The JSON format gets all block variables. [source,ini] ---- [click-loop] full_text=Click me! command=while read button; do echo "Got click $button"; done interval=persist [click-loop-json] full_text=Click me! command=ruby -r json -n -e '$_ = JSON.parse($_)' -e '$_["full_text"] = "Click %s at (%d,%d)" % $_.slice("button", "x", "y").values' -e 'puts JSON.dump($_)' -e 'STDOUT.flush' interval=persist format=json ---- == FAQ Frequently Asked Questions and Troubleshooting. [qanda] What is a blocklet?:: A blocklet is the configuration of a single block, part of the status line. There are plenty listed in the link:https://vivien.github.io/i3blocks/blocklets[blocklets page]. Can I use my own variables?:: Yes, any variable defined in the block is exported as is to the environment of its command. The `foo=bar` property can be accessed with `$foo` from a shell script, `ENV["foo"]` from Ruby, and so on. + The IEEE and The Open Group state that link:http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html["The name space of environment variable names containing lowercase letters is reserved for applications."]. i3bar suggests to prefix your own keys with an underscore (`_`), but it might be more intuitive to use uppercase environment variables, so it is your call to define your own naming convention. Why `$foo` doesn't work from the configuration file?:: {progname} does not do string interpolation of any sort. The definitions found in the configuration file are just raw strings, this means that `bar=$baz` defines a _bar_ variable equal to literally `$baz` (a dollar sign followed by "baz"). + String interpolation does work in the _command_ property though, since it is interpreted by a shell which has access to the environment variables. How can I simulate a button?:: This is pretty straightforward actually. Just make sure not to override the _full_text_, for example: + [source,ini] ---- [calc-button] full_text=Calculator command=gnome-calculator >/dev/null ---- Can a block start a GUI application?:: Sure. And if you do not wish your command to block until the application is closed, ask i3 to start it for you with `i3-msg -q exec myapp`. Why Pango isn't working?:: The Pango markup requires a Pango font. Make sure you configured link:https://i3wm.org/docs/userguide.html#_font[i3bar] to use a Pango font. For example: + [source] ---- font pango:Inconsolata, Icons 12 ---- Why is the output from my persistent block not displayed?:: Make sure to flush stdout, for example: + [source,ini] ---- [ruby-loop] full_text=Click me command=ruby -p -e '$_.prepend("Got button ")' -e 'STDOUT.flush' interval=persist ---- Can I use a time interval below 1 second?:: No, the time unit for interval is the second. + But even though I wouldn't recommend it, you can still update faster than that with loops: + [source,ini] ---- [nano1] command=sleep .5; date +%N interval=repeat [nano2] command=while sleep .5; do date +%N; done interval=persist ---- Can I change the block separator?:: Not with {progname} itself, separators are drawn by i3bar. You can change the _separator_symbol_ in the link:https://i3wm.org/docs/userguide.html#_custom_separator_symbol[i3bar configuration]. + Alternatively, you can define static blocks as custom separators in your {progname} configuration. In the example below, we use the _"\xe3\x80\x89"_ UTF-8 character: + [source,ini] ---- # Define the custom separator in global properties for boilerplate full_text=〉 align=center color=#666666 separator=false separator_block_width=7 [time] instance=la TZ=America/Los_Angeles command=date +%T interval=5 [separator] [time] instance=nc TZ=Pacific/Noumea command=date +%T interval=5 [separator] [time] instance=mtl TZ=America/Montreal command=date +%T interval=5 ---- == Debugging The log level can be increased with the `-v` option. If your window manager (and thus this program) is run via systemd, you can inspect the program outputs with `journalctl -t -f`. You may also use this in conjonction with running the program manually with `systemd-cat -t ./i3blocks`. Alternatively you can redirect the standard output and error streams from the program invokation with: [source] ---- bar { status_command 2>/tmp/i3blocks.err /path/to/i3blocks -vvv -c /path/to/config | tee /tmp/i3blocks.out } ---- And inspect the log with `tail -f /tmp/i3blocks.err`. See the link:{progname}.1{outfilesuffix}[manpage] for details about the command line options and {progname} usage. == License {progname} is Copyright (C) Vivien Didelot See the file COPYING for information of licensing and distribution. i3blocks-1.5/docs/Rakefile000066400000000000000000000007331352435032100154660ustar00rootroot00000000000000require 'asciidoctor' task :default do Asciidoctor.convert_file 'README.adoc', safe: :unsafe, to_file: 'index.html', attributes: { 'reproducible' => true, 'toc' => 'left' } Asciidoctor.convert_file 'blocklets.adoc', safe: :unsafe, attributes: { 'reproducible' => true } Asciidoctor.convert_file 'i3blocks.1.adoc', safe: :unsafe, attributes: { 'reproducible' => true, 'toc' => 'left' } Asciidoctor.convert_file 'i3blocks.1.adoc', safe: :unsafe, backend: :manpage end i3blocks-1.5/docs/blocklets-docinfo.html000066400000000000000000000003051352435032100203030ustar00rootroot00000000000000 i3blocks-1.5/docs/blocklets.adoc000066400000000000000000000007251352435032100166340ustar00rootroot00000000000000= Blocklets :docinfo: This page lists blocklets found in community projects. TIP: Have your blocklet(s) shown in that list! + Your repository will be included in the page automatically if it has both the **i3blocks** and **blocklet** topics. + Data is fetch from link:https://github.com/search?q=topic:i3blocks+topic:blocklet[the official Github search page]. IMPORTANT: This page needs some front-end love 💔 [pass]
i3blocks-1.5/docs/blocklets.css000066400000000000000000000014131352435032100165110ustar00rootroot00000000000000.card-container { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 30px; } .card { display: grid; grid-template-columns: 1fr 3fr 1fr; grid-template-rows: 1fr 1fr; grid-gap: 8px; grid-template-areas: "top-left top-center top-right" "bottom bottom bottom"; } .card-top-left { grid-area: top-left; } .card-top-center { grid-area: top-center; } .card-top-right { grid-area: top-right; } .card-bottom { grid-area: bottom; } .repo { width: 400px; height: 150px; border-radius: 5px; border: 1px solid #d3d3d3; padding: 8px; color: #555; } .repo p { margin: 0; } .repo-owner-avatar { height: 64px; width: 64px; } .repo-stars, .repo-language, .repo-last-update { font-size: 12px; } .repo-stars span { font-size: 24px; } i3blocks-1.5/docs/blocklets.html000066400000000000000000000757271352435032100167100ustar00rootroot00000000000000 Blocklets

This page lists blocklets found in community projects.

Tip
Have your blocklet(s) shown in that list!
Your repository will be included in the page automatically if it has both the i3blocks and blocklet topics.
Data is fetch from the official Github search page.
Important
This page needs some front-end love 💔
i3blocks-1.5/docs/blocklets.js000066400000000000000000000022241352435032100163360ustar00rootroot00000000000000document.onreadystatechange = function () { if (document.readyState === 'complete') { var repos = document.querySelector('#repos'); var request = new XMLHttpRequest(); request.open('GET', "https://api.github.com/search/repositories?q=topic:i3blocks+topic:blocklet"); request.onload = function () { var data = JSON.parse(request.responseText); data.items.forEach(function (repo) { repos.innerHTML += `
${ repo.owner.login }

${ repo.name }

Include ${ repo.language } code

Updated ${ moment(repo.updated_at).fromNow() }

${ repo.stargazers_count }

${ repo.description }

`; }); } request.send(); } } i3blocks-1.5/docs/i3blocks.1000066400000000000000000000055601352435032100156170ustar00rootroot00000000000000'\" t .\" Title: i3blocks .\" Author: [see the "AUTHOR(S)" section] .\" Generator: Asciidoctor 2.0.10 .\" Date: 2019-08-12 .\" Manual: \ \& .\" Source: \ \& .\" Language: English .\" .TH "I3BLOCKS" "1" "2019-08-12" "\ \&" "\ \&" .ie \n(.g .ds Aq \(aq .el .ds Aq ' .ss \n[.ss] 0 .nh .ad l .de URL \fI\\$2\fP <\\$1>\\$3 .. .als MTO URL .if \n[.g] \{\ . mso www.tmac . am URL . ad l . . . am MTO . ad l . . . LINKSTYLE blue R < > .\} .SH "NAME" i3blocks \- A feed generator for text based status bars .SH "SYNOPSIS" .sp \fBi3blocks\fP [\fIOPTION\fP]... .SH "DESCRIPTION" .sp The i3blocks(1) command generates a status line for i3bar(1). It schedules command lines described in a simple configuration file at specified time intervals, upon signal reception or on clicks. .SH "OPTIONS" .sp \fB\-h\fP .RS 4 Show the help message and exit. .RE .sp \fB\-c\fP \fICONFIGFILE\fP .RS 4 Specifies an alternate configuration file path. .RE .sp \fB\-v\fP .RS 4 Increase log level. This option is a cumulative. By default only fatal errors are shown in the status bar. Passing this option once will show error messages as well. Using \fB\-vv\fP and more will show more debug output on standard error. .RE .SH "CONFIGURATION" .sp i3blocks must be defined as the status line command of the \fBbar\fP block described in your i3(1) configuration file: .sp .if n .RS 4 .nf bar { status_command i3blocks } .fi .if n .RE .sp By default, i3blocks looks for a configuration file in the following order (note that /etc may be prefixed with /usr/local depending on the compilation flags): .sp .RS 4 .ie n \{\ \h'-04' 1.\h'+01'\c .\} .el \{\ . sp -1 . IP " 1." 4.2 .\} \fI$XDG_CONFIG_HOME/i3blocks/config\fP (or \fI~/.config/i3blocks/config\fP) .RE .sp .RS 4 .ie n \{\ \h'-04' 2.\h'+01'\c .\} .el \{\ . sp -1 . IP " 2." 4.2 .\} \fI~/.i3blocks.conf\fP .RE .sp .RS 4 .ie n \{\ \h'-04' 3.\h'+01'\c .\} .el \{\ . sp -1 . IP " 3." 4.2 .\} \fI$XDG_CONFIG_DIRS/i3blocks/config\fP (or \fI/etc/xdg/i3blocks/config\fP) .RE .sp .RS 4 .ie n \{\ \h'-04' 4.\h'+01'\c .\} .el \{\ . sp -1 . IP " 4." 4.2 .\} \fI/etc/i3blocks.conf\fP .RE .sp For the content of the configuration file, please refer to the i3blocks website: \c .URL "https://vivien.github.io/i3blocks" "" "" .SH "SEE ALSO" .sp i3(1), i3bar(1), i3status(1) .SH "AUTHORS" .sp i3blocks is written by Vivien Didelot and other contributors. .SH "RESOURCES" .sp \fBProject web site:\fP \c .URL "https://vivien.github.io/i3blocks" "" "" .sp \fBGit source repository and issue tracker:\fP \c .URL "https://github.com/vivien/i3blocks" "" "" .sp \fBOfficial collection of scripts for i3blocks:\fP \c .URL "https://github.com/vivien/i3blocks\-contrib" "" "" .sp \fBi3bar protocol:\fP \c .URL "http://i3wm.org/docs/i3bar\-protocol.html" "" "" .SH "COPYING" .sp Copyright \(co Vivien Didelot. Free use of this software is granted under the terms of the \fIGPLv3+\fP License.i3blocks-1.5/docs/i3blocks.1.adoc000066400000000000000000000035751352435032100165300ustar00rootroot00000000000000:progname: i3blocks = {progname}(1) == NAME {progname} - A feed generator for text based status bars == SYNOPSIS *{progname}* [_OPTION_]... == DESCRIPTION The {progname}(1) command generates a status line for i3bar(1). It schedules command lines described in a simple configuration file at specified time intervals, upon signal reception or on clicks. == OPTIONS *-h*:: Show the help message and exit. *-c* _CONFIGFILE_:: Specifies an alternate configuration file path. *-v*:: Increase log level. This option is a cumulative. By default only fatal errors are shown in the status bar. Passing this option once will show error messages as well. Using *-vv* and more will show more debug output on standard error. == CONFIGURATION {progname} must be defined as the status line command of the *bar* block described in your i3(1) configuration file: [source] ---- bar { status_command i3blocks } ---- By default, {progname} looks for a configuration file in the following order (note that /etc may be prefixed with /usr/local depending on the compilation flags): . _$XDG_CONFIG_HOME/i3blocks/config_ (or _~/.config/i3blocks/config_) . _~/.i3blocks.conf_ . _$XDG_CONFIG_DIRS/i3blocks/config_ (or _/etc/xdg/i3blocks/config_) . _/etc/i3blocks.conf_ For the content of the configuration file, please refer to the i3blocks website: https://vivien.github.io/i3blocks == SEE ALSO i3(1), i3bar(1), i3status(1) == AUTHORS {progname} is written by Vivien Didelot and other contributors. == RESOURCES *Project web site:* https://vivien.github.io/i3blocks *Git source repository and issue tracker:* https://github.com/vivien/i3blocks *Official collection of scripts for {progname}:* https://github.com/vivien/i3blocks-contrib *i3bar protocol:* http://i3wm.org/docs/i3bar-protocol.html == COPYING Copyright (C) Vivien Didelot. Free use of this software is granted under the terms of the _GPLv3+_ License. i3blocks-1.5/docs/i3blocks.1.html000066400000000000000000001046011352435032100165560ustar00rootroot00000000000000 i3blocks(1)

NAME

i3blocks - A feed generator for text based status bars

SYNOPSIS

i3blocks [OPTION]…​

DESCRIPTION

The i3blocks(1) command generates a status line for i3bar(1). It schedules command lines described in a simple configuration file at specified time intervals, upon signal reception or on clicks.

OPTIONS

-h

Show the help message and exit.

-c CONFIGFILE

Specifies an alternate configuration file path.

-v

Increase log level. This option is a cumulative. By default only fatal errors are shown in the status bar. Passing this option once will show error messages as well. Using -vv and more will show more debug output on standard error.

CONFIGURATION

i3blocks must be defined as the status line command of the bar block described in your i3(1) configuration file:

bar {
  status_command i3blocks
}

By default, i3blocks looks for a configuration file in the following order (note that /etc may be prefixed with /usr/local depending on the compilation flags):

  1. $XDG_CONFIG_HOME/i3blocks/config (or ~/.config/i3blocks/config)

  2. ~/.i3blocks.conf

  3. $XDG_CONFIG_DIRS/i3blocks/config (or /etc/xdg/i3blocks/config)

  4. /etc/i3blocks.conf

For the content of the configuration file, please refer to the i3blocks website: https://vivien.github.io/i3blocks

SEE ALSO

i3(1), i3bar(1), i3status(1)

AUTHORS

i3blocks is written by Vivien Didelot and other contributors.

RESOURCES

Git source repository and issue tracker: https://github.com/vivien/i3blocks

Official collection of scripts for i3blocks: https://github.com/vivien/i3blocks-contrib

COPYING

Copyright © Vivien Didelot. Free use of this software is granted under the terms of the GPLv3+ License.

i3blocks-1.5/docs/index.html000066400000000000000000001510311352435032100160140ustar00rootroot00000000000000 i3blocks

A feed generator for text based status bars

i3blocks executes your command lines and generates a status line from their output. Commands are scheduled at configured time intervals, upon signal reception or on clicks.

The generated line is meant to be displayed by the i3 window manager through its i3bar component, as an alternative to i3status.

i3blocks is meant to be highly flexible but intuitive. No library package is required, just output what your status bar expects, from your favorite programming language and your preferred format.

Example

[click]
full_text=Click me!
command=echo "Got clicked with button $button"
color=#F79494

# Guess the weather hourly
[weather]
command=curl -Ss 'https://wttr.in?0&T&Q' | cut -c 16- | head -2 | xargs echo
interval=3600
color=#A4C2F4

# Query my default IP address only on startup
[ip]
command=hostname -i | awk '{ print "IP:" $1 }'
interval=once
color=#91E78B

# Update time every 5 seconds
[time]
command=date +%T
interval=5

Installation

i3blocks is already packaged for:

Or can be installed from source with:

git clone https://github.com/vivien/i3blocks
cd i3blocks
./autogen.sh
./configure
make
make install

Getting started

In your i3 configuration file, define i3blocks as the status line command of a new bar block:

bar {
  status_command i3blocks
}
Important
The project’s repository does not include default scripts anymore.

For the lazy, you can start from our collection of scripts:

git clone https://github.com/vivien/i3blocks-contrib ~/.config/i3blocks
cd !$
cp config.example config

For the picky, you can start a configuration file in one of the following preferred paths:

  • $XDG_CONFIG_HOME/i3blocks/config (or ~/.config/i3blocks/config);

  • ~/.i3blocks.conf;

  • $XDG_CONFIG_DIRS/i3blocks/config (or /etc/xdg/i3blocks/config);

  • /etc/i3blocks.conf;

  • or any other path that you will specify using the -c option.

Note
By default /etc is prefixed by /usr/local when you installed from source.

Use the example above or dig in the configuration details below.

Now restart i3 with i3-msg restart to apply your changes.

Blocks

The configuration file uses a simplified INI file format:

# Properties not preceded by a section are considered global
# and merged into every section declarations.
foo=bar

[block1]
baz=qux

# This is a comment
[block2]
quux= quuz

In this example, block2 contains a foo property equal to "bar" and a quux property equal to " quuz" (including the leading space). Everything after the equal sign will be part of the value, thus inline comments won’t be stripped out.

At runtime, these properties are simply variables, that are passed along to the status bar program when printing is necessary. However on startup, i3blocks checks some optional properties to eventually setup the scheduling of a command.

If a block specifies a command, then all of its properties are passed as environment variables at execution, which means that the foo=bar property will be available from a shell script with $foo. The output of the command is used to update the values of these variables. The values are reset to default (as defined in the configuration file) before the update, so that blocks get a consistent behavior at each execution.

i3bar properties

In order to use i3blocks with i3, its status bar command i3bar expects specific keys. To know how to customize the blocks of your status line, you must refer to the i3bar protocol.

Note
full_text is the only mandatory key, the block will be skipped if this key is absent or empty.

Unless overriden, the section name of the block defines the name key.

Below are examples of static blocks interacting with i3bar.

[simple]
full_text=This is a looong white on red text
short_text=Short white on red text
background=#FF0000
color=#FFFFFF

# Block with a fixed width
[aligned]
full_text=Here.
min_width=100
align=center

# Fancy text with multiple colors and shapes
[funky]
full_text=<span foreground="red" size="x-large">Roses</span> and <i><span color="#EE37B8">violets</span></i>!
markup=pango

i3blocks properties

These are some special properties checked by i3blocks on startup. These will be considered as simple variables at runtime.

command

The optional command property specifies a command line to be executed with sh -c. The command can be relative to the configuration file where it is defined. If the command outputs some text, it is used to update the block.

An exit code of 0 means success. A special exit code of 33 will set the urgent i3bar key to true. Any other exit code will raise an error.

[pacman]
full_text=c ·
command=echo "· ${full_text~~}"
color=#FFFF00

interval

The optional interval property specifies when the command must be scheduled.

A positive value represents the number of seconds to wait between exectutions.

# Print seconds since 1970-01-01
[epoch]
command=date +%s
interval=1

A value of 0 (or undefined) means the command is not timed whatsoever and will not be executed on startup. This is useful to trigger the command only on user input (e.g. signal or click), not before.

# Restart i3 on click
[restart]
full_text=Restart
command=i3-msg -q restart
#interval=0

The interval value once (or -1) will schedule the command only on startup. This tells i3blocks not to schedule the command again on a time basis. But events such as signals and clicks will execute the command again of course.

# Fetch the public IP address only on startup
[public-ip]
command=wget -qO - icanhazip.com
interval=once

The interval value repeat (or -2) will respawn the command as soon as it terminates. This is convenient for blocking programs which exit as soon as the awaited event arises.

Note
clicks are not supported with this value, since such commands are unlikely to expect data on their standard input.
# Print the last command entered in Bash
[history]
command=inotifywait -qq -e close_write ~/.bash_history; tail -1 ~/.bash_history
interval=repeat

The interval value persist (or -3) expects the command to be an infinite loop. Each line of the output will trigger an update of the block.

[window]
command=xtitle -s
interval=persist

signal

Blocks can be scheduled upon reception of a real-time signal (think prioritized and queueable). The range of available signal numbers is 1 to N, where SIGRTMIN+N = SIGRTMAX. (Note: there are 31 real-time signals in Linux.)

[caps-lock]
command=xset -q | grep Caps | awk '{ print $2, $3, $4 }'
interval=once
signal=10

This example block above will be scheduled once i3blocks handles the SIGRTMIN+10 signal. This can be sent directly from an i3 binding on Caps Lock release with the following configuration:

bindsym --release Caps_Lock exec pkill -SIGRTMIN+10 i3blocks

format

There are several formats supported to specify which variables i3blocks must update. Some favor simplicity over flexibility but thus can be limited.

When undefined, a raw format is assumed. Each line of the output corresponds to an i3bar key, in the order of definition found in the i3bar protocol:

  • the 1st line updates the full_text;

  • the 2nd line updates the short_text;

  • the 3rd line updates the color;

  • the 4th line updates the background.

Excess lines are considered an error. Below is an example of a simple battery script.

battery.sh
#!/bin/bash

BAT=$(acpi -b | grep -E -o '[0-9][0-9]?%')

# Full and short texts
echo "Battery: $BAT"
echo "BAT: $BAT"

# Set urgent flag below 5% or use orange below 20%
[ ${BAT%?} -le 5 ] && exit 33
[ ${BAT%?} -le 20 ] && echo "#FF8000"

exit 0
[battery]
command=battery.sh
interval=10

The json format can update any variable.

[counter]
_count=0
command=printf '{"full_text":"Counter: %s", "_count":%d}\n' $_count $((_count + 1))
format=json
interval=1

Click

When you click on a block, data such as the button number and coordinates are merged into the block variables.

Note
name and instance are the two keys used by i3bar to identify a block.

The data sent on click is detailed in the i3bar protocol.

If the block command isn’t already spawned, it is executed again.

# Print click data
[clickme]
align=center
full_text=Click me!
min_width=Button=? x=? y=?
command=echo "Button=$button x=$x y=$y"

If the value of the block’s interval is persist, then the data is written on the command standard input, one line per click. What gets written depends on the block’s format. The raw format only gets the click button. The JSON format gets all block variables.

[click-loop]
full_text=Click me!
command=while read button; do echo "Got click $button"; done
interval=persist

[click-loop-json]
full_text=Click me!
command=ruby -r json -n -e '$_ = JSON.parse($_)' -e '$_["full_text"] = "Click %s at (%d,%d)" % $_.slice("button", "x", "y").values' -e 'puts JSON.dump($_)' -e 'STDOUT.flush'
interval=persist
format=json

FAQ

Frequently Asked Questions and Troubleshooting.

  1. What is a blocklet?

    A blocklet is the configuration of a single block, part of the status line. There are plenty listed in the blocklets page.

  2. Can I use my own variables?

    Yes, any variable defined in the block is exported as is to the environment of its command. The foo=bar property can be accessed with $foo from a shell script, ENV["foo"] from Ruby, and so on.

    The IEEE and The Open Group state that "The name space of environment variable names containing lowercase letters is reserved for applications.". i3bar suggests to prefix your own keys with an underscore (_), but it might be more intuitive to use uppercase environment variables, so it is your call to define your own naming convention.

  3. Why $foo doesn’t work from the configuration file?

    i3blocks does not do string interpolation of any sort. The definitions found in the configuration file are just raw strings, this means that bar=$baz defines a bar variable equal to literally $baz (a dollar sign followed by "baz").

    String interpolation does work in the command property though, since it is interpreted by a shell which has access to the environment variables.

  4. How can I simulate a button?

    This is pretty straightforward actually. Just make sure not to override the full_text, for example:

    [calc-button]
    full_text=Calculator
    command=gnome-calculator >/dev/null
  5. Can a block start a GUI application?

    Sure. And if you do not wish your command to block until the application is closed, ask i3 to start it for you with i3-msg -q exec myapp.

  6. Why Pango isn’t working?

    The Pango markup requires a Pango font. Make sure you configured i3bar to use a Pango font. For example:

    font pango:Inconsolata, Icons 12
  7. Why is the output from my persistent block not displayed?

    Make sure to flush stdout, for example:

    [ruby-loop]
    full_text=Click me
    command=ruby -p -e '$_.prepend("Got button ")' -e 'STDOUT.flush'
    interval=persist
  8. Can I use a time interval below 1 second?

    No, the time unit for interval is the second.

    But even though I wouldn’t recommend it, you can still update faster than that with loops:

    [nano1]
    command=sleep .5; date +%N
    interval=repeat
    
    [nano2]
    command=while sleep .5; do date +%N; done
    interval=persist
  9. Can I change the block separator?

    Not with i3blocks itself, separators are drawn by i3bar. You can change the separator_symbol in the i3bar configuration.

    Alternatively, you can define static blocks as custom separators in your i3blocks configuration. In the example below, we use the "\xe3\x80\x89" UTF-8 character:

    # Define the custom separator in global properties for boilerplate
    full_text=〉
    align=center
    color=#666666
    separator=false
    separator_block_width=7
    
    [time]
    instance=la
    TZ=America/Los_Angeles
    command=date +%T
    interval=5
    
    [separator]
    
    [time]
    instance=nc
    TZ=Pacific/Noumea
    command=date +%T
    interval=5
    
    [separator]
    
    [time]
    instance=mtl
    TZ=America/Montreal
    command=date +%T
    interval=5

Debugging

The log level can be increased with the -v option.

If your window manager (and thus this program) is run via systemd, you can inspect the program outputs with journalctl -t <identifier> -f. You may also use this in conjonction with running the program manually with systemd-cat -t <identifier> ./i3blocks.

Alternatively you can redirect the standard output and error streams from the program invokation with:

bar {
  status_command 2>/tmp/i3blocks.err /path/to/i3blocks -vvv -c /path/to/config | tee /tmp/i3blocks.out
}

And inspect the log with tail -f /tmp/i3blocks.err.

See the manpage for details about the command line options and i3blocks usage.

License

i3blocks is Copyright © Vivien Didelot

See the file COPYING for information of licensing and distribution.

i3blocks-1.5/docs/pre-commit000077500000000000000000000007061352435032100160230ustar00rootroot00000000000000#!/bin/sh set -e pushd docs >/dev/null if git diff --name-only --staged -- *.adoc | grep -q ^ then rake -v echo "Documentation was regenerated." if git diff --name-only -- *.adoc | grep -q ^ then echo "Some documentation source files are unstaged," echo "stage and commit hunks yourself with:" echo echo " git commit --no-verify --patch *.1 *.html" echo exit 1 fi git add -v -u *.1 *.html fi popd >/dev/null i3blocks-1.5/i3bar.c000066400000000000000000000153141352435032100142360ustar00rootroot00000000000000/* * i3bar.c - i3bar (plus i3-gaps and sway) protocol support * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "bar.h" #include "block.h" #include "json.h" #include "line.h" #include "log.h" #include "map.h" #include "term.h" /* See https://i3wm.org/docs/i3bar-protocol.html for details */ static struct { const char * const key; bool string; } i3bar_keys[] = { { "", false }, /* unknown key */ /* Standard keys */ { "full_text", true }, { "short_text", true }, { "color", true }, { "background", true }, { "border", true }, { "min_width", false }, /* can also be a number */ { "align", true }, { "name", true }, { "instance", true }, { "urgent", false }, { "separator", false }, { "separator_block_width", false }, { "markup", true }, /* i3-gaps features */ { "border_top", false }, { "border_bottom", false }, { "border_left", false }, { "border_right", false }, }; static unsigned int i3bar_indexof(const char *key) { unsigned int i; for (i = 0; i < sizeof(i3bar_keys) / sizeof(i3bar_keys[0]); i++) if (strcmp(i3bar_keys[i].key, key) == 0) return i; return 0; } static int i3bar_line_cb(char *line, size_t num, void *data) { unsigned int index = num + 1; struct map *map = data; const char *key; if (index >= sizeof(i3bar_keys) / sizeof(i3bar_keys[0])) { debug("ignoring excess line %d: %s", num, line); return 0; } key = i3bar_keys[index].key; return map_set(map, key, line); } int i3bar_read(int fd, size_t count, struct map *map) { return line_read(fd, count, i3bar_line_cb, map); } static void i3bar_print_term(const struct bar *bar) { struct block *block = bar->blocks; const char *full_text; term_restore_cursor(); while (block) { full_text = map_get(block->env, "full_text"); if (full_text) fprintf(stdout, "%s ", full_text); block = block->next; } fflush(stdout); } static int i3bar_print_pair(const char *key, const char *value, void *data) { unsigned int index = i3bar_indexof(key); bool string = i3bar_keys[index].string; unsigned int *pcount = data; char buf[BUFSIZ]; bool escape; int err; /* Skip unknown keys */ if (!index) return 0; if (!value) value = "null"; if (string) { if (json_is_string(value)) escape = false; /* Expected string already quoted */ else escape = true; /* Enforce the string type */ } else { if (json_is_valid(value)) escape = false; /* Already valid JSON */ else escape = true; /* Unquoted string */ } if (escape) { err = json_escape(value, buf, sizeof(buf)); if (err) return err; value = buf; } if ((*pcount)++) fprintf(stdout, ","); fprintf(stdout, "\"%s\":%s", key, value); return 0; } static int i3bar_print_block(struct block *block, void *data) { const char *full_text = map_get(block->env, "full_text"); unsigned int *mcount = data; unsigned int pcount = 0; int err; /* "full_text" is the only mandatory key */ if (!full_text) { block_debug(block, "no text to display, skipping"); return 0; } if ((*mcount)++) fprintf(stdout, ","); fprintf(stdout, "{"); err = map_for_each(block->env, i3bar_print_pair, &pcount); fprintf(stdout, "}"); return err; } int i3bar_print(const struct bar *bar) { struct block *block = bar->blocks; unsigned int mcount = 0; int err; if (bar->term) { i3bar_print_term(bar); return 0; } fprintf(stdout, ",["); while (block) { err = i3bar_print_block(block, &mcount); if (err) break; block = block->next; } fprintf(stdout, "]\n"); fflush(stdout); return err; } int i3bar_printf(struct block *block, int lvl, const char *msg) { const struct bar *bar = block->bar; struct map *map = block->env; int err; if (bar->term || lvl > LOG_ERROR) return 0; block->tainted = true; err = map_set(map, "full_text", msg); if (err) return err; if (lvl <= LOG_ERROR) { err = map_set(map, "urgent", "true"); if (err) return err; } return i3bar_print(bar); } int i3bar_start(struct bar *bar) { if (bar->term) { term_save_cursor(); term_restore_cursor(); } else { fprintf(stdout, "{\"version\":1,\"click_events\":true}\n[[]\n"); fflush(stdout); } return 0; } void i3bar_stop(struct bar *bar) { if (bar->term) { term_reset_cursor(); } else { fprintf(stdout, "]\n"); fflush(stdout); } } static struct block *i3bar_find(struct bar *bar, const struct map *map) { const char *block_name, *block_instance; const char *map_name, *map_instance; struct block *block = bar->blocks; /* "name" and "instance" are the only identifiers provided by i3bar */ map_name = map_get(map, "name") ? : ""; map_instance = map_get(map, "instance") ? : ""; while (block) { block_name = block_get(block, "name") ? : ""; block_instance = block_get(block, "instance") ? : ""; if (strcmp(block_name, map_name) == 0 && strcmp(block_instance, map_instance) == 0) return block; block = block->next; } return NULL; } int i3bar_click(struct bar *bar) { struct block *block; struct map *click; int err; click = map_create(); if (!click) return -ENOMEM; for (;;) { /* Each click is one JSON object per line */ err = json_read(STDIN_FILENO, 1, click); if (err) { if (err == -EAGAIN) err = 0; break; } /* Look for the corresponding block */ block = i3bar_find(bar, click); if (block) { if (block->tainted) { err = block_reset(block); if (err) break; block->tainted = false; err = i3bar_print(bar); if (err) break; } else { err = map_copy(block->env, click); if (err) break; err = block_click(block); if (err) break; } } map_clear(click); } map_destroy(click); return err; } int i3bar_setup(struct block *block) { const char *instance = map_get(block->config, "instance"); const char *name = map_get(block->config, "name"); char buf[BUFSIZ]; int err; /* A block needs a name to be clickable */ if (!name) { name = "foo"; err = map_set(block->config, "name", name); if (err) return err; } if (instance) snprintf(buf, sizeof(buf), "%s:%s", name, instance); else snprintf(buf, sizeof(buf), "%s", name); block->name = strdup(buf); if (!block->name) return -ENOMEM; return 0; } i3blocks-1.5/i3blocks.conf000066400000000000000000000007521352435032100154520ustar00rootroot00000000000000# i3blocks configuration file # # The i3blocks man page describes the usage of the binary, # and its website describes the configuration: # # https://vivien.github.io/i3blocks # Global properties separator=true separator_block_width=15 [documentation] full_text=Documentation website=https://vivien.github.io/i3blocks command=xdg-open "$website" color=#f12711 [greetings] color=#f5af19 command=echo "Hello, $USER!" interval=once [time] command=date '+%Y-%m-%d %H:%M:%S' interval=1 i3blocks-1.5/ini.c000066400000000000000000000044301352435032100140120ustar00rootroot00000000000000/* * ini.c - generic INI parser * Copyright (C) 2017-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include "ini.h" #include "line.h" #include "log.h" struct ini { ini_sec_cb_t *sec_cb; ini_prop_cb_t *prop_cb; void *data; }; static int ini_section(struct ini *ini, char *section) { if (!ini->sec_cb) return 0; return ini->sec_cb(section, ini->data); } static int ini_property(struct ini *ini, char *key, char *value) { if (!ini->prop_cb) return 0; return ini->prop_cb(key, value, ini->data); } static int ini_parse_line(char *line, size_t num, void *data) { /* comment or empty line? */ if (*line == '\0' || *line == '#') return 0; /* section? */ if (*line == '[') { char *closing, *section; closing = strchr(line, ']'); if (!closing) { error("malformated section \"%s\"", line); return -EINVAL; } if (*(closing + 1) != '\0') { error("trailing characters \"%s\"", closing); return -EINVAL; } section = line + 1; *closing = '\0'; return ini_section(data, section); } /* property? */ if (isalpha(*line) || *line == '_') { char *equals, *key, *value; equals = strchr(line, '='); if (!equals) { error("malformated property, should be a key=value pair"); return -EINVAL; } *equals = '\0'; key = line; value = equals + 1; return ini_property(data, key, value); } error("invalid INI syntax for line: \"%s\"", line); return -EINVAL; } int ini_read(int fd, size_t count, ini_sec_cb_t *sec_cb, ini_prop_cb_t *prop_cb, void *data) { struct ini ini = { .sec_cb = sec_cb, .prop_cb = prop_cb, .data = data, }; return line_read(fd, count, ini_parse_line, &ini); } i3blocks-1.5/ini.h000066400000000000000000000017621352435032100140240ustar00rootroot00000000000000/* * ini.h - generic INI format parsing header * Copyright (C) 2017-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef INI_H #define INI_H typedef int ini_sec_cb_t(char *section, void *data); typedef int ini_prop_cb_t(char *key, char *value, void *data); int ini_read(int fd, size_t count, ini_sec_cb_t *sec_cb, ini_prop_cb_t *prop_cb, void *data); #endif /* INI_H */ i3blocks-1.5/json.c000066400000000000000000000203741352435032100142110ustar00rootroot00000000000000/* * json.c - flat JSON parsing * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include "json.h" #include "line.h" #include "log.h" #include "map.h" #include "sys.h" /* Return the number of UTF-8 bytes on success, 0 if it is invalid */ static size_t json_parse_codepoint(const char *str, char *buf, size_t size) { uint16_t codepoint = 0; char utf8[3]; size_t len; int hex; char c; int i; for (i = 0; i < 4; i++) { c = str[i]; if (!isxdigit(c)) return 0; if (c >= '0' && c <= '9') hex = c - '0'; else if (c >= 'a' && c <= 'f') hex = c - 'a' + 10; else hex = c - 'A' + 10; codepoint |= hex << (12 - i * 4); } /* Support Only a single surrogate at the moment */ if (codepoint <= 0x7f) { len = 1; utf8[0] = codepoint; } else if (codepoint <= 0x7ff) { len = 2; utf8[0] = 0xc0 | (codepoint >> 6); utf8[1] = 0x80 | (codepoint & 0x3f); } else { len = 3; utf8[0] = (0xe0 | (codepoint >> 12)); utf8[1] = (0x80 | ((codepoint >> 6) & 0x3f)); utf8[2] = (0x80 | (codepoint & 0x3f)); } if (buf) { if (size < len) return 0; memcpy(buf, utf8, len); } return len; } /* Return the length of the parsed string, 0 if it is invalid */ static size_t json_parse_string(const char *str, char *buf, size_t size) { const char *end = str; size_t len; char c; if (*end != '"') return 0; do { len = 0; switch (*++end) { case '\0': return 0; case '"': c = '\0'; break; case '\\': switch (*++end) { case '"': c = '"'; break; case '\\': c = '\\'; break; case '/': c = '/'; break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'u': len = json_parse_codepoint(++end, buf, size); if (!len) return 0; end += 3; /* jump to last hex digit */ break; default: return 0; } break; default: if (iscntrl(*end)) return 0; c = *end; break; } if (buf) { if (!len) { if (size < 1) return 0; *buf = c; len = 1; } buf += len; size -= len; } } while (c); return ++end - str; } /* Return the length of the parsed non scalar (with open/close delimiter), 0 if it is invalid */ static size_t json_parse_nested_struct(const char *str, char open, char close, char *buf, size_t size) { const char *end = str; size_t len; int nested; if (*str != open) return 0; nested = 1; while (nested) { ++end; /* control character or end-of-line? */ if (iscntrl(*end) || *end == '\0') return 0; if (*end == open) nested++; else if (*end == close) nested--; } len = ++end - str; if (!len) return 0; if (buf) { if (size <= len) return 0; strncpy(buf, str, len); buf[len] = '\0'; } return len; } /* Return the length of the parsed array, 0 if it is invalid */ static size_t json_parse_nested_array(const char *str, char *buf, size_t size) { return json_parse_nested_struct(str, '[', ']', buf, size); } /* Return the length of the parsed object, 0 if it is invalid */ static size_t json_parse_nested_object(const char *str, char *buf, size_t size) { return json_parse_nested_struct(str, '{', '}', buf, size); } /* Return the length of the parsed number, 0 if it is invalid */ static size_t json_parse_number(const char *str, char *buf, size_t size) { size_t len; char *end; strtoul(str, &end, 10); len = end - str; if (!len) return 0; if (buf) { if (size <= len) return 0; strncpy(buf, str, len); buf[len] = '\0'; } return len; } /* Return the length of the parsed literal, 0 if it is invalid */ static size_t json_parse_literal(const char *str, const char *literal, char *buf, size_t size) { const size_t len = strlen(literal); if (strncmp(str, literal, len) != 0) return 0; if (buf) { strncpy(buf, literal, size); if (buf[size - 1] != '\0') return 0; } return len; } /* A value can be a string, number, object, array, true, false, or null */ static size_t json_parse_value(const char *str, char *buf, size_t size) { size_t len; len = json_parse_string(str, buf, size); if (len) return len; len = json_parse_number(str, buf, size); if (len) return len; len = json_parse_nested_object(str, buf, size); if (len) return len; len = json_parse_nested_array(str, buf, size); if (len) return len; len = json_parse_literal(str, "true", buf, size); if (len) return len; len = json_parse_literal(str, "false", buf, size); if (len) return len; len = json_parse_literal(str, "null", buf, size); if (len) return len; return 0; } /* Return the length of a separator optionally enclosed by whitespaces, 0 otherwise */ static size_t json_parse_sep(const char *str, char sep) { size_t len = 0; while (isspace(*str)) str++, len++; if (*str != sep) return 0; str++; len++; while (isspace(*str)) str++, len++; return len; } /* Parse an inline ["name"][\s+:\s+][value] name-value pair */ static size_t json_parse_pair(const char *str, char *name, size_t namesiz, char *val, size_t valsiz) { size_t pair_len = 0; size_t len; len = json_parse_string(str, name, namesiz); if (!len) return 0; pair_len += len; str += len; len = json_parse_sep(str, ':'); if (!len) return 0; pair_len += len; str += len; len = json_parse_value(str, val, valsiz); if (!len) return 0; pair_len += len; return pair_len; } static int json_line_cb(char *line, size_t num, void *data) { struct map *map = data; char name[BUFSIZ]; char val[BUFSIZ]; size_t len; int err; for (;;) { /* Only support inline flattened structures at the moment */ while (*line == '[' || *line == ']' || *line == ',' || *line == '{' || *line == '}' || isspace(*line)) line++; if (*line == '\0') break; memset(name, 0, sizeof(name)); memset(val, 0, sizeof(val)); len = json_parse_pair(line, name, sizeof(name), val, sizeof(val)); if (!len) return -EINVAL; line += len; /* valid delimiters after a pair */ if (*line != ',' && *line != '}' && *line != '\0' && !isspace(*line)) return -EINVAL; if (*line != '\0') line++; if (map) { err = map_set(map, name, val); if (err) return err; } } return 0; } int json_read(int fd, size_t count, struct map *map) { return line_read(fd, count, json_line_cb, map); } bool json_is_string(const char *str) { size_t len; len = strlen(str); if (!len) return false; return json_parse_string(str, NULL, 0) == len; } bool json_is_valid(const char *str) { size_t len; len = strlen(str); if (!len) return false; return json_parse_value(str, NULL, 0) == len; } int json_escape(const char *str, char *buf, size_t size) { size_t null = strlen(str) + 1; char c = '\0'; int len; do { switch (c) { case '\0': len = snprintf(buf, size, "\""); break; case '\b': len = snprintf(buf, size, "\\b"); break; case '\f': len = snprintf(buf, size, "\\f"); break; case '\n': len = snprintf(buf, size, "\\n"); break; case '\r': len = snprintf(buf, size, "\\r"); break; case '\t': len = snprintf(buf, size, "\\t"); break; case '\\': len = snprintf(buf, size, "\\\\"); break; case '"': len = snprintf(buf, size, "\\\""); break; default: if (iscntrl(c)) len = snprintf(buf, size, "\\u%04x", c); else len = snprintf(buf, size, "%c", c); break; } /* Ensure the result was not truncated */ if (len < 0 || len >= size) return -ENOSPC; size -= len; buf += len; c = *str; if (c) str++; } while (null--); return 0; } i3blocks-1.5/json.h000066400000000000000000000017651352435032100142210ustar00rootroot00000000000000/* * json.h - JSON manipulation header * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef JSON_H #define JSON_H #include struct map; int json_read(int fd, size_t count, struct map *map); bool json_is_string(const char *str); bool json_is_valid(const char *str); int json_escape(const char *str, char *buf, size_t size); #endif /* JSON_H */ i3blocks-1.5/line.c000066400000000000000000000037041352435032100141650ustar00rootroot00000000000000/* * line.c - generic line parser * Copyright (C) 2015-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "line.h" #include "log.h" #include "sys.h" /* Read a single character and return a negative error code if none was read */ static int line_getc(int fd, char *c) { return sys_read(fd, c, 1, NULL); } /* Read a line including the newline character and return its positive length */ static ssize_t line_gets(int fd, char *buf, size_t size) { size_t len = 0; int err; for (;;) { if (len == size) return -ENOSPC; err = line_getc(fd, buf + len); if (err) return err; if (buf[len++] == '\n') break; } /* at least 1 */ return len; } /* Read a line excluding the newline character */ static int line_parse(int fd, line_cb_t *cb, size_t num, void *data) { char buf[BUFSIZ]; ssize_t len; int err; len = line_gets(fd, buf, sizeof(buf)); if (len < 0) return len; /* replace newline with terminating null byte */ buf[len - 1] = '\0'; debug("&%d:%.3d: %s", fd, num, buf); if (cb) { err = cb(buf, num, data); if (err) return err; } return 0; } /* Read up to count lines excluding their newline character */ int line_read(int fd, size_t count, line_cb_t *cb, void *data) { size_t lines = 0; int err; while (count--) { err = line_parse(fd, cb, lines++, data); if (err) return err; } return 0; } i3blocks-1.5/line.h000066400000000000000000000016421352435032100141710ustar00rootroot00000000000000/* * line.h - generic line parsing header * Copyright (C) 2015-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef IO_H #define IO_H #include typedef int line_cb_t(char *line, size_t num, void *data); int line_read(int fd, size_t count, line_cb_t *cb, void *data); #endif /* IO_H */ i3blocks-1.5/log.h000066400000000000000000000031751352435032100140260ustar00rootroot00000000000000/* * log.h - syslog friendly error and debug printing macros * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef LOG_H #define LOG_H #include #include #include #include #define SYSLOG_CRIT "<2>" #define SYSLOG_ERR "<3>" #define SYSLOG_NOTICE "<5>" #define SYSLOG_DEBUG "<7>" extern enum { LOG_FATAL, LOG_ERROR, LOG_TRACE, LOG_DEBUG, } log_level; static inline void log_printf(int lvl, const char *fmt, ...) { va_list ap; if (lvl <= LOG_ERROR || lvl <= log_level) { va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); } } #define fatal(fmt, ...) \ log_printf(LOG_FATAL, SYSLOG_CRIT fmt "\n", ##__VA_ARGS__) #define error(fmt, ...) \ log_printf(LOG_ERROR, SYSLOG_ERR fmt "\n", ##__VA_ARGS__) #define trace(fmt, ...) \ log_printf(LOG_TRACE, SYSLOG_NOTICE fmt "\n", ##__VA_ARGS__) #define debug(fmt, ...) \ log_printf(LOG_DEBUG, SYSLOG_DEBUG "%s:%s:%d: " fmt "\n", \ __FILE__, __func__, __LINE__, ##__VA_ARGS__) #endif /* LOG_H */ i3blocks-1.5/main.c000066400000000000000000000032441352435032100141610ustar00rootroot00000000000000/* * main.c - main entry point * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifdef HAVE_CONFIG_H #include "i3blocks-config.h" #endif #include #include #include #include "bar.h" #include "log.h" #include "sys.h" unsigned int log_level; int main(int argc, char *argv[]) { char *output = NULL; char *path = NULL; bool term; int c; while (c = getopt(argc, argv, "c:o:vhV"), c != -1) { switch (c) { case 'c': path = optarg; break; case 'o': output = optarg; break; case 'v': log_level++; break; case 'h': printf("Usage: %s [-c ] [-o ] [-v] [-h] [-V]\n", argv[0]); return EXIT_SUCCESS; case 'V': printf(PACKAGE_STRING " © 2014-2019 Vivien Didelot and contributors\n"); return EXIT_SUCCESS; default: error("Try '%s -h' for more information.", argv[0]); return EXIT_FAILURE; } } term = !sys_isatty(STDOUT_FILENO); if (output) term = !strcmp(output, "term"); if (bar_init(term, path)) return EXIT_FAILURE; return EXIT_SUCCESS; } i3blocks-1.5/map.c000066400000000000000000000074551352435032100140220ustar00rootroot00000000000000/* * map.c - implementation of an associative array * Copyright (C) 2017-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include "map.h" struct pair { char *key; char *value; struct pair *next; }; struct map { struct pair *head; }; static struct pair *map_head(const struct map *map) { return map->head; } /* Return previous pair if key is found, last pair otherwise */ static struct pair *map_prev(const struct map *map, const char *key) { struct pair *prev = map_head(map); struct pair *next = prev->next; while (next) { if (strcmp(next->key, key) == 0) break; prev = next; next = next->next; } return prev; } /* Update the value of a pair */ static int map_reassign(struct pair *pair, const char *value) { free(pair->value); pair->value = NULL; if (value) { pair->value = strdup(value); if (!pair->value) return -ENOMEM; } return 0; } /* Create a new key-value pair */ static struct pair *map_pair(const char *key, const char *value) { struct pair *pair; int err; pair = calloc(1, sizeof(struct pair)); if (!pair) return NULL; pair->key = strdup(key); if (!pair->key) { free(pair); return NULL; } err = map_reassign(pair, value); if (err) { free(pair->key); free(pair); return NULL; } return pair; } /* Destroy a new key-value pair */ void map_unpair(struct pair *pair) { map_reassign(pair, NULL); free(pair->key); free(pair); } /* Insert a key-value pair after a given pair */ static int map_insert(struct pair *prev, const char *key, const char *value) { struct pair *pair; pair = map_pair(key, value); if (!pair) return -ENOMEM; pair->next = prev->next; prev->next = pair; return 0; } /* Delete the key-value pair after a given pair */ static void map_delete(struct pair *prev) { struct pair *pair = prev->next; prev->next = pair->next; map_unpair(pair); } const char *map_get(const struct map *map, const char *key) { struct pair *prev = map_prev(map, key); struct pair *next = prev->next; if (next) return next->value; else return NULL; } int map_set(struct map *map, const char *key, const char *value) { struct pair *prev = map_prev(map, key); struct pair *next = prev->next; if (next) return map_reassign(next, value); else return map_insert(prev, key, value); } int map_for_each(const struct map *map, map_func_t *func, void *data) { struct pair *pair = map_head(map); int err; while (pair->next) { pair = pair->next; err = func(pair->key, pair->value, data); if (err) return err; } return 0; } void map_clear(struct map *map) { struct pair *pair = map_head(map); while (pair->next) map_delete(pair); } static int map_dup(const char *key, const char *value, void *data) { struct map *map = data; return map_set(map, key, value); } int map_copy(struct map *map, const struct map *base) { return map_for_each(base, map_dup, map); } void map_destroy(struct map *map) { map_clear(map); free(map->head); free(map); } struct map *map_create(void) { struct map *map; map = calloc(1, sizeof(struct map)); if (!map) return NULL; map->head = calloc(1, sizeof(struct pair)); if (!map->head) { free(map); return NULL; } return map; } i3blocks-1.5/map.h000066400000000000000000000023231352435032100140140ustar00rootroot00000000000000/* * map.h - definition of an associative array * Copyright (C) 2017-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef MAP_H #define MAP_H struct map; struct map *map_create(void); void map_destroy(struct map *map); int map_copy(struct map *map, const struct map *base); void map_clear(struct map *map); int map_set(struct map *map, const char *key, const char *value); const char *map_get(const struct map *map, const char *key); typedef int map_func_t(const char *key, const char *value, void *data); int map_for_each(const struct map *map, map_func_t *func, void *data); #endif /* MAP_H */ i3blocks-1.5/sys.c000066400000000000000000000171371352435032100140610ustar00rootroot00000000000000/* * sys.c - system calls * Copyright (C) 2017-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #define _GNU_SOURCE /* for F_SETSIG */ #include #include #include #include #include #include #include #include #include #include #include #include "log.h" #define sys_errno(msg, ...) \ trace(msg ": %s", ##__VA_ARGS__, strerror(errno)) int sys_chdir(const char *path) { int rc; rc = chdir(path); if (rc == -1) { sys_errno("chdir(%s)", path); rc = -errno; return rc; } return 0; } int sys_gettime(unsigned long *interval) { struct timespec ts; int rc; rc = clock_gettime(CLOCK_MONOTONIC, &ts); if (rc == -1) { sys_errno("clock_gettime(CLOCK_MONOTONIC)"); rc = -errno; return rc; } *interval = ts.tv_sec; return 0; } int sys_setitimer(unsigned long interval) { struct itimerval itv = { .it_value.tv_sec = interval, .it_interval.tv_sec = interval, }; int rc; rc = setitimer(ITIMER_REAL, &itv, NULL); if (rc == -1) { sys_errno("setitimer(ITIMER_REAL, %ld)", interval); rc = -errno; return rc; } return 0; } int sys_waitid(pid_t *pid) { siginfo_t infop; int rc; /* Non-blocking check for dead child(ren) */ rc = waitid(P_ALL, 0, &infop, WEXITED | WNOHANG | WNOWAIT); if (rc == -1) { sys_errno("waitid()"); rc = -errno; return rc; } if (infop.si_pid == 0) return -ECHILD; *pid = infop.si_pid; return 0; } int sys_waitpid(pid_t pid, int *code) { int status; int rc; rc = waitpid(pid, &status, 0); if (rc == -1) { sys_errno("waitpid(%d)", pid); rc = -errno; return rc; } if (rc == 0) return -ECHILD; if (code) *code = WEXITSTATUS(status); return 0; } int sys_waitanychild(void) { int err; for (;;) { err = sys_waitpid(-1, NULL); if (err) { if (err == -ECHILD) break; return err; } } return 0; } int sys_setenv(const char *name, const char *value) { int rc; rc = setenv(name, value, 1); if (rc == -1) { sys_errno("setenv(%s=%s)", name, value); rc = -errno; return rc; } return 0; } const char *sys_getenv(const char *name) { return getenv(name); } int sys_sigemptyset(sigset_t *set) { int rc; rc = sigemptyset(set); if (rc == -1) { sys_errno("sigemptyset()"); rc = -errno; return rc; } return 0; } int sys_sigfillset(sigset_t *set) { int rc; rc = sigfillset(set); if (rc == -1) { sys_errno("sigfillset()"); rc = -errno; return rc; } return 0; } int sys_sigaddset(sigset_t *set, int sig) { int rc; rc = sigaddset(set, sig); if (rc == -1) { sys_errno("sigaddset(%d (%s))", sig, strsignal(sig)); rc = -errno; return rc; } return 0; } static int sys_sigprocmask(const sigset_t *set, int how) { int rc; rc = sigprocmask(how, set, NULL); if (rc == -1) { sys_errno("sigprocmask()"); rc = -errno; return rc; } return 0; } int sys_sigunblock(const sigset_t *set) { return sys_sigprocmask(set, SIG_UNBLOCK); } int sys_sigsetmask(const sigset_t *set) { return sys_sigprocmask(set, SIG_SETMASK); } int sys_sigwaitinfo(sigset_t *set, int *sig, int *fd) { siginfo_t siginfo; int rc; rc = sigwaitinfo(set, &siginfo); if (rc == -1) { sys_errno("sigwaitinfo()"); rc = -errno; return rc; } *sig = rc; *fd = siginfo.si_fd; return 0; } int sys_open(const char *path, int *fd) { int rc; rc = open(path, O_RDONLY | O_NONBLOCK); if (rc == -1) { sys_errno("open(%s)", path); rc = -errno; return rc; } *fd = rc; return 0; } int sys_close(int fd) { int rc; rc = close(fd); if (rc == -1) { sys_errno("close(%d)", fd); rc = -errno; return rc; } return 0; } /* Read up to size bytes and store the positive count on success */ int sys_read(int fd, void *buf, size_t size, size_t *count) { ssize_t rc; rc = read(fd, buf, size); if (rc == -1) { sys_errno("read(%d, %ld)", fd, size); rc = -errno; if (rc == -EWOULDBLOCK) rc = -EAGAIN; return rc; } /* End of file or pipe */ if (rc == 0) return -EAGAIN; if (count) *count = rc; return 0; } int sys_dup(int fd1, int fd2) { int rc; /* Defensive check */ if (fd1 == fd2) return 0; /* Close fd2, and reopen bound to fd1 */ rc = dup2(fd1, fd2); if (rc == -1) { sys_errno("dup2(%d, %d)", fd1, fd2); rc = -errno; return rc; } return 0; } static int sys_setsig(int fd, int sig) { int rc; rc = fcntl(fd, F_SETSIG, sig); if (rc == -1) { sys_errno("fcntl(%d, F_SETSIG, %d (%s))", fd, sig, strsignal(sig)); rc = -errno; return rc; } return 0; } static int sys_setown(int fd, pid_t pid) { int rc; rc = fcntl(fd, F_SETOWN, pid); if (rc == -1) { sys_errno("fcntl(%d, F_SETOWN, %d)", fd, pid); rc = -errno; return rc; } return 0; } static int sys_getfd(int fd, int *flags) { int rc; rc = fcntl(fd, F_GETFD); if (rc == -1) { sys_errno("fcntl(%d, F_GETFD)", fd); rc = -errno; return rc; } *flags = rc; return 0; } static int sys_setfd(int fd, int flags) { int rc; rc = fcntl(fd, F_SETFD, flags); if (rc == -1) { sys_errno("fcntl(%d, F_SETFD, %d)", fd, flags); rc = -errno; return rc; } return 0; } static int sys_getfl(int fd, int *flags) { int rc; rc = fcntl(fd, F_GETFL); if (rc == -1) { sys_errno("fcntl(%d, F_GETFL)", fd); rc = -errno; return rc; } *flags = rc; return 0; } static int sys_setfl(int fd, int flags) { int rc; rc = fcntl(fd, F_SETFL, flags); if (rc == -1) { sys_errno("fcntl(%d, F_SETFL, %d)", fd, flags); rc = -errno; return rc; } return 0; } int sys_cloexec(int fd) { int flags; int err; err = sys_getfd(fd, &flags); if (err) return err; return sys_setfd(fd, flags | FD_CLOEXEC); } /* Enable signal-driven I/O, formerly known as asynchronous I/O */ int sys_async(int fd, int sig) { pid_t pid; int flags; int err; err = sys_getfl(fd, &flags); if (err) return err; if (sig) { pid = getpid(); flags |= (O_ASYNC | O_NONBLOCK); } else { pid = 0; flags &= ~(O_ASYNC | O_NONBLOCK); } /* Establish a handler for the signal */ err = sys_setsig(fd, sig); if (err) return err; /* Set calling process as owner, that is to receive the signal */ err = sys_setown(fd, pid); if (err) return err; /* Enable/disable nonblocking I/O and signal-driven I/O */ return sys_setfl(fd, flags); } int sys_pipe(int *fds) { int rc; rc = pipe(fds); if (rc == -1) { sys_errno("pipe()"); rc = -errno; return rc; } return 0; } int sys_fork(pid_t *pid) { int rc; rc = fork(); if (rc == -1) { sys_errno("fork()"); rc = -errno; return rc; } *pid = rc; return 0; } void sys_exit(int status) { _exit(status); } int sys_execsh(const char *command) { int rc; static const char * const shell = "/bin/sh"; rc = execl(shell, shell, "-c", command, (char *) NULL); if (rc == -1) { sys_errno("execl(%s -c \"%s\")", shell, command); rc = -errno; return rc; } /* Unreachable */ return 0; } int sys_isatty(int fd) { int rc; rc = isatty(fd); if (rc == 0) { sys_errno("isatty(%d)", fd); rc = -errno; if (rc == -EINVAL) rc = -ENOTTY; return rc; } return 0; } i3blocks-1.5/sys.h000066400000000000000000000033541352435032100140620ustar00rootroot00000000000000/* * sys.h - system calls * Copyright (C) 2017-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef SYS_H #define SYS_H #include /* for dirname(3) */ #include #include int sys_chdir(const char *path); int sys_gettime(unsigned long *interval); int sys_setitimer(unsigned long interval); int sys_waitid(pid_t *pid); int sys_waitpid(pid_t pid, int *code); int sys_waitanychild(void); int sys_setenv(const char *name, const char *value); const char *sys_getenv(const char *name); int sys_sigemptyset(sigset_t *set); int sys_sigfillset(sigset_t *set); int sys_sigaddset(sigset_t *set, int sig); int sys_sigunblock(const sigset_t *set); int sys_sigsetmask(const sigset_t *set); int sys_sigwaitinfo(sigset_t *set, int *sig, int *fd); int sys_open(const char *path, int *fd); int sys_close(int fd); int sys_read(int fd, void *buf, size_t size, size_t *count); int sys_dup(int fd1, int fd2); int sys_cloexec(int fd); int sys_async(int fd, int sig); int sys_pipe(int *fds); int sys_fork(pid_t *pid); void sys_exit(int status); int sys_execsh(const char *command); int sys_isatty(int fd); #endif /* SYS_H */ i3blocks-1.5/term.h000066400000000000000000000020511352435032100142040ustar00rootroot00000000000000/* * term.h - terminal output handling functions * Copyright (C) 2014-2019 Vivien Didelot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef TERM_H #define TERM_H #include static inline void term_save_cursor(void) { fprintf(stdout, "\033[s\033[?25l"); } static inline void term_restore_cursor(void) { fprintf(stdout, "\033[u\033[K"); } static inline void term_reset_cursor(void) { fprintf(stdout, "\033[?25h"); } #endif /* TERM_H */