├── .gitignore ├── LICENSE ├── README.md ├── dev └── user.clj ├── project.clj ├── src └── crdt_edit │ ├── api │ └── routes.clj │ ├── control.clj │ ├── gui │ ├── LogootSwingDocument.clj │ ├── frame.clj │ └── logoot_swing_document_helper.clj │ ├── logoot.clj │ ├── runner.clj │ └── system.clj └── test └── crdt_edit └── test └── logoot.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of Washington and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # crdt-edit 2 | 3 | An experimental collaborative text editor built on CRDTs. This was built using the Logoot CRDT. See [the Logoot paper](http://hal.archives-ouvertes.fr/docs/00/34/59/11/PDF/main.pdf) for more information. 4 | 5 | ## Usage 6 | 7 | ### REPL 8 | 9 | * Run `lein repl` 10 | * Enter `(reset)` 11 | * This will start two instances of the editor within one repl that will be connected to one another. 12 | 13 | ### Command Line 14 | 15 | * Build it 16 | * `lein uberjar` 17 | * Run it 18 | * `java -jar target/crdt-edit-0.1.0-SNAPSHOT-standalone.jar --port 3000 --site alpha` 19 | * Enter the hostname and port of another collaborator on the local network or you can start up an additional instance for testing on a different port. 20 | 21 | 22 | ## TODOs 23 | 24 | * Nice To haves 25 | * Use persistent http connections 26 | * Add text area showing the current logoot document. 27 | 28 | ## License 29 | 30 | Copyright © 2014 Jason Gilman 31 | 32 | Distributed under the Eclipse Public License either version 1.0 or (at 33 | your option) any later version. 34 | -------------------------------------------------------------------------------- /dev/user.clj: -------------------------------------------------------------------------------- 1 | (ns user 2 | (:require [clojure.pprint :refer (pprint pp)] 3 | [clojure.test :refer (run-all-tests run-tests)] 4 | [clojure.tools.namespace.repl :refer (refresh refresh-all)]) 5 | (:use [clojure.repl] 6 | [alex-and-georges.debug-repl]) 7 | (:import java.net.InetAddress)) 8 | 9 | 10 | (def ip-address 11 | "Manually set this ip address if this fails with an exception" 12 | (.getHostAddress (InetAddress/getLocalHost))) 13 | 14 | (def system-a nil) 15 | 16 | (def system-b nil) 17 | 18 | (defn get-var 19 | [v] 20 | (var-get (find-var v))) 21 | 22 | (defn start [] 23 | (require 'crdt-edit.system) 24 | (let [create-fn (get-var 'crdt-edit.system/create) 25 | start-fn (get-var 'crdt-edit.system/start) 26 | system-a (create-fn :a 3000 ip-address [(str ip-address ":3001")]) 27 | system-b (create-fn :b 3001 ip-address [(str ip-address ":3000")])] 28 | (alter-var-root #'system-a 29 | (constantly (start-fn system-a))) 30 | (alter-var-root #'system-b 31 | (constantly (start-fn system-b))))) 32 | 33 | (defn stop [] 34 | (when ((set (map str (all-ns))) "crdt-edit.system") 35 | (let [stop-fn (get-var 'crdt-edit.system/stop)] 36 | (alter-var-root #'system-a (constantly 37 | (when system-a 38 | (stop-fn system-a)))) 39 | (alter-var-root #'system-b (constantly 40 | (when system-b 41 | (stop-fn system-b))))))) 42 | 43 | (defn print-logoot-doc 44 | [] 45 | ((get-var 'crdt-edit.system/print-logoot-doc) system-a)) 46 | 47 | (defn reset 48 | [] 49 | (stop) 50 | (refresh :after 'user/start)) 51 | 52 | (println "Custom user.clj loaded.") -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject crdt-edit "0.1.0-SNAPSHOT" 2 | :description "An experimental collaborative text editor built on CRDTs" 3 | :url "http://example.com/FIXME" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.6.0"] 7 | [org.clojure/core.async "0.1.303.0-886421-alpha"] 8 | [org.clojure/tools.cli "0.3.1"] 9 | [seesaw "1.4.4"] 10 | [compojure "1.1.8"] 11 | [ring "1.3.0"] 12 | [ring/ring-jetty-adapter "1.3.0"] 13 | [com.velisco/tagged "0.3.4"] 14 | [clj-http "0.9.2"]] 15 | 16 | :profiles 17 | {:dev {:source-paths ["dev" "src"] 18 | :dependencies [[org.clojure/test.check "0.5.8"] 19 | [org.clojure/tools.namespace "0.2.4"] 20 | [org.clojars.gjahad/debug-repl "0.3.3"]] 21 | :aot [crdt-edit.gui.LogootSwingDocument]} 22 | :uberjar {:main crdt-edit.runner 23 | :aot :all}}) 24 | -------------------------------------------------------------------------------- /src/crdt_edit/api/routes.clj: -------------------------------------------------------------------------------- 1 | (ns crdt-edit.api.routes 2 | (:require [compojure.handler :as handler] 3 | [compojure.route :as route] 4 | [compojure.core :refer :all] 5 | [ring.adapter.jetty :as jetty] 6 | [miner.tagged :as tag] 7 | [clojure.core.async :as a :refer [go go-loop !]])) 8 | 9 | (defn define-routes 10 | [system] 11 | (let [{:keys [incoming collaborators]} system] 12 | (routes 13 | (POST "/updates" {body :body} 14 | (let [updates (tag/read-string (slurp body))] 15 | (go (>! incoming updates)) 16 | {:status 200 :body ""})) 17 | (POST "/collaborators" {body :body} 18 | (let [collaborator (tag/read-string (slurp body))] 19 | (println "Adding collaborator via API" collaborator) 20 | (swap! collaborators conj collaborator)) 21 | {:status 200 :body ""}) 22 | (route/not-found "Not Found")))) 23 | 24 | (defn make-api 25 | [system] 26 | (-> (define-routes system) 27 | handler/site )) 28 | 29 | (defn create-server 30 | [port] 31 | {:port port 32 | :jetty nil}) 33 | 34 | (defn start-server 35 | [server system] 36 | (let [jetty (jetty/run-jetty (make-api system) 37 | {:port (:port server) 38 | :join? false})] 39 | (println "Jetty running on port" (:port server)) 40 | (assoc server :jetty jetty))) 41 | 42 | (defn stop-server 43 | [server system] 44 | (when-let [jetty (:jetty server)] 45 | (.stop jetty)) 46 | (dissoc server :jetty)) -------------------------------------------------------------------------------- /src/crdt_edit/control.clj: -------------------------------------------------------------------------------- 1 | (ns crdt-edit.control 2 | (:require [clojure.core.async :as a :refer [go go-loop !]] 3 | [crdt-edit.gui.LogootSwingDocument] 4 | [crdt-edit.logoot :as l] 5 | [clj-http.client :as client] 6 | [clj-http.conn-mgr :as conn-mgr] 7 | [miner.tagged :as tag]) 8 | (:import crdt_edit.gui.LogootSwingDocument 9 | crdt_edit.logoot.PositionIdentifier 10 | crdt_edit.logoot.Position 11 | crdt_edit.logoot.PositionedCharacter)) 12 | 13 | (defmulti process-update 14 | "Processes an update by type" 15 | (fn [logoot-swing-doc update] 16 | (:type update))) 17 | 18 | (defmethod process-update :insert 19 | [logoot-swing-doc {:keys [positioned-character]}] 20 | (.insertPositionedCharacter logoot-swing-doc positioned-character)) 21 | 22 | (defmethod process-update :remove 23 | [logoot-swing-doc {:keys [position]}] 24 | (.removePosition logoot-swing-doc position)) 25 | 26 | (defn process-incoming 27 | "Takes incoming logoot document changes and applies it to the swing document" 28 | [system] 29 | (let [{:keys [running-flag ^LogootSwingDocument logoot-swing-doc incoming]} system] 30 | (go 31 | (while @running-flag 32 | (try 33 | (let [updates ( (Runtime/getRuntime) 60 | (.availableProcessors) 61 | (* 2) 62 | (+ 42)) 63 | cm (clj-http.conn-mgr/make-reusable-conn-manager {:threads num-threads})] 64 | (go 65 | (while @running-flag 66 | (let [updates ( initial-caret-position 0) (<= offset initial-caret-position)) 108 | (.setCaretPosition text-area (dec initial-caret-position))))) 109 | (finally 110 | (.writeUnlockSuper this)))) 111 | 112 | -------------------------------------------------------------------------------- /src/crdt_edit/gui/frame.clj: -------------------------------------------------------------------------------- 1 | (ns crdt-edit.gui.frame 2 | (:require [crdt-edit.gui.LogootSwingDocument] 3 | [seesaw.core :as sw] 4 | [seesaw.dev :as sd] 5 | [clojure.string :as str]) 6 | (:import crdt_edit.gui.LogootSwingDocument 7 | java.net.InetAddress)) 8 | 9 | (defn update-collborators 10 | [collaborators-text collaborators-atom] 11 | (println "Setting collaborators to" collaborators-text) 12 | (let [collaborators (set (str/split collaborators-text #",\s*"))] 13 | (reset! collaborators-atom collaborators))) 14 | 15 | (defn create 16 | "Creates an instance of the GUI. Returns a map of the swing document 17 | and the frame." 18 | [site ip-address port logoot-doc outgoing collaborators-atom] 19 | 20 | (let [collaborators-text-area (sw/text :text (str/join ", " @collaborators-atom) 21 | :editable? true) 22 | text-area (sw/text 23 | :text "" 24 | :multi-line? true 25 | :wrap-lines? true 26 | :editable? true) 27 | document (LogootSwingDocument. site logoot-doc outgoing text-area)] 28 | (.setDocument text-area document) 29 | 30 | ;; Automatically update the collaborators text area when the collaborators change. 31 | (add-watch collaborators-atom :collaborators-text-update 32 | (fn [_ _ _ collaborators] 33 | (sw/text! collaborators-text-area (str/join ", " collaborators)))) 34 | 35 | 36 | {:logoot-swing-doc document 37 | :frame (sw/frame :title (format "CRDT Edit %s:%d for site %s" 38 | ip-address port site) 39 | :content (sw/top-bottom-split 40 | (sw/horizontal-panel 41 | :items ["Collaborators (comma separated)" 42 | collaborators-text-area 43 | (sw/button :text "Update" 44 | :listen [:action (fn [& args] (update-collborators (sw/text collaborators-text-area) 45 | collaborators-atom))])]) 46 | (sw/scrollable text-area)) 47 | :minimum-size [440 :by 380] 48 | :on-close :exit)})) 49 | 50 | (defn display 51 | [frame] 52 | (sw/invoke-later 53 | (-> frame 54 | sw/pack! 55 | sw/show!))) 56 | 57 | (defn close 58 | [frame] 59 | (sw/invoke-later 60 | (sw/dispose! frame))) 61 | -------------------------------------------------------------------------------- /src/crdt_edit/gui/logoot_swing_document_helper.clj: -------------------------------------------------------------------------------- 1 | (ns crdt-edit.gui.logoot-swing-document-helper 2 | "Provides implementations of the functions in the LogootDocument class" 3 | (:require [crdt-edit.logoot :as l] 4 | [clojure.core.async :as a :refer [go !]])) 5 | 6 | (defn- insert-string-at-offset 7 | "Inserts the string into the logoot document at the given offset. 8 | Returns the logoot-doc and a list of the positioned characters that were added." 9 | ([site logoot-doc offset string] 10 | (insert-string-at-offset site logoot-doc offset string [])) 11 | ([site logoot-doc offset string chars-added] 12 | (if (empty? string) 13 | [logoot-doc chars-added] 14 | (let [new-pos (l/new-position-at-index site logoot-doc offset) 15 | pos-char (l/->PositionedCharacter (first string) new-pos)] 16 | (recur site 17 | (l/insert logoot-doc pos-char) 18 | (inc offset) 19 | (rest string) 20 | (conj chars-added pos-char)))))) 21 | 22 | (defn handle-insert-string 23 | "Handles inserting a string on the GUI as typed in by a user." 24 | [gui-atom offset string] 25 | 26 | (let [gui-data (swap! 27 | gui-atom 28 | (fn [{:keys [logoot-doc site] :as gui-data}] 29 | (let [[logoot-doc chars-added] 30 | (insert-string-at-offset site logoot-doc offset string)] 31 | (assoc gui-data 32 | :logoot-doc logoot-doc 33 | :last-inserts chars-added)))) 34 | {:keys [outgoing last-inserts]} gui-data] 35 | 36 | ;; Write the last inserted character to the outgoing changes 37 | (go 38 | (>! outgoing (map #(hash-map :type :insert 39 | :positioned-character %) 40 | last-inserts)))) 41 | nil) 42 | 43 | (defn handle-insert-positioned-character 44 | "Handles inserting a positioned character. Returns a tuple of the offset and the string to insert 45 | in the text area." 46 | [gui-atom pos-char] 47 | 48 | (let [gui-data (swap! 49 | gui-atom 50 | (fn [{:keys [logoot-doc] :as gui-data}] 51 | (let [logoot-doc (l/insert logoot-doc pos-char)] 52 | (assoc gui-data :logoot-doc logoot-doc)))) 53 | updated-doc (:logoot-doc gui-data)] 54 | [(l/position->index updated-doc (:position pos-char)) 55 | (str (:character pos-char))])) 56 | 57 | (defn- remove-at-offset 58 | "Removes the characters at the document at the given offset and length. 59 | Returns the updated logoot document and the positions removed" 60 | ([logoot-doc offset length] 61 | (remove-at-offset logoot-doc offset length [])) 62 | ([logoot-doc offset length positions-removed] 63 | (if (= length 0) 64 | [logoot-doc positions-removed] 65 | (let [position (l/index->position logoot-doc offset)] 66 | (recur (l/delete logoot-doc position) 67 | offset 68 | (dec length) 69 | (conj positions-removed position)))))) 70 | 71 | (defn handle-remove 72 | "Handles delete characters removed by typing delete/backspace in the text area." 73 | [gui-atom offset length] 74 | 75 | (let [gui-data (swap! 76 | gui-atom 77 | (fn [{:keys [logoot-doc] :as gui-data}] 78 | (let [[logoot-doc positions-removed] 79 | (remove-at-offset logoot-doc offset length)] 80 | (assoc gui-data 81 | :logoot-doc logoot-doc 82 | :last-removes positions-removed)))) 83 | {:keys [outgoing last-removes]} gui-data] 84 | 85 | ;; Write the last inserted character to the outgoing changes 86 | (go 87 | (>! outgoing (map #(hash-map :type :remove 88 | :position %) 89 | last-removes)))) 90 | nil) 91 | 92 | (defn handle-remove-position 93 | "Handles delete characters received from incoming. Returns the offset of the character that was 94 | removed." 95 | [gui-atom position] 96 | (let [gui-data (swap! 97 | gui-atom 98 | (fn [{:keys [logoot-doc] :as gui-data}] 99 | (let [pos-index (l/position->index logoot-doc position) 100 | logoot-doc (l/delete logoot-doc position)] 101 | (assoc gui-data 102 | :logoot-doc logoot-doc 103 | :last-remove pos-index))))] 104 | (:last-remove gui-data))) -------------------------------------------------------------------------------- /src/crdt_edit/logoot.clj: -------------------------------------------------------------------------------- 1 | (ns crdt-edit.logoot 2 | "An implementation of the Logoot CRDT. See http://hal.archives-ouvertes.fr/docs/00/34/59/11/PDF/main.pdf" 3 | (:require [clojure.string :as str])) 4 | 5 | (defprotocol ToLogootString 6 | "Converts a logoot structure into a string for human readability of the logoot structure as shown 7 | in the Logoot paper." 8 | (to-logoot-string 9 | [i])) 10 | 11 | ;; Represents portion of a position. Contains a number and the site which created this identifier. 12 | (defrecord PositionIdentifier 13 | [ 14 | ;; Integer identifying a position 15 | pos-id 16 | ;; A symbol identifying the site 17 | site 18 | ] 19 | 20 | java.lang.Comparable 21 | 22 | (compareTo 23 | [pid1 pid2] 24 | ;; TODO implement comparable for PositionIdentifier 25 | -1 26 | ) 27 | 28 | ToLogootString 29 | 30 | (to-logoot-string 31 | [pid] 32 | (str "<" (:pos-id pid) "," (:site pid) ">"))) 33 | 34 | ;; Represents a position in a logoot document. 35 | (defrecord Position 36 | [ 37 | ;; A list of position identifiers 38 | identifiers 39 | ] 40 | java.lang.Comparable 41 | 42 | (compareTo 43 | [pos1 pos2] 44 | ;; TODO implement comparable for Position 45 | -1 46 | ) 47 | 48 | ToLogootString 49 | 50 | (to-logoot-string 51 | [pc] 52 | (str/join "." (map to-logoot-string identifiers)))) 53 | 54 | ;; Represents a single character positioned withing a logoot document. 55 | (defrecord PositionedCharacter 56 | [ 57 | ;; A single character with a position in the document. 58 | character 59 | 60 | ;; The position of the character within the document 61 | position 62 | ] 63 | 64 | java.lang.Comparable 65 | 66 | (compareTo 67 | [pc1 pc2] 68 | ;; TODO implement comparable for PositionedCharacter 69 | -1 70 | ) 71 | 72 | ToLogootString 73 | 74 | (to-logoot-string 75 | [pc] 76 | (str "(" 77 | (to-logoot-string (:position pc)) 78 | "," 79 | (:character pc) 80 | ")"))) 81 | 82 | (defn pos-id 83 | "Creates a new position idenfier" 84 | [pos site] 85 | (->PositionIdentifier pos site)) 86 | 87 | (def DOCUMENT_BEGINNING 88 | "Special positioned character representing the beginning of the document" 89 | (->PositionedCharacter \B (->Position [(->PositionIdentifier 0 :begin)]))) 90 | 91 | (def DOCUMENT_END 92 | "Special positioned character representing the end of the document" 93 | (->PositionedCharacter \E (->Position [(->PositionIdentifier Integer/MAX_VALUE :begin)]))) 94 | 95 | (defn create 96 | "Returns a new empty data structure" 97 | [] 98 | (sorted-set DOCUMENT_BEGINNING DOCUMENT_END)) 99 | 100 | (defn doc-string 101 | "Returns the document as a string" 102 | [document] 103 | (apply str (map :character (drop-last (drop 1 document))))) 104 | 105 | (defn logoot-string 106 | "Returns the document as a string as represented in the logoot paper" 107 | [document] 108 | (str/join "\n" (map to-logoot-string document))) 109 | 110 | (defn intermediate-position 111 | "Creates an intermediate position between pos1 and pos2. Site is the site of the current agent. 112 | Also allows for the random function to be specified that chooses a value between two other values" 113 | [site pos-id1 pos-id2] 114 | 115 | ;; TODO implement this 116 | 117 | ;; Note that with example based testing it may be useful to accept a fourth optional argument 118 | ;; of a function that will find a number between two others. When implementing this we should use 119 | ;; a random function. Example based tests work better when they can predict the exact output and would 120 | ;; pass in a function that wwould be more predictive like average. 121 | 122 | ) 123 | 124 | (defn index->position 125 | "Returns the position of the document at the given index" 126 | [document idx] 127 | ;; TODO implement this 128 | ) 129 | 130 | (defn position->index 131 | "Returns the index in the document of the given position. Returns nil if not in document." 132 | [document position] 133 | ;; TODO implement this 134 | ) 135 | 136 | (defn new-position-at-index 137 | "Returns a new position between the characters at the index and 1 before the index." 138 | [site document idx] 139 | (let [before-pos (index->position document (dec idx)) 140 | after-pos (index->position document idx)] 141 | (intermediate-position site before-pos after-pos))) 142 | 143 | (defn insert 144 | "Inserts a positioned character into the logoot document" 145 | [document pc] 146 | (conj document pc)) 147 | 148 | (defn delete 149 | "Removes a character from the document at the given position." 150 | [document position] 151 | (disj document (->PositionedCharacter nil position))) 152 | 153 | 154 | 155 | -------------------------------------------------------------------------------- /src/crdt_edit/runner.clj: -------------------------------------------------------------------------------- 1 | (ns crdt-edit.runner 2 | (:require [crdt-edit.system :as system] 3 | [clojure.tools.cli :as cli]) 4 | (:import java.net.InetAddress) 5 | (:gen-class)) 6 | 7 | (def cli-options 8 | ;; An option with a required argument 9 | [["-p" "--port PORT" "Port number" 10 | :id :port 11 | :default 3000 12 | :parse-fn #(Integer/parseInt %) 13 | :validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]] 14 | ["-i" "--ip-address IP" "Current IP Address" 15 | :id :ip-address] 16 | ["-s" "--site SITE" "Site" 17 | :id :site 18 | :default (keyword (.getHostAddress (InetAddress/getLocalHost))) 19 | :parse-fn keyword] 20 | ;; A boolean option defaulting to nil 21 | ["-h" "--help"]]) 22 | 23 | (defn -main 24 | [& args] 25 | (let [{{:keys [port site ip-address]} :options} (cli/parse-opts args cli-options) 26 | system (system/start (system/create site port ip-address []))] 27 | (println "Running..."))) -------------------------------------------------------------------------------- /src/crdt_edit/system.clj: -------------------------------------------------------------------------------- 1 | (ns crdt-edit.system 2 | (:require [crdt-edit.gui.frame :as frame] 3 | [crdt-edit.logoot :as logoot] 4 | [crdt-edit.control :as control] 5 | [clojure.core.async :as async] 6 | [crdt-edit.api.routes :as api] 7 | [clojure.set :as set] 8 | [clj-http.client :as client]) 9 | (:import java.net.InetAddress)) 10 | 11 | (defn create 12 | "Creates an initial system" 13 | [site port ip-address collaborators] 14 | (let [outgoing (async/chan 10) 15 | incoming (async/chan 5) 16 | logoot-doc (logoot/create) 17 | ip-address (or ip-address (.getHostAddress (InetAddress/getLocalHost))) 18 | collaborators-atom (atom (set collaborators) 19 | ;; Don't allow self as a collaborator 20 | :validator (fn [current-value] 21 | (nil? (get current-value (str ip-address ":" port))))) 22 | {:keys [logoot-swing-doc frame]} (frame/create site ip-address port logoot-doc outgoing collaborators-atom)] 23 | 24 | {:ip-address ip-address 25 | :port port 26 | 27 | ;; The web server that accepts updates. 28 | :server (api/create-server port) 29 | 30 | ;; The java.swing.text.Document that handles typing updates 31 | :logoot-swing-doc logoot-swing-doc 32 | 33 | ;; The swing frame containing the GUI displayed to the user. 34 | :frame frame 35 | 36 | ;; Core.async channel of incoming changes from other collaborators. 37 | :incoming incoming 38 | ;; Core.async channel of changes to send to other collaborators. 39 | :outgoing outgoing 40 | 41 | ;; List of host names of collaborating editors 42 | :collaborators collaborators-atom 43 | 44 | ;; Running flag is used to signal go blocks that we are done. 45 | :running-flag (atom false)})) 46 | 47 | (defn get-logoot-doc 48 | [system] 49 | (-> system 50 | :logoot-swing-doc 51 | (.data) 52 | deref 53 | :logoot-doc)) 54 | 55 | (defn print-logoot-doc 56 | [system] 57 | (println (logoot/logoot-string (get-logoot-doc system)))) 58 | 59 | (defn- notify-collaborotors-when-added 60 | [system] 61 | (add-watch 62 | (:collaborators system) 63 | :discovery-collaborators 64 | (fn [_ _ prev-collaborators new-collaborators] 65 | (println (pr-str prev-collaborators) (pr-str new-collaborators)) 66 | (let [changed-collabs (set/difference new-collaborators prev-collaborators) 67 | my-location (str (:ip-address system) ":" (:port system))] 68 | (doseq [collaborator changed-collabs] 69 | (when (not= my-location collaborator) 70 | (println "Adding" my-location "as a collaborator to" collaborator) 71 | (let [url (format "http://%s/collaborators" collaborator)] 72 | (client/post url {:headers {:content-type "application/edn"} 73 | :body (pr-str my-location)})))))))) 74 | 75 | (defn start 76 | "Starts the system and returns it." 77 | [system] 78 | (let [{:keys [frame 79 | running-flag]} system] 80 | ;; Set the running flag to true. Must be done before control go blocks start. 81 | (reset! running-flag true) 82 | 83 | ;; Start asynchronously processing incoming changes 84 | (control/process-incoming system) 85 | 86 | ;; Send outgoing changes to another server 87 | (control/process-outgoing system) 88 | 89 | ;; Display the GUI 90 | (frame/display frame) 91 | 92 | (notify-collaborotors-when-added system) 93 | 94 | (update-in system [:server] api/start-server system))) 95 | 96 | (defn stop 97 | "Stops the system and returns it" 98 | [system] 99 | 100 | (let [{:keys [frame 101 | running-flag]} system] 102 | ;; Stop processing changes on the channels 103 | (reset! running-flag false) 104 | 105 | ;; Hide the gui 106 | (frame/close frame) 107 | 108 | (update-in system [:server] api/stop-server system))) 109 | 110 | 111 | -------------------------------------------------------------------------------- /test/crdt_edit/test/logoot.clj: -------------------------------------------------------------------------------- 1 | (ns crdt-edit.test.logoot 2 | (:require [clojure.test :refer :all] 3 | [clojure.test.check.properties :refer [for-all]] 4 | [clojure.test.check.clojure-test :refer [defspec]] 5 | [clojure.test.check :as tc] 6 | [clojure.test.check.generators :as gen] 7 | [crdt-edit.logoot :as l] 8 | [clojure.pprint :refer [pprint]])) 9 | 10 | (def site-gen 11 | "Site generator." 12 | (gen/elements [:a :b :c :d])) 13 | 14 | (def position-identifier-gen 15 | "Position identifier generator." 16 | (gen/fmap (partial apply l/->PositionIdentifier) 17 | (gen/tuple gen/pos-int site-gen))) 18 | 19 | (def position-gen 20 | "Position generator" 21 | (gen/fmap l/->Position 22 | (gen/vector position-identifier-gen 1 5))) 23 | 24 | (def two-unique-positions-in-order 25 | "Generator of two unique positions in sorted order." 26 | (gen/fmap 27 | sort 28 | (gen/such-that 29 | (partial apply not=) 30 | (gen/vector position-gen 2)))) 31 | 32 | (defn mid 33 | "Returns the middle integer between two ints" 34 | [^long n1 ^long n2] 35 | (int (/ (+ n1 n2) 2))) 36 | 37 | ;; Checks that between any two positions another position can be found and inserted correctly 38 | (defspec intermediate-position-spec 1000 39 | (for-all [positions two-unique-positions-in-order 40 | site site-gen] 41 | (let [[pos1 pos2] positions 42 | middle-pos (l/intermediate-position site pos1 pos2) 43 | expected-order [pos1 middle-pos pos2]] 44 | (and 45 | (= expected-order (sort expected-order)) 46 | (not= pos1 middle-pos) 47 | (not= pos2 middle-pos))))) 48 | 49 | (defn pos-builder 50 | "Helps build positions. Takes a sequence a position int site pairs" 51 | [& pairs] 52 | (->> pairs 53 | (partition 2) 54 | (map (partial apply l/->PositionIdentifier)) 55 | l/->Position)) 56 | 57 | 58 | (def max-int Integer/MAX_VALUE) 59 | (def min-int Integer/MIN_VALUE) 60 | 61 | (deftest intermediate-position-examples 62 | (are [site pos1-parts pos2-parts expected-parts] 63 | (let [pos1 (apply pos-builder pos1-parts) 64 | pos2 (apply pos-builder pos2-parts) 65 | expected (apply pos-builder expected-parts) 66 | actual (l/intermediate-position site pos1 pos2 mid)] 67 | (if (= expected actual) 68 | true 69 | (do 70 | (println "expected:") 71 | (pprint expected) 72 | (println "actual") 73 | (pprint actual)))) 74 | :a [1 :a 5 :a 8 :a] [3 :a] [2 :a] 75 | :a [4 :a 1 :a] [4 :a 3 :a] [4 :a 2 :a] 76 | 77 | ;; Use site to find position in between matching or separated by one. 78 | :f [5 :a 1 :e] [5 :a 2 :a] [5 :a 1 :f] 79 | :d [5 :a 1 :e] [5 :a 2 :a] [5 :a 1 :e (mid 0 max-int) :d] 80 | :b [5 :a 1 :a] [5 :a 1 :c] [5 :a 1 :b] 81 | 82 | :r [5 :a 1 :a 10 :a] [5 :a 1 :c] [5 :a 1 :a (mid 10 max-int) :r] 83 | 84 | :a [0 :a] [0 :a 0 :a] [0 :a (mid min-int 0) :a] 85 | :a [3 :a 1 :a] [4 :a 0 :a] [3 :a (mid 1 max-int) :a] 86 | 87 | ;; Best case but harder to implement 88 | ; :a [3 :a 0 :a] [4 :a 0 :a] [3 :a (mid 0 max-int) :a] 89 | :a [3 :a 0 :a] [4 :a 0 :a] [3 :a 0 :a (mid 0 max-int) :a] 90 | 91 | )) 92 | 93 | 94 | --------------------------------------------------------------------------------