sled

Једноставни уређивач текста
git clone https://git.sr.ht/~strahinja/sled
Дневник | Датотеке | Референце | ПРОЧИТАЈМЕ | ЛИЦЕНЦА

чување de90619ab74b2a0cefccb2ed79abe6a4c67b7f8e
Аутор: Страхиња Радић <contact@strahinja.org>
Датум:   Sat, 12 Feb 2022 20:46:27 +0100

Initial commit

Signed-off-by: Страхиња Радић <contact@strahinja.org>

Diffstat:
A.gitignore | 27+++++++++++++++++++++++++++
ALICENSE | 674+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ALICENSE.termbox | 19+++++++++++++++++++
AREADME | 22++++++++++++++++++++++
Aall.do | 1+
Abytebuffer.inl | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aclean.do | 1+
Aconfig.def.h | 33+++++++++++++++++++++++++++++++++
Aconfig.h | 33+++++++++++++++++++++++++++++++++
Adate.do | 3+++
Adefault.do | 10++++++++++
Adefault.gz.do | 2++
Adefault.h.do | 12++++++++++++
Adefault.o.do | 5+++++
Ado | 446+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adraw.c | 544+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adraw.h | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ainput.inl | 228+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Arebuild.do | 1+
Asled.1.in | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asled.c | 1504+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asled.do | 8++++++++
Aterm.inl | 311+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atermbox.c | 681+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atermbox.h | 320+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autf8.c | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autil.c | 466+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autil.h | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aversion.do | 5+++++
Aversion.h.in | 4++++
измењених датотека: 30, додавања: 5764(+), брисања: 0(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,27 @@ +.cache +.redo +.gdbinit +*.session +.do_built +.do_built.dir +*~ +*.bak +*.orig +*.rej +*.o +*.swp +*.did +nohup.out +*.err +*.gz +*.xz +*.pdf +*.1 +*.pkg.tar.zst +src +PKGBUILD +sled +sled.1 +date +version +version.h diff --git a/LICENSE b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + 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. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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 <https://www.gnu.org/licenses/>. + +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: + + <program> Copyright (C) <year> <name of author> + 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 +<https://www.gnu.org/licenses/>. + + 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 +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/LICENSE.termbox b/LICENSE.termbox @@ -0,0 +1,19 @@ +Copyright (C) 2010-2013 nsf <no.smile.face@gmail.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README b/README @@ -0,0 +1,22 @@ +sled - Simple text editor +========================= + +License +------- + +sled - Simple text editor +Copyright (C) 2022 Страхиња Радић + +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 includes code from the termbox TUI library, + + https://github.com/termbox/termbox + +The file LICENSE.termbox applies to the portion of this program which is from +the termbox library. diff --git a/all.do b/all.do @@ -0,0 +1 @@ +redo-ifchange version.h sled sled.1.gz diff --git a/bytebuffer.inl b/bytebuffer.inl @@ -0,0 +1,70 @@ +struct bytebuffer { + char *buf; + int len; + int cap; +}; + +static void bytebuffer_reserve(struct bytebuffer *b, int cap) { + if (b->cap >= cap) { + return; + } + + // prefer doubling capacity + if (b->cap * 2 >= cap) { + cap = b->cap * 2; + } + + char *newbuf = realloc(b->buf, cap); + b->buf = newbuf; + b->cap = cap; +} + +static void bytebuffer_init(struct bytebuffer *b, int cap) { + b->cap = 0; + b->len = 0; + b->buf = 0; + + if (cap > 0) { + b->cap = cap; + b->buf = malloc(cap); // just assume malloc works always + } +} + +static void bytebuffer_free(struct bytebuffer *b) { + if (b->buf) + free(b->buf); +} + +static void bytebuffer_clear(struct bytebuffer *b) { + b->len = 0; +} + +static void bytebuffer_append(struct bytebuffer *b, const char *data, int len) { + bytebuffer_reserve(b, b->len + len); + memcpy(b->buf + b->len, data, len); + b->len += len; +} + +static void bytebuffer_puts(struct bytebuffer *b, const char *str) { + bytebuffer_append(b, str, strlen(str)); +} + +static void bytebuffer_resize(struct bytebuffer *b, int len) { + bytebuffer_reserve(b, len); + b->len = len; +} + +static void bytebuffer_flush(struct bytebuffer *b, int fd) { + write(fd, b->buf, b->len); + bytebuffer_clear(b); +} + +static void bytebuffer_truncate(struct bytebuffer *b, int n) { + if (n <= 0) + return; + if (n > b->len) + n = b->len; + const int nmove = b->len - n; + memmove(b->buf, b->buf+n, nmove); + b->len -= n; +} diff --git a/clean.do b/clean.do @@ -0,0 +1 @@ +rm -f *~ *.o sled version date diff --git a/config.def.h b/config.def.h @@ -0,0 +1,33 @@ +/* See the file LICENSE for copyright and license details. */ + +#define DLG_FG TB_BLACK +#define DLG_BG TB_WHITE +#define ERROR_FG TB_WHITE | TB_BOLD +#define ERROR_BG TB_RED +#define PROMPT_FG TB_YELLOW | TB_BOLD +#define PROMPT_BG TB_MAGENTA +#define SHADOW_FG TB_BLACK +#define SHADOW_BG TB_BLACK | TB_BOLD +#define TITLE_FG TB_BLACK +#define TITLE_BG TB_WHITE + +void format_filename(char* result, size_t result_size, const char* format, + const struct DrawState* state); + +static const struct StatusSegment status_segments[] = { + {.format = "%s%s", + .callback = format_filename, + .fg = TB_BLACK, + .bg = TB_WHITE, + .alignment = LEFT}, + {.format = "%ld/%ld (%ldu/%ldf/%ldo)", + .callback = NULL, + .fg = TB_WHITE | TB_BOLD, + .bg = TB_BLUE, + .alignment = CENTER}, + {.format = "H=HELP, q=QUIT", + .callback = NULL, + .fg = TB_BLACK, + .bg = TB_WHITE, + .alignment = RIGHT}, +}; diff --git a/config.h b/config.h @@ -0,0 +1,33 @@ +/* See the file LICENSE for copyright and license details. */ + +#define DLG_FG TB_BLACK +#define DLG_BG TB_WHITE +#define ERROR_FG TB_WHITE | TB_BOLD +#define ERROR_BG TB_RED +#define PROMPT_FG TB_YELLOW | TB_BOLD +#define PROMPT_BG TB_MAGENTA +#define SHADOW_FG TB_BLACK +#define SHADOW_BG TB_BLACK | TB_BOLD +#define TITLE_FG TB_BLACK +#define TITLE_BG TB_WHITE + +void format_filename(char* result, size_t result_size, const char* format, + const struct DrawState* state); + +static const struct StatusSegment status_segments[] = { + {.format = "%s%s", + .callback = format_filename, + .fg = TB_BLACK, + .bg = TB_WHITE, + .alignment = LEFT}, + {.format = "%ld/%ld (%ldu/%ldf/%ldo)", + .callback = NULL, + .fg = TB_WHITE | TB_BOLD, + .bg = TB_BLUE, + .alignment = CENTER}, + {.format = "H=HELP, q=QUIT", + .callback = NULL, + .fg = TB_BLACK, + .bg = TB_WHITE, + .alignment = RIGHT}, +}; diff --git a/date.do b/date.do @@ -0,0 +1,3 @@ +LC_ALL=C date +'%d %b %Y' >$3 +redo-always +redo-stamp <$3 diff --git a/default.do b/default.do @@ -0,0 +1,10 @@ +if [ -r $1.in ]; then + redo-ifchange $1.in version date + read VERSION <version + read DATE <date + sed -e "s/%VERSION%/$VERSION/g" \ + -e "s/%DATE%/$DATE/g" <$1.in +else + echo "$0: don't know how to build '$1'" >&2 + exit 99 +fi diff --git a/default.gz.do b/default.gz.do @@ -0,0 +1,2 @@ +redo-ifchange $2 +gzip -cf $2 >$3 diff --git a/default.h.do b/default.h.do @@ -0,0 +1,12 @@ +if [ -r $1.in ]; then + redo-ifchange $1.in version date + read VERSION <version + read DATE <date + sed -e "s/%VERSION%/$VERSION/g" \ + -e "s/%DATE%/$DATE/g" <$1.in +else + if [ -f $2.def.h ]; then + redo-ifchange $2.def.h + cat $2.def.h > $3 + fi +fi diff --git a/default.o.do b/default.o.do @@ -0,0 +1,5 @@ +for f in *.h; do + echo $f +done | xargs redo-ifchange +redo-ifchange $2.c +${SLED_CC:-gcc -g} -Wall -std=c99 -c $2.c -o $3 diff --git a/do b/do @@ -0,0 +1,446 @@ +#!/usr/bin/env sh +# +# A minimal alternative to djb redo that doesn't support incremental builds. +# For the full version, visit http://github.com/apenwarr/redo +# +# The author disclaims copyright to this source file and hereby places it in +# the public domain. (2010 12 14; updated 2019 02 24) +# +USAGE=" +usage: do [-d] [-x] [-v] [-c] <targets...> + -d print extra debug messages (mostly about dependency checks) + -v run .do files with 'set -v' + -x run .do files with 'set -x' + -c clean up all old targets before starting + + Note: do is an implementation of redo that does *not* check dependencies. + It will never rebuild a target it has already built, unless you use -c. +" + +# CDPATH apparently causes unexpected 'cd' output on some platforms. +unset CDPATH + +# By default, no output coloring. +green="" +bold="" +plain="" + +if [ -n "$TERM" -a "$TERM" != "dumb" ] && tty <&2 >/dev/null 2>&1; then + green="$(printf '\033[32m')" + bold="$(printf '\033[1m')" + plain="$(printf '\033[m')" +fi + +# The 'seq' command is not available on all platforms. +_seq() { + local x=0 max="$1" + while [ "$x" -lt "$max" ]; do + x=$((x + 1)) + echo "$x" + done +} + +# Split $1 into a dir part ($_dirsplit_dir) and base filename ($_dirsplit_base) +_dirsplit() { + _dirsplit_base=${1##*/} + _dirsplit_dir=${1%$_dirsplit_base} +} + +# Like /usr/bin/dirname, but avoids a fork and uses _dirsplit semantics. +qdirname() ( + _dirsplit "$1" + dir=${_dirsplit_dir%/} + echo "${dir:-.}" +) + +_dirsplit "$0" +REDO=$(cd "$(pwd -P)" && + cd "${_dirsplit_dir:-.}" && + echo "$PWD/$_dirsplit_base") +export REDO +_cmd=$_dirsplit_base + +DO_TOP= +if [ -z "$DO_BUILT" ]; then + export _do_opt_debug= + export _do_opt_exec= + export _do_opt_verbose= + export _do_opt_clean= +fi +while getopts 'dxvcj:h?' _opt; do + case $_opt in + d) _do_opt_debug=1 ;; + x) _do_opt_exec=x ;; + v) _do_opt_verbose=v ;; + c) _do_opt_clean=1 ;; + j) ;; # silently ignore, for compat with real redo + \?|h|*) printf "%s" "$USAGE" >&2 + exit 99 + ;; + esac +done +shift "$((OPTIND - 1))" +_debug() { + [ -z "$_do_opt_debug" ] || echo "$@" >&2 +} + +if [ -z "$DO_BUILT" -a "$_cmd" != "redo-whichdo" ]; then + DO_TOP=1 + if [ "$#" -eq 0 ] && [ "$_cmd" = "do" -o "$_cmd" = "redo" ]; then + set all # only toplevel redo has a default target + fi + export DO_STARTDIR="$(pwd -P)" + # If starting /bin/pwd != $PWD, this will fix it. + # That can happen when $PWD contains symlinks that the shell is + # trying helpfully (but unsuccessfully) to hide from the user. + cd "$DO_STARTDIR" || exit 99 + export DO_BUILT="$PWD/.do_built" + if [ -z "$_do_opt_clean" -a -e "$DO_BUILT" ]; then + echo "do: Incremental mode. Use -c for clean rebuild." >&2 + fi + : >>"$DO_BUILT" + sort -u "$DO_BUILT" >"$DO_BUILT.new" + while read f; do + [ -n "$_do_opt_clean" ] && printf "%s\0%s.did\0" "$f" "$f" + printf "%s.did.tmp\0" "$f" + done <"$DO_BUILT.new" | + xargs -0 rm -f 2>/dev/null + mv "$DO_BUILT.new" "$DO_BUILT" + export DO_PATH="$DO_BUILT.dir" + export PATH="$DO_PATH:$PATH" + rm -rf "$DO_PATH" + mkdir "$DO_PATH" + for d in redo redo-ifchange redo-whichdo; do + ln -s "$REDO" "$DO_PATH/$d" + done + for d in redo-ifcreate redo-stamp redo-always redo-ood \ + redo-targets redo-sources; do + echo "#!/bin/sh" >"$DO_PATH/$d" + chmod a+rx "$DO_PATH/$d" + done +fi + + +# Chop the "file" part off a /path/to/file pathname. +# Note that if the filename already ends in a /, we just remove the slash. +_updir() +{ + local v="${1%/*}" + [ "$v" != "$1" ] && echo "$v" + # else "empty" which means we went past the root +} + + +# Returns true if $1 starts with $2. +_startswith() +{ + [ "${1#"$2"}" != "$1" ] +} + + +# Returns true if $1 ends with $2. +_endswith() +{ + [ "${1%"$2"}" != "$1" ] +} + + +# Prints $1 if it's absolute, or $2/$1 if $1 is not absolute. +_abspath() +{ + local here="$2" there="$1" + if _startswith "$1" "/"; then + echo "$1" + else + echo "$2/$1" + fi +} + + +# Prints $1 as a path relative to $PWD (not starting with /). +# If it already doesn't start with a /, doesn't change the string. +_relpath() +{ + local here="$2" there="$1" out= hadslash= + #echo "RP start '$there' hs='$hadslash'" >&2 + _startswith "$there" "/" || { echo "$there" && return; } + [ "$there" != "/" ] && _endswith "$there" "/" && hadslash=/ + here=${here%/}/ + while [ -n "$here" ]; do + #echo "RP out='$out' here='$here' there='$there'" >&2 + [ "${here%/}" = "${there%/}" ] && there= && break; + [ "${there#$here}" != "$there" ] && break + out=../$out + _dirsplit "${here%/}" + here=$_dirsplit_dir + done + there=${there#$here} + if [ -n "$there" ]; then + echo "$out${there%/}$hadslash" + else + echo "${out%/}$hadslash" + fi +} + + +# Prints a "normalized relative" path, with ".." resolved where possible. +# For example, a/b/../c will be reduced to just a/c. +_normpath() +( + local path="$1" relto="$2" out= isabs= + #echo "NP start '$path'" >&2 + if _startswith "$path" "/"; then + isabs=1 + else + path="${relto%/}/$path" + fi + set -f + IFS=/ + for d in ${path%/}; do + #echo "NP out='$out' d='$d'" >&2 + if [ "$d" = ".." ]; then + out=$(_updir "${out%/}")/ + else + out=$out$d/ + fi + done + #echo "NP out='$out' (done)" >&2 + out=${out%/} + if [ -n "$isabs" ]; then + echo "${out:-/}" + else + _relpath "${out:-/}" "$relto" + fi +) + + +# Prints a "real" path, with all symlinks resolved where possible. +_realpath() +{ + local path="$1" relto="$2" isabs= rest= + if _startswith "$path" "/"; then + isabs=1 + else + path="${relto%/}/$path" + fi + ( + for d in $(_seq 100); do + #echo "Trying: $PWD--$path" >&2 + if cd -P "$path" 2>/dev/null; then + # success + pwd=$(pwd -P) + #echo " chdir ok: $pwd--$rest" >&2 + np=$(_normpath "${pwd%/}/$rest" "$relto") + if [ -n "$isabs" ]; then + echo "$np" + else + _relpath "$np" "$relto" + fi + break + fi + _dirsplit "${path%/}" + path=$_dirsplit_dir + rest="$_dirsplit_base/$rest" + done + ) +} + + +# List the possible names for default*.do files in dir $1 matching the target +# pattern in $2. We stop searching when we find the first one that exists. +_find_dofiles_pwd() +{ + local dodir="$1" dofile="$2" + _startswith "$dofile" "default." || dofile=${dofile#*.} + while :; do + dofile=default.${dofile#default.*.} + echo "$dodir$dofile" + [ -e "$dodir$dofile" ] && return 0 + [ "$dofile" = default.do ] && break + done + return 1 +} + + +# List the possible names for default*.do files in $PWD matching the target +# pattern in $1. We stop searching when we find the first name that works. +# If there are no matches in $PWD, we'll search in .., and so on, to the root. +_find_dofiles() +{ + local target="$1" dodir= dofile= newdir= + _debug "find_dofile: '$PWD' '$target'" + dofile="$target.do" + echo "$dofile" + [ -e "$dofile" ] && return 0 + + # Try default.*.do files, walking up the tree + _dirsplit "$dofile" + dodir=$_dirsplit_dir + dofile=$_dirsplit_base + [ -n "$dodir" ] && dodir=${dodir%/}/ + [ -e "$dodir$dofile" ] && return 0 + for i in $(_seq 100); do + [ -n "$dodir" ] && dodir=${dodir%/}/ + #echo "_find_dofiles: '$dodir' '$dofile'" >&2 + _find_dofiles_pwd "$dodir" "$dofile" && return 0 + newdir=$(_realpath "${dodir}.." "$PWD") + [ "$newdir" = "$dodir" ] && break + dodir=$newdir + done + return 1 +} + + +# Print the last .do file returned by _find_dofiles. +# If that file exists, returns 0, else 1. +_find_dofile() +{ + local files="$(_find_dofiles "$1")" + rv=$? + #echo "files='$files'" >&2 + [ "$rv" -ne 0 ] && return $rv + echo "$files" | { + while read -r linex; do line=$linex; done + printf "%s\n" "$line" + } +} + + +# Actually run the given $dofile with the arguments in $@. +# Note: you should always run this in a subshell. +_run_dofile() +{ + export DO_DEPTH="$DO_DEPTH " + export REDO_TARGET="$PWD/$target" + local line1 + set -e + read line1 <"$PWD/$dofile" || true + cmd=${line1#"#!/"} + if [ "$cmd" != "$line1" ]; then + set -$_do_opt_verbose$_do_opt_exec + exec /$cmd "$PWD/$dofile" "$@" + else + set -$_do_opt_verbose$_do_opt_exec + # If $dofile is empty, "." might not change $? at + # all, so we clear it first with ":". + :; . "$PWD/$dofile" + fi +} + + +# Find and run the right .do file, starting in dir $1, for target $2, +# providing a temporary output file as $3. Renames the temp file to $2 when +# done. +_do() +{ + local dir="$1" target="$1$2" tmp="$1$2.redo.tmp" tdir= + local dopath= dodir= dofile= ext= + if [ "$_cmd" = "redo" ] || + ( [ ! -e "$target" -o -d "$target" ] && + [ ! -e "$target.did" ] ); then + printf '%sdo %s%s%s%s\n' \ + "$green" "$DO_DEPTH" "$bold" "$target" "$plain" >&2 + dopath=$(_find_dofile "$target") + if [ ! -e "$dopath" ]; then + echo "do: $target: no .do file ($PWD)" >&2 + return 1 + fi + _dirsplit "$dopath" + dodir=$_dirsplit_dir dofile=$_dirsplit_base + if _startswith "$dofile" "default."; then + ext=${dofile#default} + ext=${ext%.do} + else + ext= + fi + target=$PWD/$target + tmp=$PWD/$tmp + cd "$dodir" || return 99 + target=$(_relpath "$target" "$PWD") || return 98 + tmp=$(_relpath "$tmp" "$PWD") || return 97 + base=${target%$ext} + tdir=$(qdirname "$target") + [ ! -e "$DO_BUILT" ] || [ ! -w "$tdir/." ] || + : >>"$target.did.tmp" + # $qtmp is a temporary file used to capture stdout. + # Since it might be accidentally deleted as a .do file + # does its work, we create it, then open two fds to it, + # then immediately delete the name. We use one fd to + # redirect to stdout, and the other to read from after, + # because there's no way to fseek(fd, 0) in sh. + qtmp=$DO_PATH/do.$$.tmp + ( + rm -f "$qtmp" + ( _run_dofile "$target" "$base" "$tmp" >&3 3>&- 4<&- ) + rv=$? + if [ $rv != 0 ]; then + printf "do: %s%s\n" "$DO_DEPTH" \ + "$target: got exit code $rv" >&2 + rm -f "$tmp.tmp" "$tmp.tmp2" "$target.did" + return $rv + fi + echo "$PWD/$target" >>"$DO_BUILT" + if [ ! -e "$tmp" ]; then + # if $3 wasn't created, copy from stdout file + cat <&4 >$tmp + # if that's zero length too, forget it + [ -s "$tmp" ] || rm -f "$tmp" + fi + ) 3>$qtmp 4<$qtmp # can't use "|| return" here... + # ...because "|| return" would mess up "set -e" inside the () + # on some shells. Running commands in "||" context, even + # deep inside, will stop "set -e" from functioning. + rv=$? + [ "$rv" = 0 ] || return "$rv" + mv "$tmp" "$target" 2>/dev/null + [ -e "$target.did.tmp" ] && + mv "$target.did.tmp" "$target.did" || + : >>"$target.did" + else + _debug "do $DO_DEPTH$target exists." >&2 + fi +} + + +# Implementation of the "redo" command. +_redo() +{ + local i startdir="$PWD" dir base + set +e + for i in "$@"; do + i=$(_abspath "$i" "$startdir") + ( + cd "$DO_STARTDIR" || return 99 + i=$(_realpath "$(_relpath "$i" "$PWD")" "$PWD") + _dirsplit "$i" + dir=$_dirsplit_dir base=$_dirsplit_base + _do "$dir" "$base" + ) + [ "$?" = 0 ] || return 1 + done +} + + +# Implementation of the "redo-whichdo" command. +_whichdo() +{ + _find_dofiles "$1" +} + + +case $_cmd in + do|redo|redo-ifchange) _redo "$@" ;; + redo-whichdo) _whichdo "$1" ;; + do.test) ;; + *) printf "do: '%s': unexpected redo command" "$_cmd" >&2; exit 99 ;; +esac +[ "$?" = 0 ] || exit 1 + +if [ -n "$DO_TOP" ]; then + if [ -n "$_do_opt_clean" ]; then + echo "do: Removing stamp files..." >&2 + [ ! -e "$DO_BUILT" ] || + while read f; do printf "%s.did\0" "$f"; done <"$DO_BUILT" | + xargs -0 rm -f 2>/dev/null + fi +fi diff --git a/draw.c b/draw.c @@ -0,0 +1,544 @@ +/* See the file LICENSE for copyright and license details. */ +#include <errno.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "termbox.h" +#include "util.h" +//#include "po.h" +#include "draw.h" +#include "config.h" +#include "version.h" + +/* clang-format off */ +static const char* help_title = "Main view help"; +static const char* help[] = { + "Esc - Close dialog, clear error", + "H or F1 - Show this screen", + "q or C-Q - Quit", + "See the manual (man sled) for full help."}; +const char* errors[] = { + [ERR_UNKNOWN_KEY] = "Unknown key (press H for help)", + [ERR_EXIT_KEY] = "Press q or C-Q to quit", + [ERR_DLG_OPEN] = "Press Esc to close dialog or q/C-Q to quit", + [ERR_DLG_OPEN_QUIT] = "Press Esc to close dialog", + [ERR_CANT_ALLOC] = "Memory allocation failed", + [ERR_CANT_SAVE] = "File is not writeable", + [ERR_CANT_MOVE] = "Cannot move temporary file"}; +const char* program_name = "sled"; +const char* prompt_dirty = "File changed, save [y/n/ESC]?"; +const char* prompt_cancel_dirty = "Entry changed, save [y/n/ESC]?"; +const char* prompt_overwrite = "Not empty, overwrite? [y/n/ESC]?"; +/* clang-format on */ + +void +init_bufferline(struct BufferLine* bl) +{ + if (!bl) + return; + bl->text = NULL; + bl->length = 0; + bl->fg = 0; + bl->bg = 0; +} + +void +free_bufferline(struct BufferLine* bl) +{ + if (!bl) + return; + free(bl->text); + bl->text = NULL; + bl->length = 0; + bl->fg = 0; + bl->bg = 0; +} + +void +init_drawstate(struct DrawState* state, char* error, char* filename, + char* prompt) +{ + state->error = error; + state->filename = filename; + state->buffer = NULL; + state->column = 0; + state->display_column = 0; + state->first_shown_column = 0; + state->first_shown_row = 0; + state->row = 0; + state->rows_count = 0; + state->saved_column = -1; + state->help_width = calculate_help_width(state); + state->paste_buffer = NULL; + state->paste_rows_count = 0; + state->prompt = prompt; + state->prompt_callback = NULL; + state->running = 1; + state->dirty = 0; + state->in_prompt = 0; + state->show_help = 0; +} + +void +free_drawstate(struct DrawState* state) +{ + struct BufferLine* current = NULL; + size_t i = 0; + + for (i = 0; i < state->rows_count; i++) + { + current = state->buffer + i; + free_bufferline(current); + } + free(state->buffer); + for (i = 0; i < state->paste_rows_count; i++) + { + current = state->paste_buffer + i; + free_bufferline(current); + } + free(state->paste_buffer); +} + +/* Calculates display length of a buffer line. + * max_index = the buffer index up to which the length is calculated + */ +size_t +display_length(const struct DrawState* state, uint32_t* buffer, + const size_t max_index) +{ + size_t len = 0; + uint32_t* pbuf = buffer; + + for (size_t i = 0; *pbuf && i < max_index; i++) + { + pbuf = buffer + i; + if (*pbuf == '\t') + len += TAB_SIZE - (len % TAB_SIZE); + else + len++; + } + + return len; +} + +/* Calculates buffer length from a display length. + * max_index = the display index up to which the length is calculated + */ +size_t +buffer_length(const struct DrawState* state, uint32_t* buffer, + const size_t max_index) +{ + size_t len = 0; + uint32_t* pbuf = buffer; + size_t i = 0; + + for (i = 0; *pbuf && len < max_index; i++) + { + pbuf = buffer + i; + if (*pbuf == '\t') + len += MIN(TAB_SIZE - (len % TAB_SIZE), max_index - len); + else + len++; + } + + return i; +} + +int +calculate_help_width(const struct DrawState* state) +{ + return state->maxx > HELP_WIDTH + 2 ? HELP_WIDTH : state->maxx - 2; +} + +void +draw_rect(const int startx, const int endx, const int starty, const int endy, + const uint16_t fg, const uint16_t bg) +{ + for (int y = starty; y < endy; y++) + for (int x = startx; x < endx; x++) + tb_change_cell(x, y, ' ', fg, bg); +} + +void +draw_box(const int startx, const int endx, const int starty, const int endy, + const uint16_t fg, const uint16_t bg) +{ + int x, y; + + tb_change_cell(startx, starty, BORDER_NW, fg, bg); + for (x = startx + 1; x < endx - 1; x++) + tb_change_cell(x, starty, BORDER_HOR, fg, bg); + tb_change_cell(endx - 1, starty, BORDER_NE, fg, bg); + + for (y = starty + 1; y < endy - 2; y++) + { + tb_change_cell(startx, y, BORDER_VER, fg, bg); + for (x = startx + 1; x < endx - 1; x++) + tb_change_cell(x, y, ' ', fg, bg); + tb_change_cell(endx - 1, y, BORDER_VER, fg, bg); + tb_change_cell(endx, y, ' ', SHADOW_FG, SHADOW_BG); + } + + tb_change_cell(startx, endy - 2, BORDER_SW, fg, bg); + for (x = startx + 1; x < endx - 1; x++) + tb_change_cell(x, endy - 2, BORDER_HOR, fg, bg); + tb_change_cell(endx - 1, endy - 2, BORDER_SE, fg, bg); + tb_change_cell(endx, endy - 2, ' ', SHADOW_FG, SHADOW_BG); + + for (x = startx + 1; x < endx + 1; x++) + tb_change_cell(x, endy - 1, ' ', SHADOW_FG, SHADOW_BG); +} + +/* mc - (max cols) pack text and padding into this many columns + * fc - (fill cols) this many columns from the left/right/center will be + * filled + * p_? - (padding) this many cells will be skipped from ? side + * ds - (display start) string starts being displayed from this display column + * counted from the start of the string; an "entry point" joining string + * index with screen + * fill - boolean; 1 = fill fc, 0 = don't fill fc + * srch - search string; if empty or NULL no highlighting happens + * sfg - fg color of search highlght + * sbg - bg color of search highlight + * */ +const char* +draw_string(const int x, const int y, const uint16_t fg, const uint16_t bg, + const char* s, const int mc, const int fc, const int p_l, const int p_r, + const Alignment align, const int ds, const int fill, + const uint32_t* srch, const uint16_t sfg, const uint16_t sbg) +{ + uint32_t* us = calloc(strlen(s) + 1, sizeof(uint32_t)); + if (!us) + return NULL; + u8_string_to_unicode(us, s, mc); + u32_draw_string(x, y, fg, bg, us, mc, fc, p_l, p_r, align, ds, fill, + srch, sfg, sbg); + free(us); + return s; +} + +/* mc - (max cols) pack text and padding into this many columns + * fc - (fill cols) this many columns from the left/right/center will be + * filled + * p_? - (padding) this many cells will be skipped from ? side + * ds - (display start) string starts being displayed from this display column + * counted from the start of the string; an "entry point" joining string + * index with screen + * fill - boolean; 1 = fill fc, 0 = don't fill fc + * srch - search string; if empty or NULL no highlighting happens + * sfg - fg color of search highlght + * sbg - bg color of search highlight + * */ +void +u32_draw_string(const int x, const int y, const uint16_t fg, const uint16_t bg, + const uint32_t* s, const int mc, const int fc, const int p_l, + const int p_r, const Alignment align, const int ds, const int fill, + const uint32_t* srch, const uint16_t sfg, const uint16_t sbg) +{ + /* + * <-------- visible part ----------> + * +---------+-------+----------------+---------+ + * | | | | | + * |<-- d -->|<-p_l->|<------ c ----->|<- p_r ->| + * | |<-------------- mc -------------->| + * |<------------------ fc -------------------->| + * x | | + * ds ds+c + * <.....(sc).....> + * (align == RIGHT in this case) + * */ + + int d = 0; /* distance, in screen columns, from x to + * visible part of the string, followed by + * p_l */ + + int c = 0; /* distance in screen columns from + * d + p_l to d + mc - p_r (part of the + * displayed string containing text, between + * padding; string fits within this many columns + * */ + + int sc = 0; /* current screen column; goes from 0..c-1 + * only increased when actual characters are + * written + */ + + int ssc = 0; /* current string screen column; goes from start + * of the string until ds+c */ + + const int ts = TAB_SIZE; + + const uint32_t* ps = s; /* pointer to current character in string; + * string index: ps-s */ + + uint16_t cfg = fg; /* current fg */ + uint16_t cbg = bg; /* current bg */ + + int hctl = 0; /* highlight "characters to live", when this + * reaches zero the highlighting is turned + * off */ + + c = mc - p_l - p_r; + + if (align == LEFT) + d = 0; + else if (align == RIGHT) + d = fc >= mc ? fc - mc : 0; + else if (align == CENTER) + d = fc >= mc ? (fc - mc) / 2 : 0; + + /* fill */ + if (fill) + for (int j = 0; j < fc; j++) + tb_change_cell(x + j, y, ' ', fg, bg); + + /* left padding */ + for (int j = 0; j < p_l; j++) + tb_change_cell(x + d + j, y, ' ', fg, bg); + + sc = 0; + + /* + * main idea: we go from start of the string to the end and count + * displayed characters until we get to ds, then we also output + * characters; tabs count as spaces up to multiple of ts, counted from + * the start of the string + * + * exit condition is also sc == c, when we have reached the maximum + * number of characters to output + * */ + while (ps && *ps && sc < c) + { + if (srch && *srch && hctl == 0) + { + if (u32_starts_with(ps, srch)) + { + hctl = u32_strlen(srch); + cfg = sfg; + cbg = sbg; + } + } + + if (*ps == '\t') + { + if (ssc < ds) + { + /* ssc-(ssc%ts)+ts + * \t | = ssc+(ts-(ssc%ts)) + * ----------|-----[ :|::: ] + * | | | + * | | ds + * ssc-(ssc%ts) | + * ssc + * */ + if (ssc - (ssc % ts) + ts >= ds) + { + for (int j = 0; + j < ssc - (ssc % ts) + ts - ds; + j++) + tb_change_cell(x + d + p_l + sc + + j, + y, ' ', cfg, cbg); + sc += ssc + (ts - (ssc % ts)) - ds; + hctl -= ssc + (ts - (ssc % ts)) - ds; + if (hctl < 0) + hctl = 0; + } + /* else, just increase counter + * + * \t + * ----------|----[ ::::: ] + * | | | + * | | ds + * | ssc-(ssc%ts)+ts + * ssc = ssc + (ts-(ssc%ts)) + * */ + ssc += (ts - (ssc % ts)); + } + else /* ssc >= ds */ + { + /* + * ds ssc+(ts-(ssc%ts)) + * | \t | + * [ ::::::: ]---|----- + * | | + * | ds+c + * ssc + * */ + if (ssc + (ts - (ssc % ts)) >= ds + c) + { + for (int j = 0; j < ds + c - ssc; j++) + tb_change_cell(x + d + p_l + sc + + j, + y, ' ', cfg, cbg); + sc = c; + ssc = ds + c; + hctl = 0; + cfg = fg; + cbg = bg; + } + else /* ssc+(ts-(ssc%ts)) < ds+c */ + { + /* + * \t + * [ :::::::::::|::: ]----- + * | | | | + * | | | ds+c + * | | ssc+(ts-(ssc%ts)) + * | ssc + * ds + * */ + for (int j = 0; j < ts - (ssc % ts); j++) + tb_change_cell(x + d + p_l + sc + + j, + y, ' ', cfg, cbg); + sc += ts - (ssc % ts); + hctl -= ts - (ssc % ts); + if (hctl < 0) + hctl = 0; + ssc += ts - (ssc % ts); + } + } + } + else + { + if (ssc >= ds) + { + if (sc < c) + tb_change_cell(x + d + p_l + sc, y, *ps, + cfg, cbg); + sc++; + hctl--; + if (hctl < 0) + hctl = 0; + } + ssc++; + } + if (hctl == 0) + { + cfg = fg; + cbg = bg; + } + ps++; + } + + /* right padding */ + for (int j = 0; j < p_r; j++) + tb_change_cell(x + d + p_l + c + j, y, ' ', fg, bg); +} + +const struct DrawState* +draw_help(const struct DrawState* state) +{ + if (!state) + return NULL; + + int startx, endx, starty, endy; + int w = state->help_width; + int h = HELP_HEIGHT; + int row = 0; + int maxx = state->maxx; + int maxy = state->maxy; + + startx = w > maxx ? 0 : (maxx - w) / 2; + endx = w > maxx ? maxx - 1 : maxx - startx; + + starty = h > maxy - 1 ? 0 : (maxy - h) / 2; + endy = h > maxy - 1 ? maxy - 2 : maxy - starty; + + draw_box(startx, endx, starty, endy, DLG_FG, DLG_BG); + if (!draw_string(startx, starty, TITLE_FG, TITLE_BG, help_title, + strlen(help_title) + 2, w - 2, 1, 1, CENTER, 0, 0, NULL, 0, + 0)) + return NULL; + while (row < LEN(help)) + { + if (!draw_string(startx + 1, starty + 1 + row, DLG_FG, DLG_BG, + help[row], w - 2, w - 2, 1, 1, LEFT, 0, 1, NULL, 0, + 0)) + return NULL; + row++; + } + return state; +} + +const struct DrawState* +draw_screen(const struct DrawState* state) +{ + if (!state) + return NULL; + + return state; +} + +const struct DrawState* +draw_status(const struct DrawState* state) +{ + if (!state) + return NULL; + + char buf[MAXBUFLINE]; + int seg_size = state->maxx / 3; + int current_start = 0; + const struct StatusSegment* pseg = status_segments; + + if (state->in_prompt && state->prompt[0]) + { + if (!draw_string(0, state->maxy - 1, PROMPT_FG, PROMPT_BG, + state->prompt, strlen(state->prompt) + 2, + state->maxx, 1, 1, CENTER, 0, 1, NULL, 0, 0)) + return NULL; + } + else if (state->error && state->error[0]) + { + if (!draw_string(0, state->maxy - 1, ERROR_FG, ERROR_BG, + state->error, strlen(state->error) + 2, state->maxx, + 1, 1, CENTER, 0, 1, NULL, 0, 0)) + return NULL; + } + else + while (pseg < status_segments + LEN(status_segments)) + { + int last = pseg - status_segments + == LEN(status_segments) - 1; + buf[0] = 0; + if (pseg->callback) + pseg->callback(buf, MAXBUFLINE, pseg->format, + state); + else + strncpy(buf, pseg->format, MAXBUFLINE - 1); + buf[MAXBUFLINE - 1] = 0; + if (pseg == status_segments + LEN(status_segments) - 1) + seg_size = state->maxx - 1 - current_start; + if (!draw_string(current_start, state->maxy - 1, + pseg->fg, pseg->bg, buf, + MIN(seg_size, strlen(buf) + 2), + last ? seg_size + 1 : seg_size, 1, 1, + pseg->alignment, 0, 1, NULL, 0, 0)) + return NULL; + pseg++; + current_start += seg_size; + } + + return state; +} + +const struct DrawState* +draw(const struct DrawState* state) +{ + if (!state) + return NULL; + + if (state->show_help) + if (!draw_help(state)) + return NULL; + + if (!draw_screen(state)) + return NULL; + + if (!draw_status(state)) + return NULL; + + return state; +} diff --git a/draw.h b/draw.h @@ -0,0 +1,85 @@ +/* See the file LICENSE for copyright and license details. */ +#include <stddef.h> + +#include "termbox.h" + +#define BORDER_NW ((uint32_t)L'\u250c') +#define BORDER_NE ((uint32_t)L'\u2510') +#define BORDER_SW ((uint32_t)L'\u2514') +#define BORDER_SE ((uint32_t)L'\u2518') +#define BORDER_VER ((uint32_t)L'\u2502') +#define BORDER_HOR ((uint32_t)L'\u2500') + +#define HELP_WIDTH 50 +#define HELP_HEIGHT 21 +#define TAB_SIZE 8 + +typedef enum { LEFT, CENTER, RIGHT } Alignment; + +struct BufferLine { + uint32_t* text; + size_t length; + uint16_t fg; + uint16_t bg; +}; + +struct DrawState { + char* error; + char* prompt; + char* filename; + struct BufferLine* buffer; + int column; + int row; + int first_shown_column; + int first_shown_row; + int rows_count; + int display_column; + int saved_column; + int help_width; + struct BufferLine* paste_buffer; + int paste_rows_count; + void (*prompt_callback)(struct DrawState*, struct tb_event*); + int running; + int dirty; + int in_prompt; + int show_help; + int maxx; + int maxy; +}; + +struct StatusSegment { + const char* format; + void (*callback)(char*, size_t, const char*, const struct DrawState*); + uint16_t fg; + uint16_t bg; + Alignment alignment; +}; + +void init_bufferline(struct BufferLine* bl); +void free_bufferline(struct BufferLine* bl); +void init_drawstate(struct DrawState* state, char* error, char* filename, + char* prompt); +void free_drawstate(struct DrawState* state); +size_t display_length(const struct DrawState* state, uint32_t* buffer, + const size_t max_index); +size_t buffer_length(const struct DrawState* state, uint32_t* buffer, + const size_t max_index); +int calculate_help_width(const struct DrawState* state); +void draw_rect(const int startx, const int endx, const int starty, + const int endy, const uint16_t fg, const uint16_t bg); +void draw_box(const int startx, const int endx, const int starty, + const int endy, const uint16_t fg, const uint16_t bg); +const char* draw_string(const int x, const int y, const uint16_t fg, + const uint16_t bg, const char* s, const int max_cols, + const int fill_cols, const int padding_left, const int padding_right, + const Alignment align, const int ds, const int fill, + const uint32_t* srch, const uint16_t sfg, const uint16_t sbg); +void u32_draw_string(const int x, const int y, const uint16_t fg, + const uint16_t bg, const uint32_t* s, const int max_cols, + const int fill_cols, const int padding_left, const int padding_right, + const Alignment align, const int ds, const int fill, + const uint32_t* srch, const uint16_t sfg, const uint16_t sbg); +const struct DrawState* draw_help(const struct DrawState* state); +const struct DrawState* draw_screen(const struct DrawState* state); +const struct DrawState* draw_status(const struct DrawState* state); +const struct DrawState* draw(const struct DrawState* state); diff --git a/input.inl b/input.inl @@ -0,0 +1,228 @@ +// if s1 starts with s2 returns true, else false +// len is the length of s1 +// s2 should be null-terminated +static bool starts_with(const char *s1, int len, const char *s2) +{ + int n = 0; + while (*s2 && n < len) { + if (*s1++ != *s2++) + return false; + n++; + } + return *s2 == 0; +} + +static int parse_mouse_event(struct tb_event *event, const char *buf, int len) { + if (len >= 6 && starts_with(buf, len, "\033[M")) { + // X10 mouse encoding, the simplest one + // \033 [ M Cb Cx Cy + int b = buf[3] - 32; + switch (b & 3) { + case 0: + if ((b & 64) != 0) + event->key = TB_KEY_MOUSE_WHEEL_UP; + else + event->key = TB_KEY_MOUSE_LEFT; + break; + case 1: + if ((b & 64) != 0) + event->key = TB_KEY_MOUSE_WHEEL_DOWN; + else + event->key = TB_KEY_MOUSE_MIDDLE; + break; + case 2: + event->key = TB_KEY_MOUSE_RIGHT; + break; + case 3: + event->key = TB_KEY_MOUSE_RELEASE; + break; + default: + return -6; + } + event->type = TB_EVENT_MOUSE; // TB_EVENT_KEY by default + if ((b & 32) != 0) + event->mod |= TB_MOD_MOTION; + + // the coord is 1,1 for upper left + event->x = (uint8_t)buf[4] - 1 - 32; + event->y = (uint8_t)buf[5] - 1 - 32; + + return 6; + } else if (starts_with(buf, len, "\033[<") || starts_with(buf, len, "\033[")) { + // xterm 1006 extended mode or urxvt 1015 extended mode + // xterm: \033 [ < Cb ; Cx ; Cy (M or m) + // urxvt: \033 [ Cb ; Cx ; Cy M + int i, mi = -1, starti = -1; + int isM, isU, s1 = -1, s2 = -1; + int n1 = 0, n2 = 0, n3 = 0; + + for (i = 0; i < len; i++) { + // We search the first (s1) and the last (s2) ';' + if (buf[i] == ';') { + if (s1 == -1) + s1 = i; + s2 = i; + } + + // We search for the first 'm' or 'M' + if ((buf[i] == 'm' || buf[i] == 'M') && mi == -1) { + mi = i; + break; + } + } + if (mi == -1) + return 0; + + // whether it's a capital M or not + isM = (buf[mi] == 'M'); + + if (buf[2] == '<') { + isU = 0; + starti = 3; + } else { + isU = 1; + starti = 2; + } + + if (s1 == -1 || s2 == -1 || s1 == s2) + return 0; + + n1 = strtoul(&buf[starti], NULL, 10); + n2 = strtoul(&buf[s1 + 1], NULL, 10); + n3 = strtoul(&buf[s2 + 1], NULL, 10); + + if (isU) + n1 -= 32; + + switch (n1 & 3) { + case 0: + if ((n1&64) != 0) { + event->key = TB_KEY_MOUSE_WHEEL_UP; + } else { + event->key = TB_KEY_MOUSE_LEFT; + } + break; + case 1: + if ((n1&64) != 0) { + event->key = TB_KEY_MOUSE_WHEEL_DOWN; + } else { + event->key = TB_KEY_MOUSE_MIDDLE; + } + break; + case 2: + event->key = TB_KEY_MOUSE_RIGHT; + break; + case 3: + event->key = TB_KEY_MOUSE_RELEASE; + break; + default: + return mi + 1; + } + + if (!isM) { + // on xterm mouse release is signaled by lowercase m + event->key = TB_KEY_MOUSE_RELEASE; + } + + event->type = TB_EVENT_MOUSE; // TB_EVENT_KEY by default + if ((n1&32) != 0) + event->mod |= TB_MOD_MOTION; + + event->x = (uint8_t)n2 - 1; + event->y = (uint8_t)n3 - 1; + + return mi + 1; + } + + return 0; +} + +// convert escape sequence to event, and return consumed bytes on success (failure == 0) +static int parse_escape_seq(struct tb_event *event, const char *buf, int len) +{ + int mouse_parsed = parse_mouse_event(event, buf, len); + + if (mouse_parsed != 0) + return mouse_parsed; + + // it's pretty simple here, find 'starts_with' match and return + // success, else return failure + int i; + for (i = 0; keys[i]; i++) { + if (starts_with(buf, len, keys[i])) { + event->ch = 0; + event->key = 0xFFFF-i; + return strlen(keys[i]); + } + } + return 0; +} + +static bool extract_event(struct tb_event *event, struct bytebuffer *inbuf, int inputmode) +{ + const char *buf = inbuf->buf; + const int len = inbuf->len; + if (len == 0) + return false; + + if (buf[0] == '\033') { + int n = parse_escape_seq(event, buf, len); + if (n != 0) { + bool success = true; + if (n < 0) { + success = false; + n = -n; + } + bytebuffer_truncate(inbuf, n); + return success; + } else { + // it's not escape sequence, then it's ALT or ESC, + // check inputmode + if (inputmode&TB_INPUT_ESC) { + // if we're in escape mode, fill ESC event, pop + // buffer, return success + event->ch = 0; + event->key = TB_KEY_ESC; + event->mod = 0; + bytebuffer_truncate(inbuf, 1); + return true; + } else if (inputmode&TB_INPUT_ALT) { + // if we're in alt mode, set ALT modifier to + // event and redo parsing + event->mod = TB_MOD_ALT; + bytebuffer_truncate(inbuf, 1); + return extract_event(event, inbuf, inputmode); + } + assert(!"never got here"); + } + } + + // if we're here, this is not an escape sequence and not an alt sequence + // so, it's a FUNCTIONAL KEY or a UNICODE character + + // first of all check if it's a functional key + if ((unsigned char)buf[0] <= TB_KEY_SPACE || + (unsigned char)buf[0] == TB_KEY_BACKSPACE2) + { + // fill event, pop buffer, return success */ + event->ch = 0; + event->key = (uint16_t)buf[0]; + bytebuffer_truncate(inbuf, 1); + return true; + } + + // feh... we got utf8 here + + // check if there is all bytes + if (len >= tb_utf8_char_length(buf[0])) { + /* everything ok, fill event, pop buffer, return success */ + tb_utf8_char_to_unicode(&event->ch, buf); + event->key = 0; + bytebuffer_truncate(inbuf, tb_utf8_char_length(buf[0])); + return true; + } + + // event isn't recognized, perhaps there is not enough bytes in utf8 + // sequence + return false; +} diff --git a/rebuild.do b/rebuild.do @@ -0,0 +1 @@ +redo clean all diff --git a/sled.1.in b/sled.1.in @@ -0,0 +1,116 @@ +'\" t +.\" Manpage for sled(1) +.\" vim: set filetype=groff: +. +.mso an-ext.tmac +.de CDS +.EX +.RS \\$1 +.sp 1 +.. +.de CDE +.sp 1 +.RE +.EE +.. +.de RDS +.RS \\$1 +.sp 1 +.. +.de RDE +.sp 1 +.RE +.. +. +.TH SLED "1" "%DATE%" "sled %VERSION%" "General Commands Manual" +.SH NAME +sled \- Simple text editor +. +.SH SYNOPSIS +. +.SY sled +.OP "\-h \fR|\fP \-\-help" +.YS +. +.SY sled +.OP "\-v \fR|\fP \-\-version" +.YS +. +.SY sled +.RI [ filename ] +.YS +. +.SH COPYRIGHT +. +.LP +sled Copyright \(co 2022 Strahinya Radich. +.br +This program is licensed under GNU GPL v3 or later. See the file +.I LICENSE +in the sled repository for details. For licensing details about the portion of +the code taken from the termbox library, see the file +.IR "LICENSE.termbox" . +. +.SH DESCRIPTION +. +.LP +.B sled +is a simple text editor with a terminal UI. +.SH "KEY BINDINGS" +. +.LP +Main window key bindings are as follows: +. +.TS +box tab(@); +l l. +\fBKey\fP@\fBAction\fP +_ +\fCEsc\fP@Close dialog or clear error +\fCH\fP or \fCF1\fP@Show help dialog +.TE +. +.sp 1 +. +.SH "STATUS LINE" +. +.LP +Status line is comprised of a number of segments, by default three.. +. +.SH AUTHOR +. +Strahinya Radich, +.UR https://\:strahinja.org +.UE +. +.SH "KNOWN LIMITATIONS" +. +.IP \(bu 4 +UTF-8 character set is assumed. +. +.IP \(bu +CJK characters are unsupported/problematic. This is a limitation of termbox +library. See +. +.IP "" 4 +.UR https://\:github.com/\:nsf/\:termbox +.UE +. +.IP +for more details. +. +.IP \(bu +Only one file can be edited at a time, and no additional files can be loaded at +runtime. This is a design decision. +. +.IP \(bu +The directory of the edited file must be writable by the user in order to write +the changes to the file. This is due to creating backups in order to avoid the +potential data loss under specific circumstances (loss of power during write). +. +.SH BUGS +. +.LP +Bugs can be reported using the ticket tracker at: +.UR https://\:todo.sr.ht/\:~strahinja/\:sled +.UE diff --git a/sled.c b/sled.c @@ -0,0 +1,1504 @@ +/* See the file LICENSE for copyright and license details. */ + +#define _POSIX_C_SOURCE 200809L + +#include <errno.h> +#include <stdarg.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> + +#include "version.h" +#include "termbox.h" +#include "util.h" +//#include "po.h" +#include "draw.h" +#include "config.h" + +enum { + LOAD_ERR_NONE = 0, + LOAD_ERR_CANT_ALLOC = 1, + LOAD_ERR_CANT_OPEN_FILE = 2, +}; + +enum { + SAVE_ERR_NONE = 0, + SAVE_ERR_CANT_ALLOC = 1, + SAVE_ERR_CANT_OPEN_FILE = 2, + SAVE_ERR_CANT_MOVE_FILE = 3 +}; + +extern const char* errors[]; +extern const char* prompt_dirty; +extern const char* prompt_cancel_dirty; +extern const char* prompt_overwrite; +extern const char* program_name; + +int print_error(const int code, const char* msg, ...); +int version(); +int usage(); +void format_filename(char* result, size_t result_size, const char* format, + const struct DrawState* state); +void format_msgs(char* result, size_t result_size, const char* format, + const struct DrawState* state); +void overwrite_copy_msgid_callback(struct DrawState* state, struct tb_event* ev); +void overwrite_paste_callback(struct DrawState* state, struct tb_event* ev); +void cancel_callback(struct DrawState* state, struct tb_event* ev); +void quit_callback(struct DrawState* state, struct tb_event* ev); +struct BufferLine* load_info(struct DrawState* state); +struct DrawState* load_msgstr(struct DrawState* state); +int load_file(struct DrawState* dstate, long* lineno, long* col); +int save_file(struct DrawState* state); +void save_msgstr(struct DrawState* state); +void cancel_msgstr(struct DrawState* state); +//struct DrawState* copy_msgid_to_input(struct DrawState* state); +//struct DrawState* yank_msgstr_to_paste_buffer(struct DrawState* state); +//struct DrawState* paste_paste_buffer_to_input(struct DrawState* state); +void goto_msgid(struct DrawState* state, const size_t msgid_number); +//void next_match(struct DrawState* state); +//void prev_match(struct DrawState* state); +//void next_untranslated(struct DrawState* state); +//void next_fuzzy(struct DrawState* state); +void show_edit(struct DrawState* state); +void move_up(struct DrawState* state); +void move_down(struct DrawState* state); +void edit_page_up(struct DrawState* state); +void edit_page_down(struct DrawState* state); +void move_start(struct DrawState* state); +void move_left(struct DrawState* state); +void move_right(struct DrawState* state); +void move_prev_word(struct DrawState* state); +void move_next_word(struct DrawState* state); +void erase_prev_word(struct DrawState* state); +void move_end(struct DrawState* state); +void move_list_up(struct DrawState* state); +void move_list_down(struct DrawState* state); +void move_list_start(struct DrawState* state); +void move_list_end(struct DrawState* state); +void move_list_page_up(struct DrawState* state); +void move_list_page_down(struct DrawState* state); +void next_plural(struct DrawState* state); +void prev_plural(struct DrawState* state); +void insert_char(struct DrawState* state, uint32_t ch); +void erase_backwards(struct DrawState* state); +void erase_forward(struct DrawState* state); +void erase_to_start(struct DrawState* state); +void erase_to_end(struct DrawState* state); +struct DrawState* insert_line(struct DrawState* state); +struct DrawState* join_lines(struct DrawState* state, size_t first_line, + int forward); +void handle_editbox_key_event(struct tb_event* ev, struct DrawState* state); +void handle_key_event(struct tb_event* ev, struct DrawState* state); +void handle_search_key_event(struct tb_event* ev, struct DrawState* state); + +int +print_error(const int code, const char* msg, ...) +{ + char buf[MAXBUFLINE]; + va_list args; + va_start(args, msg); + vsnprintf(buf, sizeof(buf), msg, args); + va_end(args); + fprintf(stderr, "%s: %s\n", program_name, buf); + return code; +} + +int +version() +{ + printf("%s %s, built on %s\n", program_name, VERSION, DATE); + return 0; +} + +int +usage() +{ + printf("Usage: %s [-h|--help] [-v|--version] [filename]\n", + program_name); + return 0; +} + +void +format_filename(char* result, size_t result_size, const char* format, + const struct DrawState* state) +{ + if (!result) + return; + snprintf(result, result_size, format, u8_basename(state->filename), + state->dirty ? "*" : ""); +} + +void +format_msgs(char* result, size_t result_size, const char* format, + const struct DrawState* state) +{ + if (!result) + return; + +} + +void +overwrite_copy_msgid_callback(struct DrawState* state, struct tb_event* ev) +{ + if (!state) + return; +/* + if (ev->ch == 'y') + copy_msgid_to_input(state); + */ + state->prompt_callback = NULL; +} + +void +overwrite_paste_callback(struct DrawState* state, struct tb_event* ev) +{ + if (!state) + return; +/* + if (ev->ch == 'y') + paste_paste_buffer_to_input(state); + */ + state->prompt_callback = NULL; +} + +void +cancel_callback(struct DrawState* state, struct tb_event* ev) +{ + if (!state) + return; + + if (ev->ch == 'y') + save_msgstr(state); + else + cancel_msgstr(state); + state->prompt_callback = NULL; +} + +void +quit_callback(struct DrawState* state, struct tb_event* ev) +{ + if (!state) + return; + + if (ev->ch == 'y') + { + int result = save_file(state); + switch (result) + { + case SAVE_ERR_CANT_ALLOC: + strcpy(state->error, errors[ERR_CANT_ALLOC]); + break; + case SAVE_ERR_CANT_OPEN_FILE: + strcpy(state->error, errors[ERR_CANT_SAVE]); + break; + default: + state->error[0] = 0; + } + } + state->dirty = 0; + state->prompt_callback = NULL; + state->running = 0; +} + +struct DrawState* +load_msgstr(struct DrawState* state) +{ +/* + int msgstr_index = state->msgstr_index; + struct PoEntry* current = &state->entries[state->msgid_number - 1]; + size_t num_lines = current->msgstr_count == 0 + ? 1 + : u32_lines_in_string(*(current->msgstr + msgstr_index), 0, 0); + struct BufferLine* newbuf = NULL; + struct BufferLine* pnewbuf = NULL; + + for (size_t i = 0; i < state->input_rows_count; i++) + free_bufferline(state->input_buffer + i); + free(state->input_buffer); + + newbuf = calloc(num_lines, sizeof(struct BufferLine)); + if (!newbuf) + return NULL; + + pnewbuf = newbuf; + for (size_t i = 0; i < num_lines; i++) + { + init_bufferline(pnewbuf); + uint32_t* newtext = calloc(MAXBUFLINE, sizeof(uint32_t)); + if (!newtext) + return NULL; + pnewbuf->text = newtext; + pnewbuf++; + } + + state->input_rows_count = num_lines; + + if (current->msgstr_count > 0) + { + const uint32_t* pumsgstr = *(current->msgstr + msgstr_index); + if (pumsgstr) + { + pnewbuf = newbuf; + while (*pumsgstr) + { + size_t len = 0; + size_t newlen = 0; + const uint32_t* old_pumsgstr = pumsgstr; + len = u32_next_line(*(current->msgstr + + msgstr_index), + &pumsgstr, 0, 0); + u32_strncpy(pnewbuf->text, old_pumsgstr, + MIN(len + 1, MAXBUFLINE)); + newlen = u32_decode_tabs(pnewbuf->text, + MAXBUFLINE); + pnewbuf->length = newlen; + pnewbuf++; + } + } + else + newbuf[0].length = 0; + } + else + newbuf[0].length = 0; + + state->input_buffer = newbuf; + */ + return state; +} + +int +load_file(struct DrawState* dstate, long* lineno, long* col) +{ + return LOAD_ERR_NONE; +} + +int +save_file(struct DrawState* state) +{ + return SAVE_ERR_NONE; +} + +void +save_msgstr(struct DrawState* state) +{ + /* + uint32_t* to_save = NULL; + size_t to_save_size = 0; + struct PoEntry* current = NULL; + + if (state->buffer) + { + to_save_size = state->input_rows_count * MAXMSGLINE; + to_save = calloc(to_save_size, sizeof(uint32_t)); + if (!to_save) + { + strcpy(state->error, errors[ERR_CANT_ALLOC]); + return; + } + struct BufferLine* pinput_buffer = NULL; + for (size_t i = 0; i < state->input_rows_count; i++) + { + pinput_buffer = state->input_buffer + i; + if (i == 0) + u32_strncpy(to_save, pinput_buffer->text, + to_save_size * sizeof(uint32_t)); + else + { + u32_strncat(to_save, (uint32_t*)L"\\n", + to_save_size * sizeof(uint32_t)); + u32_strncat(to_save, pinput_buffer->text, + to_save_size * sizeof(uint32_t)); + } + free_bufferline(pinput_buffer); + } + } + free(state->input_buffer); + state->input_buffer = NULL; + state->input_rows_count = 0; + for (size_t i = 0; i < state->info_rows_count; i++) + free_bufferline(state->info_buffer + i); + free(state->info_buffer); + state->dirty = (state->dirty_before_edit || state->dirty); + state->info_rows_count = 0; + state->info_buffer = NULL; + u32_encode_tabs(to_save, to_save_size * sizeof(uint32_t)); + current = &state->entries[state->msgid_number - 1]; + u32_match_msgid_ending(current->msgid, to_save, + to_save_size * sizeof(uint32_t)); + u32_set_msgstr(current, to_save, state->msgstr_index, 0, state); + update_warning(current->msgid, to_save, &current->warning); + state->input_changed_fuzzy = UNCHANGED; + + tb_set_cursor(TB_HIDE_CURSOR, TB_HIDE_CURSOR); + free(to_save); + */ +} + +void +cancel_msgstr(struct DrawState* state) +{ + if (!state->in_prompt && state->dirty) + { + state->in_prompt = 1; + strcpy(state->prompt, prompt_cancel_dirty); + state->prompt_callback = cancel_callback; + return; + } + + /* + state->show_edit = 0; + state->edit_info_focused = 0; + + for (size_t i = 0; i < state->input_rows_count; i++) + free_bufferline(state->input_buffer + i); + free(state->input_buffer); + state->input_buffer = NULL; + state->input_rows_count = 0; + if (state->info_buffer) + for (size_t i = 0; i < state->info_rows_count; i++) + free_bufferline(state->info_buffer + i); + free(state->info_buffer); + state->info_buffer = NULL; + state->info_rows_count = 0; + state->dirty = state->dirty_before_edit; + state->fuzzy_count = state->fuzzy_before_edit; + switch (state->input_changed_fuzzy) + { + case SET: + state->entries[state->msgid_number - 1].flags &= ~FL_FUZZY; + break; + case CLEARED: + state->entries[state->msgid_number - 1].flags |= FL_FUZZY; + break; + default:; + } + state->input_changed_fuzzy = UNCHANGED; +*/ + tb_set_cursor(TB_HIDE_CURSOR, TB_HIDE_CURSOR); +} + +struct DrawState* +paste_paste_buffer_to_input(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + return state; + + if (!state->in_prompt && *state->input_buffer->text) + { + state->in_prompt = 1; + strcpy(state->prompt, prompt_overwrite); + state->prompt_callback = overwrite_paste_callback; + return state; + } + + if (state->msgid_number == 1) + { + strcpy(state->error, errors[ERR_ILLEGAL_ON_FIRST]); + return NULL; + } + + size_t lines_to_init = 0; + size_t lines_to_free = 0; + struct BufferLine* pinput = NULL; + struct BufferLine* newbuf = NULL; + struct BufferLine* ppaste = NULL; + + if (!state->paste_buffer || !(*state->paste_buffer).text + || !*(*state->paste_buffer).text) + { + / leave one row / + for (size_t i = 1; i < state->input_rows_count; i++) + free_bufferline(state->input_buffer + i); + state->input_buffer = realloc(state->input_buffer, + sizeof(struct BufferLine)); + *(state->input_buffer->text) = 0; + state->input_column = 0; + state->input_display_column = 0; + state->input_first_shown_column = 0; + state->input_first_shown_row = 0; + state->input_row = 0; + state->input_rows_count = 1; + state->dirty = 1; + return state; + } + + lines_to_init = state->input_rows_count < state->paste_rows_count + ? state->paste_rows_count - state->input_rows_count + : 0; + lines_to_free = state->input_rows_count > state->paste_rows_count + ? state->input_rows_count - state->paste_rows_count + : 0; + + for (size_t i = 0; i < lines_to_free; i++) + free_bufferline( + state->input_buffer + state->input_rows_count - i - 1); + newbuf = realloc(state->input_buffer, + state->paste_rows_count * sizeof(struct BufferLine)); + ppaste = state->paste_buffer; + + if (!newbuf) + return NULL; + + for (size_t i = 0; i < lines_to_init; i++) + { + pinput = newbuf + state->paste_rows_count - 1 - i; + init_bufferline(pinput); + uint32_t* newtext = calloc(MAXBUFLINE, sizeof(uint32_t)); + if (!newtext) + return NULL; + pinput->text = newtext; + } + + if (ppaste) + for (size_t i = 0; i < state->paste_rows_count; i++) + { + pinput = newbuf + i; + u32_strncpy(pinput->text, ppaste->text, + MIN(ppaste->length + 1, MAXBUFLINE)); + pinput->length = ppaste->length; + ppaste++; + } + + state->input_rows_count = state->paste_rows_count; + state->input_buffer = newbuf; + state->dirty = 1; +*/ + return state; +} + +void +move_up(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + if (state->info_first_shown_row > 0) + state->info_first_shown_row--; + return; + } + + if (state->input_row > 0) + state->input_row--; + if (state->input_first_shown_row > state->input_row) + state->input_first_shown_row = state->input_row; + if (state->saved_column == -1) + state->saved_column = state->input_display_column; + size_t dlen = display_length(state, + state->input_buffer[state->input_row].text, + state->input_buffer[state->input_row].length); + if (dlen < state->saved_column) + state->input_display_column = dlen; + else + state->input_display_column = state->saved_column; + state->input_column = input_length(state, + state->input_buffer[state->input_row].text, + state->input_display_column); + if (state->input_first_shown_column > state->input_display_column) + state->input_first_shown_column = state->input_display_column; + if (state->input_first_shown_column + state->edit_width - 4 + < state->input_display_column) + state->input_first_shown_column + = state->input_display_column - state->edit_width + 4; + state->input_display_column = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column); + */ +} + +void +move_down(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + if (state->info_first_shown_row + (EDIT_HEIGHT - 3) / 2 + < state->info_rows_count) + state->info_first_shown_row++; + return; + } + + if (state->input_row < state->input_rows_count - 1) + state->input_row++; + if (state->input_first_shown_row + (EDIT_HEIGHT - 3) / 2 + < state->input_row) + state->input_first_shown_row + = state->input_row - (EDIT_HEIGHT - 3) / 2; + if (state->saved_column == -1) + state->saved_column = state->input_display_column; + size_t dlen = display_length(state, + state->input_buffer[state->input_row].text, + state->input_buffer[state->input_row].length); + if (dlen < state->saved_column) + state->input_display_column = dlen; + else + state->input_display_column = state->saved_column; + state->input_column = input_length(state, + state->input_buffer[state->input_row].text, + state->input_display_column); + if (state->input_first_shown_column > state->input_display_column) + state->input_first_shown_column = state->input_display_column; + if (state->input_first_shown_column + state->edit_width - 4 + < state->input_display_column) + state->input_first_shown_column + = state->input_display_column - state->edit_width + 4; + state->input_display_column = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column); + */ +} + +void +edit_page_up(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + if (state->info_first_shown_row > (EDIT_HEIGHT - 3) / 2) + state->info_first_shown_row -= (EDIT_HEIGHT - 3) / 2; + else + move_start(state); + return; + } + + if (state->dirty) + save_msgstr(state); + else / No need to call cancel_msgstr / + state->dirty = state->dirty_before_edit; + move_list_up(state); + state->msgstr_index = 0; + show_edit(state); + */ +} + +void +edit_page_down(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + if (state->info_first_shown_row + (EDIT_HEIGHT - 3) / 2 + < state->info_rows_count - 1) + state->info_first_shown_row += (EDIT_HEIGHT - 3) / 2; + return; + } + + if (state->dirty) + save_msgstr(state); + else / No need to call cancel_msgstr / + state->dirty = state->dirty_before_edit; + move_list_down(state); + state->msgstr_index = 0; + show_edit(state); + */ +} + +void +move_start(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + state->info_first_shown_row = 0; + state->info_first_shown_column = 0; + return; + } + + state->input_column = 0; + state->input_display_column = 0; + state->input_first_shown_column = 0; + */ +} + +void +move_left(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + if (state->info_first_shown_column > 0) + state->info_first_shown_column--; + return; + } + + if (state->input_column == 0) + return; + + if (state->input_buffer[state->input_row].text[state->input_column - 1] + == '\t') + state->input_display_column = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column - 1); + else + state->input_display_column--; + state->input_column--; + + if (state->input_display_column < state->input_first_shown_column) + state->input_first_shown_column = state->input_display_column; + */ +} + +void +move_right(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + if (state->info_first_shown_column + state->edit_width - 3 + < state->info_rows_maxlen + 1) + state->info_first_shown_column++; + return; + } + + size_t len = state->input_buffer[state->input_row].length; + if (state->input_column == len) + return; + + if (state->input_buffer[state->input_row].text[state->input_column] + == '\t') + state->input_display_column = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column + 1); + else + state->input_display_column++; + state->input_column++; + + if (state->input_display_column - state->input_first_shown_column + > state->edit_width - 4) + state->input_first_shown_column + = state->input_display_column - state->edit_width + 4; + */ +} + +void +move_prev_word(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + strcpy(state->error, errors[ERR_DLG_OPEN_QUIT]); + return; + } + + int i = state->input_column; + uint32_t* pline = state->input_buffer[state->input_row].text; + + if (i > 0 && u32_is_word_boundary(pline[i - 1], 0)) + i--; + while (i > 0 && u32_is_word_boundary(pline[i], 0)) + i--; + while (i > 0 && !u32_is_word_boundary(pline[i], 0) + && !u32_is_word_boundary(pline[i - 1], 0)) + i--; + + state->input_column = i; + state->input_display_column = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column); + if (state->input_display_column < state->input_first_shown_column) + state->input_first_shown_column = state->input_display_column; + */ +} + +void +move_next_word(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + strcpy(state->error, errors[ERR_DLG_OPEN_QUIT]); + return; + } + + int i = state->input_column; + uint32_t* pline = state->input_buffer[state->input_row].text; + size_t len = state->input_buffer[state->input_row].length; + + while (i < len && !u32_is_word_boundary(pline[i], 0)) + i++; + while (i < len && u32_is_word_boundary(pline[i], 0)) + i++; + state->input_column = i; + state->input_display_column = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column); + if (state->input_display_column - state->input_first_shown_column + > state->edit_width - 4) + state->input_first_shown_column + = state->input_display_column - state->edit_width + 4; + */ +} + +void +erase_prev_word(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + strcpy(state->error, errors[ERR_DLG_OPEN_QUIT]); + return; + } + + int i = state->input_column; + size_t len = state->input_buffer[state->input_row].length; + + uint32_t* pline = state->input_buffer[state->input_row].text; + + if (i > 0 && u32_is_word_boundary(pline[i - 1], 0)) + i--; + while (i > 0 && u32_is_word_boundary(pline[i], 0)) + i--; + while (i > 0 && !u32_is_word_boundary(pline[i], 0) + && !u32_is_word_boundary(pline[i - 1], 0)) + i--; + + int d = state->input_column - i; + + for (int j = i; j < len - d; j++) + pline[j] = pline[j + d]; + + len -= d; + state->input_buffer[state->input_row].length = len; + pline[len] = 0; + state->input_column = i; + state->input_display_column = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column); + state->dirty = 1; + */ +} + +void +move_end(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + if (state->info_rows_count > (EDIT_HEIGHT - 3) / 2) + state->info_first_shown_row = state->info_rows_count + - (EDIT_HEIGHT - 3) / 2; + state->info_first_shown_column = 0; + return; + } + + size_t len = state->input_buffer[state->input_row].length; + state->input_column = len; + size_t dlen = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column); + state->input_display_column = dlen; + if (dlen > state->edit_width - 4) + state->input_first_shown_column = dlen - state->edit_width + 4; + else + state->input_first_shown_column = 0; + */ +} + +void +move_list_up(struct DrawState* state) +{ + /* + if (state->msgid_number > 1) + { + state->error[0] = 0; + state->msgid_number--; + if (state->msgid_number < state->first_shown_msgid) + state->first_shown_msgid--; + } + */ +} + +void +move_list_down(struct DrawState* state) +{ + /* + if (state->msgid_number < state->msgid_count) + { + state->error[0] = 0; + state->msgid_number++; + if (state->msgid_number - state->first_shown_msgid + > state->maxy - 2) + state->first_shown_msgid++; + } + */ +} + +void +move_list_start(struct DrawState* state) +{ + /* + state->error[0] = 0; + state->msgid_number = state->msgid_count > 0 ? 1 : 0; + state->first_shown_msgid = state->msgid_number; + */ +} + +void +move_list_end(struct DrawState* state) +{ + /* + state->error[0] = 0; + state->msgid_number = state->msgid_count; + state->first_shown_msgid = state->msgid_count > 0 + ? MAX(1, state->msgid_number - (state->maxy - 2)) + : 0; + */ +} + +void +move_list_page_up(struct DrawState* state) +{ + /* + state->error[0] = 0; + if (state->msgid_number > state->maxy - 2) + { + state->msgid_number -= state->maxy - 2; + if (state->msgid_number < state->first_shown_msgid) + state->first_shown_msgid = state->msgid_number; + } + else + move_list_start(state); + */ +} + +void +move_list_page_down(struct DrawState* state) +{ + /* + state->error[0] = 0; + if (state->msgid_number < state->msgid_count - state->maxy - 2) + { + state->msgid_number += state->maxy - 2; + if (state->msgid_number - state->first_shown_msgid + > state->maxy - 2) + state->first_shown_msgid + = state->msgid_number - (state->maxy - 2); + } + else + move_list_end(state); + */ +} + +void +next_plural(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + return; + struct PoEntry* current = &state->entries[state->msgid_number - 1]; + save_msgstr(state); + if (state->msgstr_index + 1 < current->msgstr_count) + state->msgstr_index++; + show_edit(state); + */ +} + +void +prev_plural(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + return; + save_msgstr(state); + if (state->msgstr_index > 0) + state->msgstr_index--; + show_edit(state); + */ +} + +void +insert_char(struct DrawState* state, uint32_t ch) +{ + /* + if (state->edit_info_focused) + return; + struct BufferLine* buffer_line = &state->input_buffer[state->input_row]; + size_t len = buffer_line->length; + if (state->input_column < MAXBUFLINE - 1) + { + size_t i = len + 1; + int add_null = buffer_line->text[state->input_column] == 0; + while (i < MAXBUFLINE - 2 && i > state->input_column) + { + buffer_line->text[i] = buffer_line->text[i - 1]; + i--; + } + buffer_line->text[state->input_column++] = ch; + buffer_line->length++; + if (state->input_column == MAXBUFLINE) + state->input_column = MAXBUFLINE - 1; + state->input_display_column = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column); + if (state->input_display_column - state->input_first_shown_column + > state->edit_width - 4) + { + state->input_first_shown_column + = state->input_display_column + - state->edit_width + 4; + state->input_display_column = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column); + } + if (add_null) + buffer_line->text[state->input_column] = 0; + } + state->dirty = 1; + */ +} + +void +erase_backwards(struct DrawState* state) +{ + /* + struct BufferLine* buffer_line = &state->input_buffer[state->input_row]; + + if (state->input_column > 0) + { + size_t i = state->input_column; + do + { + buffer_line->text[i - 1] = buffer_line->text[i]; + i++; + } while (buffer_line->text[i]); + buffer_line->text[i - 1] = 0; + buffer_line->length--; + state->input_column--; + if (state->input_first_shown_column > 0) + { + const struct BufferLine* current_line + = &state->input_buffer[state->input_row]; + if (display_length(state, current_line->text, + current_line->length) + >= state->edit_width - 4) + state->input_first_shown_column--; + } + state->input_display_column = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column); + if (state->input_display_column + < state->input_first_shown_column) + state->input_first_shown_column + = state->input_display_column; + state->dirty = 1; + } + else if (state->input_row > 0) + { + move_up(state); + move_end(state); + erase_forward(state); + } + */ +} + +void +erase_forward(struct DrawState* state) +{ + /* + struct BufferLine* buffer_line = &state->input_buffer[state->input_row]; + + if (buffer_line->text[state->input_column]) + { + size_t i = state->input_column; + while (i < MAXBUFLINE - 2 && buffer_line->text[i + 1]) + { + buffer_line->text[i] = buffer_line->text[i + 1]; + i++; + } + buffer_line->text[i] = 0; + buffer_line->length--; + state->dirty = 1; + } + else if (state->input_row < state->input_rows_count - 1) + { + if (!join_lines(state, state->input_row, 1)) + { + strcpy(state->error, errors[ERR_CANT_ALLOC]); + state->running = 0; + } + } + */ +} + +void +erase_to_start(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + { + strcpy(state->error, errors[ERR_DLG_OPEN_QUIT]); + return; + } + + size_t i = state->input_column; + struct BufferLine* buffer_line = &state->input_buffer[state->input_row]; + size_t len = buffer_line->length; + do + { + buffer_line->text[i - state->input_column] + = buffer_line->text[i]; + i++; + } while (buffer_line->text[i]); + buffer_line->text[len - state->input_column] = 0; + buffer_line->length = len - state->input_column; + move_start(state); + state->dirty = 1; + */ +} + +void +erase_to_end(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + return; + struct BufferLine* buffer_line = &state->input_buffer[state->input_row]; + buffer_line->text[state->input_column] = 0; + buffer_line->length = state->input_column; + move_end(state); + state->dirty = 1; + */ +} + +struct DrawState* +insert_line(struct DrawState* state) +{ + /* + if (state->edit_info_focused) + return state; + state->input_rows_count++; + struct BufferLine* newbuf = realloc(state->input_buffer, + state->input_rows_count * sizeof(struct BufferLine)); + if (!newbuf) + return NULL; + + state->input_buffer = newbuf; + init_bufferline(&state->input_buffer[state->input_rows_count - 1]); + uint32_t* newtext = calloc(MAXBUFLINE, sizeof(uint32_t)); + if (!newtext) + return NULL; + state->input_buffer[state->input_rows_count - 1].text = newtext; + for (size_t i = state->input_rows_count - 1; i > state->input_row + 1; + i--) + { + u32_strncpy(state->input_buffer[i].text, + state->input_buffer[i - 1].text, MAXBUFLINE); + state->input_buffer[i].length + = state->input_buffer[i - 1].length; + } + u32_strncpy(state->input_buffer[state->input_row + 1].text, + state->input_buffer[state->input_row].text + state->input_column, + MAXBUFLINE); + state->input_buffer[state->input_row + 1].length + = u32_strlen(state->input_buffer[state->input_row + 1].text); + state->input_buffer[state->input_row].text[state->input_column] = 0; + state->input_buffer[state->input_row].length + = u32_strlen(state->input_buffer[state->input_row].text); + + state->input_row++; + if (state->input_row + > state->input_first_shown_row + (EDIT_HEIGHT - 3) / 2) + state->input_first_shown_row + = state->input_row - (EDIT_HEIGHT - 3) / 2; + move_start(state); + state->dirty = 1; +*/ + return state; +} + +struct DrawState* +join_lines(struct DrawState* state, size_t first_line, int forward) +{ + if (!state) + return NULL; + + /* + state->input_column = state->input_buffer[first_line].length; + state->input_display_column = display_length(state, + state->input_buffer[state->input_row].text, + state->input_column); + u32_strncat(state->input_buffer[first_line].text, + state->input_buffer[first_line + 1].text, MAXBUFLINE); + state->input_buffer[first_line].length + = u32_strlen(state->input_buffer[first_line].text); + if (!forward) + { + state->input_row--; + if (state->input_row < 0) + state->input_row = 0; + } + for (size_t i = first_line + 1; i < state->input_rows_count - 1; i++) + { + u32_strncpy(state->input_buffer[i].text, + state->input_buffer[i + 1].text, MAXBUFLINE); + state->input_buffer[i].length + = state->input_buffer[i + 1].length; + } + free_bufferline(state->input_buffer + state->input_rows_count - 1); + state->input_rows_count--; + struct BufferLine* newbuf = realloc(state->input_buffer, + state->input_rows_count * sizeof(struct BufferLine)); + if (!newbuf) + return NULL; + state->input_buffer = newbuf; + state->dirty = 1; +*/ + return state; +} + +void +handle_editbox_key_event(struct tb_event* ev, struct DrawState* state) +{ + if (state->in_prompt) + { + if (ev->ch == 'y' || ev->ch == 'n') + { + if (state->prompt_callback) + state->prompt_callback(state, ev); + state->in_prompt = 0; + *state->prompt = 0; + } + else if (ev->key == TB_KEY_ESC) + { + state->in_prompt = 0; + *state->prompt = 0; + } + return; + } + + if (*state->error) + *state->error = 0; + + if (ev->key != TB_KEY_ARROW_DOWN && ev->key != TB_KEY_ARROW_UP) + state->saved_column = -1; + + if (ev->key == TB_KEY_ARROW_DOWN) + move_down(state); + else if (ev->key == TB_KEY_ARROW_LEFT) + move_left(state); + else if (ev->key == TB_KEY_ARROW_RIGHT) + move_right(state); + else if (ev->key == TB_KEY_ARROW_UP) + move_up(state); + else if ((ev->key == TB_KEY_BACKSPACE || ev->key == TB_KEY_BACKSPACE2) + /*&& !state->edit_info_focused*/) + erase_backwards(state); + else if (ev->key == TB_KEY_CTRL_C) + ;//yank_msgstr_to_paste_buffer(state); + else if (ev->key == TB_KEY_CTRL_K) + erase_to_end(state); + else if (ev->key == TB_KEY_CTRL_N) + next_plural(state); + else if (ev->key == TB_KEY_CTRL_P) + prev_plural(state); + else if (ev->key == TB_KEY_CTRL_Q) + strcpy(state->error, errors[ERR_DLG_OPEN_QUIT]); + else if (ev->key == TB_KEY_CTRL_R) + move_prev_word(state); + else if (ev->key == TB_KEY_CTRL_S) + save_msgstr(state); + else if (ev->key == TB_KEY_CTRL_T) + move_next_word(state); + else if (ev->key == TB_KEY_CTRL_U) + erase_to_start(state); + else if (ev->key == TB_KEY_CTRL_V) + paste_paste_buffer_to_input(state); + else if (ev->key == TB_KEY_CTRL_W) + erase_prev_word(state); + else if (ev->key == TB_KEY_CTRL_Z) + ;//toggle_fuzzy(state); + else if (ev->key == TB_KEY_DELETE/* && !state->edit_info_focused*/) + erase_forward(state); + else if (ev->key == TB_KEY_END || ev->key == TB_KEY_CTRL_E) + move_end(state); + else if (ev->key == TB_KEY_ENTER) + { + if (!insert_line(state)) + { + strcpy(state->error, errors[ERR_CANT_ALLOC]); + state->running = 0; + } + } + else if (ev->key == TB_KEY_ESC) + cancel_msgstr(state); + else if (ev->key == TB_KEY_F5) + ;//copy_msgid_to_input(state); + else if (ev->key == TB_KEY_F6) + //state->edit_info_focused = !state->edit_info_focused; + ; + else if (ev->key == TB_KEY_F8) + ;//next_untranslated(state); + else if (ev->key == TB_KEY_F9) + ;//next_fuzzy(state); + else if (ev->key == TB_KEY_HOME || ev->key == TB_KEY_CTRL_A) + move_start(state); + else if (ev->key == TB_KEY_PGDN || ev->key == TB_KEY_CTRL_F) + edit_page_down(state); + else if (ev->key == TB_KEY_PGUP || ev->key == TB_KEY_CTRL_B) + edit_page_up(state); + else if (ev->key == TB_KEY_SPACE) + insert_char(state, ' '); + else if (ev->key == TB_KEY_TAB) + insert_char(state, '\t'); + else if (ev->ch != 0) + insert_char(state, ev->ch); +} + +void +handle_key_event(struct tb_event* ev, struct DrawState* state) +{ + if (!state) + return; + + /* + if (state->show_edit) + handle_editbox_key_event(ev, state); + else if (state->show_search) + handle_search_key_event(ev, state); + else */ + if (ev->key == TB_KEY_ESC) + { + if (state->error[0]) + state->error[0] = 0; + else if (state->in_prompt) + { + state->in_prompt = 0; + state->prompt[0] = 0; + return; + } + else if (state->show_help) + state->show_help = 0; + else + strcpy(state->error, errors[ERR_EXIT_KEY]); + } + else if ((ev->ch == 'y' || ev->ch == 'n') && state->in_prompt) + { + if (state->prompt_callback) + state->prompt_callback(state, ev); + state->in_prompt = 0; + *state->prompt = 0; + } + else if (state->in_prompt) + return; + else if (ev->ch == 'q' || ev->key == TB_KEY_CTRL_Q) + { + if (state->dirty) + { + state->in_prompt = 1; + strcpy(state->prompt, prompt_dirty); + state->prompt_callback = quit_callback; + } + else + state->running = 0; + state->error[0] = 0; + } + else if (state->show_help) + strcpy(state->error, errors[ERR_DLG_OPEN]); + else if (ev->key == TB_KEY_ARROW_DOWN || ev->ch == 'j') + move_list_down(state); + else if (ev->key == TB_KEY_ARROW_UP || ev->ch == 'k') + move_list_up(state); + else if (ev->key == TB_KEY_CTRL_B || ev->key == TB_KEY_PGUP) + move_list_page_up(state); + else if (ev->key == TB_KEY_CTRL_F || ev->key == TB_KEY_PGDN) + move_list_page_down(state); + else if (ev->key == TB_KEY_CTRL_S || ev->ch == 'w') + { + if (!state->dirty) + return; + /* + int result = save_file(state->entries, state->real_msgid_count, + state->filename, state->nplurals); + switch (result) + { + case SAVE_ERR_CANT_ALLOC: + strcpy(state->error, errors[ERR_CANT_ALLOC]); + state->running = 0; + break; + case SAVE_ERR_CANT_OPEN_FILE: + strcpy(state->error, errors[ERR_CANT_SAVE]); + state->running = 0; + break; + case SAVE_ERR_CANT_MOVE_FILE: + strcpy(state->error, strerror(errno)); + state->running = 0; + break; + case SAVE_ERR_NONE: + default: + state->error[0] = 0; + } + */ + state->dirty = 0; + } + else if (ev->key == TB_KEY_CTRL_Z || ev->ch == 'z') + ;//toggle_fuzzy(state); + else if (ev->key == TB_KEY_END || ev->ch == 'G') + move_list_end(state); + else if (ev->key == TB_KEY_ENTER) + { + /* + if (state->msgid_count == 0) + strcpy(state->error, errors[ERR_EMPTY_FILE]); + else + { + state->msgstr_index = 0; + show_edit(state); + } + */ + } + else if (ev->key == TB_KEY_F1 || ev->ch == 'H') + { + state->show_help = 1; + state->error[0] = 0; + } + else if (ev->key == TB_KEY_F3 || ev->ch == 'n') + ;//next_match(state); + else if (ev->key == TB_KEY_F4 || ev->ch == 'N') + ;//prev_match(state); + else if (ev->key == TB_KEY_F7 || ev->ch == '/') + ;//show_search(state); + else if (ev->key == TB_KEY_F8 || ev->ch == 'u') + ;//next_untranslated(state); + else if (ev->key == TB_KEY_F9 || ev->ch == 'f') + ;//next_fuzzy(state); + else if (ev->key == TB_KEY_HOME || ev->ch == 'g') + move_list_start(state); + else + strcpy(state->error, errors[ERR_UNKNOWN_KEY]); +} + +void +handle_search_key_event(struct tb_event* ev, struct DrawState* state) +{ + if (!state) + return; +/* + if (ev->key == TB_KEY_ARROW_LEFT) + ;//move_search_left(state); + else if (ev->key == TB_KEY_ARROW_RIGHT) + ;//move_search_right(state); + else if ((ev->key == TB_KEY_BACKSPACE || ev->key == TB_KEY_BACKSPACE2)) + ;//erase_search_backwards(state); + else if (ev->key == TB_KEY_CTRL_K) + erase_search_to_end(state); + else if (ev->key == TB_KEY_CTRL_R) + move_search_prev_word(state); + else if (ev->key == TB_KEY_CTRL_T) + move_search_next_word(state); + else if (ev->key == TB_KEY_CTRL_U) + erase_search_to_start(state); + else if (ev->key == TB_KEY_CTRL_W) + erase_search_prev_word(state); + else if (ev->key == TB_KEY_DELETE) + erase_search_forward(state); + else if (ev->key == TB_KEY_END || ev->key == TB_KEY_CTRL_E) + move_search_end(state); + else if (ev->key == TB_KEY_ENTER) + hide_search(state); + else if (ev->key == TB_KEY_ESC) + cancel_search(state); + else if (ev->key == TB_KEY_F3) + next_match(state); + else if (ev->key == TB_KEY_F4) + prev_match(state); + else if (ev->key == TB_KEY_HOME || ev->key == TB_KEY_CTRL_A) + move_search_start(state); + else if (ev->key == TB_KEY_SPACE) + insert_search_char(state, ' '); + else if (ev->key == TB_KEY_TAB) + insert_search_char(state, '\t'); + else if (ev->ch != 0) + insert_search_char(state, ev->ch); + */ +} + +int +main(int argc, char** argv) +{ + struct tb_event ev; + struct timespec sleep_spec; + char error[MAXBUFLINE]; + char prompt[MAXBUFLINE]; + struct DrawState state; + FILE* input = NULL; + char filename[MAXPATH]; + + error[0] = 0; + prompt[0] = 0; + filename[0] = 0; + + if (argc == 1) + return print_error(1, "No filename given"); + + if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) + return usage(); + else if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) + return version(); + else + { + strncpy(filename, argv[1], MAXPATH - 1); + filename[MAXPATH - 1] = 0; + if (!*filename) + return print_error(EINVAL, "No filename given"); + } + + if (!(input = fopen(filename, "rt"))) + return print_error(ENOENT, "No such file `%s'", filename); + fclose(input); + + init_drawstate(&state, error, filename, prompt); + + long lineno = 1; + long col = 1; + int result = load_file(&state, &lineno, &col); + switch (result) + { + case LOAD_ERR_CANT_ALLOC: + return print_error(result, "Allocation failed (out of memory?)"); + case LOAD_ERR_CANT_OPEN_FILE: + return print_error(result, "Cannot open file `%s'", filename); + case LOAD_ERR_NONE: + if (error[0] != 0) + return print_error(1, error); + break; + default: + return print_error(1, "Unknown error (%d)", result); + } + + tb_init(); + *error = 0; + state.maxx = 0; + + while (state.running) + { + tb_clear(); + + int maxx = tb_width(); + if (maxx != state.maxx) + { + state.maxx = maxx; + state.help_width = calculate_help_width(&state); + } + state.maxy = tb_height(); + + if (!draw(&state)) + strcpy(state.error, errors[ERR_CANT_ALLOC]); + tb_present(); + if (tb_peek_event(&ev, 20) > 0 && ev.type == TB_EVENT_KEY) + handle_key_event(&ev, &state); + if (state.running) + { + sleep_spec.tv_nsec = 500; + sleep_spec.tv_sec = 0; + nanosleep(&sleep_spec, NULL); + } + } + tb_shutdown(); + if (state.error && *state.error) + return print_error(1, state.error); + + free_drawstate(&state); + return 0; +} diff --git a/sled.do b/sled.do @@ -0,0 +1,8 @@ +for f in *.h.in; do + echo $f | sed -e's/\.in$//g' +done | xargs redo-ifchange +for f in *.h *.c; do + echo $f + echo $f | sed -e's/\.c$/.o/g' +done | xargs redo-ifchange +${SLED_CC:-gcc -g} -Wall -std=c99 -o $3 sled.o draw.o termbox.o util.o utf8.o diff --git a/term.inl b/term.inl @@ -0,0 +1,311 @@ +enum { + T_ENTER_CA, + T_EXIT_CA, + T_SHOW_CURSOR, + T_HIDE_CURSOR, + T_CLEAR_SCREEN, + T_SGR0, + T_UNDERLINE, + T_BOLD, + T_BLINK, + T_REVERSE, + T_ENTER_KEYPAD, + T_EXIT_KEYPAD, + T_ENTER_MOUSE, + T_EXIT_MOUSE, + T_FUNCS_NUM, +}; + +#define ENTER_MOUSE_SEQ "\x1b[?1000h\x1b[?1002h\x1b[?1015h\x1b[?1006h" +#define EXIT_MOUSE_SEQ "\x1b[?1006l\x1b[?1015l\x1b[?1002l\x1b[?1000l" + +#define EUNSUPPORTED_TERM -1 + +// rxvt-256color +static const char *rxvt_256color_keys[] = { + "\033[11~","\033[12~","\033[13~","\033[14~","\033[15~","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033[7~","\033[8~","\033[5~","\033[6~","\033[A","\033[B","\033[D","\033[C", 0 +}; +static const char *rxvt_256color_funcs[] = { + "\0337\033[?47h", "\033[2J\033[?47l\0338", "\033[?25h", "\033[?25l", "\033[H\033[2J", "\033[m", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "\033=", "\033>", ENTER_MOUSE_SEQ, EXIT_MOUSE_SEQ, +}; + +// Eterm +static const char *eterm_keys[] = { + "\033[11~","\033[12~","\033[13~","\033[14~","\033[15~","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033[7~","\033[8~","\033[5~","\033[6~","\033[A","\033[B","\033[D","\033[C", 0 +}; +static const char *eterm_funcs[] = { + "\0337\033[?47h", "\033[2J\033[?47l\0338", "\033[?25h", "\033[?25l", "\033[H\033[2J", "\033[m", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "", "", "", "", +}; + +// screen +static const char *screen_keys[] = { + "\033OP","\033OQ","\033OR","\033OS","\033[15~","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033[1~","\033[4~","\033[5~","\033[6~","\033OA","\033OB","\033OD","\033OC", 0 +}; +static const char *screen_funcs[] = { + "\033[?1049h", "\033[?1049l", "\033[34h\033[?25h", "\033[?25l", "\033[H\033[J", "\033[m", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "\033[?1h\033=", "\033[?1l\033>", ENTER_MOUSE_SEQ, EXIT_MOUSE_SEQ, +}; + +// rxvt-unicode +static const char *rxvt_unicode_keys[] = { + "\033[11~","\033[12~","\033[13~","\033[14~","\033[15~","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033[7~","\033[8~","\033[5~","\033[6~","\033[A","\033[B","\033[D","\033[C", 0 +}; +static const char *rxvt_unicode_funcs[] = { + "\033[?1049h", "\033[r\033[?1049l", "\033[?25h", "\033[?25l", "\033[H\033[2J", "\033[m\033(B", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "\033=", "\033>", ENTER_MOUSE_SEQ, EXIT_MOUSE_SEQ, +}; + +// linux +static const char *linux_keys[] = { + "\033[[A","\033[[B","\033[[C","\033[[D","\033[[E","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033[1~","\033[4~","\033[5~","\033[6~","\033[A","\033[B","\033[D","\033[C", 0 +}; +static const char *linux_funcs[] = { + "", "", "\033[?25h\033[?0c", "\033[?25l\033[?1c", "\033[H\033[J", "\033[0;10m", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "", "", "", "", +}; + +// xterm +static const char *xterm_keys[] = { + "\033OP","\033OQ","\033OR","\033OS","\033[15~","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033OH","\033OF","\033[5~","\033[6~","\033OA","\033OB","\033OD","\033OC", 0 +}; +static const char *xterm_funcs[] = { + "\033[?1049h", "\033[?1049l", "\033[?12l\033[?25h", "\033[?25l", "\033[H\033[2J", "\033(B\033[m", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "\033[?1h\033=", "\033[?1l\033>", ENTER_MOUSE_SEQ, EXIT_MOUSE_SEQ, +}; + +static struct term { + const char *name; + const char **keys; + const char **funcs; +} terms[] = { + {"rxvt-256color", rxvt_256color_keys, rxvt_256color_funcs}, + {"Eterm", eterm_keys, eterm_funcs}, + {"screen", screen_keys, screen_funcs}, + {"rxvt-unicode", rxvt_unicode_keys, rxvt_unicode_funcs}, + {"linux", linux_keys, linux_funcs}, + {"xterm", xterm_keys, xterm_funcs}, + {0, 0, 0}, +}; + +static bool init_from_terminfo = false; +static const char **keys; +static const char **funcs; + +static int try_compatible(const char *term, const char *name, + const char **tkeys, const char **tfuncs) +{ + if (strstr(term, name)) { + keys = tkeys; + funcs = tfuncs; + return 0; + } + + return EUNSUPPORTED_TERM; +} + +static int init_term_builtin(void) +{ + int i; + const char *term = getenv("TERM"); + + if (term) { + for (i = 0; terms[i].name; i++) { + if (!strcmp(terms[i].name, term)) { + keys = terms[i].keys; + funcs = terms[i].funcs; + return 0; + } + } + + /* let's do some heuristic, maybe it's a compatible terminal */ + if (try_compatible(term, "xterm", xterm_keys, xterm_funcs) == 0) + return 0; + if (try_compatible(term, "rxvt", rxvt_unicode_keys, rxvt_unicode_funcs) == 0) + return 0; + if (try_compatible(term, "linux", linux_keys, linux_funcs) == 0) + return 0; + if (try_compatible(term, "Eterm", eterm_keys, eterm_funcs) == 0) + return 0; + if (try_compatible(term, "screen", screen_keys, screen_funcs) == 0) + return 0; + if (try_compatible(term, "tmux", screen_keys, screen_funcs) == 0) + return 0; + /* let's assume that 'cygwin' is xterm compatible */ + if (try_compatible(term, "cygwin", xterm_keys, xterm_funcs) == 0) + return 0; + } + + return EUNSUPPORTED_TERM; +} + +//---------------------------------------------------------------------- +// terminfo +//---------------------------------------------------------------------- + +static char *read_file(const char *file) { + FILE *f = fopen(file, "rb"); + if (!f) + return 0; + + struct stat st; + if (fstat(fileno(f), &st) != 0) { + fclose(f); + return 0; + } + + char *data = malloc(st.st_size); + if (!data) { + fclose(f); + return 0; + } + + if (fread(data, 1, st.st_size, f) != (size_t)st.st_size) { + fclose(f); + free(data); + return 0; + } + + fclose(f); + return data; +} + +static char *terminfo_try_path(const char *path, const char *term) { + char tmp[4096]; + snprintf(tmp, sizeof(tmp), "%s/%c/%s", path, term[0], term); + tmp[sizeof(tmp)-1] = '\0'; + char *data = read_file(tmp); + if (data) { + return data; + } + + // fallback to darwin specific dirs structure + snprintf(tmp, sizeof(tmp), "%s/%x/%s", path, term[0], term); + tmp[sizeof(tmp)-1] = '\0'; + return read_file(tmp); +} + +static char *load_terminfo(void) { + char tmp[4096]; + const char *term = getenv("TERM"); + if (!term) { + return 0; + } + + // if TERMINFO is set, no other directory should be searched + const char *terminfo = getenv("TERMINFO"); + if (terminfo) { + return terminfo_try_path(terminfo, term); + } + + // next, consider ~/.terminfo + const char *home = getenv("HOME"); + if (home) { + snprintf(tmp, sizeof(tmp), "%s/.terminfo", home); + tmp[sizeof(tmp)-1] = '\0'; + char *data = terminfo_try_path(tmp, term); + if (data) + return data; + } + + // next, TERMINFO_DIRS + const char *dirs = getenv("TERMINFO_DIRS"); + if (dirs) { + snprintf(tmp, sizeof(tmp), "%s", dirs); + tmp[sizeof(tmp)-1] = '\0'; + char *dir = strtok(tmp, ":"); + while (dir) { + const char *cdir = dir; + if (strcmp(cdir, "") == 0) { + cdir = "/usr/share/terminfo"; + } + char *data = terminfo_try_path(cdir, term); + if (data) + return data; + dir = strtok(0, ":"); + } + } + + // fallback to /usr/share/terminfo + return terminfo_try_path("/usr/share/terminfo", term); +} + +#define TI_MAGIC 0432 +#define TI_ALT_MAGIC 542 +#define TI_HEADER_LENGTH 12 +#define TB_KEYS_NUM 22 + +static const char *terminfo_copy_string(char *data, int str, int table) { + const int16_t off = *(int16_t*)(data + str); + const char *src = data + table + off; + int len = strlen(src); + char *dst = malloc(len+1); + strcpy(dst, src); + return dst; +} + +static const int16_t ti_funcs[] = { + 28, 40, 16, 13, 5, 39, 36, 27, 26, 34, 89, 88, +}; + +static const int16_t ti_keys[] = { + 66, 68 /* apparently not a typo; 67 is F10 for whatever reason */, 69, + 70, 71, 72, 73, 74, 75, 67, 216, 217, 77, 59, 76, 164, 82, 81, 87, 61, + 79, 83, +}; + +static int init_term(void) { + int i; + char *data = load_terminfo(); + if (!data) { + init_from_terminfo = false; + return init_term_builtin(); + } + + int16_t *header = (int16_t*)data; + + const int number_sec_len = header[0] == TI_ALT_MAGIC ? 4 : 2; + + if ((header[1] + header[2]) % 2) { + // old quirk to align everything on word boundaries + header[2] += 1; + } + + const int str_offset = TI_HEADER_LENGTH + + header[1] + header[2] + number_sec_len * header[3]; + const int table_offset = str_offset + 2 * header[4]; + + keys = malloc(sizeof(const char*) * (TB_KEYS_NUM+1)); + for (i = 0; i < TB_KEYS_NUM; i++) { + keys[i] = terminfo_copy_string(data, + str_offset + 2 * ti_keys[i], table_offset); + } + keys[TB_KEYS_NUM] = 0; + + funcs = malloc(sizeof(const char*) * T_FUNCS_NUM); + // the last two entries are reserved for mouse. because the table offset is + // not there, the two entries have to fill in manually + for (i = 0; i < T_FUNCS_NUM-2; i++) { + funcs[i] = terminfo_copy_string(data, + str_offset + 2 * ti_funcs[i], table_offset); + } + + funcs[T_FUNCS_NUM-2] = ENTER_MOUSE_SEQ; + funcs[T_FUNCS_NUM-1] = EXIT_MOUSE_SEQ; + + init_from_terminfo = true; + free(data); + return 0; +} + +static void shutdown_term(void) { + if (init_from_terminfo) { + int i; + for (i = 0; i < TB_KEYS_NUM; i++) { + free((void*)keys[i]); + } + // the last two entries are reserved for mouse. because the table offset + // is not there, the two entries have to fill in manually and do not + // need to be freed. + for (i = 0; i < T_FUNCS_NUM-2; i++) { + free((void*)funcs[i]); + } + free(keys); + free(funcs); + } +} diff --git a/termbox.c b/termbox.c @@ -0,0 +1,681 @@ +#define _POSIX_C_SOURCE 200809L +#define _XOPEN_SOURCE + +#include <assert.h> +#include <stdlib.h> +#include <string.h> +#include <errno.h> +#include <fcntl.h> +#include <signal.h> +#include <stdio.h> +#include <stdbool.h> +#include <sys/select.h> +#include <sys/ioctl.h> +#include <sys/time.h> +#include <sys/stat.h> +#include <termios.h> +#include <unistd.h> +#include <wchar.h> + +#include "termbox.h" + +#include "bytebuffer.inl" +#include "term.inl" +#include "input.inl" + +struct cellbuf { + int width; + int height; + struct tb_cell *cells; +}; + +#define CELL(buf, x, y) (buf)->cells[(y) * (buf)->width + (x)] +#define IS_CURSOR_HIDDEN(cx, cy) (cx == -1 || cy == -1) +#define LAST_COORD_INIT -1 + +static struct termios orig_tios; + +static struct cellbuf back_buffer; +static struct cellbuf front_buffer; +static struct bytebuffer output_buffer; +static struct bytebuffer input_buffer; + +static int termw = -1; +static int termh = -1; + +static int inputmode = TB_INPUT_ESC; +static int outputmode = TB_OUTPUT_NORMAL; + +static int inout; +static int winch_fds[2]; + +static int lastx = LAST_COORD_INIT; +static int lasty = LAST_COORD_INIT; +static int cursor_x = -1; +static int cursor_y = -1; + +static uint16_t background = TB_DEFAULT; +static uint16_t foreground = TB_DEFAULT; + +static void write_cursor(int x, int y); +static void write_sgr(uint16_t fg, uint16_t bg); + +static void cellbuf_init(struct cellbuf *buf, int width, int height); +static void cellbuf_resize(struct cellbuf *buf, int width, int height); +static void cellbuf_clear(struct cellbuf *buf); +static void cellbuf_free(struct cellbuf *buf); + +static void update_size(void); +static void update_term_size(void); +static void send_attr(uint16_t fg, uint16_t bg); +static void send_char(int x, int y, uint32_t c); +static void send_clear(void); +static void sigwinch_handler(int xxx); +static int wait_fill_event(struct tb_event *event, struct timeval *timeout); + +/* may happen in a different thread */ +static volatile int buffer_size_change_request; + +/* -------------------------------------------------------- */ + +int tb_init_fd(int inout_) +{ + inout = inout_; + if (inout == -1) { + return TB_EFAILED_TO_OPEN_TTY; + } + + if (init_term() < 0) { + close(inout); + return TB_EUNSUPPORTED_TERMINAL; + } + + if (pipe(winch_fds) < 0) { + close(inout); + return TB_EPIPE_TRAP_ERROR; + } + + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = sigwinch_handler; + sa.sa_flags = 0; + sigaction(SIGWINCH, &sa, 0); + + tcgetattr(inout, &orig_tios); + + struct termios tios; + memcpy(&tios, &orig_tios, sizeof(tios)); + + tios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP + | INLCR | IGNCR | ICRNL | IXON); + tios.c_oflag &= ~OPOST; + tios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); + tios.c_cflag &= ~(CSIZE | PARENB); + tios.c_cflag |= CS8; + tios.c_cc[VMIN] = 0; + tios.c_cc[VTIME] = 0; + tcsetattr(inout, TCSAFLUSH, &tios); + + bytebuffer_init(&input_buffer, 128); + bytebuffer_init(&output_buffer, 32 * 1024); + + bytebuffer_puts(&output_buffer, funcs[T_ENTER_CA]); + bytebuffer_puts(&output_buffer, funcs[T_ENTER_KEYPAD]); + bytebuffer_puts(&output_buffer, funcs[T_HIDE_CURSOR]); + send_clear(); + + update_term_size(); + cellbuf_init(&back_buffer, termw, termh); + cellbuf_init(&front_buffer, termw, termh); + cellbuf_clear(&back_buffer); + cellbuf_clear(&front_buffer); + + return 0; +} + +int tb_init_file(const char* name){ + return tb_init_fd(open(name, O_RDWR)); +} + +int tb_init(void) +{ + return tb_init_file("/dev/tty"); +} + +void tb_shutdown(void) +{ + if (termw == -1) { + fputs("tb_shutdown() should not be called twice.", stderr); + abort(); + } + + bytebuffer_puts(&output_buffer, funcs[T_SHOW_CURSOR]); + bytebuffer_puts(&output_buffer, funcs[T_SGR0]); + bytebuffer_puts(&output_buffer, funcs[T_CLEAR_SCREEN]); + bytebuffer_puts(&output_buffer, funcs[T_EXIT_CA]); + bytebuffer_puts(&output_buffer, funcs[T_EXIT_KEYPAD]); + bytebuffer_puts(&output_buffer, funcs[T_EXIT_MOUSE]); + bytebuffer_flush(&output_buffer, inout); + tcsetattr(inout, TCSAFLUSH, &orig_tios); + + shutdown_term(); + close(inout); + close(winch_fds[0]); + close(winch_fds[1]); + + cellbuf_free(&back_buffer); + cellbuf_free(&front_buffer); + bytebuffer_free(&output_buffer); + bytebuffer_free(&input_buffer); + termw = termh = -1; +} + +void tb_present(void) +{ + int x,y,w,i; + struct tb_cell *back, *front; + + /* invalidate cursor position */ + lastx = LAST_COORD_INIT; + lasty = LAST_COORD_INIT; + + if (buffer_size_change_request) { + update_size(); + buffer_size_change_request = 0; + } + + for (y = 0; y < front_buffer.height; ++y) { + for (x = 0; x < front_buffer.width; ) { + back = &CELL(&back_buffer, x, y); + front = &CELL(&front_buffer, x, y); + w = wcwidth(back->ch); + if (w < 1) w = 1; + if (memcmp(back, front, sizeof(struct tb_cell)) == 0) { + x += w; + continue; + } + memcpy(front, back, sizeof(struct tb_cell)); + send_attr(back->fg, back->bg); + if (w > 1 && x >= front_buffer.width - (w - 1)) { + // Not enough room for wide ch, so send spaces + for (i = x; i < front_buffer.width; ++i) { + send_char(i, y, ' '); + } + } else { + send_char(x, y, back->ch); + for (i = 1; i < w; ++i) { + front = &CELL(&front_buffer, x + i, y); + front->ch = 0; + front->fg = back->fg; + front->bg = back->bg; + } + } + x += w; + } + } + if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y)) + write_cursor(cursor_x, cursor_y); + bytebuffer_flush(&output_buffer, inout); +} + +void tb_set_cursor(int cx, int cy) +{ + if (IS_CURSOR_HIDDEN(cursor_x, cursor_y) && !IS_CURSOR_HIDDEN(cx, cy)) + bytebuffer_puts(&output_buffer, funcs[T_SHOW_CURSOR]); + + if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y) && IS_CURSOR_HIDDEN(cx, cy)) + bytebuffer_puts(&output_buffer, funcs[T_HIDE_CURSOR]); + + cursor_x = cx; + cursor_y = cy; + if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y)) + write_cursor(cursor_x, cursor_y); +} + +void tb_put_cell(int x, int y, const struct tb_cell *cell) +{ + if ((unsigned)x >= (unsigned)back_buffer.width) + return; + if ((unsigned)y >= (unsigned)back_buffer.height) + return; + CELL(&back_buffer, x, y) = *cell; +} + +void tb_change_cell(int x, int y, uint32_t ch, uint16_t fg, uint16_t bg) +{ + struct tb_cell c = {ch, fg, bg}; + tb_put_cell(x, y, &c); +} + +void tb_blit(int x, int y, int w, int h, const struct tb_cell *cells) +{ + if (x + w < 0 || x >= back_buffer.width) + return; + if (y + h < 0 || y >= back_buffer.height) + return; + int xo = 0, yo = 0, ww = w, hh = h; + if (x < 0) { + xo = -x; + ww -= xo; + x = 0; + } + if (y < 0) { + yo = -y; + hh -= yo; + y = 0; + } + if (ww > back_buffer.width - x) + ww = back_buffer.width - x; + if (hh > back_buffer.height - y) + hh = back_buffer.height - y; + + int sy; + struct tb_cell *dst = &CELL(&back_buffer, x, y); + const struct tb_cell *src = cells + yo * w + xo; + size_t size = sizeof(struct tb_cell) * ww; + + for (sy = 0; sy < hh; ++sy) { + memcpy(dst, src, size); + dst += back_buffer.width; + src += w; + } +} + +struct tb_cell *tb_cell_buffer(void) +{ + return back_buffer.cells; +} + +int tb_poll_event(struct tb_event *event) +{ + return wait_fill_event(event, 0); +} + +int tb_peek_event(struct tb_event *event, int timeout) +{ + struct timeval tv; + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout - (tv.tv_sec * 1000)) * 1000; + return wait_fill_event(event, &tv); +} + +int tb_width(void) +{ + return termw; +} + +int tb_height(void) +{ + return termh; +} + +void tb_clear(void) +{ + if (buffer_size_change_request) { + update_size(); + buffer_size_change_request = 0; + } + cellbuf_clear(&back_buffer); +} + +int tb_select_input_mode(int mode) +{ + if (mode) { + if ((mode & (TB_INPUT_ESC | TB_INPUT_ALT)) == 0) + mode |= TB_INPUT_ESC; + + /* technically termbox can handle that, but let's be nice and show here + what mode is actually used */ + if ((mode & (TB_INPUT_ESC | TB_INPUT_ALT)) == (TB_INPUT_ESC | TB_INPUT_ALT)) + mode &= ~TB_INPUT_ALT; + + inputmode = mode; + if (mode&TB_INPUT_MOUSE) { + bytebuffer_puts(&output_buffer, funcs[T_ENTER_MOUSE]); + bytebuffer_flush(&output_buffer, inout); + } else { + bytebuffer_puts(&output_buffer, funcs[T_EXIT_MOUSE]); + bytebuffer_flush(&output_buffer, inout); + } + } + return inputmode; +} + +int tb_select_output_mode(int mode) +{ + if (mode) + outputmode = mode; + return outputmode; +} + +void tb_set_clear_attributes(uint16_t fg, uint16_t bg) +{ + foreground = fg; + background = bg; +} + +/* -------------------------------------------------------- */ + +static int convertnum(uint32_t num, char* buf) { + int i, l = 0; + int ch; + do { + buf[l++] = '0' + (num % 10); + num /= 10; + } while (num); + for(i = 0; i < l / 2; i++) { + ch = buf[i]; + buf[i] = buf[l - 1 - i]; + buf[l - 1 - i] = ch; + } + return l; +} + +#define WRITE_LITERAL(X) bytebuffer_append(&output_buffer, (X), sizeof(X)-1) +#define WRITE_INT(X) bytebuffer_append(&output_buffer, buf, convertnum((X), buf)) + +static void write_cursor(int x, int y) { + char buf[32]; + WRITE_LITERAL("\033["); + WRITE_INT(y+1); + WRITE_LITERAL(";"); + WRITE_INT(x+1); + WRITE_LITERAL("H"); +} + +static void write_sgr(uint16_t fg, uint16_t bg) { + char buf[32]; + + if (fg == TB_DEFAULT && bg == TB_DEFAULT) + return; + + switch (outputmode) { + case TB_OUTPUT_256: + case TB_OUTPUT_216: + case TB_OUTPUT_GRAYSCALE: + WRITE_LITERAL("\033["); + if (fg != TB_DEFAULT) { + WRITE_LITERAL("38;5;"); + WRITE_INT(fg); + if (bg != TB_DEFAULT) { + WRITE_LITERAL(";"); + } + } + if (bg != TB_DEFAULT) { + WRITE_LITERAL("48;5;"); + WRITE_INT(bg); + } + WRITE_LITERAL("m"); + break; + case TB_OUTPUT_NORMAL: + default: + WRITE_LITERAL("\033["); + if (fg != TB_DEFAULT) { + WRITE_LITERAL("3"); + WRITE_INT(fg - 1); + if (bg != TB_DEFAULT) { + WRITE_LITERAL(";"); + } + } + if (bg != TB_DEFAULT) { + WRITE_LITERAL("4"); + WRITE_INT(bg - 1); + } + WRITE_LITERAL("m"); + break; + } +} + +static void cellbuf_init(struct cellbuf *buf, int width, int height) +{ + buf->cells = (struct tb_cell*)malloc(sizeof(struct tb_cell) * width * height); + assert(buf->cells); + buf->width = width; + buf->height = height; +} + +static void cellbuf_resize(struct cellbuf *buf, int width, int height) +{ + if (buf->width == width && buf->height == height) + return; + + int oldw = buf->width; + int oldh = buf->height; + struct tb_cell *oldcells = buf->cells; + + cellbuf_init(buf, width, height); + cellbuf_clear(buf); + + int minw = (width < oldw) ? width : oldw; + int minh = (height < oldh) ? height : oldh; + int i; + + for (i = 0; i < minh; ++i) { + struct tb_cell *csrc = oldcells + (i * oldw); + struct tb_cell *cdst = buf->cells + (i * width); + memcpy(cdst, csrc, sizeof(struct tb_cell) * minw); + } + + free(oldcells); +} + +static void cellbuf_clear(struct cellbuf *buf) +{ + int i; + int ncells = buf->width * buf->height; + + for (i = 0; i < ncells; ++i) { + buf->cells[i].ch = ' '; + buf->cells[i].fg = foreground; + buf->cells[i].bg = background; + } +} + +static void cellbuf_free(struct cellbuf *buf) +{ + free(buf->cells); +} + +static void get_term_size(int *w, int *h) +{ + struct winsize sz; + memset(&sz, 0, sizeof(sz)); + + ioctl(inout, TIOCGWINSZ, &sz); + + if (w) *w = sz.ws_col; + if (h) *h = sz.ws_row; +} + +static void update_term_size(void) +{ + struct winsize sz; + memset(&sz, 0, sizeof(sz)); + + ioctl(inout, TIOCGWINSZ, &sz); + + termw = sz.ws_col; + termh = sz.ws_row; +} + +static void send_attr(uint16_t fg, uint16_t bg) +{ +#define LAST_ATTR_INIT 0xFFFF + static uint16_t lastfg = LAST_ATTR_INIT, lastbg = LAST_ATTR_INIT; + if (fg != lastfg || bg != lastbg) { + bytebuffer_puts(&output_buffer, funcs[T_SGR0]); + + uint16_t fgcol; + uint16_t bgcol; + + switch (outputmode) { + case TB_OUTPUT_256: + fgcol = fg & 0xFF; + bgcol = bg & 0xFF; + break; + + case TB_OUTPUT_216: + fgcol = fg & 0xFF; if (fgcol > 215) fgcol = 7; + bgcol = bg & 0xFF; if (bgcol > 215) bgcol = 0; + fgcol += 0x10; + bgcol += 0x10; + break; + + case TB_OUTPUT_GRAYSCALE: + fgcol = fg & 0xFF; if (fgcol > 23) fgcol = 23; + bgcol = bg & 0xFF; if (bgcol > 23) bgcol = 0; + fgcol += 0xe8; + bgcol += 0xe8; + break; + + case TB_OUTPUT_NORMAL: + default: + fgcol = fg & 0x0F; + bgcol = bg & 0x0F; + } + + if (fg & TB_BOLD) + bytebuffer_puts(&output_buffer, funcs[T_BOLD]); + if (bg & TB_BOLD) + bytebuffer_puts(&output_buffer, funcs[T_BLINK]); + if (fg & TB_UNDERLINE) + bytebuffer_puts(&output_buffer, funcs[T_UNDERLINE]); + if ((fg & TB_REVERSE) || (bg & TB_REVERSE)) + bytebuffer_puts(&output_buffer, funcs[T_REVERSE]); + + write_sgr(fgcol, bgcol); + + lastfg = fg; + lastbg = bg; + } +} + +static void send_char(int x, int y, uint32_t c) +{ + char buf[7]; + int bw = tb_utf8_unicode_to_char(buf, c); + if (x-1 != lastx || y != lasty) + write_cursor(x, y); + lastx = x; lasty = y; + if(!c) buf[0] = ' '; // replace 0 with whitespace + bytebuffer_append(&output_buffer, buf, bw); +} + +static void send_clear(void) +{ + send_attr(foreground, background); + bytebuffer_puts(&output_buffer, funcs[T_CLEAR_SCREEN]); + if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y)) + write_cursor(cursor_x, cursor_y); + bytebuffer_flush(&output_buffer, inout); + + /* we need to invalidate cursor position too and these two vars are + * used only for simple cursor positioning optimization, cursor + * actually may be in the correct place, but we simply discard + * optimization once and it gives us simple solution for the case when + * cursor moved */ + lastx = LAST_COORD_INIT; + lasty = LAST_COORD_INIT; +} + +static void sigwinch_handler(int xxx) +{ + (void) xxx; + const int zzz = 1; + write(winch_fds[1], &zzz, sizeof(int)); +} + +static void update_size(void) +{ + update_term_size(); + cellbuf_resize(&back_buffer, termw, termh); + cellbuf_resize(&front_buffer, termw, termh); + cellbuf_clear(&front_buffer); + send_clear(); +} + +static int read_up_to(int n) { + assert(n > 0); + const int prevlen = input_buffer.len; + bytebuffer_resize(&input_buffer, prevlen + n); + + int read_n = 0; + while (read_n <= n) { + ssize_t r = 0; + if (read_n < n) { + r = read(inout, input_buffer.buf + prevlen + read_n, n - read_n); + } +#ifdef __CYGWIN__ + // While linux man for tty says when VMIN == 0 && VTIME == 0, read + // should return 0 when there is nothing to read, cygwin's read returns + // -1. Not sure why and if it's correct to ignore it, but let's pretend + // it's zero. + if (r < 0) r = 0; +#endif + if (r < 0) { + // EAGAIN / EWOULDBLOCK shouldn't occur here + assert(errno != EAGAIN && errno != EWOULDBLOCK); + return -1; + } else if (r > 0) { + read_n += r; + } else { + bytebuffer_resize(&input_buffer, prevlen + read_n); + return read_n; + } + } + assert(!"unreachable"); + return 0; +} + +static int wait_fill_event(struct tb_event *event, struct timeval *timeout) +{ + // ;-) +#define ENOUGH_DATA_FOR_PARSING 64 + fd_set events; + memset(event, 0, sizeof(struct tb_event)); + + // try to extract event from input buffer, return on success + event->type = TB_EVENT_KEY; + if (extract_event(event, &input_buffer, inputmode)) + return event->type; + + // it looks like input buffer is incomplete, let's try the short path, + // but first make sure there is enough space + int n = read_up_to(ENOUGH_DATA_FOR_PARSING); + if (n < 0) + return -1; + if (n > 0 && extract_event(event, &input_buffer, inputmode)) + return event->type; + + // n == 0, or not enough data, let's go to select + while (1) { + FD_ZERO(&events); + FD_SET(inout, &events); + FD_SET(winch_fds[0], &events); + int maxfd = (winch_fds[0] > inout) ? winch_fds[0] : inout; + int result = select(maxfd+1, &events, 0, 0, timeout); + if (!result) + return 0; + + if (FD_ISSET(inout, &events)) { + event->type = TB_EVENT_KEY; + n = read_up_to(ENOUGH_DATA_FOR_PARSING); + if (n < 0) + return -1; + + if (n == 0) + continue; + + if (extract_event(event, &input_buffer, inputmode)) + return event->type; + } + if (FD_ISSET(winch_fds[0], &events)) { + event->type = TB_EVENT_RESIZE; + int zzz = 0; + read(winch_fds[0], &zzz, sizeof(int)); + buffer_size_change_request = 1; + get_term_size(&event->w, &event->h); + return TB_EVENT_RESIZE; + } + } +} diff --git a/termbox.h b/termbox.h @@ -0,0 +1,320 @@ +#pragma once + +#include <stdint.h> + +/* for shared objects */ +#if __GNUC__ >= 4 + #define SO_IMPORT __attribute__((visibility("default"))) +#else + #define SO_IMPORT +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* Key constants. See also struct tb_event's key field. + * + * These are a safe subset of terminfo keys, which exist on all popular + * terminals. Termbox uses only them to stay truly portable. + */ +#define TB_KEY_F1 (0xFFFF-0) +#define TB_KEY_F2 (0xFFFF-1) +#define TB_KEY_F3 (0xFFFF-2) +#define TB_KEY_F4 (0xFFFF-3) +#define TB_KEY_F5 (0xFFFF-4) +#define TB_KEY_F6 (0xFFFF-5) +#define TB_KEY_F7 (0xFFFF-6) +#define TB_KEY_F8 (0xFFFF-7) +#define TB_KEY_F9 (0xFFFF-8) +#define TB_KEY_F10 (0xFFFF-9) +#define TB_KEY_F11 (0xFFFF-10) +#define TB_KEY_F12 (0xFFFF-11) +#define TB_KEY_INSERT (0xFFFF-12) +#define TB_KEY_DELETE (0xFFFF-13) +#define TB_KEY_HOME (0xFFFF-14) +#define TB_KEY_END (0xFFFF-15) +#define TB_KEY_PGUP (0xFFFF-16) +#define TB_KEY_PGDN (0xFFFF-17) +#define TB_KEY_ARROW_UP (0xFFFF-18) +#define TB_KEY_ARROW_DOWN (0xFFFF-19) +#define TB_KEY_ARROW_LEFT (0xFFFF-20) +#define TB_KEY_ARROW_RIGHT (0xFFFF-21) +#define TB_KEY_MOUSE_LEFT (0xFFFF-22) +#define TB_KEY_MOUSE_RIGHT (0xFFFF-23) +#define TB_KEY_MOUSE_MIDDLE (0xFFFF-24) +#define TB_KEY_MOUSE_RELEASE (0xFFFF-25) +#define TB_KEY_MOUSE_WHEEL_UP (0xFFFF-26) +#define TB_KEY_MOUSE_WHEEL_DOWN (0xFFFF-27) + +/* These are all ASCII code points below SPACE character and a BACKSPACE key. */ +#define TB_KEY_CTRL_TILDE 0x00 +#define TB_KEY_CTRL_2 0x00 /* clash with 'CTRL_TILDE' */ +#define TB_KEY_CTRL_A 0x01 +#define TB_KEY_CTRL_B 0x02 +#define TB_KEY_CTRL_C 0x03 +#define TB_KEY_CTRL_D 0x04 +#define TB_KEY_CTRL_E 0x05 +#define TB_KEY_CTRL_F 0x06 +#define TB_KEY_CTRL_G 0x07 +#define TB_KEY_BACKSPACE 0x08 +#define TB_KEY_CTRL_H 0x08 /* clash with 'CTRL_BACKSPACE' */ +#define TB_KEY_TAB 0x09 +#define TB_KEY_CTRL_I 0x09 /* clash with 'TAB' */ +#define TB_KEY_CTRL_J 0x0A +#define TB_KEY_CTRL_K 0x0B +#define TB_KEY_CTRL_L 0x0C +#define TB_KEY_ENTER 0x0D +#define TB_KEY_CTRL_M 0x0D /* clash with 'ENTER' */ +#define TB_KEY_CTRL_N 0x0E +#define TB_KEY_CTRL_O 0x0F +#define TB_KEY_CTRL_P 0x10 +#define TB_KEY_CTRL_Q 0x11 +#define TB_KEY_CTRL_R 0x12 +#define TB_KEY_CTRL_S 0x13 +#define TB_KEY_CTRL_T 0x14 +#define TB_KEY_CTRL_U 0x15 +#define TB_KEY_CTRL_V 0x16 +#define TB_KEY_CTRL_W 0x17 +#define TB_KEY_CTRL_X 0x18 +#define TB_KEY_CTRL_Y 0x19 +#define TB_KEY_CTRL_Z 0x1A +#define TB_KEY_ESC 0x1B +#define TB_KEY_CTRL_LSQ_BRACKET 0x1B /* clash with 'ESC' */ +#define TB_KEY_CTRL_3 0x1B /* clash with 'ESC' */ +#define TB_KEY_CTRL_4 0x1C +#define TB_KEY_CTRL_BACKSLASH 0x1C /* clash with 'CTRL_4' */ +#define TB_KEY_CTRL_5 0x1D +#define TB_KEY_CTRL_RSQ_BRACKET 0x1D /* clash with 'CTRL_5' */ +#define TB_KEY_CTRL_6 0x1E +#define TB_KEY_CTRL_7 0x1F +#define TB_KEY_CTRL_SLASH 0x1F /* clash with 'CTRL_7' */ +#define TB_KEY_CTRL_UNDERSCORE 0x1F /* clash with 'CTRL_7' */ +#define TB_KEY_SPACE 0x20 +#define TB_KEY_BACKSPACE2 0x7F +#define TB_KEY_CTRL_8 0x7F /* clash with 'BACKSPACE2' */ + +/* These are non-existing ones. + * + * #define TB_KEY_CTRL_1 clash with '1' + * #define TB_KEY_CTRL_9 clash with '9' + * #define TB_KEY_CTRL_0 clash with '0' + */ + +/* + * Alt modifier constant, see tb_event.mod field and tb_select_input_mode function. + * Mouse-motion modifier + */ +#define TB_MOD_ALT 0x01 +#define TB_MOD_MOTION 0x02 + +/* Colors (see struct tb_cell's fg and bg fields). */ +#define TB_DEFAULT 0x00 +#define TB_BLACK 0x01 +#define TB_RED 0x02 +#define TB_GREEN 0x03 +#define TB_YELLOW 0x04 +#define TB_BLUE 0x05 +#define TB_MAGENTA 0x06 +#define TB_CYAN 0x07 +#define TB_WHITE 0x08 + +/* Attributes, it is possible to use multiple attributes by combining them + * using bitwise OR ('|'). Although, colors cannot be combined. But you can + * combine attributes and a single color. See also struct tb_cell's fg and bg + * fields. + */ +#define TB_BOLD 0x0100 +#define TB_UNDERLINE 0x0200 +#define TB_REVERSE 0x0400 + +/* A cell, single conceptual entity on the terminal screen. The terminal screen + * is basically a 2d array of cells. It has the following fields: + * - 'ch' is a unicode character + * - 'fg' foreground color and attributes + * - 'bg' background color and attributes + */ +struct tb_cell { + uint32_t ch; + uint16_t fg; + uint16_t bg; +}; + +#define TB_EVENT_KEY 1 +#define TB_EVENT_RESIZE 2 +#define TB_EVENT_MOUSE 3 + +/* An event, single interaction from the user. The 'mod' and 'ch' fields are + * valid if 'type' is TB_EVENT_KEY. The 'w' and 'h' fields are valid if 'type' + * is TB_EVENT_RESIZE. The 'x' and 'y' fields are valid if 'type' is + * TB_EVENT_MOUSE. The 'key' field is valid if 'type' is either TB_EVENT_KEY + * or TB_EVENT_MOUSE. The fields 'key' and 'ch' are mutually exclusive; only + * one of them can be non-zero at a time. + */ +struct tb_event { + uint8_t type; + uint8_t mod; /* modifiers to either 'key' or 'ch' below */ + uint16_t key; /* one of the TB_KEY_* constants */ + uint32_t ch; /* unicode character */ + int32_t w; + int32_t h; + int32_t x; + int32_t y; +}; + +/* Error codes returned by tb_init(). All of them are self-explanatory, except + * the pipe trap error. Termbox uses unix pipes in order to deliver a message + * from a signal handler (SIGWINCH) to the main event reading loop. Honestly in + * most cases you should just check the returned code as < 0. + */ +#define TB_EUNSUPPORTED_TERMINAL -1 +#define TB_EFAILED_TO_OPEN_TTY -2 +#define TB_EPIPE_TRAP_ERROR -3 + +/* Initializes the termbox library. This function should be called before any + * other functions. Function tb_init is same as tb_init_file("/dev/tty"). + * After successful initialization, the library must be + * finalized using the tb_shutdown() function. + */ +SO_IMPORT int tb_init(void); +SO_IMPORT int tb_init_file(const char* name); +SO_IMPORT int tb_init_fd(int inout); +SO_IMPORT void tb_shutdown(void); + +/* Returns the size of the internal back buffer (which is the same as + * terminal's window size in characters). The internal buffer can be resized + * after tb_clear() or tb_present() function calls. Both dimensions have an + * unspecified negative value when called before tb_init() or after + * tb_shutdown(). + */ +SO_IMPORT int tb_width(void); +SO_IMPORT int tb_height(void); + +/* Clears the internal back buffer using TB_DEFAULT color or the + * color/attributes set by tb_set_clear_attributes() function. + */ +SO_IMPORT void tb_clear(void); +SO_IMPORT void tb_set_clear_attributes(uint16_t fg, uint16_t bg); + +/* Synchronizes the internal back buffer with the terminal. */ +SO_IMPORT void tb_present(void); + +#define TB_HIDE_CURSOR -1 + +/* Sets the position of the cursor. Upper-left character is (0, 0). If you pass + * TB_HIDE_CURSOR as both coordinates, then the cursor will be hidden. Cursor + * is hidden by default. + */ +SO_IMPORT void tb_set_cursor(int cx, int cy); + +/* Changes cell's parameters in the internal back buffer at the specified + * position. + */ +SO_IMPORT void tb_put_cell(int x, int y, const struct tb_cell *cell); +SO_IMPORT void tb_change_cell(int x, int y, uint32_t ch, uint16_t fg, uint16_t bg); + +/* Copies the buffer from 'cells' at the specified position, assuming the + * buffer is a two-dimensional array of size ('w' x 'h'), represented as a + * one-dimensional buffer containing lines of cells starting from the top. + * + * (DEPRECATED: use tb_cell_buffer() instead and copy memory on your own) + */ +SO_IMPORT void tb_blit(int x, int y, int w, int h, const struct tb_cell *cells); + +/* Returns a pointer to internal cell back buffer. You can get its dimensions + * using tb_width() and tb_height() functions. The pointer stays valid as long + * as no tb_clear() and tb_present() calls are made. The buffer is + * one-dimensional buffer containing lines of cells starting from the top. + */ +SO_IMPORT struct tb_cell *tb_cell_buffer(void); + +#define TB_INPUT_CURRENT 0 /* 000 */ +#define TB_INPUT_ESC 1 /* 001 */ +#define TB_INPUT_ALT 2 /* 010 */ +#define TB_INPUT_MOUSE 4 /* 100 */ + +/* Sets the termbox input mode. Termbox has two input modes: + * 1. Esc input mode. + * When ESC sequence is in the buffer and it doesn't match any known + * ESC sequence => ESC means TB_KEY_ESC. + * 2. Alt input mode. + * When ESC sequence is in the buffer and it doesn't match any known + * sequence => ESC enables TB_MOD_ALT modifier for the next keyboard event. + * + * You can also apply TB_INPUT_MOUSE via bitwise OR operation to either of the + * modes (e.g. TB_INPUT_ESC | TB_INPUT_MOUSE). If none of the main two modes + * were set, but the mouse mode was, TB_INPUT_ESC mode is used. If for some + * reason you've decided to use (TB_INPUT_ESC | TB_INPUT_ALT) combination, it + * will behave as if only TB_INPUT_ESC was selected. + * + * If 'mode' is TB_INPUT_CURRENT, it returns the current input mode. + * + * Default termbox input mode is TB_INPUT_ESC. + */ +SO_IMPORT int tb_select_input_mode(int mode); + +#define TB_OUTPUT_CURRENT 0 +#define TB_OUTPUT_NORMAL 1 +#define TB_OUTPUT_256 2 +#define TB_OUTPUT_216 3 +#define TB_OUTPUT_GRAYSCALE 4 + +/* Sets the termbox output mode. Termbox has three output options: + * 1. TB_OUTPUT_NORMAL => [1..8] + * This mode provides 8 different colors: + * black, red, green, yellow, blue, magenta, cyan, white + * Shortcut: TB_BLACK, TB_RED, ... + * Attributes: TB_BOLD, TB_UNDERLINE, TB_REVERSE + * + * Example usage: + * tb_change_cell(x, y, '@', TB_BLACK | TB_BOLD, TB_RED); + * + * 2. TB_OUTPUT_256 => [0..256] + * In this mode you can leverage the 256 terminal mode: + * 0x00 - 0x07: the 8 colors as in TB_OUTPUT_NORMAL + * 0x08 - 0x0f: TB_* | TB_BOLD + * 0x10 - 0xe7: 216 different colors + * 0xe8 - 0xff: 24 different shades of grey + * + * Example usage: + * tb_change_cell(x, y, '@', 184, 240); + * tb_change_cell(x, y, '@', 0xb8, 0xf0); + * + * 3. TB_OUTPUT_216 => [0..216] + * This mode supports the 3rd range of the 256 mode only. + * But you don't need to provide an offset. + * + * 4. TB_OUTPUT_GRAYSCALE => [0..23] + * This mode supports the 4th range of the 256 mode only. + * But you dont need to provide an offset. + * + * Execute build/src/demo/output to see its impact on your terminal. + * + * If 'mode' is TB_OUTPUT_CURRENT, it returns the current output mode. + * + * Default termbox output mode is TB_OUTPUT_NORMAL. + */ +SO_IMPORT int tb_select_output_mode(int mode); + +/* Wait for an event up to 'timeout' milliseconds and fill the 'event' + * structure with it, when the event is available. Returns the type of the + * event (one of TB_EVENT_* constants) or -1 if there was an error or 0 in case + * there were no event during 'timeout' period. + */ +SO_IMPORT int tb_peek_event(struct tb_event *event, int timeout); + +/* Wait for an event forever and fill the 'event' structure with it, when the + * event is available. Returns the type of the event (one of TB_EVENT_* + * constants) or -1 if there was an error. + */ +SO_IMPORT int tb_poll_event(struct tb_event *event); + +/* Utility utf8 functions. */ +#define TB_EOF -1 +SO_IMPORT int tb_utf8_char_length(char c); +SO_IMPORT int tb_utf8_char_to_unicode(uint32_t *out, const char *c); +SO_IMPORT int tb_utf8_unicode_to_char(char *out, uint32_t c); + +#ifdef __cplusplus +} +#endif diff --git a/utf8.c b/utf8.c @@ -0,0 +1,79 @@ +#include "termbox.h" + +static const unsigned char utf8_length[256] = { + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1 +}; + +static const unsigned char utf8_mask[6] = { + 0x7F, + 0x1F, + 0x0F, + 0x07, + 0x03, + 0x01 +}; + +int tb_utf8_char_length(char c) +{ + return utf8_length[(unsigned char)c]; +} + +int tb_utf8_char_to_unicode(uint32_t *out, const char *c) +{ + if (*c == 0) + return TB_EOF; + + int i; + unsigned char len = tb_utf8_char_length(*c); + unsigned char mask = utf8_mask[len-1]; + uint32_t result = c[0] & mask; + for (i = 1; i < len; ++i) { + result <<= 6; + result |= c[i] & 0x3f; + } + + *out = result; + return (int)len; +} + +int tb_utf8_unicode_to_char(char *out, uint32_t c) +{ + int len = 0; + int first; + int i; + + if (c < 0x80) { + first = 0; + len = 1; + } else if (c < 0x800) { + first = 0xc0; + len = 2; + } else if (c < 0x10000) { + first = 0xe0; + len = 3; + } else if (c < 0x200000) { + first = 0xf0; + len = 4; + } else if (c < 0x4000000) { + first = 0xf8; + len = 5; + } else { + first = 0xfc; + len = 6; + } + + for (i = len - 1; i > 0; --i) { + out[i] = (c & 0x3f) | 0x80; + c >>= 6; + } + out[0] = c | first; + + return len; +} diff --git a/util.c b/util.c @@ -0,0 +1,466 @@ +/* See the file LICENSE for copyright and license details. */ +#include <bits/stdint-uintn.h> +#include <stdarg.h> +#include <stddef.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "termbox.h" +//#include "po.h" +#include "util.h" + +size_t +u8_string_to_unicode(uint32_t* us, const char* s, const size_t max) +{ + uint32_t uch; + uint32_t* pus = us; + int u8_len = 0; + size_t added = 0; + + while (s && *s && u8_len != TB_EOF) + { + u8_len = tb_utf8_char_to_unicode(&uch, s); + if (added + 1 > max) + break; + *pus++ = uch; + if (u8_len != TB_EOF) + { + s += u8_len; + added++; + } + } + *pus++ = 0; + return added; +} + +size_t +unicode_string_to_u8(char* s, const uint32_t* us, const size_t max) +{ + char ch[8]; + const uint32_t* pus = us; + size_t added = 0; + + if (!pus) + return added; + + *s = 0; + while (*pus) + { + int len = tb_utf8_unicode_to_char(ch, *pus); + if (added + 1 > max) + break; + strncat(s, ch, len); + added++; + pus++; + } + return added; +} + +size_t +u32_match_msgid_ending(const uint32_t* msgid, uint32_t* msgstr, size_t max) +{ + uint32_t* buf = calloc(max + 1, sizeof(uint32_t)); + if (!buf) + return 0; + size_t buf_len = 0; + size_t msgid_len = 0; + + buf_len = u32_strcpy(buf, msgstr); + msgid_len = u32_strlen(msgid); + + if (msgid_len > 1 + && u32_starts_with(msgid + msgid_len - 2, (uint32_t*)L"\\n")) + { + if (!(buf_len > 1 + && u32_starts_with(buf + buf_len - 2, + (uint32_t*)L"\\n"))) + { + buf_len += 2; + buf[buf_len - 2] = '\\'; + buf[buf_len - 1] = 'n'; + buf[buf_len] = 0; + } + } + else if (msgid_len > 0 + && u32_strstr((uint32_t*)L" .", msgid + msgid_len - 1)) + { + if (!(buf_len > 0 + && u32_strstr((uint32_t*)L" .", buf + buf_len - 1))) + { + buf_len++; + buf[buf_len - 1] = msgid[msgid_len - 1]; + buf[buf_len] = 0; + } + } + else if (buf_len > 1 + && u32_starts_with(buf + buf_len - 2, (uint32_t*)L"\\n")) + { + buf_len -= 2; + buf[buf_len] = 0; + } + else if (buf_len > 0 && u32_strstr((uint32_t*)L" .", buf + buf_len - 1)) + { + buf_len--; + buf[buf_len] = 0; + } + + u32_strncpy(msgstr, buf, max); + + return buf_len; +} + +size_t +u32_count_chars(const uint32_t* s, const uint32_t ch) +{ + size_t result = 0; + const uint32_t* ps = s; + while (*ps) + { + if (*ps == ch) + result++; + ps++; + } + return result; +} + +size_t +u32_count_strings(const uint32_t* haystack, const uint32_t* needle) +{ + size_t result = 0; + const uint32_t* phaystack = haystack; + size_t needle_len = 0; + + if (!haystack || !needle) + return 0; + + needle_len = u32_strlen(needle); + if (!needle_len) + return 0; + + while (*phaystack) + { + if (u32_starts_with(phaystack, needle)) + result++; + phaystack++; + } + return result; +} + +size_t +u32_encode_tabs(uint32_t* s, size_t max) +{ + uint32_t* buf = calloc(max + 1, sizeof(uint32_t)); + if (!buf) + return 0; + uint32_t* pbuf = buf; + uint32_t* ps = s; + size_t newlen = 0; + + while (*ps) + { + if (*ps == '\t') + { + *pbuf++ = '\\'; + *pbuf++ = 't'; + ps++; + newlen += 2; + } + else + { + *pbuf++ = *ps++; + newlen++; + } + } + *pbuf = 0; + u32_strncpy(s, buf, max); + free(buf); + return newlen; +} + +size_t +u32_decode_tabs(uint32_t* s, size_t max) +{ + uint32_t* buf = calloc(max + 1, sizeof(uint32_t)); + if (!buf) + return 0; + uint32_t* pbuf = buf; + uint32_t* ps = s; + size_t newlen = 0; + + while (*ps) + { + if (*ps == '\\' && *(ps + 1) == 't') + { + *pbuf++ = '\t'; + ps += 2; + newlen++; + } + else + { + *pbuf++ = *ps++; + newlen++; + } + } + *pbuf = 0; + u32_strncpy(s, buf, max); + free(buf); + return newlen; +} + +size_t +u32_strlen(const uint32_t* s) +{ + const uint32_t* ps = s; + size_t len = 0; + if (!s) + return 0; + while (*ps++) + len++; + return len; +} + +uint32_t* +u32_strstr(uint32_t* haystack, const uint32_t* needle) +{ + uint32_t* ph = haystack; + while (*ph) + { + if (u32_starts_with(ph, needle)) + return ph; + ph++; + } + return NULL; +} + +uint32_t* +u32_strchr(uint32_t* haystack, const uint32_t needle) +{ + uint32_t* ph = haystack; + while (*ph) + { + if (*ph == needle) + return ph; + ph++; + } + return NULL; +} + +size_t +u32_strcpy(uint32_t* to, const uint32_t* from) +{ + const uint32_t* pfrom = from; + size_t copied = 0; + while (*pfrom) + { + *to++ = *pfrom++; + copied++; + } + *to = 0; + return copied; +} + +size_t +u32_strncpy(uint32_t* to, const uint32_t* from, size_t max) +{ + const uint32_t* pfrom = from; + size_t copied = 0; + while (*pfrom && copied < max - 1) + { + *to++ = *pfrom++; + copied++; + } + *to = 0; + return copied; +} + +/* + * to - u32 string to concatenate to + * from - u32 string to concatenate + * max - total combined string size */ +size_t +u32_strncat(uint32_t* to, const uint32_t* from, size_t max) +{ + const uint32_t* pfrom = from; + size_t copied = 0; + while (*to) + { + to++; + copied++; + } + while (*pfrom && copied < max - 1) + { + *to++ = *pfrom++; + copied++; + } + *to = 0; + return copied; +} + +size_t +u32_u8_strncpy(uint32_t* to, const char* from, size_t max) +{ + uint32_t* ufrom = calloc(strlen(from) + 1, sizeof(uint32_t)); + if (!ufrom) + return 0; + u8_string_to_unicode(ufrom, from, max); + size_t len = u32_strncpy(to, ufrom, max); + free(ufrom); + return len; +} + +size_t +u8_u32_strncpy(char* to, const uint32_t* from, size_t max) +{ + char* cfrom = calloc(u32_strlen(from) * UTF8REPMAX + 1, 1); + if (!cfrom) + return 0; + unicode_string_to_u8(cfrom, from, max); + strncpy(to, cfrom, max); + to[max - 1] = 0; + free(cfrom); + return strlen(to); +} + +/* wrap - if >0, also wrap lines + * */ +size_t +u32_lines_in_string(const uint32_t* s, const int include_eol, const size_t wrap) +{ + size_t result = 1; + const uint32_t* ps = NULL; + int last_empty = 0; + + if (!s) + return result; + + ps = s; + while (*ps) + { + u32_next_line(s, &ps, include_eol, wrap); + if (*ps) + result++; + } + if (ps > s + 1 && *(ps - 2) == '\\' && *(ps - 1) == 'n') + last_empty = 1; + return result + last_empty; +} + +/* + * returns line length + * s - entire string (multiple lines) + * next_line - pointer to the next line; if NULL, only line length is returned + * wrap - wrap lines to this many characters (runes); if 0, don't wrap + */ +size_t +u32_next_line(const uint32_t* s, const uint32_t** next_line, + const int include_eol, const size_t wrap) +{ + size_t result = 0; + const uint32_t* ps = NULL; + const uint32_t* start = NULL; + size_t last_nonblank = 0; + int have_last_nonblank = 0; + + if (!s) + return result; + + start = s; + if (next_line) + start = *next_line; + ps = start; + while (*ps) + { + if (wrap > 0 && result > wrap) + { + size_t cutoff = wrap; + + if (have_last_nonblank) + cutoff = last_nonblank + 1; + if (next_line) + *next_line = start + cutoff; + + return cutoff; + } + + if (*ps == '\\' && *(ps + 1) == 'n') + { + if (next_line) + *next_line = ps + 2; + return result + (include_eol ? 2 : 0); + } + + if (!u32_is_word_boundary(*ps, 1) + && u32_is_word_boundary(*(ps + 1), 1)) + { + last_nonblank = ps - start; + have_last_nonblank = 1; + } + + ps++; + result++; + } + + if (next_line) + *next_line = ps; + + return result; +} + +int +u32_is_word_boundary(const uint32_t ch, const int strictly_whitespace) +{ + return strictly_whitespace + ? u32_strchr((uint32_t*)L" \v\t", ch) != NULL + : u32_strchr((uint32_t*)L" \v\t()[]{},.;:/\\", ch) != NULL; +} + +int +starts_with(const char* s, const char* with) +{ + while (*s && *s == *with) + { + if (*s != *with) + return 0; + s++; + with++; + } + return *with == 0; +} + +int +u32_starts_with(const uint32_t* s, const uint32_t* with) +{ + while (*s && *s == *with) + { + if (*s != *with) + return 0; + s++; + with++; + } + return *with == 0; +} + +const char* +u8_basename(const char* path) +{ + if (!path) + return NULL; + const char* ppath = path + strlen(path); + while (ppath != path && *ppath != '/') + ppath--; + if (*ppath == '/') + ppath++; + return ppath; +} + +void +poe_log(const char* msg, ...) +{ + va_list args; + va_start(args, msg); + FILE* log = fopen("/tmp/poe.log", "at"); + vfprintf(log, msg, args); + va_end(args); + fclose(log); +} diff --git a/util.h b/util.h @@ -0,0 +1,54 @@ +#include <bits/stdint-uintn.h> +#include <sys/types.h> +#define ABS(a) ((a < 0) ? (-a) : (a)) +#define LEN(x) (sizeof(x) / sizeof(x[0])) +#define MAX(a, b) ((a > b) ? a : b) +#define MIN(a, b) ((a < b) ? a : b) + +enum { + ERR_UNKNOWN_KEY, + ERR_EXIT_KEY, + ERR_DLG_OPEN, + ERR_DLG_OPEN_QUIT, + ERR_EMPTY_FILE, + ERR_CANT_ALLOC, + ERR_CANT_SAVE, + ERR_CANT_MOVE, + ERR_ILLEGAL_ON_FIRST, + ERR_NO_PLURAL_FORMS +}; + +#define MAXBUFLINE 4096 +#define MAXDATEBUF 80 +#define MAXFLAGSBUF (4 + 1) +#define MAXMSGLINE 1024 +#define MSGDELTA 1024 +#define MAXPATH 1024 +/* maximum chars for UTF-8 representations of Unicode chars, per Unicode char */ +#define UTF8REPMAX 6 + +size_t u8_string_to_unicode(uint32_t* us, const char* s, const size_t max); +size_t unicode_string_to_u8(char* s, const uint32_t* us, const size_t max); +size_t u32_match_msgid_ending(const uint32_t* msgid, uint32_t* msgstr, + size_t max); +size_t u32_count_chars(const uint32_t* s, const uint32_t ch); +size_t u32_count_strings(const uint32_t* haystack, const uint32_t* needle); +size_t u32_encode_tabs(uint32_t* s, size_t max); +size_t u32_decode_tabs(uint32_t* s, size_t max); +size_t u32_strlen(const uint32_t* s); +uint32_t* u32_strstr(uint32_t* haystack, const uint32_t* needle); +uint32_t* u32_strchr(uint32_t* haystack, const uint32_t needle); +size_t u32_strcpy(uint32_t* to, const uint32_t* from); +size_t u32_strncpy(uint32_t* to, const uint32_t* from, size_t max); +size_t u32_strncat(uint32_t* to, const uint32_t* from, size_t max); +size_t u32_u8_strncpy(uint32_t* to, const char* from, size_t max); +size_t u8_u32_strncpy(char* to, const uint32_t* from, size_t max); +size_t u32_lines_in_string(const uint32_t* s, const int include_eol, + const size_t wrap); +size_t u32_next_line(const uint32_t* s, const uint32_t** sptr, + const int include_eol, const size_t wrap); +int u32_is_word_boundary(const uint32_t ch, const int strictly_whitespace); +int starts_with(const char* s, const char* with); +int u32_starts_with(const uint32_t* s, const uint32_t* with); +const char* u8_basename(const char* path); +void poe_log(const char* msg, ...); diff --git a/version.do b/version.do @@ -0,0 +1,5 @@ +FALLBACKVER=${FALLBACKVER:-unknown} +{ command -v git >/dev/null 2>&1 && git describe >/dev/null 2>&1; } && \ + git describe 2>/dev/null | sed 's/^v//' >$3 || echo $FALLBACKVER >$3 +redo-always +redo-stamp <$3 diff --git a/version.h.in b/version.h.in @@ -0,0 +1,4 @@ +/* See the file LICENSE for copyright and license details. */ + +#define VERSION "%VERSION%" +#define DATE "%DATE%"