Repository: lambdaisland/trikl
Branch: master
Commit: 8d06761f72a0
Files: 16
Total size: 68.8 KB
Directory structure:
gitextract_1v1wvub8/
├── .circleci/
│ └── config.yml
├── .dir-locals.el
├── .gitignore
├── CHANGELOG.md
├── LICENSE.txt
├── README.md
├── bin/
│ └── kaocha
├── deps.edn
├── notes.org
├── src/
│ └── trikl/
│ ├── core.clj
│ ├── demo/
│ │ └── world.clj
│ ├── demo.clj
│ ├── telnet.clj
│ └── util.clj
├── test/
│ └── unit/
│ └── trikl/
│ └── core_test.clj
└── tests.edn
================================================
FILE CONTENTS
================================================
================================================
FILE: .circleci/config.yml
================================================
version: 2
jobs:
build:
docker:
- image: circleci/clojure:tools-deps
steps:
- checkout
- restore_cache:
keys:
- v1-dependencies-{{ checksum "deps.edn" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- run: clojure -A:dev:test -Spath
- save_cache:
paths:
- ~/.m2
key: v1-dependencies-{{ checksum "deps.edn" }}
- run: clojure -A:dev:test -m kaocha.runner --reporter kaocha.report/documentation
================================================
FILE: .dir-locals.el
================================================
((nil . ((cider-clojure-cli-global-options . "-A:dev:test"))))
================================================
FILE: .gitignore
================================================
.cpcache
.nrepl-port
target
repl
scratch.clj
================================================
FILE: CHANGELOG.md
================================================
# Unreleased
## Added
- `stdio-client` for a direct STDIN/STDOUT connection
- Added access to screen and bounding box dimensions during rendering
## Fixed
- Fix re-rendering when the terminal size changes, before there would often be
artifacts.
- Fix endless loop when client socket closes
## Changed
================================================
FILE: LICENSE.txt
================================================
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.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
================================================
FILE: README.md
================================================
# Trikl
"Terminal React for Clojure" => Trikl
[](https://circleci.com/gh/lambdaisland/trikl) [](https://cljdoc.org/d/lambdaisland/trikl) [](https://clojars.org/lambdaisland/trikl)
Trikl is a long-term slow moving research project. It is not intended for general consumption. There are useful bits in there, but expect to get intimately familiar with the implementation if you want to get value out of them.
The README below is from the first incarnation of Trikl, which had severe shortcomings around event handling and how it handles components. The groundwork for a new version has started in the `lambdaisland.trikl1.*` namespaces.
[Regal](https://lambdaisland.github.io/land-of-regal/) is a spin-off library created to support this work.
----
Trikl lets you write terminal applications in a way that's similar to
React/Reagent. It's main intended use case is for hobbyist/indy games.
With Trikl you use (a dialect of) Hiccup to create your Terminal UI. As your
application state changes, Trikl re-renders the UI, diffs the output with what's
currently on the screen, and sends the necessary commands to the terminal to
bring it up to date.
This is still very much work in progress and subject to change.
## Example
You can use Trikl directly by hooking it up to STDIN/STDOUT, or you can use it
as a telnet server. The telnet server is great because it makes it easy to try
stuff out from the REPL.
For instance you can do something like this:
``` clojure
(require '[trikl.core :as t])
;; store clients so we can poke at them from the REPL
(def clients (atom []))
;; Start the server on port 1357, as an accept handler just store the client in
;; the atom.
(def stop-server (t/start-server #(swap! clients conj %) 1357))
;; in a terminal: telnet localhost 1357
#_(stop-server) ;; disconnect all clients and stop listening for connections
;; Render hiccup! Re-run this as often as you like, only changes are sent to the client.
(t/render (last @clients) #_(t/stdio-client)
[:box {:x 10 :y 5 :width 20 :height 10 :styles {:bg [50 50 200]}}
[:box {:x 1 :y 1 :width 18 :height 8 :styles {:bg [200 50 0]}}
[:box {:x 3 :y 1}
[:span {:styles {:fg [30 30 150]}} "hello\n"]
[:span {:styles {:fg [100 250 100]}} " world"]]]])
;; Listen for input events
(t/add-listener (last @clients)
::my-listener
(fn [event]
(prn event)))
```
Use `stdio-client` to hook up the terminal the process is running in.
Result:

## Things you can render
You can render the following things
### String
A string is simply written to to the screen as-is. Note that strings are limited
to their current bounding box, so long strings don't wrap. You can use newlines
to use multiple lines.
``` clojure
(t/render client "hello, world!\nWhat a lovely day we're having")
```
### Sequence
A seq (so the result of calling `list`, `map`, `for`, etc. Not vectors!) will
simply render each item in the list.
``` clojure
(t/render client (repeat 20 "la"))
```
### Elements
Elements are vectors, they contain the element type (first item in the vector),
a map of attributes (optional, second element in the vector), and any remaining
child elements.
Trikl currently knows of the following elements.
#### :span
A `:span` can be used to add styling, i.e. foreground and background colors. Colors
are specified using RGB (red-green-blue) values. Each value can go from 0 to
255.
``` clojure
(t/render client [:span {:styles {:fg [100 200 0] :bg [50 50 200]}} "Oh my!"])
```
#### :box
The `:box` element changes the current bounding box. You give it a position with
`:x` and `:y`, and a size with `:width` and `:height`, and anything inside the
box will be contained within those coordinates.
If you don't supply `:x` or `:y` it will default to the top-left corner of its
surrounding bounding box. If you omit `:width` and `:height` it will take up as
much space as it has available.
You can also supply `:styles` to the box, as with `:span`. Setting a `:bg` on
the box will color the whole box.
Note for instance that this example truncates the string to "Hello,", because it
doesn't fit in the box.
``` clojure
(t/render client [:box {:x 20 :y 10, :width 7, :height 3} "Hello, world!"])
```
#### :line-box
A `:line-box` is like a box, but it gets a fancy border. This border is drawn on
the inside of the box, so you lose two rows and two columns of space to put
stuff inside, but it looks pretty nice!
By default it uses lines with rounded corners, but you can use any border
decoration you like by supplying a `:lines` attribute. This can be a string or
sequence containing the characters to use, starting from the top left corner and
moving clockwise. The default value for `:lines` is ` "╭─╮│╯─╰│"`
``` clojure
(t/render client [:line-box {:x 20 :y 10, :width 10, :height 3} "Hello, world!"])
```
#### :cols and :rows
The `:cols` and `:rows` elements will split their children into columns and rows
respectively. If any of the children have a `:width` or `:height` that will be
respected. Any remaining space is distributed equally among the ones that don't
have a fixed `:width`/`:height` already.
So you could divide the screen in four equally sized sections using:
``` clojure
(t/render (last @clients)
[:cols
[:rows
[:line-box "1"]
[:line-box "2"]]
[:rows
[:line-box "3"]
[:line-box "4"]]])
```
#### Custom Components
You can define custom components by creating a two-argument function, attributes
and children, and using the function as the first element in the vector. You can
return any of the above renderable things from the function.
``` clojure
(defn app [attrs children]
[:rows
[:line-box "Hiiiiii"]
[:line-box {:height 15 :styles {:bg [100 50 50]}}]])
(t/render client [app])
```
## App state
If you keep your app state in an atom, then you can use `render-watch!` to
automatically re-render when the atom changes.
``` clojure
(def app-state (atom {:pos [10 10]}))
(t/render-watch! client
(fn [{[x y] :pos} _]
[:box {:x x :y y} "X"])
app-state)
(swap! app-state update-in [:pos 0] inc)
(swap! app-state update-in [:pos 1] inc)
(t/unwatch! app-state)
```
## Querying the screen size and bounding box
During rendering you can use `t/*screen-size*` and `t/*bounding-box*` to find
the current dimensions you are working in. There's also a `(box-size)` helpers
which only returns the `[width height]` of the bounding box, rather than `[x y
width height]`. This should greatly alleviate the need to write your own drawing
functions, as you can now do everything with custom elements and a combination
of `[:span ...]` and `[:box ...]`. The main reason to write custom drawing
functions would be for performance, when what you are drawing does not easily
fit in the span/box paradigm. If you find yourself creating a span per character
then maybe a custom drawing function makes sense.
## Custom drawing functions
To implement custom elements, extend the `t/draw` multimethod. The method takes
two arguments, the element (the vector), and a "virtual screen". Your method
needs to return an updated version of the virtual screen.
The main reasons to do this are because this gives you access to the current
screen size (bounding box), and for performance reasons.
The `VirtualScreen` has a ":charels" key (character elements, analogues to
pixels), This is a vector of rows, each row is a vector of "charels", which have
a `:char`, `:bg`, `:fg` key. Make sure the `:char` is set to an actual `char`,
not to a String.
After drawing the virtual screen is diffed with the previous virtual screen to
figure out the minimum commands to send to the terminal to update it.
``` clojure
(defmethod t/draw :x-marks-the-spot [element screen]
(assoc-in screen [:charels 5 5 :char] \X))
```
Things to watch out for:
- Normalize your element with `t/split-el`, this always returns a three element
vector with element type, attribute map, children sequence.
- Stick to your bounding box! You probably want to start with this
``` clojure
(let [[_ attrs children] (split-el element)
[x y width height] (apply-bounding-box attrs screen)]
,,,)
```
You should not touch anything outside `[(range x (+ x width)) (range y (+ y height))]`
- If your element takes `:styles`, then use `push-styles` and `pop-styles` to
correctly restore the styles from a surrounding context.
## True Color
In theory ANSI compatible terminals are able to render 24 bit colors (16 million
shades), but in practice they don't always do.
You can try this snippet, if you see nice continuous gradients from blue to
purple then you're all set.
``` clojure
(defn app [_]
[:box
(for [y (range 50)]
[:span
(for [x (range 80)]
[:span {:styles {:bg [(* x 2) (* y 2) (+ x (* 4 y))]}} " "])
"\n"])])
```
iTerm and gnome-terminal should both be fine, but if you're using Tmux and you're not getting the desired results, then add this to your `~/.tmux.conf`
``` conf
set -g default-terminal "xterm-256color"
set-option -ga terminal-overrides ",xterm-256color:Tc"
```
## Using netcat
Not all systems come with telnet installed, notably recent versions of Mac OS X
have stopped bundling it. The common advice you'll find is to use Netcat (`nc`) instead, but these two are not the same. Telnet understands certain binary codes to configure your terminal, which Trikl needs to function correctly.
You can `brew install telnet`, or in a pinch you can use `stty` to configure
your terminal to not echo input, and to enable "raw" (direct, unbuffered) mode.
Make sure to invoke `stty` and `nc` as a single command like this:
```
stty -echo -icanon && nc localhost 1357
```
To undo the changes to your terminal do
```
stty +echo +icanon
```
## Graal compatibility
Trikl contains enough type hints to prevent Clojure's type reflection, which
makes it compatible with GraalVM. This means you can compile your project to
native binaries that boot instantly. Great for tooling!
## License
Copyright © 2018 Arne Brasseur
Licensed under the term of the Mozilla Public License 2.0, see LICENSE.
================================================
FILE: bin/kaocha
================================================
#!/bin/bash
clojure -A:test -m kaocha.runner "$@"
================================================
FILE: deps.edn
================================================
{:paths ["src" "test" "resources"]
:deps {org.clojure/clojure {:mvn/version "1.10.0-RC4"}}
:aliases
{:dev
{}
:test
{:extra-deps {lambdaisland/kaocha {:mvn/version "0.0-305"}
lambdaisland/ansi {:mvn/version "RELEASE"}}}}}
================================================
FILE: notes.org
================================================
* app ideas
** roguelike / rpg
** "graphics editor" / level editor
** interactive version upgrades
** interactive test runner
** admin UI for app
================================================
FILE: src/trikl/core.clj
================================================
(ns trikl.core
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.java.shell :as shell]
[trikl.telnet :as telnet])
(:import clojure.lang.PersistentVector
java.util.Iterator
java.lang.ProcessBuilder$Redirect
sun.misc.Signal
sun.misc.SignalHandler
[java.io InputStream OutputStream IOException]
[java.net ServerSocket Socket]
[java.nio.charset CharsetDecoder Charset CodingErrorAction]
[java.nio ByteBuffer CharBuffer]
java.io.StringWriter))
(set! *warn-on-reflection* true)
(set! *unchecked-math* true #_:warn-on-boxed)
(Thread/setDefaultUncaughtExceptionHandler
(reify Thread$UncaughtExceptionHandler
(uncaughtException [_ thread ex]
(println ex "Uncaught exception on" (.getName thread)))))
(def ESC \u001b)
(def CSI_PATTERN #"\x1b\[[\x30-x3F]*[\x20-\x2F]*[\x40-\x7E]")
(defrecord Charel [char fg bg])
(defrecord VirtualScreen [pos size bounding-box styles stack ^PersistentVector charels])
(def BLANK (map->Charel {:char \space}))
;; Can be accessed by client rendering code
(def ^:dynamic *screen-size* nil)
(def ^:dynamic *bounding-box* nil)
(defn box-size []
(when-let [[x y w h] *bounding-box*]
[w h]))
(defn csi-fg [color]
(if (nil? color)
(str ESC "[39m")
(let [[r g b] color]
(str ESC "[38;2;" r ";" g ";" b "m"))))
(defn csi-bg [color]
(if (nil? color)
(str ESC "[49m")
(let [[r g b] color]
(str ESC "[48;2;" r ";" g ";" b "m"))))
(defn csi-move [[^long col ^long row]]
(str ESC "[" (inc row) ";" (inc col) "H"))
(defn assoc-col [screen col]
(assoc-in screen [:pos 0] col))
(defn update-col [screen f & args]
(apply update-in screen [:pos 0] f args))
(defn assoc-row [screen row]
(assoc-in screen [:pos 1] row))
(defn update-row [screen f & args]
(apply update-in screen [:pos 1] f args))
(defn col ^long [screen]
(get-in screen [:pos 0]))
(defn row ^long [screen]
(get-in screen [:pos 1]))
(defn push-styles [screen styles]
(-> screen
(update :stack conj (:styles screen))
(update :styles merge styles)))
(defn pop-styles [screen]
(-> screen
(assoc :styles (last (:stack screen)))
(update :stack pop)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn split-el [el]
(when (vector? el)
(let [[tag & rst] el]
(let [fst (first rst)]
(if (map? fst)
[tag fst (rest rst)]
[tag {} (or rst ())])))))
(defmulti draw (fn [element screen]
(if (vector? element)
(if (keyword? (first element))
(first element)
(type (first element)))
(type element))))
(defn draw-line [line screen]
(let [[x y] (:pos screen)
[^long min-x ^long min-y ^long max-x ^long max-y] (:bounding-box screen)
line (remove #{\return} ;; don't want no carriage returns
(subs line 0 (max 0 (min (count line) (- max-x x)))))]
(reduce (fn [screen char]
(-> screen
(update-in [:charels (row screen) (col screen)]
#(-> %
(assoc :char char)
(merge (:styles screen))))
(update-col inc)))
screen
line)))
(defmethod draw nil [_ screen]
screen)
(defmethod draw java.util.List [els screen]
(reduce #(draw %2 %1) screen els))
(defmethod draw clojure.lang.Fn [el screen]
(let [[f attrs children] (split-el el)]
(draw (f attrs children) screen)))
(defmethod draw clojure.lang.Var [el screen]
(let [[f attrs children] (split-el el)]
(draw (f attrs children) screen)))
(defn apply-bounding-box [attrs screen]
(let [[^long vx ^long vy ^long vw ^long vh] (:bounding-box screen)
{:keys [^long x ^long y ^long width ^long height styles]
:or {x 0 y 0 width vw height vh}} attrs
x (max 0 (min (+ x vx) (+ vx vw)))
y (max 0 (min (+ y vy) (+ vy vh)))
width (min width (- vw x))
height (min height (- vh y))]
[x y width height]))
(defmethod draw :box [el screen]
(let [[_ attrs children] (split-el el)
[x y width height :as bbox] (apply-bounding-box attrs screen)
styles (:styles attrs)
coords (for [col (range x (+ x width))
row (range y (+ y height))]
[row col])
screen' (-> screen
(push-styles styles)
(assoc :pos [x y]
:bounding-box [x y (+ x width) (+ y height)])
(update :charels
(fn [charels]
(reduce #(update-in %1 %2 merge styles)
charels
coords))))]
(binding [*bounding-box* bbox]
(-> (reduce #(draw %2 %1) screen' children)
(assoc :pos (:pos screen)
:bounding-box (:bounding-box screen))
(pop-styles)))))
(defmethod draw :span [el screen]
(let [[_ attrs children] (split-el el)
{:keys [styles]} attrs
screen' (push-styles screen styles)]
(-> (reduce #(draw %2 %1) screen' children)
(pop-styles))))
(defmethod draw String [s screen]
(let [[x y] (:pos screen)
[^long min-x ^long min-y ^long max-x ^long max-y]
(:bounding-box screen)]
(let [lines (str/split s #"(?<=\n)")]
(reduce (fn [screen line]
(if (>= (row screen) max-y)
(reduced screen)
(let [nl? (= \newline (last line))
line (cond->> line nl? butlast nl? (apply str))]
(cond-> (draw-line line screen)
nl? (assoc-col min-x)
nl? (update-row inc)))))
screen
lines))))
(defmethod draw Character [char screen]
(let [[x y] (:pos screen)
[^long min-x ^long min-y ^long max-x ^long max-y]
(:bounding-box screen)]
(if (and (<= min-x x max-x) (<= min-y y max-y))
(-> screen
(update-in [:charels (row screen) (col screen)]
#(-> %
(assoc :char char)
(merge (:styles screen))))
(update-col inc))
screen)))
(defmethod draw :line-box [el screen]
(let [[_ attrs children] (split-el el)
[x y width height :as bbox] (apply-bounding-box attrs screen)
[tl t tr r br b bl l] (:lines attrs "╭─╮│╯─╰│")]
(binding [*bounding-box* [(inc x) (inc y) (dec width) (dec height)]]
(draw [:box attrs
tl (repeat (- width 2) t) tr "\n"
(repeat (- height 2)
(str l
(apply str (repeat (- width 2) \space))
r
"\n"))
bl (repeat (- width 2) b) br "\n"
[:box (assoc attrs :x 1 :y 1 :width (- width 2) :height (- height 2))
children]]
screen))))
(defmethod draw :cols [el screen]
(let [[_ attrs children] (split-el el)
[x y width height :as bbox] (apply-bounding-box attrs screen)
ratios (:ratios attrs (repeat (count children) 1))
widths (map #(:width (second (split-el %))) children)
remaining (- width (apply + (remove nil? widths)))
total (apply + (keep (fn [[w r]]
(when (nil? w) r))
(map vector widths ratios)))]
(assert (= (count children) (count ratios) (count widths)))
(binding [*bounding-box* bbox]
(let [children (reduce (fn [res [c w r]]
(let [x (apply + (map #(get-in % [1 :width]) res))
ww (or w (Math/round (double (/ (* remaining r) total))))
ww (if (= (count res) (dec (count children)))
(- width x)
ww)]
(conj res
(if w
(-> c
(assoc-in [1 :x] x)
(assoc-in [1 :width] ww))
[:box {:x x
:width ww}
c]))))
[]
(map vector children widths ratios))]
(->> children
(reduce (fn [s ch] (draw ch s)) screen))))))
(defmethod draw :rows [el screen]
(let [[_ attrs children] (split-el el)
[^long x ^long y ^long width ^long height :as bbox] (apply-bounding-box attrs screen)
ratios (:ratios attrs (repeat (count children) 1))
heights (map #(:height (second (split-el %))) children)
^long remaining (- height (apply + (remove nil? heights)))
^long total (apply + (keep (fn [[w r]]
(when (nil? w) r))
(map vector heights ratios)))]
(assert (= (count children) (count ratios) (count heights)))
(binding [*bounding-box* bbox]
(let [children (reduce (fn [res [c w r]]
(let [y (apply + (map #(get-in % [1 :height]) res))
ww (or w (Math/round (double (/ (* remaining r) total))))
ww (if (= (count res) (dec (count children)))
(- height y)
ww)]
(conj res
(if w
(-> c
(assoc-in [1 :y] y)
(assoc-in [1 :height] ww))
[:box {:y y
:height ww}
c]))))
[]
(map vector children heights ratios))]
(->> children
(reduce (fn [s ch] (draw ch s)) screen))))))
(defn ^VirtualScreen virtual-screen [rows cols]
(map->VirtualScreen {:pos [0 0]
:size [cols rows]
:bounding-box [0 0 cols rows]
:styles {:fg nil :bg nil}
:stack []
:charels (vec (repeat rows (vec (repeat cols BLANK))))}))
(def NULL_ITERATOR
(reify java.util.Iterator
(hasNext [_] false)
(next [_] nil)))
(defn diff-row [^StringBuilder sb row-idx styles ^PersistentVector old ^PersistentVector new]
(let [^Iterator old-it (if old (.iterator old) NULL_ITERATOR)
^Iterator new-it (if new (.iterator new) NULL_ITERATOR)]
(loop [styles styles
col-idx 0
streak? false
old-ch (and (.hasNext old-it) (.next old-it))
new-ch (and (.hasNext new-it) (.next new-it))]
(let [old-next? (.hasNext old-it)
new-next? (.hasNext new-it)]
(if (= old-ch new-ch)
(if new-next?
(recur styles
(inc col-idx)
false
(when old-next? (.next old-it))
(when new-next? (.next new-it)))
styles)
(let [{:keys [char fg bg] :or {char \space}} new-ch
fg? (not= fg (:fg styles))
bg? (not= bg (:bg styles))]
(when-not streak?
(.append sb (csi-move [col-idx row-idx])))
(when fg? (.append sb (csi-fg fg)))
(when bg? (.append sb (csi-bg bg)))
(.append sb char)
(let [new-styles (if (or fg? bg?) new-ch styles)]
(if new-next?
(recur new-styles
(inc col-idx)
true
(when old-next? (.next old-it))
(when new-next? (.next new-it)))
new-styles))))))))
(defn diff-screen [sb ^VirtualScreen old ^VirtualScreen new]
(let [^PersistentVector old-charels (:charels old)
^PersistentVector new-charels (:charels new)
^Iterator old-row-it (.iterator old-charels)
^Iterator new-row-it (.iterator new-charels)]
(loop [styles (:styles old)
row-idx 0
old-row (and (.hasNext old-row-it) (.next old-row-it))
new-row (and (.hasNext new-row-it) (.next new-row-it))]
(let [old-next? (.hasNext old-row-it)
new-next? (.hasNext new-row-it)]
(let [styles (diff-row sb row-idx styles old-row new-row)]
(if new-next?
(recur styles
(inc row-idx)
(when old-next? (.next old-row-it))
(when new-next? (.next new-row-it)))
(assoc new :styles styles)))))))
(defn parse-screen-size [csi]
(when csi
(when-let [[_ row col] (re-find #"(\d+);(\d+)R" csi)]
[(Integer/parseInt row) (Integer/parseInt col)])))
(defn ^CharsetDecoder charset-decoder
([]
(charset-decoder "UTF-8"))
([encoding]
(-> (Charset/forName encoding)
.newDecoder
(.onMalformedInput CodingErrorAction/IGNORE)
(.onUnmappableCharacter CodingErrorAction/IGNORE))))
(defn char-in-range? [min ch max]
(<= (long min) (long ch) (long max)))
(defn input-consumer-loop [^InputStream in handler]
(let [buf-size 8192
buffer (byte-array buf-size)
buffer' (byte-array buf-size)
decoder (charset-decoder)]
(try
(loop [state {}]
#_(prn state)
(let [{:keys [^CharBuffer char-buf]} state]
(if (or (nil? char-buf) (not (.hasRemaining char-buf)))
;; Fill byte buffer, pull out telnet codes, decode to char buffer
(let [end (.read in buffer 0 buf-size)
{:keys [dest-end commands]}
(telnet/filter-commands {:src buffer :dest buffer' :end end})
^CharacterBuffer char-buf (.decode decoder (ByteBuffer/wrap buffer' 0 dest-end))]
(run! #(handler {:type :telnet :command %}) commands)
(recur {:char-buf char-buf}))
;; handle next character
(let [ch (char (.get char-buf))
ansi-state (:ansi-state state)]
(cond
;; The ESC [ is followed by any number (including none) of "parameter bytes" in
;; the range 0x30–0x3F (ASCII 0–9:;<=>?), then by any number of "intermediate
;; bytes" in the range 0x20–0x2F (ASCII space and !"#$%&'()*+,-./), then finally
;; by a single "final byte" in the range 0x40–0x7E (ASCII @A–Z[\]^_`a–z{|}~).
(= ch (char ESC))
(if (.hasRemaining char-buf)
(recur (assoc state
:ansi-state :init
:ansi-command []))
(do
(handler {:type :input :char ch})
(recur state)))
(and (= :init ansi-state) (= \[ ch))
(recur (-> state
(assoc :ansi-state :param-bytes)
(update :ansi-command conj ch)))
(and (= :init ansi-state) (= \O ch))
(recur (-> (assoc state :ansi-state :fn-key)
(update :ansi-command conj ch)))
(and (= :param-bytes ansi-state) (char-in-range? \0 ch \?))
(recur (update state :ansi-command conj ch))
(and (#{:param-bytes :interm-bytes} ansi-state) (char-in-range? \space ch \/))
(recur (-> (assoc state :ansi-state :interm-bytes)
(update :ansi-command conj ch)))
(and (#{:param-bytes :interm-bytes :fn-key} ansi-state) (char-in-range? \@ ch \~))
(do
(handler {:type :ansi :command (String. (chars (into-array Character/TYPE (conj (:ansi-command state) ch))))})
(recur (dissoc state :ansi-state :ansi-command)))
:else
(do
(handler {:type :input :char ch})
(recur (dissoc state :ansi-state :ansi-command))))))))
(catch IOException e
(println "Input loop closed")
:done)
(catch Exception e
(println "Error during input loop" e)))))
(def ansi-key-commands
{"" :esc
"[A" :up
"[B" :down
"[C" :right
"[D" :left
"[H" :home
"[E" :end
"[2~" :insert
"[3~" :delete
"OP" :f1
"OQ" :f2
"OR" :f3
"OS" :f4
"[15~" :f5
"[17~" :f6
"[18~" :f7
"[19~" :f8
"[20~" :f9
"[21~" :f10
"[23~" :f11
"[24~" :f12})
(defn char->key [ch]
(cond
(= 27 (long ch))
:escape
(= 32 (long ch))
:space
(char-in-range? 0 ch 31)
(keyword (str "ctrl-" (char (+ (long ch) 64))))
(char-in-range? 33 ch 126)
(keyword (str ch))
(= ch \u007F)
:backspace
:else
nil))
(defn listener-handler [{:keys [listeners]}]
(fn [{:keys [type command char] :as msg}]
#_(prn msg)
(let [emit (fn [message]
#_(prn message)
(let [m (assoc message :time (System/currentTimeMillis))]
(run! (fn [l] (l m))
(vals @listeners))))]
(case type
:telnet
(when (= (take 3 command) [:IAC :SUBNEGOTIATION :NAWS])
(let [raw-msg (:telnet/raw (meta command))
[_ _ _ _ cols _ rows] raw-msg]
(when (and (int? cols) (int? rows))
(emit {:type :screen-size
:screen-size [rows cols]}))))
:ansi
(if-let [screen-size (parse-screen-size command)]
(emit {:type :screen-size
:screen-size screen-size})
(if-let [key (get ansi-key-commands command)]
(emit {:type :input
:key key})))
:input
(emit (assoc msg :key (char->key (:char msg))))))))
(defn start-input-loop [{:keys [^InputStream in] :as client}]
(assoc client
:input-loop
(future
(loop [result (input-consumer-loop in (listener-handler client))]
(when-not (= :done result)
(recur (input-consumer-loop in (listener-handler client))))))))
(defn request-screen-size [^OutputStream out]
(let [csi (fn [& args]
(let [^String code (apply str ESC "[" args)]
(.write out (.getBytes code))))
buffer (byte-array 1024)]
(csi "s") ;; save cursor position
(csi "5000;5000H")
(csi "6n")
(csi "u")))
(def CSI-ALTERNATE-SCREEN (str ESC "[?1049h"))
(def CSI-REGULAR-SCREEN (str ESC "[?1049l"))
(def CSI-CLEAR-SCREEN (str ESC "[2J"))
(def CSI-UPPER-LEFT (str ESC "[H"))
(def CSI-RESET-STYLES (str ESC "[m"))
(def CSI-SHOW-CURSOR (str ESC "[?25h"))
(def CSI-HIDE-CURSOR (str ESC "[?25l"))
(defn start-client [{:keys [^OutputStream out] :as client}]
(when (:socket client)
(telnet/prep-telnet out))
(.write out (.getBytes (str CSI-ALTERNATE-SCREEN
CSI-CLEAR-SCREEN
CSI-UPPER-LEFT
CSI-RESET-STYLES
CSI-HIDE-CURSOR)))
(request-screen-size out))
(defn stop-client [{:keys [^OutputStream out ^Socket socket] :as client}]
(try
(.write out (.getBytes (str CSI-REGULAR-SCREEN
CSI-RESET-STYLES
CSI-SHOW-CURSOR)))
(when socket
(.close socket))
(catch IOException _)))
(defn add-shutdown-hook [^clojure.lang.IFn f]
(.addShutdownHook (java.lang.Runtime/getRuntime)
(Thread. f)))
(defn make-client [in out & [socket]]
(let [size (atom nil)
client {:socket socket
:in in
:out out
:size size
:screen (atom nil)
:listeners (atom {:resize (fn [e]
(when-let [s (:screen-size e)]
(reset! size (with-meta s {:trikl/message e}))))})}]
(start-client client)
(let [client (start-input-loop client)]
(add-shutdown-hook #(stop-client client))
client)))
(defn ^"[Ljava.lang.String;" string-array [args]
(into-array String args))
(defn exec-stty [& args]
(let [^Process
process (-> (ProcessBuilder. (string-array (cons "stty" args)))
(.redirectInput (ProcessBuilder$Redirect/from (io/file "/dev/tty")))
(.start))
^StringWriter err (StringWriter.)]
{:exit (.waitFor process)
:err @(future
(with-open [^StringWriter err (StringWriter.)]
(io/copy (.getErrorStream process) err)
(.toString err)))
:out @(future
(with-open [^StringWriter out (StringWriter.)]
(io/copy (.getInputStream process) out)
(.toString out)))}))
(defn stdio-client []
(exec-stty "-echo" "-icanon")
(let [client (make-client System/in System/out)]
(add-shutdown-hook (fn []
(stop-client client)
(exec-stty "+echo" "+icanon")))
(Signal/handle (Signal. "WINCH")
(reify SignalHandler
(^void handle [this ^Signal s]
(let [out (:out (exec-stty "size"))]
(when-let [[_ rows cols] (re-find #"(\d+) (\d+)" out)]
(run! #(% (with-meta {:type :screen-size
:screen-size [(Long/parseLong rows) (Long/parseLong cols)]}
{:trikl/source :SIGWINCH}))
(vals @(:listeners client))))))))
client))
(defn add-listener [client key listener]
(swap! (:listeners client) assoc key listener))
(defn remove-listener [client key]
(swap! (:listeners client) dissoc key))
(defmacro time-info [expr desc]
`(let [start# (System/nanoTime)
ret# ~expr]
(println (str ~desc ": " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " ms"))
ret#))
(defn start-server
([client-handler]
(start-server client-handler 1357))
([client-handler port]
(let [^ServerSocket server (telnet/server-socket port)
clients (atom [])
stop! (fn []
(run! stop-client @clients)
(try
(.close server)
(catch IOException _)))]
(future
(try
(loop [^Socket client-sock (telnet/accept-connection server)]
(let [client (make-client (.getInputStream client-sock)
(.getOutputStream client-sock)
client-sock)]
(swap! clients conj client)
(client-handler client)
(recur (telnet/accept-connection server))))
(catch IOException _
;; socket closed
)
(catch Throwable t
(println "Exception in server loop" t))))
stop!)))
(defn render [{:keys [^VirtualScreen screen ^OutputStream out size] :as client} element]
(let [size @size]
(assert (= 2 (count size)))
(binding [*screen-size* size
*bounding-box* (into [0 0] size)]
(let [sb (StringBuilder. ^String CSI-RESET-STYLES)
prev-screen @screen
styles (:styles prev-screen)
empty-screen (apply virtual-screen size)
prev-screen (if (= (:size prev-screen) size)
(or prev-screen empty-screen)
(do
(.append sb CSI-CLEAR-SCREEN)
empty-screen))
next-screen (draw element empty-screen)
new-screen (diff-screen sb prev-screen next-screen)
commands (str sb)]
(.write out (.getBytes commands))
(reset! screen new-screen))))
nil)
(defn force-render [client element]
(reset! (:screen client) (apply virtual-screen @(:size client)))
(render client element))
(defn render-watch! [client element state]
(render client [element @state])
(add-watch state ::render (fn [_ _ _ new-state]
(render client [element new-state]))))
(defn unwatch! [state]
(remove-watch state ::render))
================================================
FILE: src/trikl/demo/world.clj
================================================
(ns trikl.demo.world)
(defn tile [kind glyph color]
{:tile/kind kind
:entity/glyph glyph
:entity/color color})
(def tiles
{:floor (tile :floor "." :white)
:wall (tile :wall "#" :white)
:bound (tile :bound "X" :black)})
(defn get-tile [tiles x y]
(get-in tiles [y x] (:bound tiles)))
(defn random-tile []
(if (< (rand) 0.45)
(:wall tiles)
(:floor tiles)))
(defn random-tiles [cols rows]
(vec (for [row (range rows)]
(vec (for [col (range cols)]
(assoc (random-tile) :entity/col col :entity/row row))))))
(defn neighbors [tiles x y]
(let [sx (max 0 (dec x))
sy (max 0 (dec y))]
(for [px (range sx (+ sx 3))
py (range sy (+ sy 3))]
(get-in tiles [py px]))))
(defn tile-count [ts kind]
(count (filter (comp #{kind} :tile/kind) ts)))
(defn smooth [ts]
(vec
(for [row (range (count ts))]
(vec
(for [col (range (count (get ts row)))]
(let [tile (get-in ts [row col])
neighbors (neighbors ts col row)
wall-count (tile-count neighbors :wall)]
(if (> wall-count 4)
(merge tile (:wall tiles))
(merge tile (:floor tiles)))))))))
(comment
(defn inspect [tiles]
(mapv (comp (partial apply str)
(partial map :entity/glyph)) tiles))
(def ts (random-tiles 160 50))
[".##...##.#"
".#..###..."
"#.##..#.#."
"#..###...#"
"....#...#."
"#..#.#.##."
"...##....#"
"#.#.#.##.."
".#.##....#"
"###..#.###"]
(-> (random-tiles 10 10)
smooth
smooth
smooth
inspect)
(tile-count
(neighbors ts 2 1)
:floor))
================================================
FILE: src/trikl/demo.clj
================================================
(ns trikl.demo
(:require [trikl.core :as t]
[trikl.demo.world :as world]
[trikl.util :refer [reduce-for]]))
(def clients (atom []))
(def stop-server (t/start-server #(swap! clients conj %) 1357))
(def stop-server (t/start-server #(t/render % [:cols
[:line-box { :styles {:bg [50 50 200]}}]
[:line-box { :styles {:bg [200 50 0]}}
[:box {:x 3 :y 1}
[:span {:styles {:fg [30 30 150]}} "hello\n"]
[:span {:styles {:fg [100 250 100]}} \x " world"]]]]) 1357))
(t/render (last @clients)
[:cols
[:line-box { :styles {:bg [50 50 200]}}]
[:line-box { :styles {:bg [200 50 0]}}
[:box {:x 3 :y 1}
[:span {:styles {:fg [30 30 150]}} "hello\n"]
[:span {:styles {:fg [100 250 100]}} \x " world"]]]])
#_(stop-server)
(reset! (:size (last @clients)) [9 19])
(t/stop-client (last @clients))
(Math/cos Math/PI)
;; => 1.0
(Math/sin (* 2 Math/PI))
(def stop? (atom false))
(reset! stop? true)
(future
(loop [step 0]
(let [steps 30
circle (* 2 Math/PI)
radius 8
x (Math/round (+ 44 (* 2 radius (Math/cos (/ (* circle step) steps)))))
y (Math/round (+ 8 (* radius (Math/sin (/ (* circle step) steps)))))]
(t/render (last @clients)
[:line-box {:x x :y y :width 12 :height 5 :styles {:bg [50 50 200]}}
[:span {:x 5 :y 3} "Hix!!!!"]])
(Thread/sleep 80)
(when-not @stop?
(recur (if (< step (dec steps))
(inc step)
0))))))
(last @clients)
(t/render (last @clients)
[:cols
[:line-box { :styles {:bg [50 50 200]}}]
[:line-box { :styles {:bg [200 50 0]}}
[:box {:x 3 :y 1}
[:span {:styles {:fg [30 30 150]}} "hello\n"]
[:span {:styles {:fg [100 250 100]}} \x " world"]]]])
(t/render (last @clients)
[:box
[:line-box {:x 10 :y 6 :width 20 :height 12 :styles {:bg [50 50 200]}}]
[:line-box {:x 5 :y 2 :width 18 :height 8 :styles {:bg [200 50 0]}}
[:box {:x 3 :y 1}
[:span {:styles {:fg [30 30 150]}} "hello\n"]
[:span {:styles {:fg [100 250 100]}} \x " world"]]]])
(t/render (last @clients)
[:rows {:ratios [3 1]}
[:cols
[:line-box {:styles {:bg [0 0 200]}}]
[:line-box {:styles {:bg [50 50 200]}}]]
[:line-box {:styles {:bg [200 50 100]
:fg [255 80 130]}}
[:box {:x 3 :y 1}
[:span {:styles {:fg [30 30 150]}} "hello\n"]
[:span {:styles {:fg [100 250 100]}} \x " world"]]]])
(t/add-listener (last @clients)
::my-listener
(fn [event]
(prn event)))
(t/render (last @clients)
[:box
(for [x (range 79)
y (range 53)
:let [page 2]]
[:box {:x x :y y} (str (char (+ 255 (* page 79 53) x (* 53 y))))]
)
]
)
(defmethod t/draw :line-box [el screen]
(let [[_ attrs children] (t/split-el el)
[x y width height] (t/apply-bounding-box attrs screen)
[tl t tr r br b bl l] (:lines attrs "╭─╮│╯─╰│")]
(t/draw [:box attrs
tl (repeat (- width 2) t) tr "\n"
(repeat (- height 2)
(str l
(apply str (repeat (- width 2) \space))
r
"\n")
)
bl (repeat (- width 2) b) br "\n"
[:box (assoc attrs :x 1 :y 1 :width (- width 2) :height (- height 2))
children]]
screen)))
" ━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞
┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓
┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿▀▁▂▃▄▅▆▇█
╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟"
(apply str (map #(char %) (range 1100 1400)))
(range 30 110)
(char 100)
(defn app [{:keys [offset]} _]
[:box
(for [y (range 50)]
[:span
(for [x (range 80)]
[:span {:styles {:bg [(+ offset (* x 2)) (+ offset (* y 2)) (+ offset x (* 4 y))]}} ({0 "-"
5 "\\"
10 "|"
15 "/"
20 "."
25 "*"} offset)])
"\n"])])
(def state (atom {:size [300 300]
:pos [150 150]
:world (->> (world/random-tiles 300 300)
(iterate world/smooth)
(drop 3)
first)
}))
(defmethod t/draw :world-map [el {:keys [charels] :as screen}]
(let [[el attrs] (t/split-el el)
[^long x ^long y ^long width ^long height] (t/apply-bounding-box attrs screen)
{:keys [world pos]} attrs
[x-center y-center] pos
x-offset (Math/round (double (- x-center (/ width 2))))
y-offset (Math/round (double (- y-center (/ height 2))))]
(assoc screen
:charels
(reduce-for charels [col (range width)
row (range height)]
(assoc-in % [(+ y row) (+ x col) :char]
(first (get-in world [(+ y row y-offset) (+ x col x-offset) :entity/glyph])))))))
(first (get-in (world/random-tiles 3 3) [1 1 :entity/glyph]))
(t/render (last @clients) (repeat 20 "la"))
(t/render (last @clients)[:span {:styles {:fg [100 200 0] :bg [50 50 200]}} "Oh my!"])
(t/render (last @clients)[:box {:x 20 :y 10, :width 7, :height 3} "Hello, world!"])
(t/render (last @clients) (repeat 200 "*"))
(t/render (last @clients) [:line-box {}])
(t/time-info
(t/render (last @clients) [:world-map (assoc @state :pos [152 148])])
"render")
(t/render-watch! (last @clients) (fn [attrs _] [:world-map attrs]) state)
(t/render (last @clients)
[:cols
[:rows
[:line-box "1"]
[:line-box "2"]]
[:rows
[:line-box "3"]
[:line-box "4"]]])
(t/split-el [:line-box ])
(do
(swap! state update-in [:pos 0] dec)
nil
)
(unwatch! state)
(swap! state update :offset + 5)
(defn app [attrs children]
[:rows
[:line-box "Hiiiiii"]
[:line-box {:height 15 :styles {:bg [100 50 50]}}]])
(t/render (last @clients) [app])
(def app-state (atom {:pos [10 10]}))
(t/render-watch! (last @clients)
(fn [{[x y] :pos} _]
[:box {:x x :y y} "X"])
app-state)
(swap! app-state update-in [:pos 0] inc)
(swap! app-state update-in [:pos 1] inc)
(t/unwatch! app-state)
================================================
FILE: src/trikl/telnet.clj
================================================
(ns trikl.telnet
(:import java.net.ServerSocket
javax.net.ServerSocketFactory))
(set! *warn-on-reflection* true)
(set! *unchecked-math* true #_:warn-on-boxed)
(defn ^ServerSocket server-socket [^long port]
(.createServerSocket (ServerSocketFactory/getDefault) port))
(defn accept-connection [^ServerSocket server-socket]
(doto (.accept server-socket)
(.setTcpNoDelay true)))
(def TELNET
{:SUBNEGOTIATION_END 0xf0
:SUBNEGOTIATION 0xfa
:WILL 0xfb
:WONT 0xfc
:DO 0xfd
:DONT 0xfe
:IAC 0xff
:TRANSMIT_BINARY 0x00
:ECHO 0x01
:RECONNECTION 0x02
:SUPPRESS_GO_AHEAD 0x03
:NAWS 0x1f
:LINEMODE 0x22})
(defn send-telnet-command [^java.net.SocketOutputStream out & args]
(->> args
(map #(TELNET % %))
(map unchecked-byte)
^bytes (into-array Byte/TYPE)
(.write out)))
(defn prep-telnet [out]
(send-telnet-command out
:IAC :DO :LINEMODE
:IAC :SUBNEGOTIATION :LINEMODE
(byte 1) (byte 0)
:IAC :SUBNEGOTIATION_END
:IAC :WILL :ECHO
:IAC :DO :NAWS))
(defn filter-commands
"Copy buffer `src` to `dest`, filtering out any Telnet protocol commands along
the way. These are returned separately."
[{:keys [^bytes src ^bytes dest ^long end]}]
#_(prn (take end (seq src)))
(let [IAC (unchecked-byte (TELNET :IAC))
subneg-start (unchecked-byte (TELNET :SUBNEGOTIATION))
subneg-end (unchecked-byte (TELNET :SUBNEGOTIATION_END))
subcmd-min (unchecked-byte (TELNET :WILL))
subcmd-max (unchecked-byte (TELNET :DONT))
cmd->kw (into {} (map (juxt (comp unchecked-byte val) key)) TELNET)
byte->long #(if (< % 0)
(+ 255 (long %))
(long %))]
(loop [state {:src-pos 0
:dest-pos 0
:commands []}]
(let [{:keys [src-pos dest-pos cmd commands]} state]
(if (= src-pos end)
{:src-pos (- src-pos (count cmd)) ;; if a command is in flight then
;; don't consume the last bytes of
;; the buffer
:dest-end dest-pos
:commands commands}
(let [b (aget src src-pos)
{:keys [cmd cmd? subneg?]} state]
(cond
(and subneg? (not= subneg-end b))
(recur (-> state
(update :src-pos inc)
(update :cmd conj b)))
(= IAC b)
(recur (-> state
(update :src-pos inc)
(assoc :cmd? true
:cmd [b])))
(and cmd? (= subneg-start b))
(recur (-> state
(update :src-pos inc)
(update :cmd conj b)
(assoc :cmd? false
:subneg? true)))
(and cmd? (<= subcmd-min b subcmd-max))
(recur (-> state
(update :src-pos inc)
(update :cmd conj b)))
(or cmd? (and subneg? (= subneg-end b)))
(let [command (conj cmd b)]
(recur (-> state
(assoc :src-pos (inc src-pos))
(dissoc :cmd :cmd? :subneg?)
(update :commands
conj (with-meta
(mapv #(cmd->kw % (byte->long %)) command)
{:telnet/raw (mapv byte->long command)})))))
:else
(do
(aset dest dest-pos b)
(recur (-> state
(update :src-pos inc)
(update :dest-pos inc)))))))))))
#_
(let [src-buf (byte-array 10)
dest-buf (byte-array 10)]
(aset src-buf 0 (byte 60))
(aset src-buf 1 (byte 61))
(aset src-buf 2 (byte 62))
(aset src-buf 3 (unchecked-byte (TELNET :IAC)))
(aset src-buf 4 (unchecked-byte (TELNET :WILL)))
(aset src-buf 5 (unchecked-byte (TELNET :LINEMODE)))
(aset src-buf 6 (byte 70))
(-> (buffer-filter-commands {:src src-buf :dest dest-buf :end 7})
:commands
first
meta)
#_(seq dest-buf)
)
================================================
FILE: src/trikl/util.clj
================================================
(ns trikl.util)
(defn reduce-for* [binding-pairs init body]
(if (next binding-pairs)
(let [[[v val]] binding-pairs
res (gensym "res")]
`(reduce (fn [~res ~v]
~(reduce-for* (next binding-pairs) res body))
~init
~val))
(let [[[v val]] binding-pairs]
`(reduce (fn [~'% ~v]
~@body)
~init
~val))))
(defmacro reduce-for
{:style/indent 2}
[init bindings & body]
(let [binding-pairs (partition 2 bindings)]
(reduce-for* binding-pairs init body)))
(comment
(reduce-for [] [x (range 3)
y (range 3)]
(conj % [x y])))
================================================
FILE: test/unit/trikl/core_test.clj
================================================
(ns trikl.core-test
(:require [trikl.core :as t]
[clojure.test :refer :all]
[lambdaisland.ansi :as ansi]))
(is (= [[{:row 1, :col 1} "x"] {}]
(let [sb (StringBuilder.)
styles (t/diff-row
sb
0
{}
[t/BLANK]
[(t/map->Charel {:char \x})])]
[(ansi/token-stream (str sb)) styles])))
(is (=
(let [sb (StringBuilder.)
styles (t/diff-row
sb
0
{}
[(t/map->Charel {:char \x})]
[(t/map->Charel {:char \x})])]
[(ansi/token-stream (str sb)) styles])
))
(+ 1 1)
(let [sb (StringBuilder.)
styles (t/diff-row
sb
0
{}
[t/BLANK]
[(t/map->Charel {:char \y :fg [10 20 30]})])]
[(ansi/token-stream (str sb)) styles])
[[{:row 1, :col 1}
{:foreground [:rgb 10 20 30]}
"y"]
{:char \y, :fg [10 20 30], :bg nil}]
(let [sb (StringBuilder.)
styles (t/diff-row
sb
0
{}
[t/BLANK t/BLANK]
[(t/map->Charel {:char \x :fg [10 20 30]})
(t/map->Charel {:char \y :fg [10 20 30]})])]
[(ansi/token-stream (str sb)) styles])
[[{:row 1, :col 1}
{:foreground [:rgb 10 20 30]}
"xy"]
{:char \x, :fg [10 20 30], :bg nil}]
(let [sb (StringBuilder.)
styles (t/diff-row
sb
0
{}
[]
[(t/map->Charel {:char \x :fg [10 20 30]})
(t/map->Charel {:char \y :fg [10 20 30]})])]
[(ansi/token-stream (str sb)) styles])
[[{:row 1, :col 1}
{:foreground [:rgb 10 20 30]}
"xy"]
{:char \x, :fg [10 20 30], :bg nil}]
(let [sb (StringBuilder.)
styles (t/diff-row
sb
0
{}
[(t/map->Charel {:char \x :fg [10 20 30]})
(t/map->Charel {:char \y :fg [10 20 30]})]
[])]
[(ansi/token-stream (str sb)) styles])
[[{:row 1, :col 1} " "] {}]
(t/time-info
(let [sb (StringBuilder.)
styles (t/diff-row
sb
0
{}
[t/BLANK t/BLANK t/BLANK]
[(t/map->Charel {:char \x :fg [10 20 30]})
t/BLANK
(t/map->Charel {:char \y :fg [10 20 30]})])]
[(ansi/token-stream (str sb)) styles])
"")
[[{:row 1, :col 1}
{:foreground [:rgb 10 20 30]}
"x"
{:row 1, :col 3}
"y"]
{:char \x, :fg [10 20 30], :bg nil}]
================================================
FILE: tests.edn
================================================
#kaocha/v1
{}
gitextract_1v1wvub8/ ├── .circleci/ │ └── config.yml ├── .dir-locals.el ├── .gitignore ├── CHANGELOG.md ├── LICENSE.txt ├── README.md ├── bin/ │ └── kaocha ├── deps.edn ├── notes.org ├── src/ │ └── trikl/ │ ├── core.clj │ ├── demo/ │ │ └── world.clj │ ├── demo.clj │ ├── telnet.clj │ └── util.clj ├── test/ │ └── unit/ │ └── trikl/ │ └── core_test.clj └── tests.edn
Condensed preview — 16 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (74K chars).
[
{
"path": ".circleci/config.yml",
"chars": 548,
"preview": "version: 2\njobs:\n build:\n docker:\n - image: circleci/clojure:tools-deps\n steps:\n - checkout\n - res"
},
{
"path": ".dir-locals.el",
"chars": 63,
"preview": "((nil . ((cider-clojure-cli-global-options . \"-A:dev:test\"))))\n"
},
{
"path": ".gitignore",
"chars": 44,
"preview": ".cpcache\n.nrepl-port\ntarget\nrepl\nscratch.clj"
},
{
"path": "CHANGELOG.md",
"chars": 308,
"preview": "# Unreleased\n\n## Added\n\n- `stdio-client` for a direct STDIN/STDOUT connection\n- Added access to screen and bounding box "
},
{
"path": "LICENSE.txt",
"chars": 16726,
"preview": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\""
},
{
"path": "README.md",
"chars": 10505,
"preview": "# Trikl\n\n\"Terminal React for Clojure\" => Trikl\n\n[]("
},
{
"path": "bin/kaocha",
"chars": 50,
"preview": "#!/bin/bash\nclojure -A:test -m kaocha.runner \"$@\"\n"
},
{
"path": "deps.edn",
"chars": 251,
"preview": "{:paths [\"src\" \"test\" \"resources\"]\n :deps {org.clojure/clojure {:mvn/version \"1.10.0-RC4\"}}\n\n :aliases\n {:dev\n {}\n\n :"
},
{
"path": "notes.org",
"chars": 146,
"preview": "* app ideas\n** roguelike / rpg\n** \"graphics editor\" / level editor\n** interactive version upgrades\n** interactive test r"
},
{
"path": "src/trikl/core.clj",
"chars": 25102,
"preview": "(ns trikl.core\n (:require [clojure.java.io :as io]\n [clojure.string :as str]\n [clojure.java.shell"
},
{
"path": "src/trikl/demo/world.clj",
"chars": 1649,
"preview": "(ns trikl.demo.world)\n\n(defn tile [kind glyph color]\n {:tile/kind kind\n :entity/glyph glyph\n :entity/color color})\n"
},
{
"path": "src/trikl/demo.clj",
"chars": 7264,
"preview": "(ns trikl.demo\n (:require [trikl.core :as t]\n [trikl.demo.world :as world]\n [trikl.util :refer [r"
},
{
"path": "src/trikl/telnet.clj",
"chars": 4519,
"preview": "(ns trikl.telnet\n (:import java.net.ServerSocket\n javax.net.ServerSocketFactory))\n\n(set! *warn-on-reflection*"
},
{
"path": "src/trikl/util.clj",
"chars": 669,
"preview": "(ns trikl.util)\n\n(defn reduce-for* [binding-pairs init body]\n (if (next binding-pairs)\n (let [[[v val]] binding-pair"
},
{
"path": "test/unit/trikl/core_test.clj",
"chars": 2604,
"preview": "(ns trikl.core-test\n (:require [trikl.core :as t]\n [clojure.test :refer :all]\n [lambdaisland.ansi"
},
{
"path": "tests.edn",
"chars": 14,
"preview": "#kaocha/v1\n{}\n"
}
]
About this extraction
This page contains the full source code of the lambdaisland/trikl GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 16 files (68.8 KB), approximately 18.3k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.