[
  {
    "path": ".circleci/config.yml",
    "content": "version: 2\njobs:\n  build:\n    docker:\n      - image: circleci/clojure:tools-deps\n    steps:\n      - checkout\n      - restore_cache:\n          keys:\n          - v1-dependencies-{{ checksum \"deps.edn\" }}\n          # fallback to using the latest cache if no exact match is found\n          - v1-dependencies-\n      - run: clojure -A:dev:test -Spath\n      - save_cache:\n          paths:\n            - ~/.m2\n          key: v1-dependencies-{{ checksum \"deps.edn\" }}\n      - run: clojure -A:dev:test -m kaocha.runner --reporter kaocha.report/documentation\n"
  },
  {
    "path": ".dir-locals.el",
    "content": "((nil . ((cider-clojure-cli-global-options . \"-A:dev:test\"))))\n"
  },
  {
    "path": ".gitignore",
    "content": ".cpcache\n.nrepl-port\ntarget\nrepl\nscratch.clj"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Unreleased\n\n## Added\n\n- `stdio-client` for a direct STDIN/STDOUT connection\n- Added access to screen and bounding box dimensions during rendering\n\n## Fixed\n\n- Fix re-rendering when the terminal size changes, before there would often be\n  artifacts.\n- Fix endless loop when client socket closes\n\n## Changed\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\"\n    means each individual or legal entity that creates, contributes to\n    the creation of, or owns Covered Software.\n\n1.2. \"Contributor Version\"\n    means the combination of the Contributions of others (if any) used\n    by a Contributor and that particular Contributor's Contribution.\n\n1.3. \"Contribution\"\n    means Covered Software of a particular Contributor.\n\n1.4. \"Covered Software\"\n    means Source Code Form to which the initial Contributor has attached\n    the notice in Exhibit A, the Executable Form of such Source Code\n    Form, and Modifications of such Source Code Form, in each case\n    including portions thereof.\n\n1.5. \"Incompatible With Secondary Licenses\"\n    means\n\n    (a) that the initial Contributor has attached the notice described\n        in Exhibit B to the Covered Software; or\n\n    (b) that the Covered Software was made available under the terms of\n        version 1.1 or earlier of the License, but not also under the\n        terms of a Secondary License.\n\n1.6. \"Executable Form\"\n    means any form of the work other than Source Code Form.\n\n1.7. \"Larger Work\"\n    means a work that combines Covered Software with other material, in \n    a separate file or files, that is not Covered Software.\n\n1.8. \"License\"\n    means this document.\n\n1.9. \"Licensable\"\n    means having the right to grant, to the maximum extent possible,\n    whether at the time of the initial grant or subsequently, any and\n    all of the rights conveyed by this License.\n\n1.10. \"Modifications\"\n    means any of the following:\n\n    (a) any file in Source Code Form that results from an addition to,\n        deletion from, or modification of the contents of Covered\n        Software; or\n\n    (b) any new file in Source Code Form that contains any Covered\n        Software.\n\n1.11. \"Patent Claims\" of a Contributor\n    means any patent claim(s), including without limitation, method,\n    process, and apparatus claims, in any patent Licensable by such\n    Contributor that would be infringed, but for the grant of the\n    License, by the making, using, selling, offering for sale, having\n    made, import, or transfer of either its Contributions or its\n    Contributor Version.\n\n1.12. \"Secondary License\"\n    means either the GNU General Public License, Version 2.0, the GNU\n    Lesser General Public License, Version 2.1, the GNU Affero General\n    Public License, Version 3.0, or any later versions of those\n    licenses.\n\n1.13. \"Source Code Form\"\n    means the form of the work preferred for making modifications.\n\n1.14. \"You\" (or \"Your\")\n    means an individual or a legal entity exercising rights under this\n    License. For legal entities, \"You\" includes any entity that\n    controls, is controlled by, or is under common control with You. For\n    purposes of this definition, \"control\" means (a) the power, direct\n    or indirect, to cause the direction or management of such entity,\n    whether by contract or otherwise, or (b) ownership of more than\n    fifty percent (50%) of the outstanding shares or beneficial\n    ownership of such entity.\n\n2. License Grants and Conditions\n--------------------------------\n\n2.1. Grants\n\nEach Contributor hereby grants You a world-wide, royalty-free,\nnon-exclusive license:\n\n(a) under intellectual property rights (other than patent or trademark)\n    Licensable by such Contributor to use, reproduce, make available,\n    modify, display, perform, distribute, and otherwise exploit its\n    Contributions, either on an unmodified basis, with Modifications, or\n    as part of a Larger Work; and\n\n(b) under Patent Claims of such Contributor to make, use, sell, offer\n    for sale, have made, import, and otherwise transfer either its\n    Contributions or its Contributor Version.\n\n2.2. Effective Date\n\nThe licenses granted in Section 2.1 with respect to any Contribution\nbecome effective for each Contribution on the date the Contributor first\ndistributes such Contribution.\n\n2.3. Limitations on Grant Scope\n\nThe licenses granted in this Section 2 are the only rights granted under\nthis License. No additional rights or licenses will be implied from the\ndistribution or licensing of Covered Software under this License.\nNotwithstanding Section 2.1(b) above, no patent license is granted by a\nContributor:\n\n(a) for any code that a Contributor has removed from Covered Software;\n    or\n\n(b) for infringements caused by: (i) Your and any other third party's\n    modifications of Covered Software, or (ii) the combination of its\n    Contributions with other software (except as part of its Contributor\n    Version); or\n\n(c) under Patent Claims infringed by Covered Software in the absence of\n    its Contributions.\n\nThis License does not grant any rights in the trademarks, service marks,\nor logos of any Contributor (except as may be necessary to comply with\nthe notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\nNo Contributor makes additional grants as a result of Your choice to\ndistribute the Covered Software under a subsequent version of this\nLicense (see Section 10.2) or under the terms of a Secondary License (if\npermitted under the terms of Section 3.3).\n\n2.5. Representation\n\nEach Contributor represents that the Contributor believes its\nContributions are its original creation(s) or it has sufficient rights\nto grant the rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\nThis License is not intended to limit any rights You have under\napplicable copyright doctrines of fair use, fair dealing, or other\nequivalents.\n\n2.7. Conditions\n\nSections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted\nin Section 2.1.\n\n3. Responsibilities\n-------------------\n\n3.1. Distribution of Source Form\n\nAll distribution of Covered Software in Source Code Form, including any\nModifications that You create or to which You contribute, must be under\nthe terms of this License. You must inform recipients that the Source\nCode Form of the Covered Software is governed by the terms of this\nLicense, and how they can obtain a copy of this License. You may not\nattempt to alter or restrict the recipients' rights in the Source Code\nForm.\n\n3.2. Distribution of Executable Form\n\nIf You distribute Covered Software in Executable Form then:\n\n(a) such Covered Software must also be made available in Source Code\n    Form, as described in Section 3.1, and You must inform recipients of\n    the Executable Form how they can obtain a copy of such Source Code\n    Form by reasonable means in a timely manner, at a charge no more\n    than the cost of distribution to the recipient; and\n\n(b) You may distribute such Executable Form under the terms of this\n    License, or sublicense it under different terms, provided that the\n    license for the Executable Form does not attempt to limit or alter\n    the recipients' rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\nYou may create and distribute a Larger Work under terms of Your choice,\nprovided that You also comply with the requirements of this License for\nthe Covered Software. If the Larger Work is a combination of Covered\nSoftware with a work governed by one or more Secondary Licenses, and the\nCovered Software is not Incompatible With Secondary Licenses, this\nLicense permits You to additionally distribute such Covered Software\nunder the terms of such Secondary License(s), so that the recipient of\nthe Larger Work may, at their option, further distribute the Covered\nSoftware under the terms of either this License or such Secondary\nLicense(s).\n\n3.4. Notices\n\nYou may not remove or alter the substance of any license notices\n(including copyright notices, patent notices, disclaimers of warranty,\nor limitations of liability) contained within the Source Code Form of\nthe Covered Software, except that You may alter any license notices to\nthe extent required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\nYou may choose to offer, and to charge a fee for, warranty, support,\nindemnity or liability obligations to one or more recipients of Covered\nSoftware. However, You may do so only on Your own behalf, and not on\nbehalf of any Contributor. You must make it absolutely clear that any\nsuch warranty, support, indemnity, or liability obligation is offered by\nYou alone, and You hereby agree to indemnify every Contributor for any\nliability incurred by such Contributor as a result of warranty, support,\nindemnity or liability terms You offer. You may include additional\ndisclaimers of warranty and limitations of liability specific to any\njurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n---------------------------------------------------\n\nIf it is impossible for You to comply with any of the terms of this\nLicense with respect to some or all of the Covered Software due to\nstatute, judicial order, or regulation then You must: (a) comply with\nthe terms of this License to the maximum extent possible; and (b)\ndescribe the limitations and the code they affect. Such description must\nbe placed in a text file included with all distributions of the Covered\nSoftware under this License. Except to the extent prohibited by statute\nor regulation, such description must be sufficiently detailed for a\nrecipient of ordinary skill to be able to understand it.\n\n5. Termination\n--------------\n\n5.1. The rights granted under this License will terminate automatically\nif You fail to comply with any of its terms. However, if You become\ncompliant, then the rights granted under this License from a particular\nContributor are reinstated (a) provisionally, unless and until such\nContributor explicitly and finally terminates Your grants, and (b) on an\nongoing basis, if such Contributor fails to notify You of the\nnon-compliance by some reasonable means prior to 60 days after You have\ncome back into compliance. Moreover, Your grants from a particular\nContributor are reinstated on an ongoing basis if such Contributor\nnotifies You of the non-compliance by some reasonable means, this is the\nfirst time You have received notice of non-compliance with this License\nfrom such Contributor, and You become compliant prior to 30 days after\nYour receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\ninfringement claim (excluding declaratory judgment actions,\ncounter-claims, and cross-claims) alleging that a Contributor Version\ndirectly or indirectly infringes any patent, then the rights granted to\nYou by any and all Contributors for the Covered Software under Section\n2.1 of this License shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all\nend user license agreements (excluding distributors and resellers) which\nhave been validly granted by You or Your distributors under this License\nprior to termination shall survive termination.\n\n************************************************************************\n*                                                                      *\n*  6. Disclaimer of Warranty                                           *\n*  -------------------------                                           *\n*                                                                      *\n*  Covered Software is provided under this License on an \"as is\"       *\n*  basis, without warranty of any kind, either expressed, implied, or  *\n*  statutory, including, without limitation, warranties that the       *\n*  Covered Software is free of defects, merchantable, fit for a        *\n*  particular purpose or non-infringing. The entire risk as to the     *\n*  quality and performance of the Covered Software is with You.        *\n*  Should any Covered Software prove defective in any respect, You     *\n*  (not any Contributor) assume the cost of any necessary servicing,   *\n*  repair, or correction. This disclaimer of warranty constitutes an   *\n*  essential part of this License. No use of any Covered Software is   *\n*  authorized under this License except under this disclaimer.         *\n*                                                                      *\n************************************************************************\n\n************************************************************************\n*                                                                      *\n*  7. Limitation of Liability                                          *\n*  --------------------------                                          *\n*                                                                      *\n*  Under no circumstances and under no legal theory, whether tort      *\n*  (including negligence), contract, or otherwise, shall any           *\n*  Contributor, or anyone who distributes Covered Software as          *\n*  permitted above, be liable to You for any direct, indirect,         *\n*  special, incidental, or consequential damages of any character      *\n*  including, without limitation, damages for lost profits, loss of    *\n*  goodwill, work stoppage, computer failure or malfunction, or any    *\n*  and all other commercial damages or losses, even if such party      *\n*  shall have been informed of the possibility of such damages. This   *\n*  limitation of liability shall not apply to liability for death or   *\n*  personal injury resulting from such party's negligence to the       *\n*  extent applicable law prohibits such limitation. Some               *\n*  jurisdictions do not allow the exclusion or limitation of           *\n*  incidental or consequential damages, so this exclusion and          *\n*  limitation may not apply to You.                                    *\n*                                                                      *\n************************************************************************\n\n8. Litigation\n-------------\n\nAny litigation relating to this License may be brought only in the\ncourts of a jurisdiction where the defendant maintains its principal\nplace of business and such litigation shall be governed by laws of that\njurisdiction, without reference to its conflict-of-law provisions.\nNothing in this Section shall prevent a party's ability to bring\ncross-claims or counter-claims.\n\n9. Miscellaneous\n----------------\n\nThis License represents the complete agreement concerning the subject\nmatter hereof. If any provision of this License is held to be\nunenforceable, such provision shall be reformed only to the extent\nnecessary to make it enforceable. Any law or regulation which provides\nthat the language of a contract shall be construed against the drafter\nshall not be used to construe this License against a Contributor.\n\n10. Versions of the License\n---------------------------\n\n10.1. New Versions\n\nMozilla Foundation is the license steward. Except as provided in Section\n10.3, no one other than the license steward has the right to modify or\npublish new versions of this License. Each version will be given a\ndistinguishing version number.\n\n10.2. Effect of New Versions\n\nYou may distribute the Covered Software under the terms of the version\nof the License under which You originally received the Covered Software,\nor under the terms of any subsequent version published by the license\nsteward.\n\n10.3. Modified Versions\n\nIf you create software not governed by this License, and you want to\ncreate a new license for such software, you may create and use a\nmodified version of this License if you rename the license and remove\nany references to the name of the license steward (except to note that\nsuch modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary\nLicenses\n\nIf You choose to distribute Source Code Form that is Incompatible With\nSecondary Licenses under the terms of this version of the License, the\nnotice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n-------------------------------------------\n\n  This Source Code Form is subject to the terms of the Mozilla Public\n  License, v. 2.0. If a copy of the MPL was not distributed with this\n  file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular\nfile, then You may include the notice in a location (such as a LICENSE\nfile in a relevant directory) where a recipient would be likely to look\nfor such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - \"Incompatible With Secondary Licenses\" Notice\n---------------------------------------------------------\n\n  This Source Code Form is \"Incompatible With Secondary Licenses\", as\n  defined by the Mozilla Public License, v. 2.0.\n"
  },
  {
    "path": "README.md",
    "content": "# Trikl\n\n\"Terminal React for Clojure\" => Trikl\n\n[![CircleCI](https://circleci.com/gh/lambdaisland/trikl.svg?style=svg)](https://circleci.com/gh/lambdaisland/trikl) [![cljdoc badge](https://cljdoc.org/badge/lambdaisland/trikl)](https://cljdoc.org/d/lambdaisland/trikl) [![Clojars Project](https://img.shields.io/clojars/v/lambdaisland/trikl.svg)](https://clojars.org/lambdaisland/trikl)\n\nTrikl 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.\n\nThe 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.\n\n[Regal](https://lambdaisland.github.io/land-of-regal/) is a spin-off library created to support this work.\n\n----\n\nTrikl lets you write terminal applications in a way that's similar to\nReact/Reagent. It's main intended use case is for hobbyist/indy games.\n\nWith Trikl you use (a dialect of) Hiccup to create your Terminal UI. As your\napplication state changes, Trikl re-renders the UI, diffs the output with what's\ncurrently on the screen, and sends the necessary commands to the terminal to\nbring it up to date.\n\nThis is still very much work in progress and subject to change.\n\n## Example\n\nYou can use Trikl directly by hooking it up to STDIN/STDOUT, or you can use it\nas a telnet server. The telnet server is great because it makes it easy to try\nstuff out from the REPL.\n\nFor instance you can do something like this:\n\n``` clojure\n(require '[trikl.core :as t])\n\n;; store clients so we can poke at them from the REPL\n(def clients (atom []))\n\n;; Start the server on port 1357, as an accept handler just store the client in\n;; the atom.\n(def stop-server (t/start-server #(swap! clients conj %) 1357))\n\n;; in a terminal: telnet localhost 1357\n\n#_(stop-server) ;; disconnect all clients and stop listening for connections\n\n;; Render hiccup! Re-run this as often as you like, only changes are sent to the client.\n(t/render (last @clients) #_(t/stdio-client)\n          [:box {:x 10 :y 5 :width 20 :height 10 :styles {:bg [50 50 200]}}\n           [:box {:x 1 :y 1 :width 18 :height 8 :styles {:bg [200 50 0]}}\n            [:box {:x 3 :y 1}\n             [:span {:styles {:fg [30 30 150]}} \"hello\\n\"]\n             [:span {:styles {:fg [100 250 100]}} \"  world\"]]]])\n\n;; Listen for input events\n(t/add-listener (last @clients)\n                ::my-listener\n                (fn [event]\n                  (prn event)))\n```\n\nUse `stdio-client` to hook up the terminal the process is running in.\n\nResult:\n\n![](example.png)\n\n## Things you can render\n\nYou can render the following things\n\n### String\n\nA string is simply written to to the screen as-is. Note that strings are limited\nto their current bounding box, so long strings don't wrap. You can use newlines\nto use multiple lines.\n\n``` clojure\n(t/render client \"hello, world!\\nWhat a lovely day we're having\")\n```\n\n### Sequence\n\nA seq (so the result of calling `list`, `map`, `for`, etc. Not vectors!) will\nsimply render each item in the list.\n\n``` clojure\n(t/render client (repeat 20 \"la\"))\n```\n\n### Elements\n\nElements are vectors, they contain the element type (first item in the vector),\na map of attributes (optional, second element in the vector), and any remaining\nchild elements.\n\nTrikl currently knows of the following elements.\n\n#### :span\n\nA `:span` can be used to add styling, i.e. foreground and background colors. Colors\nare specified using RGB (red-green-blue) values. Each value can go from 0 to\n255.\n\n``` clojure\n(t/render client [:span {:styles {:fg [100 200 0] :bg [50 50 200]}} \"Oh my!\"])\n```\n\n#### :box\n\nThe `:box` element changes the current bounding box. You give it a position with\n`:x` and `:y`, and a size with `:width` and `:height`, and anything inside the\nbox will be contained within those coordinates.\n\nIf you don't supply `:x` or `:y` it will default to the top-left corner of its\nsurrounding bounding box. If you omit `:width` and `:height` it will take up as\nmuch space as it has available.\n\nYou can also supply `:styles` to the box, as with `:span`. Setting a `:bg` on\nthe box will color the whole box.\n\nNote for instance that this example truncates the string to \"Hello,\", because it\ndoesn't fit in the box.\n\n``` clojure\n(t/render client [:box {:x 20 :y 10, :width 7, :height 3} \"Hello, world!\"])\n```\n\n#### :line-box\n\nA `:line-box` is like a box, but it gets a fancy border. This border is drawn on\nthe inside of the box, so you lose two rows and two columns of space to put\nstuff inside, but it looks pretty nice!\n\nBy default it uses lines with rounded corners, but you can use any border\ndecoration you like by supplying a `:lines` attribute. This can be a string or\nsequence containing the characters to use, starting from the top left corner and\nmoving clockwise. The default value for `:lines` is ` \"╭─╮│╯─╰│\"`\n\n``` clojure\n(t/render client [:line-box {:x 20 :y 10, :width 10, :height 3} \"Hello, world!\"])\n```\n\n#### :cols and :rows\n\nThe `:cols` and `:rows` elements will split their children into columns and rows\nrespectively. If any of the children have a `:width` or `:height` that will be\nrespected. Any remaining space is distributed equally among the ones that don't\nhave a fixed `:width`/`:height` already.\n\nSo you could divide the screen in four equally sized sections using:\n\n``` clojure\n(t/render (last @clients)\n          [:cols\n           [:rows\n            [:line-box \"1\"]\n            [:line-box \"2\"]]\n           [:rows\n            [:line-box \"3\"]\n            [:line-box \"4\"]]])\n\n```\n\n#### Custom Components\n\nYou can define custom components by creating a two-argument function, attributes\nand children, and using the function as the first element in the vector. You can\nreturn any of the above renderable things from the function.\n\n``` clojure\n(defn app [attrs children]\n  [:rows\n   [:line-box \"Hiiiiii\"]\n   [:line-box {:height 15 :styles {:bg [100 50 50]}}]])\n\n(t/render client [app])\n```\n\n## App state\n\nIf you keep your app state in an atom, then you can use `render-watch!` to\nautomatically re-render when the atom changes.\n\n``` clojure\n(def app-state (atom {:pos [10 10]}))\n\n(t/render-watch! client\n                 (fn [{[x y] :pos} _]\n                   [:box {:x x :y y} \"X\"])\n                 app-state)\n\n(swap! app-state update-in [:pos 0] inc)\n(swap! app-state update-in [:pos 1] inc)\n\n(t/unwatch! app-state)\n```\n\n## Querying the screen size and bounding box\n\nDuring rendering you can use `t/*screen-size*` and `t/*bounding-box*` to find\nthe current dimensions you are working in. There's also a `(box-size)` helpers\nwhich only returns the `[width height]` of the bounding box, rather than `[x y\nwidth height]`. This should greatly alleviate the need to write your own drawing\nfunctions, as you can now do everything with custom elements and a combination\nof `[:span ...]` and `[:box ...]`. The main reason to write custom drawing\nfunctions would be for performance, when what you are drawing does not easily\nfit in the span/box paradigm. If you find yourself creating a span per character\nthen maybe a custom drawing function makes sense.\n\n## Custom drawing functions\n\nTo implement custom elements, extend the `t/draw` multimethod. The method takes\ntwo arguments, the element (the vector), and a \"virtual screen\". Your method\nneeds to return an updated version of the virtual screen.\n\nThe main reasons to do this are because this gives you access to the current\nscreen size (bounding box), and for performance reasons.\n\nThe `VirtualScreen` has a \":charels\" key (character elements, analogues to\npixels), This is a vector of rows, each row is a vector of \"charels\", which have\na `:char`, `:bg`, `:fg` key. Make sure the `:char` is set to an actual `char`,\nnot to a String.\n\nAfter drawing the virtual screen is diffed with the previous virtual screen to\nfigure out the minimum commands to send to the terminal to update it.\n\n``` clojure\n(defmethod t/draw :x-marks-the-spot [element screen]\n  (assoc-in screen [:charels 5 5 :char] \\X))\n```\n\nThings to watch out for:\n\n- Normalize your element with `t/split-el`, this always returns a three element\n  vector with element type, attribute map, children sequence.\n\n- Stick to your bounding box! You probably want to start with this\n\n``` clojure\n  (let [[_ attrs children] (split-el element)\n        [x y width height] (apply-bounding-box attrs screen)]\n    ,,,)\n```\n\nYou should not touch anything outside `[(range x (+ x width)) (range y (+ y height))]`\n\n- If your element takes `:styles`, then use `push-styles` and `pop-styles` to\ncorrectly restore the styles from a surrounding context.\n\n\n## True Color\n\nIn theory ANSI compatible terminals are able to render 24 bit colors (16 million\nshades), but in practice they don't always do.\n\nYou can try this snippet, if you see nice continuous gradients from blue to\npurple then you're all set.\n\n``` clojure\n(defn app [_]\n  [:box\n   (for [y (range 50)]\n     [:span\n      (for [x (range 80)]\n        [:span {:styles {:bg [(* x 2) (* y 2) (+ x (* 4 y))]}} \" \"])\n      \"\\n\"])])\n```\n\niTerm 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`\n\n``` conf\nset -g default-terminal \"xterm-256color\"\nset-option -ga terminal-overrides \",xterm-256color:Tc\"\n```\n\n## Using netcat\n\nNot all systems come with telnet installed, notably recent versions of Mac OS X\nhave 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.\n\nYou can `brew install telnet`, or in a pinch you can use `stty` to configure\nyour terminal to not echo input, and to enable \"raw\" (direct, unbuffered) mode.\n\nMake sure to invoke `stty` and `nc` as a single command like this:\n\n```\nstty -echo -icanon && nc localhost 1357\n```\n\nTo undo the changes to your terminal do\n\n```\nstty +echo +icanon\n```\n\n## Graal compatibility\n\nTrikl contains enough type hints to prevent Clojure's type reflection, which\nmakes it compatible with GraalVM. This means you can compile your project to\nnative binaries that boot instantly. Great for tooling!\n\n## License\n\nCopyright &copy; 2018 Arne Brasseur\n\nLicensed under the term of the Mozilla Public License 2.0, see LICENSE.\n"
  },
  {
    "path": "bin/kaocha",
    "content": "#!/bin/bash\nclojure -A:test -m kaocha.runner \"$@\"\n"
  },
  {
    "path": "deps.edn",
    "content": "{:paths [\"src\" \"test\" \"resources\"]\n :deps  {org.clojure/clojure {:mvn/version \"1.10.0-RC4\"}}\n\n :aliases\n {:dev\n  {}\n\n  :test\n  {:extra-deps {lambdaisland/kaocha {:mvn/version \"0.0-305\"}\n                lambdaisland/ansi   {:mvn/version \"RELEASE\"}}}}}\n"
  },
  {
    "path": "notes.org",
    "content": "* app ideas\n** roguelike / rpg\n** \"graphics editor\" / level editor\n** interactive version upgrades\n** interactive test runner\n** admin UI for app\n"
  },
  {
    "path": "src/trikl/core.clj",
    "content": "(ns trikl.core\n  (:require [clojure.java.io :as io]\n            [clojure.string :as str]\n            [clojure.java.shell :as shell]\n            [trikl.telnet :as telnet])\n  (:import clojure.lang.PersistentVector\n           java.util.Iterator\n           java.lang.ProcessBuilder$Redirect\n           sun.misc.Signal\n           sun.misc.SignalHandler\n           [java.io InputStream OutputStream IOException]\n           [java.net ServerSocket Socket]\n           [java.nio.charset CharsetDecoder Charset CodingErrorAction]\n           [java.nio ByteBuffer CharBuffer]\n           java.io.StringWriter))\n\n(set! *warn-on-reflection* true)\n(set! *unchecked-math* true #_:warn-on-boxed)\n\n(Thread/setDefaultUncaughtExceptionHandler\n (reify Thread$UncaughtExceptionHandler\n   (uncaughtException [_ thread ex]\n     (println ex \"Uncaught exception on\" (.getName thread)))))\n\n(def ESC \\u001b)\n(def CSI_PATTERN #\"\\x1b\\[[\\x30-x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]\")\n\n(defrecord Charel [char fg bg])\n(defrecord VirtualScreen [pos size bounding-box styles stack ^PersistentVector charels])\n\n(def BLANK (map->Charel {:char \\space}))\n\n;; Can be accessed by client rendering code\n(def ^:dynamic *screen-size* nil)\n(def ^:dynamic *bounding-box* nil)\n\n(defn box-size []\n  (when-let [[x y w h] *bounding-box*]\n    [w h]))\n\n(defn csi-fg [color]\n  (if (nil? color)\n    (str ESC \"[39m\")\n    (let [[r g b] color]\n      (str ESC \"[38;2;\" r \";\" g \";\" b \"m\"))))\n\n(defn csi-bg [color]\n  (if (nil? color)\n    (str ESC \"[49m\")\n    (let [[r g b] color]\n      (str ESC \"[48;2;\" r \";\" g \";\" b \"m\"))))\n\n(defn csi-move [[^long col ^long row]]\n  (str ESC \"[\" (inc row) \";\" (inc col) \"H\"))\n\n(defn assoc-col [screen col]\n  (assoc-in screen [:pos 0] col))\n\n(defn update-col [screen f & args]\n  (apply update-in screen [:pos 0] f args))\n\n(defn assoc-row [screen row]\n  (assoc-in screen [:pos 1] row))\n\n(defn update-row [screen f & args]\n  (apply update-in screen [:pos 1] f args))\n\n(defn col ^long [screen]\n  (get-in screen [:pos 0]))\n\n(defn row ^long [screen]\n  (get-in screen [:pos 1]))\n\n(defn push-styles [screen styles]\n  (-> screen\n      (update :stack conj (:styles screen))\n      (update :styles merge styles)))\n\n(defn pop-styles [screen]\n  (-> screen\n      (assoc :styles (last (:stack screen)))\n      (update :stack pop)))\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(defn split-el [el]\n  (when (vector? el)\n    (let [[tag & rst] el]\n      (let [fst (first rst)]\n        (if (map? fst)\n          [tag fst (rest rst)]\n          [tag {} (or rst ())])))))\n\n(defmulti draw (fn [element screen]\n                 (if (vector? element)\n                   (if (keyword? (first element))\n                     (first element)\n                     (type (first element)))\n                   (type element))))\n\n(defn draw-line [line screen]\n  (let [[x y] (:pos screen)\n        [^long min-x ^long min-y ^long max-x ^long max-y] (:bounding-box screen)\n        line (remove #{\\return} ;; don't want no carriage returns\n                     (subs line 0 (max 0 (min (count line) (- max-x x)))))]\n    (reduce (fn [screen char]\n              (-> screen\n                  (update-in [:charels (row screen) (col screen)]\n                             #(-> %\n                                  (assoc :char char)\n                                  (merge (:styles screen))))\n                  (update-col inc)))\n            screen\n            line)))\n\n(defmethod draw nil [_ screen]\n  screen)\n\n(defmethod draw java.util.List [els screen]\n  (reduce #(draw %2 %1) screen els))\n\n(defmethod draw clojure.lang.Fn [el screen]\n  (let [[f attrs children] (split-el el)]\n    (draw (f attrs children) screen)))\n\n(defmethod draw clojure.lang.Var [el screen]\n  (let [[f attrs children] (split-el el)]\n    (draw (f attrs children) screen)))\n\n(defn apply-bounding-box [attrs screen]\n  (let [[^long vx ^long vy ^long vw ^long vh] (:bounding-box screen)\n        {:keys [^long x ^long y ^long width ^long height styles]\n         :or {x 0 y 0 width vw height vh}} attrs\n        x (max 0 (min (+ x vx) (+ vx vw)))\n        y (max 0 (min (+ y vy) (+ vy vh)))\n        width (min width (- vw x))\n        height (min height (- vh y))]\n    [x y width height]))\n\n(defmethod draw :box [el screen]\n  (let [[_ attrs children] (split-el el)\n        [x y width height :as bbox] (apply-bounding-box attrs screen)\n        styles (:styles attrs)\n        coords (for [col (range x (+ x width))\n                     row (range y (+ y height))]\n                 [row col])\n        screen' (-> screen\n                    (push-styles styles)\n                    (assoc :pos [x y]\n                           :bounding-box [x y (+ x width) (+ y height)])\n                    (update :charels\n                            (fn [charels]\n                              (reduce #(update-in %1 %2 merge styles)\n                                      charels\n                                      coords))))]\n    (binding [*bounding-box* bbox]\n      (-> (reduce #(draw %2 %1) screen' children)\n          (assoc :pos (:pos screen)\n                 :bounding-box (:bounding-box screen))\n          (pop-styles)))))\n\n(defmethod draw :span [el screen]\n  (let [[_ attrs children] (split-el el)\n        {:keys [styles]} attrs\n        screen' (push-styles screen styles)]\n    (-> (reduce #(draw %2 %1) screen' children)\n        (pop-styles))))\n\n(defmethod draw String [s screen]\n  (let [[x y] (:pos screen)\n        [^long min-x ^long min-y ^long max-x ^long max-y]\n        (:bounding-box screen)]\n    (let [lines (str/split s #\"(?<=\\n)\")]\n      (reduce (fn [screen line]\n                (if (>= (row screen) max-y)\n                  (reduced screen)\n                  (let [nl? (= \\newline (last line))\n                        line (cond->> line nl? butlast nl? (apply str))]\n                    (cond-> (draw-line line screen)\n                      nl? (assoc-col min-x)\n                      nl? (update-row inc)))))\n              screen\n              lines))))\n\n(defmethod draw Character [char screen]\n  (let [[x y] (:pos screen)\n        [^long min-x ^long min-y ^long max-x ^long max-y]\n        (:bounding-box screen)]\n    (if (and (<= min-x x max-x) (<= min-y y max-y))\n      (-> screen\n          (update-in [:charels (row screen) (col screen)]\n                     #(-> %\n                          (assoc :char char)\n                          (merge (:styles screen))))\n          (update-col inc))\n      screen)))\n\n(defmethod draw :line-box [el screen]\n  (let [[_ attrs children] (split-el el)\n        [x y width height :as bbox] (apply-bounding-box attrs screen)\n        [tl t tr r br b bl l] (:lines attrs \"╭─╮│╯─╰│\")]\n    (binding [*bounding-box* [(inc x) (inc y) (dec width) (dec height)]]\n      (draw [:box attrs\n             tl (repeat (- width 2) t) tr \"\\n\"\n             (repeat (- height 2)\n                     (str l\n                          (apply str (repeat (- width 2) \\space))\n                          r\n                          \"\\n\"))\n             bl (repeat (- width 2) b) br \"\\n\"\n             [:box (assoc attrs :x 1 :y 1 :width (- width 2) :height (- height 2))\n              children]]\n            screen))))\n\n(defmethod draw :cols [el screen]\n  (let [[_ attrs children] (split-el el)\n        [x y width height :as bbox] (apply-bounding-box attrs screen)\n        ratios             (:ratios attrs (repeat (count children) 1))\n        widths             (map #(:width (second (split-el %))) children)\n        remaining          (- width (apply + (remove nil? widths)))\n        total              (apply + (keep (fn [[w r]]\n                                            (when (nil? w) r))\n                                          (map vector widths ratios)))]\n    (assert (= (count children) (count ratios) (count widths)))\n    (binding [*bounding-box* bbox]\n      (let [children (reduce (fn [res [c w r]]\n                               (let [x  (apply + (map #(get-in % [1 :width]) res))\n                                     ww (or w (Math/round (double (/ (* remaining r) total))))\n                                     ww (if (= (count res) (dec (count children)))\n                                          (- width x)\n                                          ww)]\n                                 (conj res\n                                       (if w\n                                         (-> c\n                                             (assoc-in [1 :x] x)\n                                             (assoc-in [1 :width] ww))\n                                         [:box {:x x\n                                                :width ww}\n                                          c]))))\n                             []\n                             (map vector children widths ratios))]\n        (->> children\n             (reduce (fn [s ch] (draw ch s)) screen))))))\n\n(defmethod draw :rows [el screen]\n  (let [[_ attrs children]                         (split-el el)\n        [^long x ^long y ^long width ^long height :as bbox] (apply-bounding-box attrs screen)\n        ratios                                     (:ratios attrs (repeat (count children) 1))\n        heights                                    (map #(:height (second (split-el %))) children)\n        ^long remaining                            (- height (apply + (remove nil? heights)))\n        ^long total                                (apply + (keep (fn [[w r]]\n                                                                    (when (nil? w) r))\n                                                                  (map vector heights ratios)))]\n    (assert (= (count children) (count ratios) (count heights)))\n    (binding [*bounding-box* bbox]\n      (let [children (reduce (fn [res [c w r]]\n                               (let [y  (apply + (map #(get-in % [1 :height]) res))\n                                     ww (or w (Math/round (double (/ (* remaining r) total))))\n                                     ww (if (= (count res) (dec (count children)))\n                                          (- height y)\n                                          ww)]\n                                 (conj res\n                                       (if w\n                                         (-> c\n                                             (assoc-in [1 :y] y)\n                                             (assoc-in [1 :height] ww))\n                                         [:box {:y      y\n                                                :height ww}\n                                          c]))))\n                             []\n                             (map vector children heights ratios))]\n        (->> children\n             (reduce (fn [s ch] (draw ch s)) screen))))))\n\n(defn ^VirtualScreen virtual-screen [rows cols]\n  (map->VirtualScreen {:pos [0 0]\n                       :size [cols rows]\n                       :bounding-box [0 0 cols rows]\n                       :styles {:fg nil :bg nil}\n                       :stack []\n                       :charels (vec (repeat rows (vec (repeat cols BLANK))))}))\n\n(def NULL_ITERATOR\n  (reify java.util.Iterator\n    (hasNext [_] false)\n    (next [_] nil)))\n\n(defn diff-row [^StringBuilder sb row-idx styles ^PersistentVector old ^PersistentVector new]\n  (let [^Iterator old-it (if old (.iterator old) NULL_ITERATOR)\n        ^Iterator new-it (if new (.iterator new) NULL_ITERATOR)]\n    (loop [styles  styles\n           col-idx 0\n           streak? false\n           old-ch  (and (.hasNext old-it) (.next old-it))\n           new-ch  (and (.hasNext new-it) (.next new-it))]\n      (let [old-next? (.hasNext old-it)\n            new-next? (.hasNext new-it)]\n        (if (= old-ch new-ch)\n          (if new-next?\n            (recur styles\n                   (inc col-idx)\n                   false\n                   (when old-next? (.next old-it))\n                   (when new-next? (.next new-it)))\n            styles)\n          (let [{:keys [char fg bg] :or {char \\space}} new-ch\n                fg? (not= fg (:fg styles))\n                bg? (not= bg (:bg styles))]\n            (when-not streak?\n              (.append sb (csi-move [col-idx row-idx])))\n            (when fg? (.append sb (csi-fg fg)))\n            (when bg? (.append sb (csi-bg bg)))\n            (.append sb char)\n            (let [new-styles (if (or fg? bg?) new-ch styles)]\n              (if new-next?\n                (recur new-styles\n                       (inc col-idx)\n                       true\n                       (when old-next? (.next old-it))\n                       (when new-next? (.next new-it)))\n                new-styles))))))))\n\n(defn diff-screen [sb ^VirtualScreen old ^VirtualScreen new]\n  (let [^PersistentVector old-charels (:charels old)\n        ^PersistentVector new-charels (:charels new)\n        ^Iterator old-row-it (.iterator old-charels)\n        ^Iterator new-row-it (.iterator new-charels)]\n    (loop [styles  (:styles old)\n           row-idx 0\n           old-row (and (.hasNext old-row-it) (.next old-row-it))\n           new-row (and (.hasNext new-row-it) (.next new-row-it))]\n      (let [old-next? (.hasNext old-row-it)\n            new-next? (.hasNext new-row-it)]\n        (let [styles (diff-row sb row-idx styles old-row new-row)]\n          (if new-next?\n            (recur styles\n                   (inc row-idx)\n                   (when old-next? (.next old-row-it))\n                   (when new-next? (.next new-row-it)))\n            (assoc new :styles styles)))))))\n\n(defn parse-screen-size [csi]\n  (when csi\n    (when-let [[_ row col] (re-find #\"(\\d+);(\\d+)R\" csi)]\n      [(Integer/parseInt row) (Integer/parseInt col)])))\n\n(defn ^CharsetDecoder charset-decoder\n  ([]\n   (charset-decoder \"UTF-8\"))\n  ([encoding]\n   (-> (Charset/forName encoding)\n       .newDecoder\n       (.onMalformedInput CodingErrorAction/IGNORE)\n       (.onUnmappableCharacter CodingErrorAction/IGNORE))))\n\n(defn char-in-range? [min ch max]\n  (<= (long min) (long ch) (long max)))\n\n(defn input-consumer-loop [^InputStream in handler]\n  (let [buf-size 8192\n        buffer   (byte-array buf-size)\n        buffer'  (byte-array buf-size)\n        decoder  (charset-decoder)]\n    (try\n      (loop [state {}]\n        #_(prn state)\n        (let [{:keys [^CharBuffer char-buf]} state]\n          (if (or (nil? char-buf) (not (.hasRemaining char-buf)))\n            ;; Fill byte buffer, pull out telnet codes, decode to char buffer\n            (let [end (.read in buffer 0 buf-size)\n\n                  {:keys [dest-end commands]}\n                  (telnet/filter-commands {:src buffer :dest buffer' :end end})\n\n                  ^CharacterBuffer char-buf (.decode decoder (ByteBuffer/wrap buffer' 0 dest-end))]\n              (run! #(handler {:type :telnet :command %}) commands)\n              (recur {:char-buf char-buf}))\n\n            ;; handle next character\n            (let [ch (char (.get char-buf))\n                  ansi-state (:ansi-state state)]\n              (cond\n                ;; The ESC [ is followed by any number (including none) of \"parameter bytes\" in\n                ;; the range 0x30–0x3F (ASCII 0–9:;<=>?), then by any number of \"intermediate\n                ;; bytes\" in the range 0x20–0x2F (ASCII space and !\"#$%&'()*+,-./), then finally\n                ;; by a single \"final byte\" in the range 0x40–0x7E (ASCII @A–Z[\\]^_`a–z{|}~).\n                (= ch (char ESC))\n                (if (.hasRemaining char-buf)\n                  (recur (assoc state\n                                :ansi-state :init\n                                :ansi-command []))\n                  (do\n                    (handler {:type :input :char ch})\n                    (recur state)))\n\n                (and (= :init ansi-state) (= \\[ ch))\n                (recur (-> state\n                           (assoc :ansi-state :param-bytes)\n                           (update :ansi-command conj ch)))\n\n                (and (= :init ansi-state) (= \\O ch))\n                (recur (-> (assoc state :ansi-state :fn-key)\n                           (update :ansi-command conj ch)))\n\n                (and (= :param-bytes ansi-state) (char-in-range? \\0 ch \\?))\n                (recur (update state :ansi-command conj ch))\n\n                (and (#{:param-bytes :interm-bytes} ansi-state) (char-in-range? \\space ch \\/))\n                (recur (-> (assoc state :ansi-state :interm-bytes)\n                           (update :ansi-command conj ch)))\n\n                (and (#{:param-bytes :interm-bytes :fn-key} ansi-state) (char-in-range? \\@ ch \\~))\n                (do\n                  (handler {:type :ansi :command (String. (chars (into-array Character/TYPE (conj (:ansi-command state) ch))))})\n                  (recur (dissoc state :ansi-state :ansi-command)))\n\n                :else\n                (do\n                  (handler {:type :input :char ch})\n                  (recur (dissoc state :ansi-state :ansi-command))))))))\n      (catch IOException e\n        (println \"Input loop closed\")\n        :done)\n      (catch Exception e\n        (println \"Error during input loop\" e)))))\n\n(def ansi-key-commands\n  {\"\" :esc\n   \"[A\" :up\n   \"[B\" :down\n   \"[C\" :right\n   \"[D\" :left\n   \"[H\" :home\n   \"[E\" :end\n   \"[2~\" :insert\n   \"[3~\" :delete\n   \"OP\" :f1\n   \"OQ\" :f2\n   \"OR\" :f3\n   \"OS\" :f4\n   \"[15~\" :f5\n   \"[17~\" :f6\n   \"[18~\" :f7\n   \"[19~\" :f8\n   \"[20~\" :f9\n   \"[21~\" :f10\n   \"[23~\" :f11\n   \"[24~\" :f12})\n\n(defn char->key [ch]\n  (cond\n    (= 27 (long ch))\n    :escape\n\n    (= 32 (long ch))\n    :space\n\n    (char-in-range? 0 ch 31)\n    (keyword (str \"ctrl-\" (char (+ (long ch) 64))))\n\n    (char-in-range? 33 ch 126)\n    (keyword (str ch))\n\n    (= ch \\u007F)\n    :backspace\n\n    :else\n    nil))\n\n(defn listener-handler [{:keys [listeners]}]\n  (fn [{:keys [type command char] :as msg}]\n    #_(prn msg)\n    (let [emit (fn [message]\n                 #_(prn message)\n                 (let [m (assoc message :time (System/currentTimeMillis))]\n                   (run! (fn [l] (l m))\n                         (vals @listeners))))]\n      (case type\n        :telnet\n        (when (= (take 3 command) [:IAC :SUBNEGOTIATION :NAWS])\n          (let [raw-msg (:telnet/raw (meta command))\n                [_ _ _ _ cols _ rows] raw-msg]\n            (when (and (int? cols) (int? rows))\n              (emit {:type :screen-size\n                     :screen-size [rows cols]}))))\n\n        :ansi\n        (if-let [screen-size (parse-screen-size command)]\n          (emit {:type :screen-size\n                 :screen-size screen-size})\n          (if-let [key (get ansi-key-commands command)]\n            (emit {:type :input\n                   :key key})))\n\n        :input\n        (emit (assoc msg :key (char->key (:char msg))))))))\n\n(defn start-input-loop [{:keys [^InputStream in] :as client}]\n  (assoc client\n         :input-loop\n         (future\n           (loop [result (input-consumer-loop in (listener-handler client))]\n             (when-not (= :done result)\n               (recur (input-consumer-loop in (listener-handler client))))))))\n\n(defn request-screen-size [^OutputStream out]\n  (let [csi (fn [& args]\n              (let [^String code (apply str ESC \"[\" args)]\n                (.write out (.getBytes code))))\n        buffer (byte-array 1024)]\n    (csi \"s\") ;; save cursor position\n    (csi \"5000;5000H\")\n    (csi \"6n\")\n    (csi \"u\")))\n\n(def CSI-ALTERNATE-SCREEN (str ESC \"[?1049h\"))\n(def CSI-REGULAR-SCREEN   (str ESC \"[?1049l\"))\n(def CSI-CLEAR-SCREEN     (str ESC \"[2J\"))\n(def CSI-UPPER-LEFT       (str ESC \"[H\"))\n(def CSI-RESET-STYLES     (str ESC \"[m\"))\n(def CSI-SHOW-CURSOR      (str ESC \"[?25h\"))\n(def CSI-HIDE-CURSOR      (str ESC \"[?25l\"))\n\n(defn start-client [{:keys [^OutputStream out] :as client}]\n  (when (:socket client)\n    (telnet/prep-telnet out))\n  (.write out (.getBytes (str CSI-ALTERNATE-SCREEN\n                              CSI-CLEAR-SCREEN\n                              CSI-UPPER-LEFT\n                              CSI-RESET-STYLES\n                              CSI-HIDE-CURSOR)))\n  (request-screen-size out))\n\n(defn stop-client [{:keys [^OutputStream out ^Socket socket] :as client}]\n  (try\n    (.write out (.getBytes (str CSI-REGULAR-SCREEN\n                                CSI-RESET-STYLES\n                                CSI-SHOW-CURSOR)))\n    (when socket\n      (.close socket))\n    (catch IOException _)))\n\n(defn add-shutdown-hook [^clojure.lang.IFn f]\n  (.addShutdownHook (java.lang.Runtime/getRuntime)\n                    (Thread. f)))\n\n(defn make-client [in out & [socket]]\n  (let [size (atom nil)\n        client {:socket    socket\n                :in        in\n                :out       out\n                :size      size\n                :screen    (atom nil)\n                :listeners (atom {:resize (fn [e]\n                                            (when-let [s (:screen-size e)]\n                                              (reset! size (with-meta s {:trikl/message e}))))})}]\n    (start-client client)\n    (let [client (start-input-loop client)]\n      (add-shutdown-hook #(stop-client client))\n      client)))\n\n(defn ^\"[Ljava.lang.String;\" string-array [args]\n  (into-array String args))\n\n(defn exec-stty [& args]\n  (let [^Process\n        process (-> (ProcessBuilder. (string-array (cons \"stty\" args)))\n                    (.redirectInput (ProcessBuilder$Redirect/from (io/file \"/dev/tty\")))\n                    (.start))\n\n        ^StringWriter err (StringWriter.)]\n    {:exit (.waitFor process)\n     :err @(future\n             (with-open [^StringWriter err (StringWriter.)]\n               (io/copy (.getErrorStream process) err)\n               (.toString err)))\n     :out @(future\n             (with-open [^StringWriter out (StringWriter.)]\n               (io/copy (.getInputStream process) out)\n               (.toString out)))}))\n\n(defn stdio-client []\n  (exec-stty \"-echo\" \"-icanon\")\n  (let [client (make-client System/in System/out)]\n    (add-shutdown-hook (fn []\n                         (stop-client client)\n                         (exec-stty \"+echo\" \"+icanon\")))\n    (Signal/handle (Signal. \"WINCH\")\n                   (reify SignalHandler\n                     (^void handle [this ^Signal s]\n                      (let [out (:out (exec-stty \"size\"))]\n                        (when-let [[_ rows cols] (re-find #\"(\\d+) (\\d+)\" out)]\n                          (run! #(% (with-meta {:type :screen-size\n                                                :screen-size [(Long/parseLong rows) (Long/parseLong cols)]}\n                                      {:trikl/source :SIGWINCH}))\n                                (vals @(:listeners client))))))))\n    client))\n\n(defn add-listener [client key listener]\n  (swap! (:listeners client) assoc key listener))\n\n(defn remove-listener [client key]\n  (swap! (:listeners client) dissoc key))\n\n(defmacro time-info [expr desc]\n  `(let [start# (System/nanoTime)\n         ret# ~expr]\n     (println (str ~desc \": \" (/ (double (- (. System (nanoTime)) start#)) 1000000.0) \" ms\"))\n     ret#))\n\n(defn start-server\n  ([client-handler]\n   (start-server client-handler 1357))\n  ([client-handler port]\n   (let [^ServerSocket server (telnet/server-socket port)\n         clients (atom [])\n         stop!  (fn []\n                  (run! stop-client @clients)\n                  (try\n                    (.close server)\n                    (catch IOException _)))]\n     (future\n       (try\n         (loop [^Socket client-sock (telnet/accept-connection server)]\n           (let [client (make-client (.getInputStream client-sock)\n                                     (.getOutputStream client-sock)\n                                     client-sock)]\n             (swap! clients conj client)\n             (client-handler client)\n             (recur (telnet/accept-connection server))))\n         (catch IOException _\n           ;; socket closed\n           )\n         (catch Throwable t\n           (println \"Exception in server loop\" t))))\n     stop!)))\n\n(defn render [{:keys [^VirtualScreen screen ^OutputStream out size] :as client} element]\n  (let [size @size]\n    (assert (= 2 (count size)))\n    (binding [*screen-size*  size\n              *bounding-box* (into [0 0] size)]\n      (let [sb           (StringBuilder. ^String CSI-RESET-STYLES)\n            prev-screen  @screen\n            styles       (:styles prev-screen)\n            empty-screen (apply virtual-screen size)\n            prev-screen  (if (= (:size prev-screen) size)\n                           (or prev-screen empty-screen)\n                           (do\n                             (.append sb CSI-CLEAR-SCREEN)\n                             empty-screen))\n            next-screen  (draw element empty-screen)\n            new-screen   (diff-screen sb prev-screen next-screen)\n            commands     (str sb)]\n        (.write out (.getBytes commands))\n        (reset! screen new-screen))))\n  nil)\n\n(defn force-render [client element]\n  (reset! (:screen client) (apply virtual-screen @(:size client)))\n  (render client element))\n\n(defn render-watch! [client element state]\n  (render client [element @state])\n  (add-watch state ::render (fn [_ _ _ new-state]\n                              (render client [element new-state]))))\n\n(defn unwatch! [state]\n  (remove-watch state ::render))\n"
  },
  {
    "path": "src/trikl/demo/world.clj",
    "content": "(ns trikl.demo.world)\n\n(defn tile [kind glyph color]\n  {:tile/kind kind\n   :entity/glyph glyph\n   :entity/color color})\n\n(def tiles\n  {:floor (tile :floor \".\" :white)\n   :wall  (tile :wall \"#\"  :white)\n   :bound (tile :bound \"X\" :black)})\n\n(defn get-tile [tiles x y]\n  (get-in tiles [y x] (:bound tiles)))\n\n(defn random-tile []\n  (if (< (rand) 0.45)\n    (:wall tiles)\n    (:floor tiles)))\n\n(defn random-tiles [cols rows]\n  (vec (for [row (range rows)]\n         (vec (for [col (range cols)]\n                (assoc (random-tile) :entity/col col :entity/row row))))))\n\n(defn neighbors [tiles x y]\n  (let [sx (max 0 (dec x))\n        sy (max 0 (dec y))]\n    (for [px (range sx (+ sx 3))\n          py (range sy (+ sy 3))]\n      (get-in tiles [py px]))))\n\n(defn tile-count [ts kind]\n  (count (filter (comp #{kind} :tile/kind) ts)))\n\n(defn smooth [ts]\n  (vec\n   (for [row (range (count ts))]\n     (vec\n      (for [col (range (count (get ts row)))]\n        (let [tile (get-in ts [row col])\n              neighbors (neighbors ts col row)\n              wall-count (tile-count neighbors :wall)]\n          (if (> wall-count 4)\n            (merge tile (:wall tiles))\n            (merge tile (:floor tiles)))))))))\n\n(comment\n  (defn inspect [tiles]\n    (mapv (comp (partial apply str)\n                (partial map :entity/glyph)) tiles))\n\n  (def ts (random-tiles 160 50))\n  [\".##...##.#\"\n   \".#..###...\"\n   \"#.##..#.#.\"\n   \"#..###...#\"\n   \"....#...#.\"\n   \"#..#.#.##.\"\n   \"...##....#\"\n   \"#.#.#.##..\"\n   \".#.##....#\"\n   \"###..#.###\"]\n\n  (-> (random-tiles 10 10)\n      smooth\n      smooth\n      smooth\n      inspect)\n\n  (tile-count\n   (neighbors ts 2 1)\n   :floor))\n"
  },
  {
    "path": "src/trikl/demo.clj",
    "content": "(ns trikl.demo\n  (:require [trikl.core :as t]\n            [trikl.demo.world :as world]\n            [trikl.util :refer [reduce-for]]))\n\n(def clients (atom []))\n\n(def stop-server (t/start-server #(swap! clients conj %) 1357))\n\n(def stop-server (t/start-server #(t/render % [:cols\n                                               [:line-box { :styles {:bg [50 50 200]}}]\n                                               [:line-box { :styles {:bg [200 50 0]}}\n                                                [:box {:x 3 :y 1}\n                                                 [:span {:styles {:fg [30 30 150]}} \"hello\\n\"]\n                                                 [:span {:styles {:fg [100 250 100]}} \\x \"  world\"]]]]) 1357))\n\n(t/render (last @clients)\n          [:cols\n           [:line-box { :styles {:bg [50 50 200]}}]\n           [:line-box { :styles {:bg [200 50 0]}}\n            [:box {:x 3 :y 1}\n             [:span {:styles {:fg [30 30 150]}} \"hello\\n\"]\n             [:span {:styles {:fg [100 250 100]}} \\x \"  world\"]]]])\n\n#_(stop-server)\n\n(reset! (:size (last @clients)) [9 19])\n\n(t/stop-client (last @clients))\n\n(Math/cos Math/PI)\n;; => 1.0\n\n\n(Math/sin (* 2 Math/PI))\n\n(def stop? (atom false))\n(reset! stop? true)\n\n(future\n  (loop [step 0]\n    (let [steps 30\n          circle (* 2 Math/PI)\n          radius 8\n          x (Math/round (+ 44 (* 2 radius (Math/cos (/ (* circle step) steps)))))\n          y (Math/round (+ 8 (* radius (Math/sin (/ (* circle step) steps)))))]\n      (t/render (last @clients)\n                [:line-box {:x x :y y :width 12 :height 5 :styles {:bg [50 50 200]}}\n                 [:span {:x 5 :y 3} \"Hix!!!!\"]])\n      (Thread/sleep 80)\n      (when-not @stop?\n        (recur (if (< step (dec steps))\n                 (inc step)\n                 0))))))\n\n(last @clients)\n\n(t/render (last @clients)\n          [:cols\n           [:line-box { :styles {:bg [50 50 200]}}]\n           [:line-box { :styles {:bg [200 50 0]}}\n            [:box {:x 3 :y 1}\n             [:span {:styles {:fg [30 30 150]}} \"hello\\n\"]\n             [:span {:styles {:fg [100 250 100]}} \\x \"  world\"]]]])\n\n(t/render (last @clients)\n          [:box\n           [:line-box {:x 10 :y 6 :width 20 :height 12 :styles {:bg [50 50 200]}}]\n           [:line-box {:x 5 :y 2 :width 18 :height 8 :styles {:bg [200 50 0]}}\n            [:box {:x 3 :y 1}\n             [:span {:styles {:fg [30 30 150]}} \"hello\\n\"]\n             [:span {:styles {:fg [100 250 100]}} \\x \"  world\"]]]])\n\n(t/render (last @clients)\n          [:rows {:ratios [3 1]}\n           [:cols\n            [:line-box {:styles {:bg [0 0 200]}}]\n            [:line-box {:styles {:bg [50 50 200]}}]]\n           [:line-box {:styles {:bg [200 50 100]\n                                :fg [255 80 130]}}\n            [:box {:x 3 :y 1}\n             [:span {:styles {:fg [30 30 150]}} \"hello\\n\"]\n             [:span {:styles {:fg [100 250 100]}} \\x \"  world\"]]]])\n\n(t/add-listener (last @clients)\n                ::my-listener\n                (fn [event]\n                  (prn event)))\n\n\n(t/render (last @clients)\n          [:box\n           (for [x (range 79)\n                 y (range 53)\n                 :let [page 2]]\n             [:box {:x x :y y} (str (char (+ 255 (* page 79 53) x (* 53 y))))]\n             )\n           ]\n          )\n\n(defmethod t/draw :line-box [el screen]\n  (let [[_ attrs children] (t/split-el el)\n        [x y width height] (t/apply-bounding-box attrs screen)\n        [tl t tr r br b bl l] (:lines attrs \"╭─╮│╯─╰│\")]\n    (t/draw [:box attrs\n             tl (repeat (- width 2) t) tr \"\\n\"\n             (repeat (- height 2)\n                     (str l\n                          (apply str (repeat (- width 2) \\space))\n                          r\n                          \"\\n\")\n                     )\n             bl (repeat (- width 2) b) br \"\\n\"\n             [:box (assoc attrs :x 1 :y 1 :width (- width 2) :height (- height 2))\n              children]]\n            screen)))\n\n\" ━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞\n┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓\n┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿▀▁▂▃▄▅▆▇█\n╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟\"\n\n(apply str (map #(char %) (range 1100 1400)))\n\n(range 30 110)\n\n(char 100)\n\n(defn app [{:keys [offset]} _]\n  [:box\n   (for [y (range 50)]\n     [:span\n      (for [x (range 80)]\n        [:span {:styles {:bg [(+ offset (* x 2)) (+ offset (* y 2)) (+ offset x (* 4 y))]}} ({0 \"-\"\n                                                                                              5 \"\\\\\"\n                                                                                              10 \"|\"\n                                                                                              15 \"/\"\n                                                                                              20 \".\"\n                                                                                              25 \"*\"} offset)])\n      \"\\n\"])])\n\n\n(def state (atom {:size [300 300]\n                  :pos [150 150]\n\n                  :world (->> (world/random-tiles 300 300)\n                              (iterate world/smooth)\n                              (drop 3)\n                              first)\n\n                  }))\n\n(defmethod t/draw :world-map [el {:keys [charels] :as screen}]\n  (let [[el attrs] (t/split-el el)\n        [^long x ^long y ^long width ^long height] (t/apply-bounding-box attrs screen)\n        {:keys [world pos]} attrs\n        [x-center y-center] pos\n        x-offset (Math/round (double (- x-center (/ width 2))))\n        y-offset (Math/round (double (- y-center (/ height 2))))]\n\n    (assoc screen\n           :charels\n           (reduce-for charels [col (range width)\n                                row (range height)]\n             (assoc-in % [(+ y row) (+ x col) :char]\n                       (first (get-in world [(+ y row y-offset) (+ x col x-offset) :entity/glyph])))))))\n\n(first (get-in (world/random-tiles 3 3) [1 1 :entity/glyph]))\n\n(t/render (last @clients) (repeat 20 \"la\"))\n(t/render (last @clients)[:span {:styles {:fg [100 200 0] :bg [50 50 200]}} \"Oh my!\"])\n(t/render (last @clients)[:box {:x 20 :y 10, :width 7, :height 3} \"Hello, world!\"])\n\n(t/render (last @clients) (repeat 200 \"*\"))\n(t/render (last @clients) [:line-box {}])\n(t/time-info\n (t/render (last @clients) [:world-map (assoc @state :pos [152 148])])\n \"render\")\n(t/render-watch! (last @clients) (fn [attrs _] [:world-map attrs]) state)\n\n(t/render (last @clients)\n          [:cols\n           [:rows\n            [:line-box \"1\"]\n            [:line-box \"2\"]]\n           [:rows\n            [:line-box \"3\"]\n            [:line-box \"4\"]]])\n\n(t/split-el [:line-box ])\n\n(do\n  (swap! state update-in [:pos 0] dec)\n  nil\n  )\n\n\n(unwatch! state)\n\n(swap! state update :offset + 5)\n(defn app [attrs children]\n  [:rows\n   [:line-box \"Hiiiiii\"]\n   [:line-box {:height 15 :styles {:bg [100 50 50]}}]])\n\n(t/render (last @clients) [app])\n\n(def app-state (atom {:pos [10 10]}))\n\n(t/render-watch! (last @clients)\n                 (fn [{[x y] :pos} _]\n                   [:box {:x x :y y} \"X\"])\n                 app-state)\n\n(swap! app-state update-in [:pos 0] inc)\n(swap! app-state update-in [:pos 1] inc)\n\n(t/unwatch! app-state)\n"
  },
  {
    "path": "src/trikl/telnet.clj",
    "content": "(ns trikl.telnet\n  (:import java.net.ServerSocket\n           javax.net.ServerSocketFactory))\n\n(set! *warn-on-reflection* true)\n(set! *unchecked-math* true #_:warn-on-boxed)\n\n(defn ^ServerSocket server-socket [^long port]\n  (.createServerSocket (ServerSocketFactory/getDefault) port))\n\n(defn accept-connection [^ServerSocket server-socket]\n  (doto (.accept server-socket)\n    (.setTcpNoDelay true)))\n\n(def TELNET\n  {:SUBNEGOTIATION_END 0xf0\n   :SUBNEGOTIATION     0xfa\n   :WILL               0xfb\n   :WONT               0xfc\n   :DO                 0xfd\n   :DONT               0xfe\n   :IAC                0xff\n\n   :TRANSMIT_BINARY   0x00\n   :ECHO              0x01\n   :RECONNECTION      0x02\n   :SUPPRESS_GO_AHEAD 0x03\n   :NAWS              0x1f\n   :LINEMODE          0x22})\n\n(defn send-telnet-command [^java.net.SocketOutputStream out & args]\n  (->> args\n       (map #(TELNET % %))\n       (map unchecked-byte)\n       ^bytes (into-array Byte/TYPE)\n       (.write out)))\n\n(defn prep-telnet [out]\n  (send-telnet-command out\n                       :IAC :DO :LINEMODE\n                       :IAC :SUBNEGOTIATION :LINEMODE\n                       (byte 1) (byte 0)\n                       :IAC :SUBNEGOTIATION_END\n                       :IAC :WILL :ECHO\n                       :IAC :DO :NAWS))\n\n(defn filter-commands\n  \"Copy buffer `src` to `dest`, filtering out any Telnet protocol commands along\n  the way. These are returned separately.\"\n  [{:keys [^bytes src ^bytes dest ^long end]}]\n  #_(prn (take end (seq src)))\n  (let [IAC          (unchecked-byte (TELNET :IAC))\n        subneg-start (unchecked-byte (TELNET :SUBNEGOTIATION))\n        subneg-end   (unchecked-byte (TELNET :SUBNEGOTIATION_END))\n        subcmd-min   (unchecked-byte (TELNET :WILL))\n        subcmd-max   (unchecked-byte (TELNET :DONT))\n        cmd->kw      (into {} (map (juxt (comp unchecked-byte val) key)) TELNET)\n        byte->long   #(if (< % 0)\n                        (+ 255 (long %))\n                        (long %))]\n    (loop [state {:src-pos  0\n                  :dest-pos 0\n                  :commands []}]\n      (let [{:keys [src-pos dest-pos cmd commands]} state]\n        (if (= src-pos end)\n          {:src-pos  (- src-pos (count cmd)) ;; if a command is in flight then\n           ;; don't consume the last bytes of\n           ;; the buffer\n           :dest-end dest-pos\n           :commands commands}\n          (let [b                          (aget src src-pos)\n                {:keys [cmd cmd? subneg?]} state]\n            (cond\n              (and subneg? (not= subneg-end b))\n              (recur (-> state\n                         (update :src-pos inc)\n                         (update :cmd conj b)))\n\n              (= IAC b)\n              (recur (-> state\n                         (update :src-pos inc)\n                         (assoc :cmd? true\n                                :cmd [b])))\n\n              (and cmd? (= subneg-start b))\n              (recur (-> state\n                         (update :src-pos inc)\n                         (update :cmd conj b)\n                         (assoc :cmd? false\n                                :subneg? true)))\n\n              (and cmd? (<= subcmd-min b subcmd-max))\n              (recur (-> state\n                         (update :src-pos inc)\n                         (update :cmd conj b)))\n\n              (or cmd? (and subneg? (= subneg-end b)))\n              (let [command (conj cmd b)]\n                (recur (-> state\n                           (assoc :src-pos (inc src-pos))\n                           (dissoc :cmd :cmd? :subneg?)\n                           (update :commands\n                                   conj (with-meta\n                                          (mapv #(cmd->kw % (byte->long %)) command)\n                                          {:telnet/raw (mapv byte->long command)})))))\n\n              :else\n              (do\n                (aset dest dest-pos b)\n                (recur (-> state\n                           (update :src-pos inc)\n                           (update :dest-pos inc)))))))))))\n\n#_\n(let [src-buf (byte-array 10)\n      dest-buf (byte-array 10)]\n  (aset src-buf 0 (byte 60))\n  (aset src-buf 1 (byte 61))\n  (aset src-buf 2 (byte 62))\n  (aset src-buf 3 (unchecked-byte (TELNET :IAC)))\n  (aset src-buf 4 (unchecked-byte (TELNET :WILL)))\n  (aset src-buf 5 (unchecked-byte (TELNET :LINEMODE)))\n  (aset src-buf 6 (byte 70))\n  (-> (buffer-filter-commands {:src src-buf :dest dest-buf :end 7})\n      :commands\n      first\n      meta)\n  #_(seq dest-buf)\n  )\n"
  },
  {
    "path": "src/trikl/util.clj",
    "content": "(ns trikl.util)\n\n(defn reduce-for* [binding-pairs init body]\n  (if (next binding-pairs)\n    (let [[[v val]] binding-pairs\n          res (gensym \"res\")]\n      `(reduce (fn [~res ~v]\n                 ~(reduce-for* (next binding-pairs) res body))\n               ~init\n               ~val))\n    (let [[[v val]] binding-pairs]\n      `(reduce (fn [~'% ~v]\n                 ~@body)\n               ~init\n               ~val))))\n\n(defmacro reduce-for\n  {:style/indent 2}\n  [init bindings & body]\n  (let [binding-pairs (partition 2 bindings)]\n    (reduce-for* binding-pairs init body)))\n\n(comment\n  (reduce-for [] [x (range 3)\n                  y (range 3)]\n    (conj % [x y])))\n"
  },
  {
    "path": "test/unit/trikl/core_test.clj",
    "content": "(ns trikl.core-test\n  (:require [trikl.core :as t]\n            [clojure.test :refer :all]\n            [lambdaisland.ansi :as ansi]))\n\n(is (= [[{:row 1, :col 1} \"x\"] {}]\n       (let [sb (StringBuilder.)\n             styles (t/diff-row\n                     sb\n                     0\n                     {}\n                     [t/BLANK]\n                     [(t/map->Charel {:char \\x})])]\n         [(ansi/token-stream (str sb)) styles])))\n\n\n(is (=\n     (let [sb (StringBuilder.)\n           styles (t/diff-row\n                   sb\n                   0\n                   {}\n                   [(t/map->Charel {:char \\x})]\n                   [(t/map->Charel {:char \\x})])]\n       [(ansi/token-stream (str sb)) styles])\n     ))\n\n(+ 1 1)\n\n(let [sb (StringBuilder.)\n      styles (t/diff-row\n              sb\n              0\n              {}\n              [t/BLANK]\n              [(t/map->Charel {:char \\y :fg [10 20 30]})])]\n  [(ansi/token-stream (str sb)) styles])\n[[{:row 1, :col 1}\n  {:foreground [:rgb 10 20 30]}\n  \"y\"]\n {:char \\y, :fg [10 20 30], :bg nil}]\n\n(let [sb (StringBuilder.)\n      styles (t/diff-row\n              sb\n              0\n              {}\n              [t/BLANK t/BLANK]\n              [(t/map->Charel {:char \\x :fg [10 20 30]})\n               (t/map->Charel {:char \\y :fg [10 20 30]})])]\n  [(ansi/token-stream (str sb)) styles])\n[[{:row 1, :col 1}\n  {:foreground [:rgb 10 20 30]}\n  \"xy\"]\n {:char \\x, :fg [10 20 30], :bg nil}]\n\n\n(let [sb (StringBuilder.)\n      styles (t/diff-row\n              sb\n              0\n              {}\n              []\n              [(t/map->Charel {:char \\x :fg [10 20 30]})\n               (t/map->Charel {:char \\y :fg [10 20 30]})])]\n  [(ansi/token-stream (str sb)) styles])\n\n[[{:row 1, :col 1}\n  {:foreground [:rgb 10 20 30]}\n  \"xy\"]\n {:char \\x, :fg [10 20 30], :bg nil}]\n\n\n\n(let [sb (StringBuilder.)\n      styles (t/diff-row\n              sb\n              0\n              {}\n              [(t/map->Charel {:char \\x :fg [10 20 30]})\n               (t/map->Charel {:char \\y :fg [10 20 30]})]\n              [])]\n  [(ansi/token-stream (str sb)) styles])\n[[{:row 1, :col 1} \"  \"] {}]\n\n\n(t/time-info\n (let [sb (StringBuilder.)\n       styles (t/diff-row\n               sb\n               0\n               {}\n               [t/BLANK t/BLANK t/BLANK]\n               [(t/map->Charel {:char \\x :fg [10 20 30]})\n                t/BLANK\n                (t/map->Charel {:char \\y :fg [10 20 30]})])]\n   [(ansi/token-stream (str sb)) styles])\n \"\")\n\n[[{:row 1, :col 1}\n  {:foreground [:rgb 10 20 30]}\n  \"x\"\n  {:row 1, :col 3}\n  \"y\"]\n {:char \\x, :fg [10 20 30], :bg nil}]\n"
  },
  {
    "path": "tests.edn",
    "content": "#kaocha/v1\n{}\n"
  }
]