diff options
| -rw-r--r-- | COPYING | 367 | ||||
| -rw-r--r-- | Makefile | 47 | ||||
| -rw-r--r-- | README.md | 34 | ||||
| -rw-r--r-- | libtui/README | 1 | ||||
| -rw-r--r-- | libtui/keys.ha | 43 | ||||
| -rw-r--r-- | libtui/layout/layout.ha | 55 | ||||
| -rw-r--r-- | libtui/layout/vlayout/vlayout.ha | 44 | ||||
| -rw-r--r-- | libtui/libtui.ha | 145 | ||||
| -rw-r--r-- | libtui/widget/README | 2 | ||||
| -rw-r--r-- | libtui/widget/ed/ed.ha | 312 | ||||
| -rw-r--r-- | libtui/widget/list/README | 1 | ||||
| -rw-r--r-- | libtui/widget/list/list.ha | 354 | ||||
| -rw-r--r-- | libtui/widget/widget.ha | 89 |
13 files changed, 1494 insertions, 0 deletions
@@ -0,0 +1,367 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ef9e49f --- /dev/null +++ b/Makefile @@ -0,0 +1,47 @@ +.POSIX: +.SUFFIXES: +HARE=hare +HAREFLAGS= +HAREDOC=haredoc + +DESTDIR= +PREFIX=/usr/local +SRCDIR=$(PREFIX)/src +HARESRCDIR=$(SRCDIR)/hare +THIRDPARTYDIR=$(HARESRCDIR)/third-party + +all: + @true # no-op + +check: + $(HARE) test + +clean: + rm -rf docs + +docs: + mkdir -p docs/libtui/layout/vlayout + mkdir -p docs/libtui/widget/list + mkdir -p docs/libtui/widget/ed + $(HAREDOC) -Fhtml libtui > docs/libtui/index.html + $(HAREDOC) -Fhtml libtui::layout > docs/libtui/layout/index.html + $(HAREDOC) -Fhtml libtui::layout::vlayout > docs/libtui/layout/vlayout/index.html + $(HAREDOC) -Fhtml libtui::widget > docs/libtui/widget/index.html + $(HAREDOC) -Fhtml libtui::widget::list > docs/libtui/widget/list/index.html + $(HAREDOC) -Fhtml libtui::widget::ed > docs/libtui/widget/ed/index.html + +install: + mkdir -p "$(DESTDIR)$(THIRDPARTYDIR)" + cp -r libtui "$(DESTDIR)$(THIRDPARTYDIR)"/libtui + chmod -R 644 "$(DESTDIR)$(THIRDPARTYDIR)"/libtui/* + chmod 755 "$(DESTDIR)$(THIRDPARTYDIR)"/libtui + chmod 755 "$(DESTDIR)$(THIRDPARTYDIR)"/libtui/layout + chmod 755 "$(DESTDIR)$(THIRDPARTYDIR)"/libtui/layout/vlayout + chmod 755 "$(DESTDIR)$(THIRDPARTYDIR)"/libtui/widget + chmod 755 "$(DESTDIR)$(THIRDPARTYDIR)"/libtui/widget/list + chmod 755 "$(DESTDIR)$(THIRDPARTYDIR)"/libtui/widget/ed + +uninstall: + rm -rf $(DESTDIR)$(THIRDPARTYDIR)/libtui + +.PHONY: all clean check docs install uninstall diff --git a/README.md b/README.md new file mode 100644 index 0000000..68940d9 --- /dev/null +++ b/README.md @@ -0,0 +1,34 @@ +# hare-libtui + +This package provides widgets and various functions for creating a tui +(terminal user interface). + +**Status**: Incomplete + +## Provided modules + +- **libtui**: main ui functions and initialization +- **libtui::layout**: common functions for widget containers +- **libtui::vlayout**: widget container focused on vertical layouts +- **libtui::widget**: common functions and types for all widgets +- **libtui::widget::list**: scrollable width-truncated list widget with relevant functions for navigation and selection +- **libtui::widget::ed**: a text editor widget + +## Dependencies + +- [hare-wcwidth][https://git.sr.ht/~ark/hare-wcwidth] +- [hare-set][https://git.sr.ht/~ark/hare-set] + +## Installation + +### System-wide installation + +``` +make install +``` + +### Vendoring + +``` +git subtree -P vendor/hare-libtui/ add https://git.sr.ht/~ark/hare-libtui master +``` diff --git a/libtui/README b/libtui/README new file mode 100644 index 0000000..dbe708c --- /dev/null +++ b/libtui/README @@ -0,0 +1 @@ +The libtui module provides widgets for creating a tui (terminal user interface). diff --git a/libtui/keys.ha b/libtui/keys.ha new file mode 100644 index 0000000..a9955ba --- /dev/null +++ b/libtui/keys.ha @@ -0,0 +1,43 @@ +// License: MPL-2.0 +// (c) 2022 Julian Hurst <ark@mansus.space> + +use encoding::utf8; + +type keycode = (specialkey, []u8); +//const BACKSPACECODE: keycode = (specialkey::BACKSPACE, [127]); +//const RIGHTCODE: keycode = (specialkey::RIGHT, [27, 91, 67]); +const keycodes: []keycode = [ + (specialkey::BACKSPACE, [127]), + (specialkey::RIGHT, [27, 91, 67]), +]; + +export type specialkey = enum { + BACKSPACE, + RIGHT, +}; + +fn iskey(r: rune, key: keycode) bool = { + const u = utf8::encoderune(r); + for (let i = 0z; i < len(u); i += 1) { + if (u[i] != key.1[i]) { + return false; + }; + }; + return true; +}; + +export fn getkey(r: rune) (specialkey | rune) = { + const u = utf8::encoderune(r); + for (let i = 0z; i < len(keycodes); i += 1) { + let b = true; + for (let j = 0z; j < len(u) && b; j += 1) { + if (len(keycodes[i].1) != len(u) || keycodes[i].1[j] != u[j]) { + b = false; + }; + }; + if (b) { + return keycodes[i].0; + }; + }; + return r; +}; diff --git a/libtui/layout/layout.ha b/libtui/layout/layout.ha new file mode 100644 index 0000000..8391c2f --- /dev/null +++ b/libtui/layout/layout.ha @@ -0,0 +1,55 @@ +use libtui; +use libtui::widget; +use io; +use unix::tty; +use fmt; +use os; + +export type layout = struct { + widgets: []*widget::widget, +}; + +// Create and return a new layout from a list of widgets. [[finishall]] must be +// called to properly free the widget's nad layout's resources. +export fn newlayout(widgets: *widget::widget...) layout = { + return layout { + widgets = widgets, + }; +}; + +// Display all the widgets contained in the given layout. +export fn print(layout: layout) (void | widget::error) = { + libtui::clear(layout.widgets[0].ui); + for (let i = 0z; i < len(layout.widgets); i += 1) { + match (layout.widgets[i].print) { + case null => + return; + case let f: *widget::print => + f(layout.widgets[i])?; + }; + }; +}; + +// Finish and free the widgets in the given layout. +export fn finishall(layout: *layout) void = { + for (let i = 0z; i < len(layout.widgets); i += 1) { + match (layout.widgets[i].finish) { + case null => + return; + case let f: *widget::finish => + f(layout.widgets[i]); + }; + }; + free(layout.widgets); +}; + +// Notify all the widgets contained in the given layout. Returns true as soon as +// one of the widget's listeners returns true, false otherwise. +export fn notifyall(layout: layout, k: libtui::key) bool = { + for (let i = 0z; i < len(layout.widgets); i += 1) { + if (widget::notify(layout.widgets[i], k)) { + return true; + }; + }; + return false; +}; diff --git a/libtui/layout/vlayout/vlayout.ha b/libtui/layout/vlayout/vlayout.ha new file mode 100644 index 0000000..579625c --- /dev/null +++ b/libtui/layout/vlayout/vlayout.ha @@ -0,0 +1,44 @@ +use libtui; +use libtui::widget; +use libtui::layout; +use unix::tty; + +export type vlayout = struct { + layout: layout::layout, +}; + +// Create and return a new vlayout from a list of widgets. [[finishall]] must be +// called to properly free the widget's and layout's resources. +export fn newvlayout(widgets: *widget::widget...) vlayout = { + let sz = libtui::getwinsize(u.list.ui)!; + let cols = sz.columns / len(widgets); + for (let i = 0z; i < len(widgets); i += 1) { + const s = tty::ttysize { + columns = cols, + rows = sz.rows, + }; + widget::setsize(widgets[i], s); + }; + return vlayout { + layout = layout { + widgets = widgets, + }, + }; +}; + +// Display all the widgets contained in the given layout. +export fn print(layout: layout::layout) (void | widget::error) = { + const layout = layout: vlayout; + for (let i = 0z; i < len(layout.widgets); i += 1) { + match (layout.widgets[i].print) { + case null => + return; + case let f: *widget::print => + f(layout.widgets[i])?; + }; + libtui::cursorhome(widgets[i].ui); + for (let j = 0z; j < widgets[i].sz.columns; j += 1) { + libtui::cursorright(widgets[i].ui); + }; + }; +}; diff --git a/libtui/libtui.ha b/libtui/libtui.ha new file mode 100644 index 0000000..3d33680 --- /dev/null +++ b/libtui/libtui.ha @@ -0,0 +1,145 @@ +// License: MPL-2.0 +// (c) 2022 Julian Hurst <ark@mansus.space> + +use fmt; +use os; +use io; +use unix::tty; +use errors; +use bufio; +use encoding::utf8; +use strings; + +export type key = (rune | specialkey); + +// A listener on a rune input that returns if the ui needs to terminate or not +export type listener = *fn(ui: *ttyui, r: key) bool; + +export type ttyui = struct { + term: tty::termios, + f: io::file, + listeners: []listener, +}; + +// Initializes the UI and returns a ttyui. +export fn init() ttyui = { + let f = match (tty::open()) { + case let f: io::file => + yield f; + case let e: tty::error => + fmt::fatal(tty::strerror(e)); + }; + if (!tty::isatty(f)) { + fmt::fatal("stream is not a tty"); + }; + let term = match (tty::termios_query(f)) { + case let t: tty::termios => + yield t; + case let e: errors::error => + fmt::fatal(errors::strerror(e)); + }; + tty::makeraw(&term)!; + //tty::noecho(&term)!; + + let ui = ttyui { + term = term, + f = f, + listeners = [], + }; + hidecursor(ui); + return ui; +}; + +export fn hidecursor(ui: ttyui) void = { + print(ui, "\x1B[?25l"); +}; + +export fn showcursor(ui: ttyui) void = { + print(ui, "\x1B[?25h"); +}; + +// Returns the window size for the given ttyui. +export fn getwinsize(ui: ttyui) (tty::ttysize | tty::error) = { + return tty::winsize(ui.f); +}; + +// Suspend the UI. To restore it, use [[resume]]. +export fn suspend(ui: *ttyui) void = { + showcursor(*ui); + tty::termios_restore(&ui.term); +}; + +// Resumes the UI after a [[suspend]]. +export fn resume(ui: *ttyui) void = { + tty::makeraw(&ui.term)!; + tty::noecho(&ui.term)!; + hidecursor(*ui); +}; + +// Restores the UI state and closes and frees the resources associated with the +// given ttyui. +export fn finish(ui: *ttyui) void = { + showcursor(*ui); + tty::termios_restore(&ui.term); + io::close(ui.f)!; + free(ui.listeners); +}; + +// Scans a rune. A convenience function for [[bufio::scanrune]]. +export fn scan(ui: ttyui) (key | utf8::invalid | io::EOF | io::error) = { + //const r = bufio::scanrune(ui.f)?; + const r = match (bufio::scanrune(ui.f)?) { + case let r: rune => + yield r; + case => + return io::EOF; + }; + return getkey(r); +}; + +// Notify (call) the ttyui's listeners with the ttyui and r as a parameter. +// Returns true if a listener returned true, false otherwise. +export fn notify(ui: *ttyui, r: (rune | specialkey)) bool = { + for (let i = 0z; i < len(ui.listeners); i += 1) { + if (ui.listeners[i](ui, r)) { + return true; + }; + }; + return false; +}; + +fn loop(ui: *ttyui) void = { + for (true) { + let r = match (bufio::scanrune(ui.f)) { + case let r: rune => + yield r; + case utf8::invalid => + fmt::fatal("Invalid utf8 sequence found"); + case io::EOF => + fmt::fatal("EOF"); + case let e: io::error => + fmt::fatal(io::strerror(e)); + }; + for (let i = 0z; i < len(ui.listeners); i += 1) { + if (ui.listeners[i](ui, r)) { + return; + }; + }; + }; +}; + +// Add a listener to the given ttyui. +export fn addlistener(ui: *ttyui, l: listener) void = { + append(ui.listeners, l); +}; + +// Print a string or rune to the ttyui. +export fn print(ui: ttyui, arg: (str | rune)) void = { + fmt::fprint(ui.f, arg)!; + //fmt::fprintf(ui.f, "{}\r", arg)!; +}; + +// Clear the ttyui. +export fn clear(ui: ttyui) void = { + fmt::fprintf(ui.f, "\x1B[2J\x1B[1;1H\r")!; +}; diff --git a/libtui/widget/README b/libtui/widget/README new file mode 100644 index 0000000..ae62628 --- /dev/null +++ b/libtui/widget/README @@ -0,0 +1,2 @@ +This module contains functions common to all widgets and provides a base for +implementing custom widget types (print, finish, ...). diff --git a/libtui/widget/ed/ed.ha b/libtui/widget/ed/ed.ha new file mode 100644 index 0000000..64157cd --- /dev/null +++ b/libtui/widget/ed/ed.ha @@ -0,0 +1,312 @@ +// License: MPL-2.0 +// (c) 2022 Julian Hurst <ark@mansus.space> + +use libtui; +use libtui::widget; +use strio; +use strconv; +use strings; +use wcwidth; +use set; +use io; +use fmt; +use os; +use encoding::utf8; + +let linestofree: set::set = set::set {...}; + +export type editorwidget = struct { + widget: widget::widget, + lines: []str, + cursor: (size, size), + marked: set::set, + frame: frame, + sz: ttysize, + mode: mode, +}; + +export type frame = struct { + start: u16, + // largest value is nb of lines + end: u16, +}; + +export type mode = enum { + NORMAL, + INSERT, +}; + +export type ttysize = struct { + rows: u16, + cols: u16, +}; + +// An input listener on an editor widget. The returning value is intended to be +// used as a signal that will be returned by [[notify]] in order to trigger +// certain more global ui events (terminate the program, change widget focus, +// etc.). To register a listener with an editorwidget, use [[addlistener]]. +export type listener = *fn(l: *editorwidget, r: (rune | libtui::specialkey)) bool; + +// Create a new editor with the given lines. +export fn neweditor(ui: libtui::ttyui, lines: str...) editorwidget = { + let sz = libtui::getwinsize(ui)!; + let rows = sz.rows - 2; + //let rows: (u16 | size) = if (sz.rows - 2 < len(items)) { + //yield sz.rows - 2; + //} else { + //yield len(items); + //}; + let w = editorwidget { + widget = widget::widget { + print = &print, + finish = &finish, + ui = ui, + ... + }, + lines = lines, + marked = set::set {...}, + cursor = (0z, 0z), + frame = frame { + start = 0u16, + end = rows: u16, + }, + sz = ttysize { + rows = rows: u16, + cols = sz.columns, + }, + mode = mode::INSERT, + }; + return w; +}; + +// Notify (call) the editorwidget's editoreners with the editorwidget and r as a +// parameter. Returns true if a editorener returned true, false otherwise. +//export fn notify(l: *editorwidget, r: rune) bool = { + //for (let i = 0z; i < len(l.widget.listeners); i += 1) { + //if (l.widget.listeners[i](l, r)) { + //return true; + //}; + //}; + //return false; +//}; + +//const SELECTED: str = "\x1B[104;1m\x1B[30m"; +const SELECTED: str = "\x1B[7m"; +const MARKED: str = "\x1B[46;1m\x1B[30m"; +const RESET: str = "\x1B[0m"; + +// Print the editor's lines while truncating the lines to not be wider than the +// editor.sz.cols. +export fn print(editor: *widget::widget) (void | widget::error) = { + const editor = editor: *editorwidget; + //let sz = libtui::getwinsize(editor.ui)?; + //let rows: (u16 | size) = if (sz.rows - 2 < len(editor.lines)) { + //yield sz.rows - 2; + //} else { + //yield len(editor.lines); + //}; + + //fmt::fprintln(os::stderr, rows)!; + + //editor.frame.end = editor.frame.start + editor.sz.rows; + + let st = strio::dynamic(); + strio::concat(&st, "\r")?; + let end = if (editor.frame.end < len(editor.lines)) { + yield editor.frame.end; + } else { + yield len(editor.lines); + }; + const maxlinenosz = len(strconv::ztos(len(editor.lines))); + for (let i = editor.frame.start; i < end: u16; i += 1) { + let lineno = strconv::ztos(i+1); + lineno = strings::padstart(lineno, ' ', maxlinenosz); + const line = strings::concat(lineno, "| ", editor.lines[i]); + const truncitem = wcwidth::truncate(line, editor.sz.cols); + defer free(truncitem); + if (editor.cursor.0 == i) { + //strio::concat(&st, SELECTED, truncitem, RESET)?; + + const linepos = editor.cursor.1 + maxlinenosz + 2; + strio::concat(&st,strings::sub(truncitem, 0, linepos))?; + strio::concat(&st, SELECTED, strings::sub(truncitem, linepos, linepos+1), RESET)?; + strio::concat(&st, strings::sub(truncitem, linepos+1, strings::end))?; + + //libtui::print(editor.ui, strings::concat("\x1B[31;1m> ", editor.lines[i], "\x1B[0m")); + } else if (set::contains(editor.marked, i) is size){ + strio::concat(&st, MARKED, truncitem, RESET)?; + //libtui::print(editor.ui, editor.lines[i]); + } else { + strio::concat(&st, truncitem)?; + }; + strio::concat(&st, "\r\n")?; + }; + // unsupported? + //io::copy(editor.ui.f, &st)?; + let s = strio::string(&st); + libtui::print(editor.widget.ui, s); + io::close(&st)?; +}; + +// Free the editor's lines, marked lines and call the common widget finish +// function [[widget::finishcommon]]. +export fn finish(editor: *widget::widget) void = { + const editor = editor: *editorwidget; + for (let i = 0z; i < len(linestofree.items); i += 1) { + free(editor.lines[linestofree.items[i]]); + }; + free(editor.lines); + //strings::freeall(editor.lines); + set::finish(&editor.marked); + set::finish(&linestofree); + widget::finishcommon(editor); +}; + +// Reset the editor's frame based on the cursor. Returns whether the frame was +// updated. +export fn reframe(l: *editorwidget) bool = { + let reframed: bool = false; + if (l.cursor.0 < l.frame.start) { + l.frame.start = l.cursor.0: u16; + l.frame.end = l.frame.start + l.sz.rows; + //l.frame.end -= l.frame.start - l.cursor: u16; + reframed = true; + }; + if (l.cursor.0 >= l.frame.end) { + l.frame.start += l.cursor.0: u16 - l.frame.end + 1; + l.frame.end = l.cursor.0: u16 + 1; + reframed = true; + }; + return reframed; +}; + +// Move the editor's cursor up one line. Returns the new cursor. +export fn up(l: *editorwidget) (size, size) = { + if (l.cursor.0 > 0) { + l.cursor.0 -= 1; + reframe(l); + resetcursorlinepos(l); + }; + return l.cursor; +}; + +// Move the editor's cursor down one line. Returns the new cursor. +export fn down(l: *editorwidget) (size, size) = { + if (l.cursor.0 < len(l.lines) - 1) { + l.cursor.0 += 1; + reframe(l); + resetcursorlinepos(l); + }; + return l.cursor; +}; + +fn resetcursorlinepos(l: *editorwidget) (size, size) = { + const line = l.lines[l.cursor.0]; + if (l.cursor.1 >= len(line)) { + l.cursor.1 = if (len(line) > 0) { + yield len(line) - 1; + } else { + yield firstcharindex(line); + }; + } else { + const firstcharidx = firstcharindex(line); + if (firstcharidx > l.cursor.1) { + l.cursor.1 = firstcharidx; + }; + }; + return l.cursor; +}; + +// Move the editor's cursor to the right one character. Returns the new cursor. +export fn right(l: *editorwidget) (size, size) = { + if (l.cursor.1 < len(l.lines[l.cursor.0]) - 1) { + l.cursor.1 += 1; + }; + return l.cursor; +}; + +// Move the editor's cursor to the left one character. Returns the new cursor. +export fn left(l: *editorwidget) (size, size) = { + if (l.cursor.1 > 0) { + l.cursor.1 -= 1; + }; + return l.cursor; +}; + +export fn insertmode(l: *editorwidget, lt: widget::listener) void = { + l.mode = mode::INSERT; + widget::clearlisteners(l); + widget::addlistener(l, lt); +}; + +export fn normalmode(l: *editorwidget, lt: widget::listener) void = { + l.mode = mode::NORMAL; + widget::clearlisteners(l); + widget::addlistener(l, lt); +}; + +export fn insertrune(l: *editorwidget, r: rune) (void | io::error) = { + //match (sanitizerune(r)) { + //case let k: libtui::keycode => + //specialkey(l, k)?; + //case let r: rune => + let line = l.lines[l.cursor.0]; + let st = strio::dynamic(); + strio::concat(&st, strings::sub(line, 0, l.cursor.1))?; + strio::appendrune(&st, r)?; + strio::concat(&st, strings::sub(line, l.cursor.1, strings::end))?; + l.lines[l.cursor.0] = strings::dup(strio::string(&st)); + right(l); + set::add(&linestofree, l.cursor.0); + io::close(&st)?; + //}; +}; + +fn specialkey(l: *editorwidget, keycode: libtui::keycode) (void | io::error) = { + switch (keycode) { + case libtui::keycode::BACKSPACE => + if (l.cursor.1 > 0) { + let line = l.lines[l.cursor.0]; + let st = strio::dynamic(); + strio::concat(&st, strings::sub(line, 0, l.cursor.1-1))?; + if (len(line) > l.cursor.1) { + strio::concat(&st, strings::sub(line, l.cursor.1, strings::end))?; + }; + l.lines[l.cursor.0] = strings::dup(strio::string(&st)); + left(l); + set::add(&linestofree, l.cursor.0); + io::close(&st)?; + }; + case libtui::keycode::RIGHT => + right(l); + //fmt::fprintln(os::stderr, "poopy")!; + }; +}; + +// Doesn't work, RIGHT ends up being 3 separate runes not one with 3 bytes... +//fn sanitizerune(r: rune) (rune | libtui::keycode) = { + //if (libtui::iskey(r, libtui::BACKSPACE)) { + //return libtui::keycode::BACKSPACE; + //}; + //if (libtui::iskey(r, libtui::RIGHT)) { + //return libtui::keycode::RIGHT; + //}; + //return r; +//}; + +fn firstcharindex(s: str) size = { + let it = strings::iter(s); + let i = 0z; + for (true) { + match (strings::next(&it)) { + case let r: rune => + if (r != ' ' && r != '\t') { + return i; + }; + case void => + return 0z; + }; + i += 1; + }; + return 0z; +}; diff --git a/libtui/widget/list/README b/libtui/widget/list/README new file mode 100644 index 0000000..c8f71db --- /dev/null +++ b/libtui/widget/list/README @@ -0,0 +1 @@ +libui::list provides a list widget that supports line truncating, scrolling, item marking (contains, fnmatch and regex) and searching. Multiple convenient navigation functions are provided such as [[up]], [[down]], [[top]] and [[bottom]]. diff --git a/libtui/widget/list/list.ha b/libtui/widget/list/list.ha new file mode 100644 index 0000000..1f8a0fb --- /dev/null +++ b/libtui/widget/list/list.ha @@ -0,0 +1,354 @@ +// License: MPL-2.0 +// (c) 2022 Julian Hurst <ark@mansus.space> + +use libtui; +use libtui::widget; +use fmt; +use os; +use strings; +use io; +use strio; +use unix::tty; +use regex; +use fnmatch; +use wcwidth; +use set; + +export type listwidget = struct { + widget: widget::widget, + items: []str, + marked: set::set, + cursor: size, + //listeners: []listener, + frame: frame, + sz: ttysize, +}; + +export type frame = struct { + start: u16, + // largest value is nb of items + end: u16, +}; + +export type ttysize = struct { + rows: u16, + cols: u16, +}; + +// An input listener on a list widget. The returning value is intended to be +// used as a signal that will be returned by [[notify]] in order to trigger +// certain more global ui events (terminate the program, change widget focus, +// etc.). To register a listener with a listwidget, use [[addlistener]]. +export type listener = *fn(l: *listwidget, r: (rune | libtui::specialkey)) bool; + +// Create a new list with the given items. The given items will be duplicated +// using [[strings::dupall]]], so the original items can be freed. +export fn newlist(ui: libtui::ttyui, items: str...) listwidget = { + let sz = libtui::getwinsize(ui)!; + let rows = sz.rows - 2; + //let rows: (u16 | size) = if (sz.rows - 2 < len(items)) { + //yield sz.rows - 2; + //} else { + //yield len(items); + //}; + let w = listwidget { + widget = widget::widget { + print = &print, + finish = &finish, + ui = ui, + ... + }, + items = strings::dupall(items), + marked = set::set {...}, + cursor = 0z, + //listeners = [], + frame = frame { + start = 0u16, + end = rows: u16, + }, + sz = ttysize { + rows = rows: u16, + cols = sz.columns, + }, + }; + return w; +}; + +// Free the list's items, marked items and call the common widget finish +// function [[widget::finishcommon]]. +export fn finish(list: *widget::widget) void = { + const list = list: *listwidget; + strings::freeall(list.items); + set::finish(&list.marked); + widget::finishcommon(list); +}; + +// Set the list's items. The given items are duplicated via [[strings::dupall]]. +// If the length of the given items is smaller than the list's current items, +// the cursor will be set to 0z and [[reframe]] will be called to reset the +// frame. +export fn setitems(list: *listwidget, items: str...) void = { + const doreset = len(items) < len(list.items); + list.items = strings::dupall(items); + if (doreset) { + reset(list); + }; +}; + +export fn reset(list: *listwidget) void = { + list.cursor = 0z; + list.frame.start = 0u16; + list.frame.end = list.sz.rows; +}; + +// Add a listener to the given list. +//export fn addlistener(list: *listwidget, l: listener) void = { + //append(list.listeners, l); +//}; + +const SELECTED: str = "\x1B[104;1m\x1B[30m"; +const MARKED: str = "\x1B[46;1m\x1B[30m"; +const RESET: str = "\x1B[0m"; + +// Print the list's items while truncating the items to not be wider than the +// list.sz.cols. +export fn print(list: *widget::widget) (void | widget::error) = { + const list = list: *listwidget; + //let sz = libtui::getwinsize(list.ui)?; + //let rows: (u16 | size) = if (sz.rows - 2 < len(list.items)) { + //yield sz.rows - 2; + //} else { + //yield len(list.items); + //}; + + //fmt::fprintln(os::stderr, rows)!; + + //list.frame.end = list.frame.start + list.sz.rows; + + let st = strio::dynamic(); + strio::concat(&st, "\r")?; + let end = if (list.frame.end < len(list.items)) { + yield list.frame.end; + } else { + yield len(list.items); + }; + for (let i = list.frame.start; i < end: u16; i += 1) { + const item = list.items[i]; + const truncitem = wcwidth::truncate(item, list.sz.cols); + if (list.cursor == i) { + strio::concat(&st, SELECTED, truncitem, RESET)?; + //libtui::print(list.ui, strings::concat("\x1B[31;1m> ", list.items[i], "\x1B[0m")); + } else if (set::contains(list.marked, i) is size){ + strio::concat(&st, MARKED, truncitem, RESET)?; + //libtui::print(list.ui, list.items[i]); + } else { + strio::concat(&st, truncitem)?; + }; + strio::concat(&st, "\r\n")?; + }; + // unsupported? + //io::copy(list.ui.f, &st)?; + let s = strio::string(&st); + libtui::print(list.widget.ui, s); + io::close(&st)?; +}; + +// Notify (call) the listwidget's listeners with the listwidget and r as a +// parameter. Returns true if a listener returned true, false otherwise. +export fn notify(l: *listwidget, r: (rune | libtui::specialkey)) bool = { + for (let i = 0z; i < len(l.widget.listeners); i += 1) { + if (l.widget.listeners[i](l, r)) { + return true; + }; + }; + return false; +}; + +// Reset the list's frame based on the cursor. Returns whether the frame was +// updated. +export fn reframe(l: *listwidget) bool = { + let reframed: bool = false; + if (l.cursor < l.frame.start) { + l.frame.start = l.cursor: u16; + l.frame.end = l.frame.start + l.sz.rows; + //l.frame.end -= l.frame.start - l.cursor: u16; + reframed = true; + }; + if (l.cursor >= l.frame.end) { + l.frame.start += l.cursor: u16 - l.frame.end + 1; + l.frame.end = l.cursor: u16 + 1; + reframed = true; + }; + return reframed; +}; + +// Use signalfd and [[unix::signal::SIGWINCH]] and call this function in the +// handler to support resizing the list. +export fn resize(l: *listwidget, oldsz: ttysize) bool = { + if (l.frame.end - l.frame.start != l.sz.rows) { + if (l.cursor < (l.frame.end / 2)) { + l.frame.end = if (l.frame.start + l.sz.rows > len(l.items)) { + l.frame.start = len(l.items): u16 - l.sz.rows; + yield len(l.items): u16; + } else { + yield l.frame.start + l.sz.rows; + }; + for (l.cursor > l.frame.end) { + l.frame.start += 1; + l.frame.end += 1; + }; + } else { + l.frame.start = if (l.frame.end: int - l.sz.rows: int < 0) { + l.frame.end = 0 + l.sz.rows; + yield 0; + } else { + yield l.frame.end - l.sz.rows; + }; + for (l.cursor < l.frame.start) { + l.frame.start -= 1; + l.frame.end -= 1; + }; + }; + return true; + }; + return false; +}; + +fn cursorinframe(l: *listwidget) bool = { + return l.cursor >= l.frame.start && l.cursor < l.frame.end; +}; + +// Move the list's cursor down one item. Returns the new cursor. +export fn down(l: *listwidget) size = { + if (l.cursor < len(l.items) - 1) { + l.cursor += 1; + reframe(l); + }; + return l.cursor; +}; + +// Move the list's cursor up one item. Returns the new cursor. +export fn up(l: *listwidget) size = { + if (l.cursor > 0) { + l.cursor -= 1; + reframe(l); + }; + return l.cursor; +}; + +// Move the list's cursor up one page. Returns the new cursor. +export fn pageup(l: *listwidget) size = { + if (l.cursor: int - l.sz.rows: int >= 0) { + l.cursor -= l.sz.rows; + } else { + l.cursor = 0z; + }; + reframe(l); + return l.cursor; +}; + +// Move the list's cursor down one page. Returns the new cursor. +export fn pagedown(l: *listwidget) size = { + if (l.cursor + l.sz.rows < len(l.items)) { + l.cursor += l.sz.rows; + } else { + l.cursor = len(l.items) - 1; + }; + reframe(l); + return l.cursor; +}; + +// Move the list's cursor to the top (first item). Returns the new cursor. +export fn top(l: *listwidget) size = { + l.cursor = 0; + l.frame.start = 0; + l.frame.end = l.frame.start + l.sz.rows; + return l.cursor; +}; + +// Move the list's cursor to the bottom (last item). Returns the new cursor. +export fn bottom(l: *listwidget) size = { + l.cursor = len(l.items) - 1; + l.frame.end = len(l.items): u16; + l.frame.start = l.frame.end - l.sz.rows; + return l.cursor; +}; + +// Forward search through the list's items for an item containing s. Returns the +// new cursor. +export fn search(l: *listwidget, s: str) size = { + for (let i = l.cursor + 1; i < len(l.items); i += 1) { + if (strings::contains(l.items[i], s)) { + l.cursor = i; + reframe(l); + return l.cursor; + }; + }; + return l.cursor; +}; + +// Backwards search through the list's items for an item containing s. Returns +// the new cursor. +export fn rsearch(l: *listwidget, s: str) size = { + // size wraps to max value for size when < 0 + for (let i = l.cursor: int - 1; i >= 0; i -= 1) { + if (strings::contains(l.items[i], s)) { + l.cursor = i: size; + reframe(l); + return l.cursor; + }; + }; + return l.cursor; +}; + +// Toggles marking the currently selected item. +export fn tmark(l: *listwidget) void = { + if (!set::add(&l.marked, l.cursor)) { + set::del(&l.marked, l.cursor); + }; +}; + +// Clears all marked items. +export fn clearmarked(l: *listwidget) void = { + set::clear(&l.marked); +}; + +// Marks items that contain s (case sensitive). +export fn containsmark(l: *listwidget, s: str) void = { + for (let i = 0z; i < len(l.items); i += 1) { + if (strings::contains(l.items[i], s)) { + set::add(&l.marked, i); + }; + }; +}; + +// Marks items based on fnmatch (globbing syntax). +export fn fnmatchmark(l: *listwidget, s: str) void = { + for (let i = 0z; i < len(l.items); i += 1) { + if (fnmatch::fnmatch(s, l.items[i])) { + set::add(&l.marked, i); + }; + }; +}; + +// Marks items according to a regular expression (POSIX ERE). +export fn regexmark(l: *listwidget, re: *regex::regex) void = { + for (let i = 0z; i < len(l.items); i += 1) { + if (regex::test(re, l.items[i])) { + set::add(&l.marked, i); + }; + }; +}; + +// Returns the selected item or marked items if there are any. +export fn selected(l: listwidget) (str | []str) = { + if (len(l.marked.items) > 0) { + let result: []str = []; + for (let i = 0z; i < len(l.marked.items); i += 1) { + append(result, l.items[l.marked.items[i]]); + }; + return result; + } else { + return l.items[l.cursor]; + }; +}; diff --git a/libtui/widget/widget.ha b/libtui/widget/widget.ha new file mode 100644 index 0000000..6875692 --- /dev/null +++ b/libtui/widget/widget.ha @@ -0,0 +1,89 @@ +// License: MPL-2.0 +// (c) 2022 Julian Hurst <ark@mansus.space> + +use libtui; +use io; +use unix::tty; + +export type error = !(io::error | tty::error); + +// A function that displays the widget. +export type print = fn(w: *widget) (void | error); + +// A function that frees the resources associated to the widget. +export type finish = fn(w: *widget) void; + +// An input listener on a widget. The returning value is intended to be used as +// a signal that will be returned by [[notify]] in order to trigger certain more +// global ui events (terminate the program, change widget focus, etc.). To +// register a listener with a widget, use [[addlistener]]. +export type listener = *fn(w: *widget, r: libtui::key) bool; + +// A widget is an abstraction around a user-defined UI component. Custom widgets +// can be created through sub-typing: +// +// export type my_widget = struct { +// widget: widget::widget, +// lines: []str, +// }; +// +// fn print(w: *widget::widget) (void | widget::error) = { +// const w = w: *my_widget; +// for (let i = 0z; i < len(w.lines); i += 1) { +// fmt::println(w.lines[i])!; +// }; +// }; +// +// fn finish(w: *widget::widget) void = { +// const w = w: *my_widget; +// free(w.lines); +// widget::finishcommon(w); +// }; +// +// let list = my_widget { +// widget = widget::widget { +// print = &print, +// finish = &finish, +// ... +// }; +// lines = strings::split("one,two,three", ","), +// }; +// let l = layout::newlayout(list); +// layout::print(l)!; +export type widget = struct { + print: nullable *print, + finish: nullable *finish, + listeners: []listener, + ui: libtui::ttyui, +}; + +// Add a listener to the given widget. +export fn addlistener(w: *widget, listener: listener) void = { + append(w.listeners, listener); +}; + +// Delete a listener from the given widget. +export fn dellistener(w: *widget, idx: size) void = { + delete(w.listeners[idx]); +}; + +// Clear the listeners of the given widget. +export fn clearlisteners(w: *widget) void = { + w.listeners = []; +}; + +// Free the widget's listeners. +export fn finishcommon(w: *widget) void = { + free(w.listeners); +}; + +// Notify (call) the widget's listeners with the widget and r as a parameter. +// Returns true if a listener returned true, false otherwise. +export fn notify(w: *widget, r: (rune | libtui::specialkey)) bool = { + for (let i = 0z; i < len(w.listeners); i += 1) { + if (w.listeners[i](w, r)) { + return true; + }; + }; + return false; +}; |
