чување e5af08f756af7c5f8c7ae58280256a7ace6d1e29
Аутор: Страхиња Радић <contact@strahinja.org>
Датум: Sun, 16 May 2021 22:58:20 +0200
Initial commit
Signed-off-by: Страхиња Радић <contact@strahinja.org>
Diffstat:
| A | .gitignore | | | 18 | ++++++++++++++++++ |
| A | LICENSE | | | 674 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | README | | | 14 | ++++++++++++++ |
| A | all.do | | | 5 | +++++ |
| A | bytebuffer.inl | | | 70 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | clean.do | | | 2 | ++ |
| A | default.o.do | | | 3 | +++ |
| A | do | | | 446 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | input.inl | | | 228 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | poe.c | | | 383 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | poe.do | | | 5 | +++++ |
| A | rebuild.do | | | 2 | ++ |
| A | term.inl | | | 311 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | termbox.c | | | 678 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | termbox.h | | | 320 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | utf8.c | | | 79 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
измењених датотека: 16, додавања: 3238(+), брисања: 0(-)
diff --git a/.gitignore b/.gitignore
@@ -0,0 +1,18 @@
+.cache
+.redo
+*.session
+.do_built
+.do_built.dir
+*~
+*.bak
+*.orig
+*.rej
+*.o
+*.swp
+*.did
+nohup.out
+*.gz
+poe
+date
+version
+
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/README b/README
@@ -0,0 +1,14 @@
+poe - .po file editor
+=====================
+
+Q: Why?
+A: - There should be no need for GNOME to edit .po files.
+ - Some folks prefer CLI to GUI.
+ - No, plugin for vi(m) isn't enough.
+
+Q: This doesn't do anything!
+A: It's a work in progress. It doesn't have to do anything (yet).
+
+Q: Why C?
+A: Because <Go/Rust/whatever soydev language of the moment> sucks.
+
diff --git a/all.do b/all.do
@@ -0,0 +1,5 @@
+for f in *.c; do
+ echo $f | sed -e's/\.c$/.o/g'
+done | xargs redo-ifchange
+redo-ifchange poe
+
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,2 @@
+rm -f *~ *.o poe
+
diff --git a/default.o.do b/default.o.do
@@ -0,0 +1,3 @@
+redo-ifchange $2.c
+gcc -g -Wall -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/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/poe.c b/poe.c
@@ -0,0 +1,383 @@
+/*
+ * poe - .po file editor
+ * Copyright (C) 2021 Страхиња Радић
+ *
+ * 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/>.
+ *
+ */
+
+#include <bits/stdint-uintn.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <time.h>
+
+#include "termbox.h"
+
+#define BORDER_NW u'\u250c'
+#define BORDER_NE u'\u2510'
+#define BORDER_SW u'\u2514'
+#define BORDER_SE u'\u2518'
+#define BORDER_VER u'\u2502'
+#define BORDER_HOR u'\u2500'
+#define PROGRAMNAME "poe"
+#define ERROR_FG TB_WHITE | TB_BOLD
+#define ERROR_BG TB_RED
+#define SHADOW_FG TB_BLACK
+#define SHADOW_BG TB_BLACK | TB_BOLD
+#define LEN(x) (sizeof(x) / sizeof(x[0]))
+
+typedef enum {
+ LEFT,
+ CENTER,
+ RIGHT
+} Alignment;
+
+enum {
+ ERR_UNKNOWN_KEY,
+ ERR_NO_PREV,
+ ERR_NO_NEXT,
+ ERR_EXITKEY
+};
+
+typedef struct {
+ const char* format;
+ void (*callback)(char*, size_t, const char*);
+ uint16_t fg;
+ uint16_t bg;
+ Alignment alignment;
+} StatusSegment;
+
+static const char* title = " poe - .po File Editor ";
+static const char* help[] = {
+ "ESC - Close dialog, clear error",
+ "H | F1 - Show this screen",
+ "k | ↑ - Previous entry",
+ "j | ↓ - Next entry",
+ "q - Quit"
+};
+static const char* errors[] = {
+ [ERR_UNKNOWN_KEY] = "Unknown key (press F1 for help)",
+ [ERR_NO_PREV] = "No previous entry",
+ [ERR_NO_NEXT] = "No next entry",
+ [ERR_EXITKEY] = "Press q to quit"
+};
+
+void format_filename(char* result, size_t result_size, const char* format);
+void format_msgs(char* result, size_t result_size, const char* format);
+
+static const StatusSegment status_segments[] = {
+ { "%s", format_filename, TB_BLACK, TB_WHITE, LEFT },
+ { "msg:%ld/%ld", format_msgs, TB_WHITE | TB_BOLD, TB_BLUE, CENTER },
+ { "H=HELP, q=QUIT", NULL, TB_BLACK, TB_WHITE, RIGHT },
+};
+
+#define MAXBUF 255
+#define MAXPATH 1024
+
+char filename[MAXPATH];
+char error[MAXBUF];
+
+long msgid_count = 0;
+long msgid_index = 0;
+int show_help = 0;
+int maxx, maxy;
+
+int
+print_error(const int code, const char* msg, ...)
+{
+ char buf[MAXBUF];
+ va_list args;
+ va_start(args, msg);
+ vsnprintf(buf, sizeof(buf), msg, args);
+ va_end(args);
+ fprintf(stderr, "%s: %s\n", PROGRAMNAME, buf);
+ return code;
+}
+
+void
+format_filename(char* result, size_t result_size, const char* format)
+{
+ if (!result)
+ return;
+
+ snprintf(result, result_size, format, filename);
+}
+
+void
+format_msgs(char* result, size_t result_size, const char* format)
+{
+ if (!result)
+ return;
+
+ snprintf(result, result_size, format, msgid_index, msgid_count);
+}
+
+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+1, starty, BORDER_NW, fg, bg);
+ for (x = startx+2; x < endx-2; x++)
+ tb_change_cell(x, starty, BORDER_HOR, fg, bg);
+ tb_change_cell(endx-2, starty, BORDER_NE, fg, bg);
+
+ for (y = starty+1; y < endy-2; y++)
+ {
+ tb_change_cell(startx+1, y, BORDER_VER, fg, bg);
+ for (x = startx+2; x < endx-2; x++)
+ tb_change_cell(x, y, ' ', fg, bg);
+ tb_change_cell(endx-2, y, BORDER_VER, fg, bg);
+ tb_change_cell(endx-1, y, ' ', SHADOW_FG, SHADOW_BG);
+ }
+
+ tb_change_cell(startx+1, endy-2, BORDER_SW, fg, bg);
+ for (x = startx+2; x < endx-2; x++)
+ tb_change_cell(x, endy-2, BORDER_HOR, fg, bg);
+ tb_change_cell(endx-2, endy-2, BORDER_SE, fg, bg);
+ tb_change_cell(endx-1, endy-2, ' ', SHADOW_FG, SHADOW_BG);
+
+ for (x = startx+2; x < endx; x++)
+ tb_change_cell(x, endy-1, ' ', SHADOW_FG, SHADOW_BG);
+}
+
+size_t
+u8_string_to_unicode(uint32_t* us, const char* s)
+{
+ uint32_t uch;
+ uint32_t* pus = us;
+ int u8_len = 0;
+ size_t result = 0;
+
+ while (*s && u8_len != TB_EOF)
+ {
+ u8_len = tb_utf8_char_to_unicode(&uch, s);
+ *pus++ = uch;
+ if (u8_len != TB_EOF)
+ {
+ s += u8_len;
+ result++;
+ }
+ }
+ return result;
+}
+
+void
+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, const Alignment align)
+{
+ int col;
+ uint32_t* us = calloc(strlen(s)+1, sizeof(uint32_t));
+ uint32_t* pus = NULL;
+ size_t us_len = 0;
+ us_len = u8_string_to_unicode(us, s);
+ pus = us;
+
+ if (align == LEFT)
+ {
+ for (col = 0; col < fill_cols; col++)
+ tb_change_cell(x+col, y, ' ', fg, bg);
+ col = 0;
+ }
+ else if (align == RIGHT)
+ {
+ for (col = 0; col < fill_cols; col++)
+ tb_change_cell(x+col, y, ' ', fg, bg);
+ col = max_cols-us_len-padding-1;
+ }
+ else if (align == CENTER)
+ {
+ for (col = (max_cols-fill_cols)/2;
+ col < (max_cols+fill_cols)/2; col++)
+ tb_change_cell(x+col, y, ' ', fg, bg);
+
+ if (s)
+ {
+ if (us_len > max_cols)
+ {
+ pus += (us_len-max_cols)/2;
+ col = 0;
+ }
+ else
+ col = (max_cols-us_len)/2-padding;
+ }
+ }
+
+ while (*pus && col < max_cols-padding)
+ {
+ tb_change_cell(x+col+padding, y, *pus, fg, bg);
+ pus++;
+ col++;
+ }
+ if (us)
+ free(us);
+}
+
+void
+draw_help()
+{
+ int startx, endx, starty, endy;
+ int w = 50;
+ int h = 20;
+ int row = 0;
+
+ 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, TB_BLACK, TB_WHITE);
+ draw_string(startx+1, starty, TB_BLACK | TB_BOLD | TB_REVERSE, TB_WHITE,
+ title, w-2, strlen(title)+2, 1, CENTER);
+ while (row < sizeof(help)/sizeof(*help))
+ {
+ draw_string(startx+2, starty+3+row, TB_BLACK, TB_WHITE,
+ help[row], w-4, w-4, 2, LEFT);
+ row++;
+ }
+}
+
+void
+draw_status()
+{
+ int seg_size = maxx/3;
+ char buf[MAXBUF];
+ int current_start = 0;
+ const StatusSegment* pseg = status_segments;
+
+ if (*error)
+ draw_string(0, maxy-1, ERROR_FG, ERROR_BG, error, maxx, maxx,
+ 1, CENTER);
+ else
+ while (pseg < status_segments + LEN(status_segments))
+ {
+ buf[0] = 0;
+ if (pseg->callback)
+ pseg->callback(buf, MAXBUF, pseg->format);
+ else
+ strncpy(buf, pseg->format, MAXBUF);
+ draw_string(current_start, maxy-1, pseg->fg, pseg->bg,
+ buf, seg_size, seg_size, 1,
+ pseg->alignment);
+ pseg++;
+ current_start += seg_size;
+ }
+}
+
+void
+draw()
+{
+ if (show_help)
+ draw_help();
+ draw_status();
+}
+
+int
+main(int argc, char** argv)
+{
+ int running = 1;
+ struct tb_event ev;
+ struct timespec sleep_spec;
+ FILE* input = NULL;
+
+ filename[0] = 0;
+
+ if (argc > 1)
+ {
+ strncpy(filename, argv[1], MAXPATH-1);
+ filename[MAXPATH-1] = 0;
+ if (!filename[0])
+ print_error(EINVAL, "Invalid argument");
+ }
+
+ if (!filename[0])
+ return print_error(1, "No filename given");
+
+ if (!(input = fopen(filename, "rt")))
+ return print_error(ENOENT, "No such file `%s'", filename);
+
+ tb_init();
+ error[0] = 0;
+ while (running)
+ {
+ tb_clear();
+ maxx = tb_width();
+ maxy = tb_height();
+ draw();
+ tb_present();
+ if (tb_peek_event(&ev, 20) > 0)
+ {
+ switch (ev.type)
+ {
+ case TB_EVENT_KEY:
+
+ if (ev.key == TB_KEY_ESC)
+ {
+ if (show_help)
+ show_help = 0;
+ else if (*error)
+ error[0] = 0;
+ else
+ strcpy(error, errors[ERR_EXITKEY]);
+ }
+ else if (ev.key == TB_KEY_F1
+ || ev.ch == 'H')
+ {
+ show_help = 1;
+ error[0] = 0;
+ }
+ else if (ev.ch == 'q')
+ running = 0;
+ else if (ev.key == TB_KEY_ARROW_UP
+ || ev.ch == 'k')
+ {
+ if (msgid_index == 0)
+ strcpy(error, errors[ERR_NO_PREV]);
+ else
+ msgid_index--;
+ }
+ else if (ev.key == TB_KEY_ARROW_DOWN
+ || ev.ch == 'j')
+ {
+ if (!msgid_count || msgid_index
+ == msgid_count-1)
+ strcpy(error, errors[ERR_NO_NEXT]);
+ else
+ msgid_index++;
+ }
+ else
+ strcpy(error, errors[ERR_UNKNOWN_KEY]);
+ break;
+ }
+ }
+ if (running)
+ {
+ sleep_spec.tv_nsec = 500;
+ sleep_spec.tv_sec = 0;
+ nanosleep(&sleep_spec, NULL);
+ }
+ }
+ fclose(input);
+ tb_shutdown();
+ return 0;
+}
+
diff --git a/poe.do b/poe.do
@@ -0,0 +1,5 @@
+for f in *.c; do
+ echo $f
+done | xargs redo-ifchange
+gcc -g -Wall -o $3 poe.o termbox.o utf8.o
+
diff --git a/rebuild.do b/rebuild.do
@@ -0,0 +1,2 @@
+redo clean all
+
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,678 @@
+#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;
+}