├── default_icon.png ├── .gitmodules ├── omgdaemon.asd ├── daemonui.lisp ├── omg.asd ├── example.lisp ├── omgutil.lisp ├── LICENSE ├── omgwidgets.lisp ├── omgdaemon.lisp └── README.md /default_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hemml/OMGlib/HEAD/default_icon.png -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "jscl"] 2 | path = jscl 3 | url = https://github.com/jscl-project/jscl.git 4 | -------------------------------------------------------------------------------- /omgdaemon.asd: -------------------------------------------------------------------------------- 1 | (defsystem "omgdaemon" 2 | :description "A deployment system for omg-based apps" 3 | :version "0.0.1" 4 | :author "Pavel Kaygorodov " 5 | :licence "GPLv3" 6 | :homepage "https://github.com/hemml/OMGlib" 7 | :source-control "https://github.com/hemml/OMGlib.git" 8 | :depends-on ("omg" "bordeaux-threads" "trivial-utf-8" "swank" "osicat" "uiop" "find-port" "inferior-shell" "iolib" "log4cl" "trivial-dump-core" "cffi") 9 | :components ((:static-file "README.md") 10 | (:static-file "LICENSE") 11 | (:file "omgdaemon") 12 | (:file "daemonui" :depends-on ("omgdaemon")))) 13 | -------------------------------------------------------------------------------- /daemonui.lisp: -------------------------------------------------------------------------------- 1 | (defpackage :daemonui 2 | (:use cl omg omgdaemon) 3 | (:export ensure-last-version 4 | get-omg-cookie-name 5 | get-my-version)) 6 | 7 | (in-package :daemonui) 8 | 9 | (defun-r need-reload () 10 | (and (not (equal *omg-version* +devel-version+)) 11 | (not (equal *omg-version* *omg-last-version*)))) 12 | 13 | (defun-r get-omg-cookie-name () 14 | +omg-version-cookie+) 15 | 16 | (defun-r get-last-version () 17 | *omg-last-version*) 18 | 19 | (defun-r get-my-version () 20 | *omg-version*) 21 | 22 | (defun-f ensure-last-version () 23 | (if (need-reload) 24 | (progn 25 | (setf (jscl::oget (jscl::%js-vref "document") "cookie") 26 | (format nil "~A=~A" (get-omg-cookie-name) (get-last-version))) 27 | ((jscl::oget (jscl::%js-vref "location") "reload") t)))) 28 | -------------------------------------------------------------------------------- /omg.asd: -------------------------------------------------------------------------------- 1 | (defsystem "omg" 2 | :description "A Common Lisp library to build fully dynamic web interfaces" 3 | :version "0.2.0" 4 | :author "Pavel Kaygorodov " 5 | :licence "GPLv3" 6 | :homepage "https://github.com/hemml/OMGlib" 7 | :source-control "https://github.com/hemml/OMGlib.git" 8 | :depends-on ("clack" "websocket-driver-server" "bordeaux-threads" "trivial-utf-8" "media-types" "hunchentoot" 9 | "pngload" "skippy" "cl-jpeg" "cl-base64" "quri") 10 | :build-operation "static-program-op" 11 | :components ((:static-file "README.md") 12 | (:static-file "LICENSE") 13 | (:file "omg") 14 | (:file "omgui" :depends-on ("omg")) 15 | (:file "omgutil" :depends-on ("omg")) 16 | (:file "omgwidgets" :depends-on ("omg" "omgui")))) 17 | 18 | (defparameter *jscl-dir* (merge-pathnames (make-pathname :directory '(:relative "jscl")) 19 | (asdf:system-source-directory :omg))) 20 | 21 | (load (merge-pathnames (make-pathname :name "jscl.lisp") *jscl-dir*)) 22 | 23 | (defparameter jscl::*jscl-js* (make-array '(0) :element-type 'base-char :fill-pointer 0 :adjustable t)) 24 | 25 | ;; Adopted from jscl.lisp: 26 | (let ((jscl::*features* (list* :jscl :jscl-xc jscl::*features*)) 27 | (jscl::*package* (find-package "JSCL")) 28 | (jscl::*default-pathname-defaults* *jscl-dir*)) 29 | (setq jscl::*environment* (jscl::make-lexenv)) 30 | (jscl::with-compilation-environment 31 | (jscl::with-output-to-string (jscl::out jscl::*jscl-js*) 32 | (format jscl::out "(function(){~%") 33 | (format jscl::out "'use strict';~%") 34 | (jscl::write-string (jscl::read-whole-file (jscl::source-pathname "prelude.js")) jscl::out) 35 | (jscl::do-source input :target 36 | (jscl::!compile-file input jscl::out :print nil)) 37 | (jscl::dump-global-environment jscl::out) 38 | (jscl::!compile-file "src/toplevel.lisp" jscl::out :print nil) 39 | (format jscl::out "})();~%")))) 40 | -------------------------------------------------------------------------------- /example.lisp: -------------------------------------------------------------------------------- 1 | ;; Load this file via (load "example.lisp") in the REPL and open http://localhost:7500 in the browser 2 | 3 | (require :omg) 4 | 5 | (defpackage :my-test 6 | (:use cl omg omgui jscl)) 7 | (in-package :my-test) 8 | 9 | ;; (setf omg::*ssl-cert* "sslcert.pem") 10 | ;; (setf omg::*ssl-key* "sslkey.pem") 11 | ;; (setf omg::*port* 7500) 12 | 13 | (defun-f play-yt (video-id) 14 | (add-youtube-player (append-element (create-element "div")) 15 | :video-id video-id 16 | :width 800 17 | :onready (lambda (ev) 18 | ((jscl::oget ev "target" "mute")) ;; respect autoplay restrictions 19 | ((jscl::oget ev "target" "playVideo")) 20 | (jslog "Starting playback")) 21 | :onstatechange (lambda (ev) 22 | (if (equal (jscl::oget ev "data") 23 | (jscl::oget (jscl::%js-vref "YT") "PlayerState" "PLAYING")) 24 | (progn 25 | (jslog "Playback started!") 26 | (execute-after 10.0 ;; Pause video after 10 sec. playback 27 | (lambda () 28 | ((jscl::oget ev "target" "pauseVideo"))))))))) 29 | 30 | 31 | (defun-f up1 (s) 32 | (string-upcase s)) 33 | 34 | (defun-r up2 (s) 35 | (string-upcase s)) 36 | 37 | (defun-r my-boot () 38 | (print "BOOT!") 39 | (set-debug-session (current-session-id))) 40 | 41 | (add-to-boot '(my-boot)) ;; call my-boot just after connection 42 | 43 | (restart-server) ;; (re)start a server on default port 7500 44 | 45 | ;; execute this via SLIME after browser connection: 46 | 47 | (in-debug-session 48 | (print 49 | (modal-dialog "The header" 50 | "The modal dialog test" 51 | :lines (list :line1 (list "Upcase on backend:" :filter #'up2) 52 | :line2 (list "Upcase on frontend:" :filter #'up1) 53 | :pass (list "Upcase on frontend:" :type "password") 54 | :line3 "Enter something:" 55 | :buttons (list (list "OK" #'dialog-ok) 56 | (list "Cancel" #'close-current-dialog)))))) 57 | 58 | (play-yt "vla6vpa1-Bk") 59 | -------------------------------------------------------------------------------- /omgutil.lisp: -------------------------------------------------------------------------------- 1 | (defpackage omgutil 2 | (:use omg cl) 3 | (:export defclass-m ;; define a both-side class 4 | sync-slot ;; slot syncronization method for mirrored instances 5 | data-sync ;; a class for objects which needs a data syncronization 6 | sync-data ;; method called if data synchronization needed for data-sync clacc 7 | get-timeouts ;; returns number of timeouts in the current session 8 | reset-timeouts) ;; resets to zero number of timeouts in the current session 9 | (:import-from omg defclass-m 10 | mirrored-object 11 | sync-all-data 12 | omg-id 13 | sync-slot-r 14 | sync-slot 15 | gethash-lock 16 | scope 17 | *session-list* 18 | *current-session* 19 | *m-scope-funcs*)) 20 | 21 | (in-package :omgutil) 22 | 23 | (defvar-f *data-sync-objects* nil) 24 | 25 | (defclass-f mirrored-object () 26 | ((omg-id :initarg :omg-internal-id))) 27 | 28 | (defmethod-f initialize-instance :after ((obj mirrored-object) &key &rest args) 29 | (setf (jscl::oget (jscl::%js-vref "self") "OMG" "objectRegistry" (slot-value obj 'omg-id)) obj) 30 | (setf (jscl::oget obj "omgObjId") (slot-value obj 'omg-id))) 31 | 32 | (defclass-m data-sync () 33 | ((data-epoch :mirrored t 34 | :initform 0 35 | :accessor data-epoch))) 36 | 37 | (defmethod-f sync-data ((obj data-sync)) 38 | (sync-slot obj 'data-epoch)) 39 | 40 | (defmethod sync-data ((obj data-sync)) 41 | (incf (data-epoch obj)) 42 | (let ((scf (gethash-lock (class-name (class-of obj)) *m-scope-funcs*))) 43 | (loop for *current-session* being the hash-values of *session-list* do 44 | (if (equal (slot-value obj 'scope) (funcall scf obj)) 45 | (remote-exec `(sync-data ,obj)))))) 46 | 47 | (defun-f sync-all-data () 48 | (map nil 49 | (lambda (obj) 50 | (let ((new-epoch (sync-slot-r obj 'data-epoch))) 51 | (if (not (= (data-epoch obj) new-epoch)) 52 | (progn 53 | (sync-data obj) 54 | (setf (slot-value obj 'data-epoch) new-epoch))))) 55 | *data-sync-objects*)) 56 | 57 | (defmethod-f initialize-instance :after ((obj data-sync) &key &rest args) 58 | (pushnew obj *data-sync-objects*)) 59 | 60 | (defun-r get-timeouts () 61 | (when omg::*current-session* 62 | (slot-value omg::*current-session* 'omg::timeouts))) 63 | 64 | (defun-r reset-timeouts () 65 | (when omg::*current-session* 66 | (setf (slot-value omg::*current-session* 'omg::timeouts) 0))) 67 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /omgwidgets.lisp: -------------------------------------------------------------------------------- 1 | (defpackage :omgwidgets 2 | (:use cl omg jscl omgui omgutil) 3 | (:export omg-widget root render-widget redraw 4 | editable-field input-size value ok cancel val 5 | modal-dialog-window 6 | progress-bar width height bg-style fg-style set-progress 7 | list-view elements current-position transfer-chunk list-view-element-class 8 | graph xmin xmax ymin ymax adjust xticks yticks xdelta ydelta xcaption ycaption show-scales plots need-rescale add-plot 9 | remove-plot remove-all-plots preserve-aspect-ratio rescale rescale-auto make-curve 10 | plot color parent 11 | func-plot func 12 | tabular-plot table 13 | matrix-plot nx ny palette matrix norm)) 14 | 15 | (in-package :omgwidgets) 16 | 17 | (defclass-f omg-widget () 18 | ((root :accessor root) 19 | (id :initform (omgui::random-id) 20 | :accessor id))) 21 | 22 | (defclass-f editable-field (omg-widget) 23 | ((root :initform (create-element "span" 24 | :|style.textDecorationStyle| "dashed" 25 | :|style.textDecorationLine| "underline" 26 | :|style.textDecorationThicknes| "1.75pt" 27 | :|style.color| "blue" 28 | :|title| "change" 29 | :add-style ":hover {cursor:pointer;}")) 30 | (input-size :initarg :input-size 31 | :initform 20 32 | :accessor input-size) 33 | (value :initarg :value 34 | :initform "" 35 | :accessor val) 36 | (ok :initarg :ok 37 | :initform (lambda (val) 38 | (declare (ignore val)) 39 | (setf (slot-value w 'value) val) 40 | val) 41 | :reader ok-callback) 42 | (cancel :initarg :cancel 43 | :initform (lambda (w) (declare (ignore w))) 44 | :reader cancel-callback) 45 | (edt-blk :accessor edt-blk 46 | :initform nil))) 47 | 48 | (defclass-f modal-dialog-window (omg-widget) 49 | ((mdw-curtain :accessor mdw-curtain))) 50 | 51 | (defclass-f progress-bar (omg-widget) 52 | ((width :accessor width 53 | :initarg :width 54 | :initform "20em") 55 | (height :accessor height 56 | :initarg :height 57 | :initform "1em") 58 | (bg-style :accessor bg-style 59 | :initarg :bg-style 60 | :initform '(:|style.border| "1px solid black" 61 | :|style.background| "white")) 62 | (fg-style :accessor fg-style 63 | :initarg :fg-style 64 | :initform '(:|style.background| "blue")) 65 | (value :accessor value 66 | :initarg :value 67 | :initform 0) 68 | (bar :accessor bar))) 69 | 70 | (defclass-m list-view (omg-widget data-sync) 71 | ((elements :accessor elements 72 | :initform nil) 73 | (current-position :accessor current-position 74 | :initform 0 75 | :mirrored t) 76 | (transfer-chunk :initform 50 77 | :accessor transfer-chunk 78 | :browser-side t) 79 | (mean-height :browser-side t 80 | :initform nil 81 | :accessor mean-height) 82 | (f-elements :accessor f-elements 83 | :initform nil 84 | :browser-side t) 85 | (list-view-element-class :browser-side t 86 | :initform 'list-view-element 87 | :accessor list-view-element-class) 88 | (root :initform (create-element "div") 89 | :accessor root))) 90 | 91 | (defclass-f list-view-element (omg-widget) 92 | ((loaded :initform nil 93 | :accessor loaded 94 | :initarg :loaded) 95 | (pos :initform (error "Position must be defined!") 96 | :accessor pos 97 | :initarg :pos))) 98 | 99 | (defclass-f graph (omg-widget) 100 | ((xmin :initarg :xmin 101 | :initform -1 102 | :accessor xmin) 103 | (xmax :initarg :xmax 104 | :initform 1 105 | :accessor xmax) 106 | (ymin :initarg :ymin 107 | :initform -1 108 | :accessor ymin) 109 | (ymax :initarg :ymax 110 | :initform 1 111 | :accessor ymax) 112 | (adjust :initarg :adjust 113 | :initform t 114 | :accessor adjust) 115 | (xticks :initarg :xticks 116 | :initform 5 117 | :accessor xticks) 118 | (yticks :initarg :yticks 119 | :initform 5 120 | :accessor yticks) 121 | (xdelta :initarg :xdelta) 122 | (ydelta :initarg :ydelta) 123 | (xcaption :initarg :xcaption 124 | :initform nil 125 | :accessor xcaption) 126 | (ycaption :initarg :ycaption 127 | :initform nil 128 | :accessor ycaption) 129 | (show-scales :initarg :scales 130 | :initform '(:bottom :left) 131 | :accessor show-scales) 132 | (graph :accessor graph) 133 | (plots :initform (list) 134 | :accessor plots) 135 | (preserve-aspect-ratio :initform nil 136 | :initarg :preserve-aspect-ratio 137 | :accessor preserve-aspect-ratio) 138 | (need-rescale :initform nil 139 | :accessor need-rescale))) 140 | 141 | (defclass-f graph-scale (omg-widget) 142 | ((root :initform nil) 143 | (parent :initarg :graph 144 | :initform (error "Parent graph must be supplied!") 145 | :accessor parent) 146 | (pos :initarg :position 147 | :accessor pos 148 | :initform (error "Scale position must be provided!")))) 149 | 150 | (defclass-f plot (omg-widget) 151 | ((root :initform nil) 152 | (color :initform "red" 153 | :initarg :color 154 | :accessor color) 155 | (parent :accessor parent))) 156 | 157 | (defclass-f func-plot (plot) 158 | ((func :initarg :func 159 | :initform (error "Function must be provided for func-plot!") 160 | :accessor func) 161 | (last-ymin :initform nil 162 | :accessor last-ymin) 163 | (last-ymax :initform nil 164 | :accessor last-ymax))) 165 | 166 | (defclass-f tabular-plot (plot) 167 | ((table :initarg :table 168 | :initform (error "Table must be provided for tabular-plot!") 169 | :accessor table))) 170 | 171 | (defclass-f matrix-plot (plot) 172 | ((nx) 173 | (ny) 174 | (xmin :accessor xmin 175 | :initarg :xmin 176 | :initform (error "matrix-plot bounds must bi defined!")) 177 | (xmax :accessor xmax 178 | :initarg :xmax 179 | :initform (error "matrix-plot bounds must bi defined!")) 180 | (ymin :accessor ymin 181 | :initarg :ymin 182 | :initform (error "matrix-plot bounds must bi defined!")) 183 | (ymax :accessor ymax 184 | :initarg :ymax 185 | :initform (error "matrix-plot bounds must bi defined!")) 186 | (palette :initarg :palette 187 | :initform (lambda (x) (list x x x)) 188 | :accessor palette) 189 | (matrix :initarg :matrix 190 | :initform (error "Matrix must be provided for matrix-plot!") 191 | :accessor matrix) 192 | (norm :initarg :norm 193 | :initform nil 194 | :accessor norm))) 195 | 196 | ;;;;;;;;;;;;;;;;; render-widget ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 197 | 198 | (defgeneric-f render-widget (w)) 199 | 200 | (defmethod-f render-widget ((w omg-widget)) 201 | (root w)) 202 | 203 | (defmethod-f render-widget ((w editable-field)) 204 | (setf (jscl::oget (root w) "onclick") 205 | (lambda (ev) 206 | (declare (ignore ev)) 207 | (to-edit-state w))) 208 | (setf (jscl::oget (root w) "innerHTML") (val w)) 209 | (root w)) 210 | 211 | (defmethod-f render-widget ((w modal-dialog-window)) 212 | (append-element (setf (slot-value w 'mdw-curtain) 213 | (create-element "div" :|style.opacity| "80%" 214 | :|style.background| "white" 215 | :|style.width| (page-width) 216 | :|style.height| (page-height) 217 | :|style.position| "absolute" 218 | :|style.top| "0" 219 | :|style.left| "0" 220 | :|style.zIndex| 100000))) 221 | (setf (slot-value w 'root) 222 | (create-element "div" :|style.visibility| "hidden" 223 | :|style.width| "auto" 224 | :|style.display| "inline-block" 225 | :|style.position| "absolute" 226 | :|style.zIndex| 200000)) 227 | (ensure-element (root w) 228 | (setf (jscl::oget (root w) "style" "left") 229 | (format nil "~Apx" 230 | (max 0 (+ (visible-left) 231 | (jsfloor (/ (- (visible-width) 232 | (element-width (root w))) 233 | 2)))))) 234 | (setf (jscl::oget (root w) "style" "top") 235 | (format nil "~Apx" 236 | (max 0 (+ (visible-top) 237 | (jsfloor (/ (- (visible-height) 238 | (element-height (root w))) 239 | 2)))) 240 | "px")) 241 | (setf (jscl::oget (root w) "style" "visibility") "visible")) 242 | (root w)) 243 | 244 | (defmethod-f render-widget ((b progress-bar)) 245 | (setf (slot-value b 'root) 246 | (apply #'create-element 247 | `("div" ,@(bg-style b) :|style.width| ,(width b) :|style.height| ,(height b) 248 | :|style.position| "relative" 249 | :append-element 250 | ,(make-svg :|viewBox| "0 0 100 100" 251 | :|style.width| "100%" 252 | :|style.height| "100%" 253 | :|style.left| "0" 254 | :|style.top| "0" 255 | :|style.display| "block" 256 | :|style.position| "absolute" 257 | :|preserveAspectRatio| "none" 258 | '(:|defs| (:|linearGradient| :|id| "boxgrad" 259 | :|x1| "0" 260 | :|x2| "1" 261 | (:|stop| :|offset| "0%" :|stop-color| "white") 262 | (:|stop| :|offset| "50%" :|stop-color| "#e0e0e0") 263 | (:|stop| :|offset| "100%" :|stop-color| "white") 264 | (:|animate| :|attributeName| "x1" 265 | :|values| "-1;1" 266 | :|dur| "1s" 267 | :|repeatCount| "indefinite") 268 | (:|animate| :|attributeName| "x2" 269 | :|values| "0;2" 270 | :|dur| "1s" 271 | :|repeatCount| "indefinite"))) 272 | '(:|rect| :|x| 0 :|y| 0 :|width| "100%" :|height| "100%" :|fill| "url('#boxgrad')")) 273 | :append-element 274 | ,(setf (slot-value b 'bar) 275 | (apply #'create-element 276 | `("div" ,@(fg-style b) 277 | :|style.height| "100%" 278 | :|style.position| "absolute" 279 | :|style.left| 0 280 | :|style.top| 0 281 | :|style.width| ,(format nil "~A%" (jsfloor (* 100 (value b)))))))))) 282 | (root b)) 283 | 284 | (defmethod-f render-widget ((e list-view-element)) 285 | (setf (slot-value e 'root) 286 | (if (loaded e) 287 | (render-widget (loaded e)) 288 | (create-element "div" :|style.position| "relative" 289 | :|style.left| 0 290 | :|style.right| 0 291 | :|style.height| "1em" 292 | :|style.marginTop| "0.2em" 293 | :|style.background| "#f0f0f0")))) 294 | 295 | (defmethod-f render-widget ((l list-view)) 296 | (let ((el (create-element "div" :append-elements (mapcar #'render-widget (slot-value l 'f-elements))))) 297 | (ensure-element el 298 | (onscroll l (f-elements l) (current-position l)) 299 | (let ((scroll-tim nil)) 300 | (setf (jscl::oget (parent-element el) "onscroll") 301 | (lambda (ev) 302 | (if scroll-tim (funcall (jscl::%js-vref "clearTimeout") scroll-tim)) 303 | (setf scroll-tim (execute-after 0.1 (lambda () (onscroll l))))))) 304 | (let ((cur-el (nth (current-position l) (f-elements l)))) 305 | (if cur-el 306 | (setf (jscl::oget (parent-element el) "scrollTop") 307 | (- (jscl::oget (slot-value cur-el 'root) "offsetTop") 308 | (jscl::oget ((jscl::oget (parent-element el) "getBoundingClientRect")) "top")))))) 309 | (setf (slot-value l 'root) el))) 310 | 311 | (defmethod-f render-widget ((g graph)) 312 | (setf (slot-value g 'graph) 313 | (apply #'create-element 314 | `("div" :|style.width| "100%" 315 | ,@(if (not (preserve-aspect-ratio g)) 316 | (list :|style.height| "100%") 317 | (list :|style.aspectRatio| (/ (- (xmax g) (xmin g)) (- (ymax g) (ymin g))))) 318 | :|style.position| "relative" 319 | :|style.left| 0 320 | :|style.top| 0 321 | :|style.overflow| "hidden" 322 | :|style.boxSizing| "border-box"))) 323 | (let* ((scales (show-scales g)) 324 | (top-scale (position :top scales)) 325 | (bottom-scale (position :bottom scales)) 326 | (left-scale (position :left scales)) 327 | (right-scale (position :right scales)) 328 | (xcap (xcaption g)) 329 | (ycap (ycaption g))) 330 | (setf (slot-value g 'root) 331 | (apply #'create-element 332 | `("table" :|style.width| "100%" 333 | :|style.height| ,(if (preserve-aspect-ratio g) "fit-content" "100%") 334 | :|style.borderSpacing| 0 335 | :|style.padding| "1em" 336 | :append-elements 337 | ,(if top-scale 338 | (list (create-element "tr" :|style.height| "1px" 339 | :append-elements (if ycap (list (create-element "td"))) 340 | :append-elements (if left-scale (list (create-element "td" :|style.height| "inherit" 341 | :|style.width| "inherit"))) 342 | :append-element 343 | (create-element "td" :|style.height| "inherit" 344 | :|style.width| "inherit" 345 | :|style.padding| 0 346 | :|style.position| "relative" 347 | ; :|style.height| "max-content" 348 | :append-element (render-widget (make-instance 'graph-scale :graph g :position :top))) 349 | :append-elements (if right-scale (list (create-element "td")))))) 350 | :append-element 351 | ,(create-element "tr" :|style.height| "1px" 352 | :append-elements 353 | (if ycap 354 | (list (create-element "td" :|style.paddingRight| "1em" 355 | :|style.height| "inherit" 356 | :append-element (create-element "span" :|style.writingMode| "vertical-lr" 357 | :|style.writingMode| "sideways-lr" 358 | :append-element ycap)))) 359 | :append-elements 360 | (if left-scale 361 | (list (create-element "td" :|style.padding| 0 362 | :|style.position| "relative" 363 | :|style.height| "inherit" 364 | :|style.width| "inherit" 365 | :append-element (render-widget (make-instance 'graph-scale :graph g :position :left))))) 366 | :append-element 367 | (create-element "td" :|style.padding| 0 368 | :|style.borderSpacing| 0 369 | :|style.width| "100%" 370 | :|style.height| "100%" 371 | :append-element 372 | (create-element "div" :|style.width| "100%" 373 | :|style.height| "100%" 374 | :|style.position| "relative" 375 | :|style.boxSizing| "border-box" 376 | :|style.background| "white" 377 | :|style.boxShadow| "black 0px 0px 0px 1px" 378 | :append-element (graph g))) 379 | :append-elements 380 | (if right-scale 381 | (list (create-element "td" :|style.padding| 0 382 | :|style.position| "relative" 383 | :|style.height| "inherit" 384 | :|style.width| "inherit" 385 | :append-element (render-widget (make-instance 'graph-scale :graph g :position :right)))))) 386 | :append-elements 387 | ,(if bottom-scale 388 | (list (create-element "tr" :|style.height| "1px" 389 | :append-elements (if ycap (list (create-element "td"))) 390 | :append-elements (if left-scale (list (create-element "td"))) 391 | :append-element 392 | (create-element "td" :|style.height| "inherit" 393 | :|style.width| "inherit" 394 | :|style.padding| 0 395 | :|style.position| "relative" 396 | ; :|style.height| "max-content" 397 | :append-element (render-widget (make-instance 'graph-scale :graph g :position :bottom))) 398 | :append-elements (if right-scale (list (create-element "td")))))) 399 | :append-elements 400 | ,(if xcap 401 | (list (create-element "tr" :|style.height| "1px" 402 | :append-elements (if ycap (list (create-element "td"))) 403 | :append-elements (if left-scale (list (create-element "td"))) 404 | :append-element (create-element "td" :|align| "center" 405 | :|style.height| "inherit" 406 | :|style.width| "inherit" 407 | :|style.padding| 0 408 | :append-element xcap) 409 | :append-elements (if right-scale (list (create-element "td")))))))))) 410 | (ensure-element (graph g) 411 | (loop for p in (plots g) do 412 | (when (not (and (root p) (jscl::oget (root p) "isConnected"))) 413 | (append-element (render-widget p) (graph g))))) 414 | (rescale-auto g) 415 | (root g)) 416 | 417 | 418 | (defmethod-f render-widget ((s graph-scale)) 419 | (setf (slot-value s 'root) 420 | (labels ((trnk (x delta) 421 | (let* ((dg (floor (/ (jsln delta) (jsln 10)))) 422 | (digits (if (< dg 1) 423 | (+ (if (< dg 0) 424 | (- dg) 425 | dg) 426 | 1) 427 | 0))) 428 | (/ (jstrunc (* (expt 10 digits) x)) 429 | (expt 10 digits))))) 430 | (let* ((g (parent s)) 431 | (adjust (adjust g)) 432 | (pos (pos s)) 433 | (horizontal (or (equal :top pos) 434 | (equal :bottom pos))) 435 | (min (if horizontal (xmin g) (ymin g))) 436 | (max (if horizontal (xmax g) (ymax g))) 437 | (delta (if horizontal (xdelta g) (ydelta g))) 438 | (ft (if adjust 439 | (* delta (jsceil (/ min delta))) 440 | min))) 441 | (create-element "div" :|style.position| "relative" 442 | ;;:|style.inset| 0 443 | (if horizontal :|style.width| :|style.height|) "100%" 444 | ; :|style.background| "green" 445 | :|style.display| "flex" 446 | :|style.flexFlow| (if horizontal "row" "column") 447 | :append-elements 448 | (let* ((ticks (funcall (if horizontal #'identity #'reverse) 449 | (loop for x100 from (* 100 ft) to (* 100 max) by (* 100 delta) 450 | for x = (/ x100 100) collect (cons x (if horizontal 451 | (/ (- x min) (- max min)) 452 | (- 1 (/ (- x min) (- max min)))))))) 453 | (tick-pos (mapcar #'cdr ticks)) 454 | (tick-val (mapcar #'car ticks))) 455 | (mapcar (lambda (x1 x2 v) 456 | (create-element "div" (if horizontal :|style.width| :|style.height|) (format nil "~A%" (* 100 (- x2 x1))) 457 | (if horizontal :|style.height| :|style.width|) "100%" 458 | :|style.overflow| "visible" 459 | :|style.position| "relative" 460 | :append-element (create-element "div" (if horizontal :|style.width| :|style.height|) "0px" 461 | (if horizontal :|style.height| :|style.width|) "0.5em" 462 | :|style.position| "absolute" 463 | (if horizontal :|style.right| :|style.bottom|) "-0.5px" 464 | (if horizontal :|style.borderRight| :|style.borderBottom|) "1px solid black" 465 | (case pos 466 | (:left :|style.right|) 467 | (:right :|style.left|) 468 | (:top :|style.bottom|) 469 | (:bottom :|style.top|)) 0) 470 | :append-element (create-element "div" :|innerHTML| (format nil "~A" (trnk v delta)) 471 | (if horizontal :|style.width| :|style.height|) "max-content" 472 | (if horizontal :|style.left| :|style.top|) "100%" 473 | :|style.translate| (format nil "~A ~A" 474 | (if horizontal 475 | (if (< v 0) 476 | "calc(-50% - 0.2em)" 477 | "-50%") 478 | "0") 479 | (if horizontal "0" "-50%")) 480 | :|style.position| "relative" 481 | (case pos 482 | (:left :|style.paddingRight|) 483 | (:right :|style.paddingLeft|) 484 | (:top :|style.paddingBottom|) 485 | (:bottom :|style.paddingTop|)) (if horizontal "0.5em" "0.6em") 486 | :|style.textAlign| (case pos 487 | (:left "right") 488 | (:right "left") 489 | (:top "bottom") 490 | (:bottom "top"))))) 491 | 492 | (cons 0 tick-pos) 493 | tick-pos 494 | tick-val))))))) 495 | 496 | (defmethod-f render-widget ((p plot)) 497 | (setf (slot-value p 'root) 498 | (let* ((g (parent p)) 499 | (xmin (xmin g)) 500 | (xmax (xmax g)) 501 | (ymin (ymin g)) 502 | (ymax (ymax g))) 503 | (make-svg :|viewBox| (format nil "~A ~A ~A ~A" xmin ymin (- xmax xmin) (- ymax ymin)) 504 | :|style.width| "100%" 505 | :|style.height| "100%" 506 | :|style.left| "0" 507 | :|style.top| "0" 508 | :|style.display| "block" 509 | :|style.position| "absolute" 510 | :|preserveAspectRatio| "none" 511 | (make-curve p))))) 512 | 513 | 514 | ;;;;;;;;;;;;;;;; redraw ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 515 | 516 | (defgeneric-f redraw (omg-widget)) 517 | 518 | (defmethod-f redraw ((w omg-widget)) 519 | (if (slot-boundp w 'root) 520 | (with-slots (root) w 521 | (let* ((old-root root) 522 | (parent (parent-element root))) 523 | (setf root (render-widget w)) 524 | (when (and old-root 525 | (jscl::oget old-root "isConnected") 526 | (not (eql old-root root))) 527 | ((jscl::oget parent "insertBefore") root old-root) 528 | (remove-element old-root))) 529 | root))) 530 | 531 | ;;;;;;;;;;;;;; editable-field ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 532 | 533 | (defmethod-f to-edit-state ((w editable-field)) 534 | (let ((ok-button (create-element "button" :|innerHTML| "update" 535 | :|style.marginLeft| "1em")) 536 | (cancel-button (create-element "button" :|innerHTML| "cancel" 537 | :|style.marginLeft| "1em")) 538 | (edit-fld (create-element "input" :|type| "text" 539 | :|value| (val w) 540 | :|size| (input-size w)))) 541 | (setf (jscl::oget ok-button "onclick") 542 | (lambda (ev) 543 | (let ((res (funcall (ok-callback w) (jscl::oget edit-fld "value")))) 544 | (if res 545 | (progn 546 | (setf (slot-value w 'value) res) 547 | (to-show-state w)))))) 548 | (setf (jscl::oget cancel-button "onclick") 549 | (lambda (ev) 550 | (to-show-state w) 551 | (if (cancel-callback w) (funcall (cancel-callback w) w)))) 552 | (setf (slot-value w 'edt-blk) 553 | (create-element "span" :|style.display| "inline-block" 554 | :append-elements `(,edit-fld ,cancel-button ,ok-button))) 555 | (setf (jscl::oget (root w) "style" "display") "none") 556 | ((jscl::oget (parent-element (root w)) "insertBefore") (edt-blk w) (root w)) 557 | ((jscl::oget edit-fld "focus")))) 558 | 559 | (defmethod-f to-show-state ((w editable-field)) 560 | (setf (jscl::oget (root w) "innerHTML" ) (val w)) 561 | (setf (jscl::oget (root w) "style" "display") "inline-block") 562 | (if (edt-blk w) (remove-element (edt-blk w)))) 563 | 564 | ;;;;;;;;;;;;;; modal-dialog-window ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 565 | 566 | (defmethod-f close ((w modal-dialog-window)) 567 | (remove-element (mdw-curtain w)) 568 | (remove-element (root w))) 569 | 570 | ;;;;;;;;;;;;;; progress-bar ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 571 | 572 | (defmethod-f set-progress ((b progress-bar) val) 573 | (setf (slot-value b 'value) (min 1 (max 0 val))) 574 | (setf (jscl::oget (bar b) "style" "width") (format nil "~A%" (* 100 (value b)))))0 575 | 576 | ;;;;;;;;;;;;;; list-view ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 577 | 578 | (defmethod-f initialize-instance :after ((l list-view) &key &rest args) 579 | (sync-data l)) 580 | 581 | (defmethod-r elements-length ((l list-view)) 582 | (length (elements l))) 583 | 584 | (defmethod-r get-elements ((l list-view) from to) 585 | (subseq (elements l) from to)) 586 | 587 | (defmethod-r get-element ((l list-view) num) 588 | (nth num (elements l))) 589 | 590 | (defmethod-f sync-data :after ((l list-view)) 591 | (setf (slot-value l 'f-elements) 592 | (let* ((cs (transfer-chunk l)) 593 | (ps (current-position l)) 594 | (start (max 0 (- ps cs))) 595 | (el (elements-length l)) 596 | (end (min (- el 1) (+ ps cs cs))) 597 | (iitms (get-elements l start (+ end 1))) 598 | (ec (list-view-element-class l))) 599 | (append (loop for i from 0 below start collect 600 | (make-instance ec :pos i)) 601 | (loop for i from start below (+ end 1) collect 602 | (make-instance ec :pos i :loaded (nth (- i start) iitms))) 603 | (loop for i from (+ end 1) below el collect 604 | (make-instance ec :pos i))))) 605 | (redraw l)) 606 | 607 | (defmethod-f onscroll ((l list-view) &optional (cdl (f-elements l)) first-passed) 608 | (if cdl 609 | (let* ((eh (jscl::oget (root (car cdl)) "clientHeight")) 610 | (tc (transfer-chunk l)) 611 | (scroll-top (jscl::oget (parent-element (root l)) "scrollTop")) 612 | (ofs (- scroll-top (* 3 tc eh))) 613 | (bot (+ ofs (jscl::oget (parent-element (root l)) "clientHeight") (* 3 tc eh))) 614 | (bnd (jscl::oget ((jscl::oget (parent-element (root l)) "getBoundingClientRect")) "top")) 615 | (stk nil) 616 | (rem nil) 617 | (first-el nil)) 618 | (loop for el on cdl do 619 | (let* ((e (car el)) 620 | (r (root e)) 621 | (rtop (- (jscl::oget r "offsetTop") bnd))) 622 | (setf rem el) 623 | (if (and (> rtop (- scroll-top bnd)) (not first-el)) 624 | (setf first-el (pos e))) 625 | (if (> rtop bot) 626 | (loop-finish) 627 | (if (and (>= rtop ofs) 628 | (not (loaded e))) 629 | (progn 630 | (push e stk) 631 | (if (>= (length stk) (transfer-chunk l)) 632 | (loop-finish))))))) 633 | (if (and (not first-passed) first-el) 634 | (setf (slot-value l 'current-position) first-el)) 635 | (if stk 636 | (map nil 637 | (lambda (e i) 638 | (setf (slot-value e 'loaded) i) 639 | (redraw e)) 640 | (reverse stk) 641 | (get-elements l (pos (car (last stk))) (+ 1 (pos (car stk)))))) 642 | (if (and stk rem) (execute-after 0.01 (lambda () (onscroll l rem first-el))))))) 643 | 644 | (defmethod-f sync-slot :after ((l list-view) slot) 645 | (if (equal slot 'elements) 646 | (redraw l))) 647 | 648 | ;;;;;;;;;;;;;; list-view ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 649 | 650 | (defgeneric make-curve (p)) 651 | 652 | (defmethod-f make-curve ((p plot)) 653 | (error "Please subclass plot and define the make-curve method!")) 654 | 655 | (defmethod-f make-curve ((p tabular-plot)) 656 | (let* ((g (parent p)) 657 | (ymin (ymin g)) 658 | (ymax (ymax g)) 659 | (tbl (table p))) 660 | `(path :|stroke| ,(color p) 661 | :|stroke-width| "1px" 662 | :|vector-effect| "non-scaling-stroke" 663 | :|fill| "none" 664 | :|d| ,(apply #'jscl::concat 665 | (cons (format nil "M~A,~A " (caar tbl) (+ ymin (- ymax (cdar tbl)))) 666 | (loop for i in (cdr tbl) collect 667 | (format nil "L~A,~A " (car i) (+ ymin (- ymax (cdr i)))))))))) 668 | 669 | (defmethod-f make-curve ((p func-plot)) 670 | (let* ((g (parent p)) 671 | (xmin (xmin g)) 672 | (xmax (xmax g)) 673 | (ymin (ymin g)) 674 | (ymax (ymax g)) 675 | (grf (graph g)) 676 | (wi (jscl::oget grf "clientWidth")) 677 | (he (jscl::oget grf "clientWidth"))) 678 | (setf (slot-value p 'last-ymin) 679 | (setf (slot-value p 'last-ymax) 680 | (funcall (func p) xmin))) 681 | `(path :|stroke| ,(color p) 682 | :|stroke-width| "1px" 683 | :|vector-effect| "non-scaling-stroke" 684 | :|fill| "none" 685 | :|d| ,(apply #'jscl::concat 686 | (cons (format nil "M~A,~A " xmin (+ ymin (- ymax (funcall (func p) xmin)))) 687 | (loop for i from 1 to wi collect 688 | (let* ((x (+ xmin (* (- xmax xmin) (/ i wi)))) 689 | (f (funcall (func p) x))) 690 | (setf (slot-value p 'last-ymin) (jsmin f (last-ymin p))) 691 | (setf (slot-value p 'last-ymax) (jsmax f (last-ymax p))) 692 | (format nil "L~A,~A " x (+ ymin (- ymax f)))))))))) 693 | 694 | (defmethod-f make-curve ((p matrix-plot)) 695 | (let* ((g (parent p)) 696 | (ymin (ymin g)) 697 | (ymax (ymax g)) 698 | (canv (create-element "canvas" :|width| (nx p) 699 | :|height| (ny p))) 700 | (ctx ((jscl::oget canv "getContext") "2d")) 701 | (idat ((jscl::oget ctx "getImageData") 0 0 (nx p) (ny p))) 702 | (dat (jscl::oget idat "data")) 703 | (mt (matrix p)) 704 | (nx (nx p)) 705 | (ny (ny p)) 706 | (min-cf (if (norm p) 707 | (loop for i below (* nx ny) minimize (aref mt i)) 708 | 0.0)) 709 | (max-cf (if (norm p) 710 | (loop for i below (* nx ny) maximize (aref mt i)) 711 | 1.0)) 712 | (delta-cf (if (and (norm p) (< min-cf max-cf)) 713 | (/ 1.0 (- max-cf min-cf)) 714 | 1.0))) 715 | (loop for i below nx do 716 | (loop for j below ny do 717 | (let* ((adr (+ i (* nx j))) 718 | (colors (funcall (palette p) 719 | (* delta-cf (- (aref mt adr) min-cf)))) 720 | (idx (* 4 adr))) 721 | (setf (aref dat (+ idx 3)) 255) 722 | (loop for o below 3 do 723 | (setf (aref dat (+ idx o)) 724 | (* 255 (- 1.0 (nth o colors)))))))) 725 | ((jscl::oget ctx "putImageData") idat 0 0) 726 | `(image :|width| ,(- (xmax p) (xmin p)) 727 | :|height| ,(- (ymax p) (ymin p)) 728 | :|x| ,(xmin p) 729 | :|y| ,(- (+ (ymax g) (ymin g)) (ymax p)) 730 | :|preserveAspectRatio| "none" 731 | :|style.imageRendering| "pixelated" 732 | ; :|transform| ,(format nil "translate(~A ~A)" (xmin p) (ymin p)) 733 | :|href| ,((jscl::oget canv "toDataURL") "image/bmp")))) 734 | 735 | (defgeneric xmin (p)) 736 | (defgeneric xmax (p)) 737 | (defgeneric ymin (p)) 738 | (defgeneric ymax (p)) 739 | 740 | (defmethod-f xmin ((p plot)) 741 | (xmin (parent p))) 742 | 743 | (defmethod-f xmax ((p plot)) 744 | (xmax (parent p))) 745 | 746 | (defmethod-f ymin ((p plot)) 747 | (ymin (parent p))) 748 | 749 | (defmethod-f ymax ((p plot)) 750 | (ymax (parent p))) 751 | 752 | (defmethod-f xmin ((p tabular-plot)) 753 | (apply #'min (mapcar #'car (table p)))) 754 | 755 | (defmethod-f xmax ((p tabular-plot)) 756 | (apply #'max (mapcar #'car (table p)))) 757 | 758 | (defmethod-f ymin ((p tabular-plot)) 759 | (apply #'min (mapcar #'cdr (table p)))) 760 | 761 | (defmethod-f ymax ((p tabular-plot)) 762 | (apply #'max (mapcar #'cdr (table p)))) 763 | 764 | (defmethod-f ymin ((p func-plot)) 765 | (if (last-ymin p) 766 | (last-ymin p) 767 | (ymin (parent p)))) 768 | 769 | (defmethod-f ymax ((p func-plot)) 770 | (if (last-ymax p) 771 | (last-ymax p) 772 | (ymax (parent p)))) 773 | 774 | (defmethod-f nx ((p matrix-plot)) 775 | (car (array-dimensions (matrix p)))) 776 | 777 | (defmethod-f ny ((p matrix-plot)) 778 | (cadr (array-dimensions (matrix p)))) 779 | 780 | (defmethod-f add-plot ((g graph) (p plot) &key rescale) 781 | (if (position p (plots g)) 782 | (remove-element (root p))) 783 | (setf (slot-value p 'parent) g) 784 | (pushnew p (slot-value g 'plots)) 785 | (if rescale 786 | (setf (slot-value g 'need-rescale) t)) 787 | (if (slot-boundp g 'graph) 788 | (ensure-element (graph g) 789 | (if (not (jscl::oget (root p) "isConnected")) 790 | (append-element (render-widget p) (graph g))) 791 | (rescale-auto g)))) 792 | 793 | (defmethod-f remove-plot ((p plot)) 794 | (setf (slot-value (parent p) 'plots) 795 | (loop for pl in (plots (parent p)) when (not (eql p pl)) collect pl)) 796 | (if (and (root p) (jscl::oget (root p) "isConnected")) 797 | (remove-element (root p)))) 798 | 799 | (defmethod-f remove-all-plots ((g graph)) 800 | (map nil 801 | (lambda (p) 802 | (if (and (root p) (jscl::oget (root p) "isConnected")) 803 | (remove-element (root p)))) 804 | (plots g)) 805 | (setf (slot-value g 'plots) (list)) 806 | (redraw g)) 807 | 808 | (defmethod-f rescale ((g graph) &key xmin xmax ymin ymax xdelta ydelta) 809 | (macrolet ((upd (&rest vl) 810 | `(progn 811 | ,@(mapcar 812 | (lambda (v) 813 | `(if ,v (setf (slot-value g ',v) ,v))) 814 | vl)))) 815 | (upd xmin xmax ymin ymax xdelta ydelta) 816 | (redraw g))) 817 | 818 | (defmethod-f rescale-auto ((g graph)) 819 | (if (need-rescale g) 820 | (let* ((plots (plots g)) 821 | (xmin (apply #'min (mapcar #'xmin plots))) 822 | (xmax (apply #'max (mapcar #'xmax plots))) 823 | (ymin (apply #'min (mapcar #'ymin plots))) 824 | (ymax (apply #'max (mapcar #'ymax plots))) 825 | (xadd (* 0.01 (- ymax ymin))) 826 | (yadd (* 0.01 (- ymax ymin)))) 827 | (setf (slot-value g 'need-rescale) nil) 828 | (if (and (> xadd 0) (> yadd 0)) 829 | (rescale g :xmin (- xmin xadd) 830 | :xmax (+ xmax xadd) 831 | :ymin (- ymin yadd) 832 | :ymax (+ ymax yadd)))))) 833 | 834 | (defun-f guess-delta (dx nt) 835 | (let* ((delta (/ dx nt)) 836 | (dgl (jsfloor (/ (jsln delta) (jsln 10)))) 837 | (d1 (expt 10 dgl))) 838 | (cond ((< (/ dx d1) (1+ nt)) d1) 839 | ((< (/ dx (* 2 d1)) (1+ nt)) (* 2 d1)) 840 | ((< (/ dx (* 2.5 d1)) (1+ nt)) (* 2.5 d1)) 841 | ((< (/ dx (* 5 d1)) (1+ nt)) (* 5 d1)) 842 | (t (* 10 d1))))) 843 | 844 | (defmethod-f xdelta ((g graph)) 845 | (if (slot-boundp g 'xdelta) 846 | (slot-value g 'xdelta) 847 | (guess-delta (- (xmax g) (xmin g)) (xticks g)))) 848 | 849 | (defmethod-f ydelta ((g graph)) 850 | (if (slot-boundp g 'ydelta) 851 | (slot-value g 'ydelta) 852 | (guess-delta (- (ymax g) (ymin g)) (yticks g)))) 853 | -------------------------------------------------------------------------------- /omgdaemon.lisp: -------------------------------------------------------------------------------- 1 | (defpackage :omgdaemon 2 | (:use cl omg inferior-shell iolib log4cl trivial-dump-core) 3 | (:export *omg-version* ;; Current version name (string) 4 | *omg-last-version* ;; Last production version name (string) 5 | omg-init ;; Init function, called after version startup. 6 | ;; Can be redefined, but must call (setf omg::*port* port) and (start-server) 7 | ;; The port is supplied as a parameter 8 | commit-devel ;; Save development version image 9 | commit-production ;; Commit the image as a production version 10 | make-omg-daemon ;; Dump daemon image, specify proxy port 11 | commit-notify ;; The fucntion called on versions when new production version commited 12 | version-set-sym ;; Set symbol value in server (version) context 13 | +omg-version-cookie+ ;; cookie name 14 | +devel-version+)) ;; development version name 15 | 16 | (in-package :omgdaemon) 17 | 18 | (if (not (find-package :hunchentoot)) 19 | (require :hunchentoot)) 20 | 21 | (defvar *main-st-i* nil) ;; Streams and lock for devel<->daemon communications 22 | (defvar *main-st-o* nil) 23 | (defvar *main-lock* nil) 24 | (defvar *start-lock* nil) 25 | 26 | (defvar +app_prefix+ "omg_app_") ;; Prefix for dumped version images 27 | (defvar +devel-version+ "devel") ;; Name of development version 28 | (defvar +omg-images-path+ (merge-pathnames (make-pathname :directory '(:relative ".omg")))) ;; path to store version images 29 | 30 | (defvar +proxy-chunk-size+ 65536) ;; Buffer size for internal proxy 31 | (defvar +omg-version-cookie+ "OMGVERSION") ;; Internal proxy cookie name 32 | 33 | (defvar +version-cookie-prefix+ (concatenate 'string +omg-version-cookie+ "=")) ;; Cookie prefix, just to speed-up cookie extraction process 34 | 35 | (defvar *forks* (make-hash-table :test #'equal)) ;; Hash to store started versions data: I/O streams and fds, pid, etc 36 | (defvar *start-locks* (make-hash-table :test #'equal)) ;; Hash to store locks, preventing multiple starups of a version 37 | 38 | (defvar *omg-version* +devel-version+) ;; Current version name (string), default to devel 39 | (defvar *omg-last-version* +devel-version+) ;; Current version name (string), default to devel 40 | 41 | (defvar +nl-code+ (char-code #\Newline)) 42 | (defvar +cr-lf+ (trivial-utf-8:string-to-utf-8-bytes (format nil "~C~C" #\Return #\Newline))) 43 | 44 | (defvar *prevent-devel-startup* nil) ;; Setf to T to temporary prevent development version startup, use to avoid race condition while new version commit 45 | 46 | (defun disable-debugger () 47 | (setf *debugger-hook* 48 | (lambda (c h) 49 | (declare (ignore h)) 50 | (log:error "Error found, while debugger is disabled: ~A" c) 51 | (uiop:quit)))) 52 | 53 | (defun omg-init (port) ;; Called at version startup 54 | (setf omg::*port* port) 55 | (restart-server :address "127.0.0.1")) 56 | 57 | (defvar +keyword-pkg+ (find-package "KEYWORD")) 58 | (defvar +nil-str+ (write-to-string (list nil))) 59 | 60 | (defun get-cmd-res (cmd) ;; Eval cmd and return results as a readable string 61 | (let* ((r1 (ignore-errors (multiple-value-list (eval cmd)))) 62 | (res (if r1 r1 (list nil))) 63 | (str (let ((*package* +keyword-pkg+)) (write-to-string res))) 64 | (re1 (ignore-errors 65 | (multiple-value-bind (r l) (read-from-string str) 66 | (declare (ignore r)) 67 | (if (= l (length str)) str +nil-str+))))) 68 | (if re1 re1 +nil-str+))) 69 | 70 | (defparameter *server-set-list* nil) 71 | (defparameter *server-set-sem* nil) 72 | 73 | (defun version-set-sym (var val) ;; Set symbol value in server (version) context 74 | (push (cons var val) *server-set-list*) 75 | (bt:signal-semaphore *server-set-sem*)) 76 | 77 | (defun run-main () ;; toplevel function, called after image startup. Waiting and executing commands from proxy 78 | (setf omg::*giant-hash-lock* (bt:make-lock)) 79 | (let* ((args (uiop:command-line-arguments)) 80 | (fds (mapcar #'parse-integer args)) 81 | (st-i (swank/backend:make-fd-stream (parse-integer (car args)) :UTF-8)) ;; I/O FDs are supplied as parameters 82 | (st-o (swank/backend:make-fd-stream (parse-integer (cadr args)) :UTF-8)) 83 | (eofv (gensym))) 84 | (loop for i from 4 to 2048 when (and (not (position i fds)) (osicat-posix:fd-open-p i)) do 85 | (log:debug "Closing FD ~A" i) 86 | (osicat-posix:close i)) ;; For security reasons closing all unneeded file descriptors 87 | (if (caddr args) ;; For devel version two additional FDs are supplied, to execute commands in proxy process 88 | (setf *main-st-i* (swank/backend:make-fd-stream (parse-integer (caddr args)) :UTF-8))) 89 | (if (cadddr args) 90 | (setf *main-st-o* (swank/backend:make-fd-stream (parse-integer (cadddr args)) :UTF-8))) 91 | (if (cddr args) 92 | (progn 93 | (setf *main-lock* (bt:make-lock)) 94 | (setf *debugger-hook* #'swank:swank-debugger-hook) 95 | (setf *server-set-sem* (bt:make-semaphore)) 96 | (bt:make-thread ;; process symbol-set requests to set symbol values in the server (version) context 97 | (lambda () 98 | (loop do 99 | (progn 100 | (bt:wait-on-semaphore *server-set-sem* :timeout 1) 101 | (if *server-set-list* 102 | (ignore-errors 103 | (progn 104 | (map nil 105 | (lambda (kv) 106 | (set (car kv) (cdr kv))) 107 | *server-set-list*) 108 | (setf *server-set-list* nil))))))))) 109 | (disable-debugger)) 110 | (loop while (and (open-stream-p st-i) (open-stream-p st-o)) do 111 | (let* ((cmd (ignore-errors (read st-i nil eofv))) 112 | (res (if (and cmd (not (equal cmd eofv))) (get-cmd-res cmd)))) 113 | (if (or (not cmd) (equal cmd eofv)) 114 | (uiop:quit)) 115 | (format st-o "~A~%" res) 116 | (force-output st-o))) 117 | (uiop:quit))) 118 | 119 | (defun version-file-path (version) ;; Return a pathname for version image 120 | (if (or (position #\/ version) ;; Version name included into filename, so it cannot include "/" symbol 121 | (= 0 (length version))) 122 | (error (format nil "Invalid version name: \"~A\"" version))) 123 | (merge-pathnames (make-pathname :name (format nil "~A~A" +app_prefix+ version)) +omg-images-path+)) 124 | 125 | (defun version-path-p (path) ;; Check is a path a version image path 126 | (and (equal (directory-namestring path) (directory-namestring +omg-images-path+)) 127 | (equal (ignore-errors (subseq (file-namestring path) 0 (length +app_prefix+))) 128 | +app_prefix+))) 129 | 130 | (defun kill-all-threads () 131 | (loop while (cdr (bt:all-threads)) do 132 | (progn 133 | (map nil 134 | (lambda (thr) 135 | (if (not (equal thr (bt:current-thread))) 136 | (bt:destroy-thread thr))) 137 | (bt:all-threads)) 138 | (if (cdr (bt:all-threads)) 139 | (sleep 1))))) 140 | 141 | (defun makimg (path) ;; save lisp image 142 | (ensure-directories-exist path) 143 | (ignore-errors (kill-server)) 144 | (let* ((ostream (make-string-output-stream :element-type 'extended-char)) 145 | (istream (make-string-input-stream "")) 146 | (*standard-output* ostream) 147 | (*error-output* ostream) 148 | (*standard-input* istream)) 149 | (kill-all-threads) 150 | (save-executable path #'run-main))) 151 | 152 | (defun make-tmp-version (version) ;; construct a temporary version name (used while image dump, just to prevent current image damage) 153 | (format nil "tmp_~A" version)) 154 | 155 | (defun tmp-version-p (version) 156 | (equal "tmp_" (subseq version 0 4))) 157 | 158 | (defun get-version-info (version) ;; Return an alist with version info -- streams, fds, pid, etc. Returns NIL if process not alive. 159 | (let* ((frk (omg::gethash-lock version *forks*)) 160 | (pid (if frk (cdr (assoc :pid frk))))) 161 | (if (and pid (not (ignore-errors (osicat-posix:kill pid 0)))) ;; Check process alive, using signal 0 162 | (progn 163 | (log:info "Process ~A of version ~A died" pid version) 164 | (osicat-posix:waitpid pid) 165 | (return-from get-version-info nil))) 166 | frk)) 167 | 168 | (defun send-cmd-to (version cmd &key no-wait) ;; Send command to the version (or to proxy if version is NIL) and return result(s) 169 | (log:debug "CMD to ~A: ~A" version cmd) 170 | (let ((frk (if version (get-version-info version)))) 171 | (if (or (not version) frk) 172 | (let ((st-i (if frk (cdr (assoc :in frk)) *main-st-i*)) 173 | (st-o (if frk (cdr (assoc :out frk)) *main-st-o*)) 174 | (lock (if frk (cdr (assoc :lock frk)) *main-lock*))) 175 | (bt:with-lock-held (lock) 176 | (format st-o "~A~%" (let ((*package* (find-package "KEYWORD"))) 177 | (write-to-string cmd))) 178 | (force-output st-o) 179 | (if (not no-wait) 180 | (apply #'values (ignore-errors (read st-i)))))) 181 | (error (format nil "Cannot find forked version ~A" version))))) 182 | 183 | (defun commit (version) ;; Save image as a version 184 | (if (not (equal *omg-version* +devel-version+)) 185 | (error "Only development version can be commited!")) 186 | (let ((tmpv (make-tmp-version version))) 187 | (send-cmd-to nil `(wait-for-commit-version ,tmpv ,version ,(osicat-posix:getpid))) 188 | (send-cmd-to nil `(send-cmd-to ,+devel-version+ 189 | '(progn 190 | (setf omgdaemon::*omg-version* ,version) 191 | (makimg (version-file-path ,tmpv))) 192 | :no-wait t)) 193 | (swank:stop-server 4008) 194 | (map nil 195 | (lambda (conn) 196 | (ignore-errors (close (swank::connection.socket-io conn)))) 197 | swank::*connections*))) 198 | 199 | (defun commit-devel () ;; Save development version image 200 | (if (not (equal *omg-version* +devel-version+)) 201 | (error "Only development version can be commited!")) 202 | (commit +devel-version+)) 203 | 204 | (defun get-top-version () ;; Return latest (by write time) production version, or "devel" if no production versions yet 205 | (let* ((files (remove-if 206 | (lambda (path) 207 | (let ((fname (file-namestring path))) 208 | (or (equal (subseq fname (length +app_prefix+)) 209 | +devel-version+) 210 | (tmp-version-p fname)))) 211 | (remove-if-not #'version-path-p 212 | (directory (merge-pathnames (make-pathname :name :wild :type :wild) +omg-images-path+))))) 213 | (tvf (car (sort (mapcar #'cons files (mapcar #'file-write-date files)) #'> :key #'cdr)))) 214 | (if tvf 215 | (subseq (file-namestring (car tvf)) (length +app_prefix+)) 216 | +devel-version+))) 217 | 218 | (defun commit-production () ;; Commit the image as a production version 219 | (if (not (equal *omg-version* +devel-version+)) 220 | (error "Only development version can be commited!")) 221 | (loop for version = (omg::random-string 8) ;; Generate random string as a version name 222 | for path = (version-file-path version) 223 | when (not (probe-file path)) return (commit version))) 224 | 225 | (defun kill-version (version) ;; Kill version process 226 | (let* ((inf (get-version-info version)) 227 | (pid (cdr (assoc :pid inf))) 228 | (fds (cdr (assoc :fds inf)))) 229 | (if inf 230 | (progn 231 | (log:info "Killing version ~A" version) 232 | (bt:make-thread 233 | (lambda () 234 | (if (and (equal version +devel-version+) *prevent-devel-startup*) ;; Don't try to restart development version while image saved 235 | (loop for i below 60 while *prevent-devel-startup* do (sleep 1))) 236 | (loop for i below 5 while (ignore-errors (osicat-posix:kill pid 0)) do (sleep 1)) 237 | (if (ignore-errors (osicat-posix:kill pid 0)) 238 | (progn 239 | (log:info "Version ~A not died, sending SIGTERM!" version) 240 | (ignore-errors (osicat-posix:kill pid osicat-posix:sigterm)) 241 | (loop for i below 5 while (ignore-errors (osicat-posix:kill pid 0)) do (sleep 1)) 242 | (if (get-version-info version) 243 | (progn 244 | (log:info "Version ~A not died, sending SIGKILL!" version) 245 | (ignore-errors (osicat-posix:kill pid osicat-posix:sigkill)))))) 246 | (osicat-posix:waitpid pid) 247 | (log:info "Version ~A killed!" version)) 248 | :name "kill-version") 249 | (log:info "Trying to quit version ~A..." version) 250 | (send-cmd-to version '(bt:make-thread (lambda () (sleep 1) (osicat-posix:exit 0)))) 251 | (map nil #'osicat-posix:close fds) 252 | (remhash version *forks*) 253 | (log:info "Version ~A unregistered" version))))) 254 | 255 | (defun posix-fork () ;; Adopted from https://gitlab.common-lisp.net/qitab/poiu/blob/master/fork.lisp 256 | #+(and allegro os-unix) 257 | (excl.osi:fork) 258 | #+(and clisp os-unix) 259 | (funcall (find-symbol* 'fork "LINUX")) 260 | #+(and clozure os-unix) 261 | (ccl:external-call "fork" :int) 262 | #+(and sbcl os-unix) 263 | (progn 264 | (sb-ext:gc) 265 | (sb-posix:fork)) 266 | #-(and os-unix (or allegro clisp clozure sbcl)) 267 | (error "Fork not implemented, sorry")) 268 | 269 | 270 | (defun version-alive-p (version &key no-cmd) ;; Check if the version up and works. If no-cmd is T, don't try to send test command 271 | (let* ((frk (get-version-info version)) 272 | (port (cdr (assoc :port frk)))) 273 | (and port 274 | (not (find-port:port-open-p port)) 275 | (or no-cmd 276 | (equal 3 (send-cmd-to version '(+ 1 2))))))) 277 | 278 | (defun wait-for-version-startup (version &optional (timeout 30)) ;; Wait up to 30 seconds (default) for version startup 279 | (loop for i below timeout while (not (version-alive-p version)) 280 | do (sleep 1))) 281 | 282 | (defparameter *swank-comm-style* :spawn) 283 | 284 | (defun run-version (version) ;; Start a version 285 | (if (get-version-info version) 286 | (log:info "The version ~A is already alive!" version) 287 | (let* ((path (version-file-path version)) 288 | (is-dev (equal version +devel-version+))) 289 | (if (and is-dev *prevent-devel-startup*) ;; Don't try to restart development version while image saved 290 | (loop for i below 60 while *prevent-devel-startup* do (sleep 1))) 291 | (if (probe-file path) 292 | (let* ((pip1 (multiple-value-list (osicat-posix:pipe))) 293 | (pip2 (multiple-value-list (osicat-posix:pipe))) 294 | (dpip1 (if is-dev (multiple-value-list (osicat-posix:pipe)))) 295 | (dpip2 (if is-dev (multiple-value-list (osicat-posix:pipe)))) 296 | (st-i (swank/backend:make-fd-stream (car pip1) :UTF-8)) 297 | (st-o (swank/backend:make-fd-stream (cadr pip2) :UTF-8)) 298 | (st-di (if is-dev (swank/backend:make-fd-stream (car dpip1) :UTF-8))) 299 | (st-do (if is-dev (swank/backend:make-fd-stream (cadr dpip2) :UTF-8))) 300 | (fds `(,@pip1 ,@pip2 ,@(if is-dev `(,@dpip1 ,@dpip2)))) ;; Collect all FDs which we need to close after process termination) 301 | (name (namestring path)) 302 | (port (find-port:find-port))) 303 | (let ((pid (osicat-posix:fork))) ;; fork-exec, to preserve open FDs 304 | (if (= pid 0) 305 | (let* ((args `(,name 306 | ,(format nil "~A" (car pip2)) 307 | ,(format nil "~A" (cadr pip1)) 308 | ,@(if is-dev 309 | `(,(format nil "~A" (car dpip2)) 310 | ,(format nil "~A" (cadr dpip1)))))) 311 | (argc (+ 2 (length args)))) 312 | (cffi:with-foreign-object (argv :pointer argc) 313 | (iolib/syscalls:bzero argv (* argc (iolib/syscalls:sizeof :pointer))) 314 | (loop for s in args and i below (length args) do (setf (cffi:mem-aref argv :pointer i) (cffi:foreign-string-alloc s))) 315 | (iolib/syscalls:execv name argv))) 316 | (let ((dev-thr (if is-dev ;; for development version we need to start sawnk server and process incoming commands 317 | (bt:make-thread 318 | (lambda () 319 | (wait-for-version-startup version) 320 | (send-cmd-to version 321 | `(progn 322 | (setf swank::*loopback-interface* "0.0.0.0") 323 | (setf swank::*globally-redirect-io* t) 324 | (bt:make-thread 325 | (lambda () 326 | (swank:create-server :port 4008 :dont-close t :style ,*swank-comm-style*))))) 327 | (loop 328 | while (and (open-stream-p st-di) 329 | (open-stream-p st-do)) 330 | do (let* ((eofv (gensym)) 331 | (cmd (ignore-errors (read st-di nil eofv))) 332 | (res (if (and cmd (not (equal cmd eofv))) (get-cmd-res cmd)))) 333 | (if (or (not cmd) (equal cmd eofv)) 334 | (return)) 335 | (format st-do "~A~%" res) 336 | (force-output st-do)))) 337 | :name "devel processing")))) 338 | (unwind-protect 339 | (progn 340 | (setf (omg::gethash-lock version *forks*) 341 | `((:out . ,st-o) 342 | (:in . ,st-i) 343 | (:fds . ,fds) 344 | (:pid . ,pid) 345 | (:port . ,port) 346 | (:lock . ,(bt:make-lock)) ;; The lock needed to prevent parallel command processing (because streams are sequental) 347 | (:fresh . t))) 348 | (send-cmd-to version `(progn 349 | (setf omgdaemon::*omg-version* ,version) ;; Allow the process to know its version 350 | (setf omgdaemon::*omg-last-version* ,(get-top-version)) 351 | (omg-init ,port))) 352 | (if is-dev (send-cmd-to version `(setf hunchentoot:*catch-errors-p* nil))) 353 | (wait-for-version-startup version) 354 | (if (version-alive-p version) 355 | (log:info "Version [~A] spawned!" version) 356 | (error (format nil "Cannot spawn version [~A]" version)))) 357 | (if (not (version-alive-p version)) 358 | (progn 359 | (if dev-thr (bt:destroy-thread dev-thr)) 360 | (kill-version version)))))))) 361 | (error (format nil "Cannot find image file for version ~A" version)))))) 362 | 363 | (defun restart-version (version) 364 | (log:info "Restarting version ~A" version) 365 | (ignore-errors (kill-version version)) 366 | (run-version version)) 367 | 368 | (defun ensure-version-working (version &key no-cmd) ;; If the version not spawned, start it 369 | (bt:with-lock-held ((bt:with-lock-held (*start-lock*) 370 | (let ((l (gethash version *start-locks*))) 371 | (if l l (setf (gethash version *start-locks*) (bt:make-lock)))))) 372 | (let ((tim0 (get-universal-time))) 373 | (loop while (and (not (version-alive-p version :no-cmd no-cmd)) 374 | (< (- (get-universal-time) tim0) 120)) do 375 | (log:info "Version ~A not responding" version) 376 | (when (and (equal version +devel-version+) *prevent-devel-startup*) 377 | (loop for i below 60 while *prevent-devel-startup* do (sleep 1))) 378 | (restart-version version) 379 | (loop for i below 10 380 | while (not (version-alive-p version)) 381 | do (sleep 1))) 382 | (version-alive-p version)))) 383 | 384 | (defun commit-notify (version) 385 | (declare (ignore version))) 386 | 387 | (defun wait-for-commit-version (tv v pid) ;; The function called (on proxy) by development version just before image dump 388 | (bt:make-thread ;; Wait, process with PID termination and tename tv image to v 389 | (lambda () 390 | (setf *prevent-devel-startup* t) 391 | (unwind-protect 392 | (let ((tv-path (version-file-path tv)) 393 | (v-path (version-file-path v)) 394 | (link-ok nil)) 395 | (osicat-posix:waitpid pid) 396 | (when (ensure-version-working tv) 397 | (kill-version tv) 398 | (if (probe-file v-path) (delete-file v-path)) 399 | (rename-file tv-path v-path) 400 | (if (not (equal v +devel-version+)) ;; For production commit, we also have to replace development version 401 | (let ((dev-path (version-file-path +devel-version+))) 402 | (unwind-protect 403 | (progn 404 | (rename-file dev-path tv-path) 405 | (osicat-posix:link v-path dev-path) 406 | (setf link-ok t) 407 | (delete-file tv-path) 408 | (map nil 409 | (lambda (vers) 410 | (bt:make-thread 411 | (lambda () 412 | (log:debug "Sending cmd to: ~A ~A" vers v) 413 | (ignore-errors 414 | (send-cmd-to vers `(ignore-errors 415 | (setf omgdaemon::*omg-last-version* ,v) 416 | (commit-notify ,v))) 417 | (log:debug "Cmd to ~A sent!" vers)))) 418 | (sleep 1)) 419 | (bt:with-lock-held (omg::*giant-hash-lock*) 420 | (loop for vers being each hash-key of *forks* when vers collect vers)))) 421 | (if (not link-ok) 422 | (rename-file tv-path dev-path))))))) 423 | (setf *prevent-devel-startup* nil))) 424 | :name "wait-for-commit") 425 | nil) 426 | 427 | (defmacro buf-append (b1 b2) 428 | (let ((bl1 (gensym)) 429 | (b1t (gensym)) 430 | (b2t (gensym))) 431 | `(let* ((,b1t ,b1) 432 | (,b2t ,b2) 433 | (,bl1 (array-dimension ,b1t 0))) 434 | (adjust-array ,b1t (list (+ ,bl1 (array-dimension ,b2t 0)))) 435 | (replace ,b1t ,b2t :start1 ,bl1) 436 | ,b1t))) 437 | 438 | (defun version-available (version) ;; Check if version image exists 439 | (probe-file (version-file-path version))) 440 | 441 | (defvar *proxy-port* 80) 442 | 443 | (defclass ring-buffer () 444 | (buf 445 | (buf-size :initform +proxy-chunk-size+ 446 | :initarg :size) 447 | (start :initform 0) 448 | (end :initform 0))) 449 | 450 | (defmethod initialize-instance :after ((b ring-buffer) &key &allow-other-keys) 451 | (with-slots (buf buf-size) b 452 | (setf buf (make-array (list buf-size) :element-type '(unsigned-byte 8))))) 453 | 454 | (defmethod get-space ((b ring-buffer) &optional size) 455 | (with-slots (start end buf buf-size) b 456 | (let ((end1 (if (and (= end buf-size) 457 | (> start 0)) 458 | 0 459 | end))) 460 | (if size 461 | (values buf end1 (min (+ end1 size) (if (<= start end1) buf-size (1- start)))) 462 | (values buf end1 (if (<= start end1) buf-size (1- start))))))) 463 | 464 | (defmethod allocate-space ((b ring-buffer) size) 465 | (with-slots (start end buf buf-size) b 466 | (when (< size 0) 467 | (error (format nil "Trying to allocate ~A btyes" size))) 468 | (let ((end1 (if (and (= end buf-size) 469 | (> start 0)) 470 | 0 471 | end))) 472 | (when (> (+ end1 size) (if (<= start end1) buf-size (1- start))) 473 | (error "Buffer overrrun!")) 474 | (setf end (+ end1 size)) 475 | (when (and (= end buf-size) (> start 0)) 476 | (setf end 0))))) 477 | 478 | (defmethod data-available ((b ring-buffer)) 479 | (with-slots (start end buf buf-size) b 480 | (if (<= start end) 481 | (values buf start end) 482 | (values buf start buf-size)))) 483 | 484 | (defmethod deallocate-space ((b ring-buffer) size) 485 | (with-slots (start end buf buf-size) b 486 | (when (< size 0) 487 | (error (format nil "Trying to deallocate ~A btyes" size))) 488 | (when (> (+ start size) (if (<= start end) end buf-size)) 489 | (error "Buffer underrun!")) 490 | (incf start size) 491 | (when (= start buf-size) 492 | (setf start 0) 493 | (when (= end buf-size) 494 | (setf end 0))))) 495 | 496 | (defmethod empty-p ((b ring-buffer)) 497 | (with-slots (start end) b 498 | (= start end))) 499 | 500 | (defmethod full-p ((b ring-buffer)) 501 | (with-slots (start end buf-size) b 502 | (not (if (<= start end) 503 | (or (< end buf-size) 504 | (> start 0)) 505 | (< end start))))) 506 | 507 | ; (defmethod extend-buf ((b ring-buffer)) 508 | ; (with-)) 509 | 510 | (defvar *active-connections* (make-hash-table)) 511 | 512 | (defclass async-conn () 513 | ((write-buf :initform (make-instance 'ring-buffer)) 514 | (read-buf :initform (make-instance 'ring-buffer)) 515 | (base :initarg :base 516 | :initform (error "IOLIB base must be specified!")) 517 | (conn :initarg :conn) 518 | (fin :initform nil) 519 | (connected :initform nil) 520 | (readed :initform 0) 521 | (written :initform 0) 522 | (write-registered :initform nil) 523 | (conn-id :initform "[unknown ip:port]"))) 524 | 525 | (defclass selector-conn (async-conn) 526 | ((last-pos :initform 0) 527 | (cookie-found :initform nil) 528 | (cookie-sent-state :initform :waiting-end-of-hdrs) 529 | (cur-str-len :initform 0) 530 | (version-id))) 531 | 532 | (defmacro wait-for (base pred &rest code) 533 | (let ((fn (gensym)) 534 | (dt (gensym)) 535 | (t0 (gensym))) 536 | `(let ((,dt 0.01) 537 | (t0 (get-universal-time))) 538 | (labels ((,fn () 539 | (if ,pred 540 | (progn ,@code) 541 | (progn 542 | (setf ,dt (min 5.0 (* 1.1 ,dt))) 543 | (if (< (- (get-universal-time) ,t0) 60) 544 | (add-timer ,base #',fn ,dt :one-shot t) 545 | (log:debug "GIVING UP")))))) 546 | (,fn))))) 547 | 548 | (defvar *version-spawn-threads* (make-hash-table :test #'equalp)) 549 | 550 | (defmethod connect-to-version ((c selector-conn) &optional (version (get-top-version))) 551 | (with-slots (cookie-found base last-pos version-id) c 552 | (log:debug "Connecting to version ~A" version) 553 | (setf cookie-found t) 554 | (let ((frk (get-version-info version))) 555 | (when (and (not frk) 556 | (not (gethash version *version-spawn-threads*))) 557 | (setf (gethash version *version-spawn-threads*) 558 | (bt:make-thread 559 | (lambda () 560 | (unwind-protect 561 | (loop for i below 5 until (ignore-errors (ensure-version-working version)) 562 | when (not (version-alive-p version)) 563 | do (let ((v1 (get-top-version))) 564 | (when (not (gethash v1 *version-spawn-threads*))) 565 | (when (not (equal v1 version)) 566 | (log:info "Cannot start version ~A, trying with ~A" version v1) 567 | (remhash version *version-spawn-threads*) 568 | (setf version v1) 569 | (if (gethash v1 *version-spawn-threads*) 570 | (return) 571 | (setf (gethash v1 *version-spawn-threads*) (bt:current-thread)))))) 572 | (remhash version *version-spawn-threads*))) 573 | :name (format nil "starting version ~A" version))))) 574 | (let ((t0 (get-universal-time))) 575 | (wait-for base (or (> (- (get-universal-time) t0) 60) 576 | (get-version-info version)) 577 | (let ((frk (get-version-info version))) 578 | (if frk 579 | (let ((vrs (make-socket :connect :active :address-family :internet :type :stream :ipv6 nil))) 580 | (when (cdr (assoc :fresh frk)) 581 | (sleep 1) 582 | (setf (cdr (assoc :fresh frk)) nil)) 583 | (connect vrs +ipv4-loopback+ :port (cdr (assoc :port frk)) :wait nil) 584 | (wait-for base (socket-connected-p vrs) 585 | (let ((vrs-conn (make-instance 'async-conn :conn vrs :base base))) 586 | (setf version-id version) 587 | (log:debug "Connected to version ~A" version) 588 | (attach c vrs-conn) 589 | (attach vrs-conn c)))) 590 | (log:debug "Cannot wait more for version ~A" version))))))) 591 | 592 | (defmethod push-to ((c selector-conn) buf &key (start 0) (end (array-dimension buf 0))) 593 | (with-slots (cookie-sent-state cur-str-len write-buf version-id) c 594 | (cond ((eql cookie-sent-state :cookie-sent) 595 | (call-next-method)) 596 | ((eql cookie-sent-state :send-a-cookie) 597 | (let* ((cookie-hdr (trivial-utf-8:string-to-utf-8-bytes 598 | (format nil "Set-cookie: ~A~A~C~C" 599 | +version-cookie-prefix+ 600 | version-id 601 | #\return #\newline))) 602 | (cookie-len (array-dimension cookie-hdr 0))) 603 | (multiple-value-bind (buf1 start1 end1) (get-space write-buf cookie-len) 604 | (when (>= (- end1 start1) cookie-len) 605 | (replace buf1 cookie-hdr :start1 start1 :start2 0 :end1 (+ start1 cookie-len) :end2 cookie-len) 606 | (allocate-space write-buf cookie-len) 607 | (register-write c) 608 | (setf cookie-sent-state :cookie-sent))) 609 | (return-from push-to 0))) 610 | ((eql cookie-sent-state :waiting-end-of-hdrs) 611 | (let ((lpos start)) 612 | (multiple-value-bind (buf1 start1 end1) (get-space write-buf (- end start)) 613 | (let ((cw (min (- end start) (- end1 start1)))) 614 | (when (> cw 0) 615 | (let ((end (+ start cw))) 616 | (loop for pos = (position +nl-code+ buf :start lpos :end end) 617 | when (and pos (= pos (1+ lpos))) do 618 | (log:debug "End of headers found, injecting a cookie header") 619 | (replace buf1 buf :start1 start1 :start2 start :end1 (+ start1 (- lpos start)) :end2 (+ start (- lpos start))) 620 | (allocate-space write-buf (- lpos start)) 621 | (register-write c) 622 | (setf cookie-sent-state :send-a-cookie) 623 | (return-from push-to (- lpos start)) 624 | when pos do 625 | (setf lpos (1+ pos)) 626 | (setf cur-str-len 0) 627 | when (not pos) do 628 | (incf cur-str-len (- end lpos)) 629 | (return-from push-to (call-next-method)))))))))))) 630 | 631 | (defmethod try-read :after ((c selector-conn)) 632 | (with-slots (connected last-pos read-buf cookie-found) c 633 | (when (and (not connected) (not cookie-found)) 634 | (if (full-p read-buf) 635 | (close-conn c) 636 | (multiple-value-bind (buf start end) (data-available read-buf) 637 | (declare (ignore start)) 638 | (loop for pos = (position +nl-code+ buf :start last-pos :end end) while pos do 639 | (let* ((s (trivial-utf-8:utf-8-bytes-to-string buf :start last-pos :end (1- pos))) 640 | (cp (position #\: s))) 641 | (when (and cp (string-equal s "cookie" :end1 cp)) 642 | (let* ((p (search +version-cookie-prefix+ s :start2 cp)) 643 | (ps (if p (+ p (length +version-cookie-prefix+)))) 644 | (pe (if p (position #\; s :start ps))) 645 | (pe2 (if pe pe (length s))) 646 | (val (if p (subseq s ps pe2)))) 647 | (when val 648 | (log:debug "Version cookie found: [~A]" val) 649 | (return (connect-to-version c val))))) 650 | (when (= 0 (length s)) 651 | (return (connect-to-version c))) 652 | (setf last-pos (1+ pos))))))))) 653 | 654 | (defmethod attach ((from async-conn) (to async-conn)) 655 | (with-slots (connected) from 656 | (setf connected to) 657 | (feed-connected from))) 658 | 659 | (defmethod close-conn ((c async-conn) &key close abort) 660 | (with-slots (conn base connected written readed conn-id) c 661 | (let ((fd (socket-os-fd conn))) 662 | (ignore-errors (remove-fd-handlers base fd :read t :write t :error t)) 663 | (log:debug "Closing connection to ~A (abort: ~A close: ~A) W: ~A R: ~A" conn-id abort close written readed) 664 | (if abort 665 | (close conn :abort t) 666 | (if close 667 | (close conn)))) 668 | (remhash c *active-connections*))) 669 | 670 | (defmethod try-write ((c async-conn)) 671 | (with-slots (conn base fin write-registered write-buf written conn-id) c 672 | (handler-case 673 | (progn 674 | (if (not (empty-p write-buf)) 675 | (multiple-value-bind (buf start end) (data-available write-buf) 676 | (let ((wb (send-to conn buf :start start :end end))) 677 | (log:debug "~A Written ~A bytes" conn-id wb) 678 | (incf written wb) 679 | (deallocate-space write-buf wb))) 680 | (progn 681 | (ignore-errors (remove-fd-handlers base (socket-os-fd conn) :write t)) 682 | (setf write-registered nil))) 683 | (when (and fin (empty-p write-buf)) 684 | (log:debug "Finalized connection ~A, closing" conn-id) 685 | (close-conn c :close t))) 686 | (socket-connection-reset-error () 687 | (log:debug "Client ~A: connection reset by peer" conn-id) 688 | (close-conn conn)) 689 | (isys:ewouldblock () 690 | (log:debug "write-some-bytes: ewouldblock")) 691 | (isys:epipe () 692 | (log:debug "Client ~A got hangup on write" conn-id) 693 | (close-conn conn))))) 694 | 695 | (defmethod fin ((c async-conn) &optional err) 696 | (with-slots (fin base conn connected read-buf) c 697 | (when (not fin) 698 | (when err (log:debug "~A" err)) 699 | (ignore-errors (remove-fd-handlers base (socket-os-fd conn) :read t)) 700 | (setf fin t) 701 | (try-write c)))) 702 | 703 | (defmethod register-write ((c async-conn)) 704 | (with-slots (conn base write-registered) c 705 | (when (not write-registered) 706 | (when (socket-connected-p conn) 707 | (set-io-handler base (socket-os-fd conn) :write (lambda (&rest args) (declare (ignore args)) (try-write c))) 708 | (setf write-registered t))))) 709 | 710 | (defmethod push-to ((c async-conn) buf &key (start 0) (end (array-dimension buf 0))) 711 | (with-slots (write-buf) c 712 | (multiple-value-bind (buf1 start1 end1) (get-space write-buf (- end start)) 713 | (let ((cw (min (- end start) (- end1 start1)))) 714 | (when (> cw 0) 715 | (replace buf1 buf :start1 start1 :start2 start :end1 (+ start1 cw) :end2 (+ start cw)) 716 | (allocate-space write-buf cw) 717 | (register-write c)) 718 | cw)))) 719 | 720 | (defmethod feed-connected ((c async-conn)) 721 | (with-slots (connected read-buf base fin conn) c 722 | (when (not (empty-p read-buf)) 723 | (let ((conn-dt 0.01) 724 | (t0 (get-universal-time))) 725 | (labels ((schedule-push () 726 | (setf conn-dt (min 5.0 (* conn-dt 1.1))) 727 | (if (< (- (get-universal-time) t0) 60) 728 | (add-timer base #'try-push conn-dt :one-shot t) 729 | (log:debug "GIVING UP 1"))) 730 | (try-push () 731 | (when connected 732 | (with-slots (write-buf) connected 733 | (if (empty-p read-buf) 734 | (when fin 735 | (fin connected)) 736 | (multiple-value-bind (buf start end) (data-available read-buf) 737 | (when (not (full-p write-buf)) 738 | (let ((cw (push-to connected buf :start start :end end))) 739 | (when (> cw 0) 740 | (deallocate-space read-buf cw)))) 741 | (schedule-push))))))) 742 | (try-push)))))) 743 | 744 | (defmethod try-read ((c async-conn)) 745 | (with-slots (fin conn base read-buf connected readed conn-id) c 746 | (when (and (not fin) (not (full-p read-buf))) 747 | (handler-case 748 | (multiple-value-bind (buf start end) (get-space read-buf) 749 | (when (> end start) 750 | (multiple-value-bind (buf rb) (receive-from conn :buffer buf :start start :end end) 751 | (declare (ignore buf)) 752 | (when (= 0 rb) 753 | (error 'end-of-file)) 754 | (log:debug "~A Readed ~A bytes" conn-id rb) 755 | (incf readed rb) 756 | (allocate-space read-buf rb) 757 | (feed-connected c)))) 758 | (socket-connection-reset-error () 759 | (fin c (format nil "Client ~A: connection reset by peer" conn-id))) 760 | (end-of-file () 761 | (fin c (format nil "Client ~A produced end-of-file on a read" conn-id))))))) 762 | 763 | (defmethod initialize-instance :after ((c async-conn) &key &allow-other-keys) 764 | (when (not (slot-boundp c 'conn)) 765 | (error "Connection must be specified!")) 766 | (with-slots (conn base conn-id) c 767 | (set-io-handler base (socket-os-fd conn) :read (lambda (&rest args) (declare (ignore args)) (try-read c))) 768 | (ignore-errors 769 | (multiple-value-bind (ip port) (remote-name conn) 770 | (setf conn-id (format nil "~A:~A" ip port))))) 771 | (setf (omg::gethash-lock c *active-connections*) (get-universal-time))) 772 | 773 | (defun proxy (port) ;; Start a proxy server 774 | (let ((ebase (make-instance 'event-base))) 775 | (unwind-protect 776 | (handler-case 777 | (with-open-socket (srv :connect :passive 778 | :address-family :internet 779 | :type :stream 780 | :ipv6 nil) 781 | ;;:external-format 'unsigned-byte) 782 | (log:debug "Created socket: ~A[fd=~A]" srv (socket-os-fd srv)) 783 | (bind-address srv +ipv4-unspecified+ :port port :reuse-addr t) 784 | (log:debug "Bound socket: ~A" srv) 785 | (listen-on srv :backlog 5) 786 | (log:info "Listening on socket bound to: ~A:~A" (local-host srv) (local-port srv)) 787 | (set-io-handler ebase (socket-os-fd srv) :read 788 | (lambda (fd ev exc) 789 | (declare (ignorable ev exc)) 790 | (let ((conn (accept-connection srv :wait t))) 791 | (log:debug "Connection accepted:" conn) 792 | (wait-for ebase (socket-connected-p conn) 793 | (with-slots (conn-id) (make-instance 'selector-conn :conn conn :base ebase) 794 | (log:info "Connection from ~A" conn-id)))))) 795 | (log:info "Entering loop!") 796 | (loop do (ignore-errors (event-dispatch ebase)) (sleep 1))) 797 | (socket-address-in-use-error () 798 | (log:info "Cannot start omgdaemon serever, address already in use!"))) 799 | (progn 800 | (log:debug "Finalize!") 801 | (loop for c being each hash-key of *active-connections* do (close-conn c :abort t)) 802 | (close ebase))))) 803 | 804 | (defun run-daemon () ;; Toplevel function for daemon startup 805 | (setf omg::*giant-hash-lock* (bt:make-lock)) 806 | (let ((devel-path (version-file-path +devel-version+))) 807 | (if (not (probe-file devel-path)) ;; If this is a first start, dump development version image 808 | (let ((pid (posix-fork))) 809 | (if (> pid 0) 810 | (osicat-posix:waitpid pid) 811 | (makimg devel-path)))) 812 | (bt:start-multiprocessing) 813 | (setf *main-lock* (bt:make-lock)) 814 | (setf *start-lock* (bt:make-lock)) 815 | (loop while (not (ensure-version-working +devel-version+))) 816 | (disable-debugger) 817 | (loop do (proxy *proxy-port*) do 818 | (log:info "Proxy exited, restarting...") 819 | (sleep 1)))) 820 | 821 | (defun make-omg-daemon (port &key (swank-comm-style :spawn)) ;; Dump daemon image, specify proxy port 822 | (swank-loader:init 823 | :delete nil ; delete any existing SWANK packages 824 | :reload nil ; reload SWANK, even if the SWANK package already exists 825 | :load-contribs nil) 826 | (setf *proxy-port* port) 827 | (setf swank::*globally-redirect-io* t) 828 | (setf *swank-comm-style* swank-comm-style) 829 | (loop for i below 20 ;; Wait for swank shutdown 830 | while (position-if (lambda (s) (search "swank" s :test #'char-equal)) (mapcar #'bt:thread-name (bt:all-threads))) 831 | do (progn 832 | (log:info "Waiting for swank shutdown...") 833 | (sleep 1))) 834 | (if (position-if (lambda (s) (search "swank" s :test #'char-equal)) (mapcar #'bt:thread-name (bt:all-threads))) 835 | (log:info "SWANK NOT DEAD!!1111")) 836 | (kill-all-threads) 837 | (disable-debugger) 838 | (save-executable (merge-pathnames (make-pathname :name "omgdaemon")) #'run-daemon)) 839 | 840 | (defun make-docker-image (&key (tag 'omgdaemon) (sbcl-version "2.5.3")) 841 | (with-input-from-string 842 | (fd (format nil "FROM debian 843 | RUN apt-get update && apt-get dist-upgrade -y 844 | RUN apt-get install -y sbcl cl-quicklisp git build-essential ziproxy libzstd-dev libfixposix-dev 845 | RUN cd /root && git clone -b sbcl-~A https://git.code.sf.net/p/sbcl/sbcl sbcl-sbcl &&\\ 846 | cd sbcl-sbcl && ./make.sh --fancy --prefix=/usr && ./install.sh && cd / &&\\ 847 | rm -fr /root/sbcl-sbcl 848 | RUN adduser omg 849 | RUN su -l omg -c 'ziproxy -d ; sbcl --load \"/usr/share/common-lisp/source/quicklisp/quicklisp.lisp\" \\ 850 | --eval \"(quicklisp-quickstart:install :proxy \\\"http://127.0.0.1:8080/\\\")\" --non-interactive' 851 | RUN su -l omg -c 'mkdir -p /home/omg/quicklisp/local-projects && cd /home/omg/quicklisp/local-projects &&\\ 852 | git clone --recurse-submodules https://github.com/hemml/OMGlib.git' 853 | RUN su -l omg -c 'ziproxy -d ; cd /home/omg && sbcl --eval \"(load \\\"/home/omg/quicklisp/setup.lisp\\\")\"\\ 854 | --eval \"(ql:quickload :omgdaemon)\" --eval \"(omgdaemon:make-omg-daemon 8081)\" --non-interactive' 855 | EXPOSE 8081 4008 856 | CMD ziproxy -d ; while true; do su -l omg -c 'cd /home/omg && ./omgdaemon' ; sleep 1 ; done" sbcl-version)) 857 | (run `(docker build :tag ,tag :pull :no-cache -) :input fd))) 858 | 859 | (defun update-omg () 860 | (run '(and (cd "/home/omg/quicklisp/local-projects/OMGlib") 861 | (git pull :rebase))) 862 | (require :omg)) 863 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OMGlib 2 | 3 | ## A Common Lisp library to build fully dynamic web interfaces 4 | 5 | The main idea of this library is to vanish a border between frontend and backend as much as possible. You can develop a CL application using REPL and SLIME on a backend, but some of you functions and macros can be declared as _browser-side_ (_b-s_) with `defun-f` and `defmacro-f` respectively: 6 | 7 | ``` 8 | (require :omg) 9 | (defpackage mytest (:use cl omg)) 10 | (in-package :mytest) 11 | (defun-f js-add (x y) 12 | (+ x y)) ;; this code will be executed in a browser 13 | ``` 14 | 15 | The `(start-server)` function starts `clack` web server on default port 7500 (can be changed by setting `omg::*port*` variable). Now, in the html-code you can inject the following line: 16 | 17 | ``` 18 | 19 | ``` 20 | 21 | or just open a page (a blank page with js-injection code). 22 | 23 | Now you call a browser-side function, just executing it in REPL, for example: 24 | 25 | ``` 26 | MYTEST> (js-add 1 2) 27 | ;; (3) 28 | ``` 29 | 30 | The function call will be converted to javascript with [JSCL](https://github.com/jscl-project/jscl) and sent to the browser via websocket, where the code will be executed and result will be returned to the backend. The result in this example will be returned as a list, because we are not specified a session (see below) and the code will be executed in _all_ connected browsers, and the list of result values will be returned. 31 | 32 | The more complicated example you can find in in _example.lisp_ file, where `omgui` package is used to manipulate DOM objects. 33 | 34 | ## OMGUI package 35 | 36 | `OMG` package is all-sufficient and can be used as is to control a frontend. You can execute any JS code on the browser-side using [JSCL](https://github.com/jscl-project/jscl) FFI: 37 | 38 | ``` 39 | (defun-f jslog (&rest args) ;; call console.log(...args) 40 | "Log function for js" 41 | (apply (jscl::oget (jscl::%js-vref "console") "log") args) 42 | nil) 43 | ``` 44 | 45 | But many of useful JS and DOM-manipulating functions are provided by `omgui` package, where you can find the following functions: 46 | 47 | - `(create-element type ...attrs)` - create and return a DOM element (like `document.createElement()`). You can provide attributes in JS notation. For example: 48 | 49 | ``` 50 | (create-element "div" :|innerHTML| "Some text" :|style.fontWeight| "lighter") 51 | ``` 52 | 53 | There is an easy way to append sub-elements to the created one: 54 | 55 | ``` 56 | (create-element "div" 57 | :append-element (create-element "h1" 58 | :append-element "Some text")) 59 | :append-elements element-list 60 | ``` 61 | 62 | Also, it is possible to add custom CSS style to the element: 63 | 64 | ``` 65 | (create-element "div" 66 | :add-style ":hover {cursor:pointer;}" 67 | ``` 68 | 69 | - `(append-element element &optional parent)` - append DOM `element` as a child to the `parent`. If the `parent` is omitted, the element will be appended to `document`. A text string can be supplied instead of DOM element to add a text node. 70 | 71 | - `(check-element ID)` - check if DOM element with `ID` exists. 72 | 73 | - `(remove-element element)` - remove `element` from DOM. 74 | 75 | - `(element-width)` `(element-height)` - return `element` dimensions in pixels. 76 | 77 | - `(get-element-id element)` - return DOM ID of the `element`. If the element has no ID, a random ID will be created and assigned to it. 78 | 79 | - `(js-get-element-by-id ID)` - get DOM element by `ID` 80 | 81 | - `(parent-element element)` returns a parent of DOM `element` 82 | 83 | - `(page-width)` `(page-height)` `(visible-width)` `(visible-height)` `(visible-left)` `(visible-top)` - get browser page dimensions. 84 | 85 | - `(execute-after time callback)` - execute the `(callback)` after `time`, where `time` specified in seconds. 86 | 87 | - `(jsfloor num)` `(jsfceil num)` `(jsftrunc num)` `(jsmax ...nums)` `(jsmin ...nums)` `(jsrandom)` `(jssin num)` `(jscos num)` `(jstan num)` `(jsasin num)` `(jsacos num)` `(jsatan num)` `(jsatan2 y x)` - JS Math functions `Math.floor()`, `Math.ceil()`, `Math.trunc()`, `Math.max()`, `Math.min()`, `Math.random()`, `Math.sin()`, `Math.cos()`, `Math.tan()`, `Math.asin()`, `Math.acos()`, `Math.atan()` and `Math.atan2()` . 88 | 89 | - `(jssorg array &optional (fn #'>))` - destructive sort an array by compare function fn, return a sorted array 90 | 91 | - `(jslog ...args)` - wrapper for `console.log()` 92 | 93 | - `(prevent-page-close)` `(allow-page-close)` - prevent and allow page closing. 94 | 95 | - `(disable-back-button)` `(enable-back-button)` - disable/enable "back" button in browser. 96 | 97 | - `(disable-scroll)` `(enable-scroll)` - disable/enable page scroll. 98 | 99 | - `(make-js-object :attr1 value1 attr2 value2 ...)` - return a JS dict object with specefied keys and values. 100 | 101 | - `(make-js-function name lambda)` - create an JS function from `lambda` which can be accesssed via `window.name` 102 | 103 | - `(load-js-script url &optional callback)` - load JS script from `url`. The optional `callback` lambda will be executed then the script is succesfully loaded. 104 | 105 | - `(register-hash-cb hash cb)` - register a callback to call when URL hash part changes. With this function you can, for example, automatically mark session as debug one, when you open URL like `http://localhost:7500/#debug`: 106 | 107 | ``` 108 | (defun-r debug-me () 109 | (set-debug-session (current-session-id))) 110 | 111 | (defun-r my-boot () 112 | (register-hash-cb "#debug" (lambda () (debug-me)))) 113 | 114 | (add-to-boot '(my-boot)) 115 | ``` 116 | 117 | If the page is loaded with the registered hash part, the callback will be executed immediately during `register-hash-cb` call. 118 | 119 | - `(browser-case (brosser* code)*)` macro - executing a code depending from user browser. `browser` must be a symbol `:safari`, `:firefox`, `:chrome`, `:opera` or `:edge`. The `T` means other (undetected or unlisted) browser. Examples: 120 | 121 | ``` 122 | (browser-case 123 | (:safari (jslog "Safari detected!")) 124 | ((:firefox :chrome) (jslog "FF or Chrome!")) 125 | (:opera (jslog "Opera!")) 126 | (:edge (jslog "Edge!"))) 127 | (t (jslog "Other browser!")) 128 | 129 | (browser-case 130 | (:safari (safari-specific-code)) ;; will be executed in Safari 131 | (t (default-code)) ;; will be executed in non-Safari browsers 132 | ``` 133 | 134 | - `(gensym2)` - like `(gensym)`, but returns interned symbol. Use for hygienic macros, defined with `defmacro-f`, because all symbols in the macro output must pass write-read chain to be transferred to the host. 135 | 136 | - `(add-style element css)` - add css style to the element 137 | 138 | Example: `(add-style el ":hover {background: #f0f0ff;}")` 139 | 140 | - `(winref name)` - a short form for `(jscl::oget (jscl::%js-vref "window") name))` 141 | 142 | - `(js-parse-float s)` - convert a string to float (browser-side) 143 | 144 | - `(is-nan n)` - check if `n` is NaN (browser-side) 145 | 146 | - `(local-storage key &optional def-val)` `(setf (local-storage key) val)` - interface to the `localStorage` API. Accepts any values, returns strings only. 147 | 148 | - `(session-storage key &optional def-val)` `(setf (session-storage key) val)` - interface to the `sessionStorage` API. Accepts any values, returns strings only. 149 | 150 | - `(show-notification header body &key period check)` - show notification (not a browser notification, just a widget) with header and body (might be strings or dom elements). Supply `period` parameter if you want to show the notification again after some period (in seconds), if user closes it. If function `check` supplied, it will called before notification reappear and if returns `nil` the notification will not be shown anymore. 151 | 152 | Example: 153 | 154 | ``` 155 | (let ((cnt 3)) 156 | (show-notification 157 | (create-element "div" :|innerHTML| "New notofocation!" 158 | :|style.color| "red") 159 | (create-element "div" 160 | :append-element "Click " 161 | :append-element (create-element "a" 162 | :|href| "#" 163 | :|onclick| (lambda (ev) 164 | (remove-element 165 | (find-widget ev "notification")) ;; Just remove notification 166 | ;; The (find-widget) used to get a DOM object of notification widget 167 | nil) 168 | :append-element "here") 169 | :append-element " and see what will happens!") 170 | :period 5 171 | :check (lambda () 172 | (setf cnt (- cnt 1)) 173 | (> cnt 0)))) 174 | ``` 175 | 176 | - `(find-widget ev &optional name)` - the function can be used to get a DOM element of the widget, which received an event `ev`. See `(show-notification)` example. 177 | 178 | - `(ensure-element el &rest body)` - macro, execute `body`, when element `el` become visible (will have non-zero dimensions) 179 | 180 | - `(on-element-remove el callback)` - execute `(callback el)` when element `el` is removed from page 181 | 182 | - `(add-event-handler path callback)`, `(rm-event-handler path callback)` - add and remove global event handlers (use it for "document.body.on..." like events). Example: 183 | 184 | ``` 185 | (defun-f my-callback (ev) 186 | ...) 187 | ... 188 | (add-event-handler "document.body.onmousemove" #'my-callback) 189 | ... 190 | (rm-event-handler "document.body.onmousemove" #'my-callback) 191 | ``` 192 | 193 | - `(add-event-listener event fn &key passive once capture)` - just a wrapper around `addEventListener` 194 | 195 | - `(make-tab-form tab-definitions)` - return DOM element, a form with multiple tabs. The tab definitions must be in the following form: 196 | 197 | ``` 198 | (make-tab-form `(("Tab1 title" . ,tab1-contents-element) 199 | ("Tab2 title" . ,tab2-contents-element))) 200 | ``` 201 | 202 | - `(now)` - returns current time is seconds, but with subsecond precision (a float number) 203 | 204 | - `(with-self var &rest code)` - an useful local macro, allows to use an element itself inside its events, for example: 205 | 206 | ``` 207 | (with-self div 208 | (create-element "div" :|style.padding| "1em" ;; this DOM element will be stored in div variable 209 | :|style.border| "1px solid red" 210 | :append-element (create-element "button" :|innerHTML| "REMOVE ME" 211 | :|onclick| (lambda (ev) (remove-element div))))) ;; remove the div when button clicked 212 | ``` 213 | 214 | - `(with-promise p &key then catch)` - a wrapper around JS Promise interface (a local macro): 215 | 216 | ``` 217 | (with-promise (funcall (jscl::oget (jscl::lisp-to-js (jscl::%js-vref "DeviceMotionEvent")) "requestPermission")) 218 | :then (lambda (res) 219 | (format t "OK: ~A" res)) 220 | :catch (lambda (err) 221 | (format t "ERR: ~A" err))) 222 | ;; Equivalent to: DeviceMotionEvent.requestPermission().then((res)=>{console.log(res)}).catch((err)=>{console.log(err)}) 223 | ``` 224 | 225 | - `(oget-bind vars el keys &rest code)` - a local macro, like `destructuring-bind`, but for js object properties (not setfable): 226 | 227 | ``` 228 | (oget-bind (ax ay) (ev "accelerationIncludingGravity") ("x" "y") 229 | (jslog x y)) ;; print ev.accelerationIncludingGravity.x and ev.accelerationIncludingGravity.y 230 | 231 | (oget-bind (ofs-x ofs-y w h) element ("offsetLeft" "offsetTop" "offsetWidth" "offsetHeight") 232 | ...) ;; binds elelent.offsetLeft, element.offsetTop 233 | ``` 234 | 235 | ### Creating SVG elements 236 | 237 | You can create `SVG` elements with `make-svg` function. The function accepts parameter pairs like `:|attributename| value` for attributes and `(tag-name ...attributes and subtags)` for inner elements. A string parameter will be inserted as a tag body. For example, the following code will return SVG-object with circle: 238 | 239 | ``` 240 | (make-svg :|viewBox| "0 0 100 100" 241 | '(circle :|cx| 50 :|cy| 50 :|r| 50 :|fill| "red")) 242 | ``` 243 | 244 | The following function returns animated spinner: 245 | 246 | ``` 247 | (defun-f make-spinner () 248 | (let* ((width 20) 249 | (ncirc 10) 250 | (r (/ width 2)) 251 | (rc (/ width 6))) 252 | (apply #'make-svg 253 | `(:|viewBox| ,(format nil "0 0 ~A ~A" width width) 254 | ,@(loop for i below ncirc 255 | for ang = (* i (/ (* 2 pi) ncirc)) 256 | collect 257 | `(circle :|cx| ,(+ r (* (- r rc) (jscos ang))) 258 | :|cy| ,(+ r (* -1 (- r rc) (jssin ang))) 259 | :|r| 0 260 | :|fill| "#505050" 261 | (animate :|attributeName| "r" 262 | :|from| ,rc 263 | :|to| ,(* rc (/ 3 (+ ncirc 2))) 264 | :|begin| ,(format nil "~As" (/ (- ncirc i 1) ncirc)) 265 | :|dur| "1s" 266 | :|repeatCount| "indefinite") 267 | (animate :|attributeName| "fill-opacity" 268 | :|from| 1 269 | :|to| 0 270 | :|begin| ,(format nil "~As" (/ (- ncirc i 1) ncirc)) 271 | :|dur| "1s" 272 | :|repeatCount| "indefinite"))))))) 273 | ``` 274 | 275 | To include text nodes use a string: 276 | 277 | ``` 278 | '(text (:|textPath| :|href| "#MyTextCurve" "The curved text!")) 279 | ``` 280 | 281 | ### Modal dialogs 282 | 283 | You can display modal dialog in the browser using the `modal-dialog` macro: 284 | 285 | ``` 286 | (in-debug-session 287 | (print (modal-dialog "Dialog header" 288 | "Dialog text")) 289 | :lines '(:line1 "field 1" 290 | :line2 ("field 2" :default "12345") 291 | :pass ("Password:" :type "password") 292 | :buttons (("OK" #'dialog-ok) 293 | ("Cancel" #'close-current-dialog)))) 294 | ;; ((:line1 "Text in the line 1")) 295 | (:line2 "Text in the line 2") 296 | ``` 297 | 298 | This code will display a modal dialog in debug session and print the result, returned as a `plist` or `nil` if the `Cancel` button was pressed. 299 | 300 | You can provide validation functions for input lines in the form `... :line1 (list "field1" :filter #'func)`, where `#'func` can be a browser-side or RPC function. Also you can provide `(lambda (s) ...)` as a validator function, and even a #'any-backend-function but you will get a security warning in last case. The function must accept a string as an argument and return an (optionally) modified string which will replace the string in the input field. See the _example.lisp_. 301 | 302 | You callbacks can use the following supplementary functions: 303 | 304 | - `(close-current-dialog)` - close current modal dialog, `modal-dialog` will return `nil`. 305 | 306 | - `(dialog-ok)` - close current modal dialog, `modal-dialog` will return data entered in fields. 307 | 308 | - `(get-dialog-data)` - returns `plist` with dialog data, can be called anytime on frontend or backend. 309 | 310 | To make a password input use line `(:mypass "Password" :type "password")` 311 | 312 | ### Yotube player 313 | 314 | - `(add-youtube-player element &key onready onstatechange onqualitychange onratechange onerror onapichange width height video-id)` - add YouTube player on the page. The `video-id` is a string with YouTube video ID; `element` must be parent element for the player; `width` and `height` -- player dimensions; `onready`, `onstatechange`, `onqualitychange`, `onratechange`, `onerror` and `onapichange` - the callbacks. See the `example.lisp`. 315 | 316 | ## Widgets 317 | 318 | The OMG library now includes support of CLOS-based widgets (see `omgwidgets.lisp`). The base class is `omg-widget`, which has slot `root` (and accessor `root`) for the root DOM object. Also a `(render-widget (w omg-widget))` and `(redraw (w omg-widget))` methods are provided. 319 | 320 | The `render-widget` method must create a root DOM and store it in the `root` slot of the widget. The root DOM must be returned. You have to subclass `omg-widget` and provide your own `render-widget` method. 321 | 322 | The `redraw` method can be used to completely rebuild root DOM (by calling `render-widget` method) and replace it on the page. For the most cases you can just use default `redraw` method of `omg-widget` class. 323 | 324 | To make a simple widget with static DOM, just use: 325 | 326 | ``` 327 | (defclass-f my-widget (omg-widget) 328 | ((root :initform (create-element "span" 329 | :|style.textDecorationStyle| "dashed" 330 | :|style.textDecorationLine| "underline" 331 | :|style.textDecorationThicknes| "1.75pt" 332 | :|style.color| "blue" 333 | :|title| "change" 334 | :add-style ":hover {cursor:pointer;}")) 335 | :append "TEST WIDGET" 336 | ``` 337 | 338 | and add it to the page: 339 | 340 | `(append-element (render-widget (make-instance 'my-widget)))` 341 | 342 | ### editable-field 343 | 344 | The editable-field widget shows a value (generally a string) with dashed underline. It is clickable, and shows a text input line to change the value. 345 | Typical use: 346 | 347 | ``` 348 | (append-element 349 | (render-widget 350 | (make-instance 'editable-field 351 | :input-size 5 ;; Size of the input field (when editing) 352 | :value (format nil "~A" *current-value*) ;; Initial value 353 | :ok (lambda (v) ;; The callback is called, when user updates the value, will get a entered value as a 354 | (let ((v1 (js-parse-float v))) ;; parameter and must return a value, which will replace an old one, or 355 | (if (> v1 0) ;; nil to keep old value 356 | v1))) 357 | :cancel (lambda (w) ;; w is an editable-field instance itself 358 | (jslog "User canceled input!"))))) 359 | ``` 360 | 361 | ### modal-dialog-window 362 | 363 | You can subclass this widget to show modal dialogs - elements, which are on top of all elements on the screen and all content below are shaded and unclickable, while wis widget is on the screen. There are some differences from an ordinary widget. First, you have to override `render` method of its subclass with `:after` keyword and modify `root` property to show your content. Second, you have to use `close` method to remove this widget: 364 | 365 | ``` 366 | (defclass-f my-dialog (modal-dialog-window) ()) 367 | 368 | (defmethod-f render-widget :after ((w my-dialog)) 369 | (append-element 370 | (create-element "div" :|style.border| "0.1em solid black" ;; rendering a window content 371 | :|style.border-radius| "0.5em" 372 | :|style.padding| "2em" 373 | :|style.background| "#fffff0" 374 | :append-element (create-element "button" :|innerHTML| "OK" 375 | :|onclick| (lambda (ev) 376 | (close w)))) ;; remove the widget 377 | (root w))) 378 | ``` 379 | 380 | ### progress-bar 381 | 382 | Renders a simple progress bar, you can use `set-progress` method to change it's value: 383 | 384 | ``` 385 | (let ((bar (make-instance 'progress-bar 386 | :bg-style '(:|style.border| "1px solid black" ;; specify the outer frame style 387 | :|style.background| "white" 388 | :|style.padding| "1em") 389 | :width "20em" ;; specify width 390 | :height "2em" ;; and height 391 | :fg-style '(:|style.background| "green") ;; specify a bar style 392 | :value 0.1))) ;; initial value 393 | (append-element (render-widget bar)) ;; show it 394 | (execute-after 3 ;; change the value after 3 sec. 395 | (set-progress bar 0.5))) ;; value must be from 0 to 1 396 | ``` 397 | 398 | ### list-view 399 | 400 | The `list-view` widget is a mirrored class (see below), displaying a list of elements, synchronized with a list on backend. The list offers lazy loading of elements, so you can display a really huge lists and browser will not hang. Each element of the list must be an `omg-widget`. 401 | Use it with the following way: 402 | 403 | ``` 404 | (defclass-f lst-element (omg-widget) 405 | ((pos :initarg :pos 406 | :accessor pos))) 407 | 408 | (defmethod-f render-widget ((el lst-element)) 409 | (setf (slot-value el 'root) 410 | (create-element "div" :|innerHTML| (format nil "Element ~A" (pos el))))) 411 | 412 | (let ((lst (make-instance 'list-view ;; Creating a list-view with 1000 elements 413 | :current-position 100 ;; And default view position is 100 414 | :elements (loop for i below 1000 collect (make-instance 'lst-element :pos i))))) 415 | (append-element (render-widget lst) 416 | ) 417 | ``` 418 | 419 | The `elements` slot of the `list-view` instance holding a list of elements. When you changing it on the backend, call `(sync-data lst)` method on the host to update it in browser(s). 420 | 421 | ### Scientific plots 422 | 423 | You can display 1D and 2D scientific plots. First, draw a coordinate system with `graph` widget: 424 | 425 | ``` 426 | (append-element 427 | (create-element "div" :|style.width| "20em" ;; you have to define an outer element, the graph will fill its bounds 428 | :|style.height| "20em" 429 | :append-element (render-widget (make-instance 'graph :xmin -1 :xmax 1 :ymin 0 :ymax 1)))) 430 | ``` 431 | 432 | The `graph` class has the following slots (with corresponding initargs): 433 | 434 | - `xmin`, `xmax`, `ymin`, `ymax` - graph bounds (user coordinates) 435 | - `xticks`, `yticks` - number of ticks on both axes 436 | - `adjust` - if `T` (default) ticks will be started not from `xmin` and `ymin`, but from nearest round values 437 | - `xdelta`, `ydelta` - if set (by default is not) will be the distance between ticks on corresponding axes 438 | - `xcaption`, `ycaption` - axes labels 439 | - `show-scales` - a list, which may contain keywords `:left`, `:right`, `:top` and `:bottom`, controls which axes scales will be shown 440 | - `preserve-aspect-ratio` - if `T` (by default is `nil`) the graph aspect ratio will be calculated as `(/ (- xmax xmin) (- ymax ymin))`, otherwise the aspect ratio will depend from outer element sizes 441 | 442 | To display data you can add `func-plot`, `tabular-plot` and `matrix-plot` instances to the `graph` via `add-plot` method: 443 | 444 | ``` 445 | (append-element 446 | (create-element "div" :|style.width| "20em" ;; you have to define an outer element, the graph will fill its bounds 447 | :|style.height| "20em" 448 | :append-element 449 | (render-widget 450 | (let ((g (make-instance 'graph :xmin (- pi) :xmax pi :ymin -1 :ymax 1 :preserve-aspect-ratio t :yticks 3))) 451 | (add-plot g (make-instance 'func-plot :func (lambda (x) (jssin x)))) 452 | g)))) 453 | ``` 454 | 455 | All of that classes has a `color` slot (by default is "red"), you can set any color in the form, supported by css. 456 | The when creating a `func-plot` you must provide a `:func` parameter which is a function of single argument, returning a number. 457 | To the `tabular-plot` you must provide a `:table` argument, which is a list of points, each is a `(x . y)` cons. 458 | The `matrix-plot` is to display a 2D map and has the following slots: 459 | 460 | - `matrix` - a matrix to display, a 2D `array` filled by numbers 461 | - `palette` - a function of a single argument (from 0 to 1), returning a list of 3 values (also from 0 to 1), corresponding to reg, green and blue components. By default it is `(lambda (x) (list x x x))` to display b/w graphs. 462 | - `norm` - if `T` (by default is `nil`) the matrix will be shifted and scaled before display to fit a whole (0..1) values range. Very useful if your matrix may contain negative values, or values higher then 1, for example. 463 | 464 | You can use `(remove-plot graph plot)` and `(remove-all-plots graph)` to remove plots from the graph. 465 | To rescale (and redraw) the graph you can use `rescale` method: 466 | 467 | ``` 468 | (rescale graph :xmin new-xmin :xmax new-xmax :ymin new-ymin :ymax new-ymax :xdelta new-xdelta :ydelta new-ydelta) 469 | ``` 470 | 471 | Also, you can use `(rescale-auto graph)` method to rescale the graph to fit containing tabilar- and matrix-plots. 472 | 473 | ## Restrictions 474 | 475 | - **All browser-side functions must be declared in your own package(s), not in CL-USER.** See [How it works](#how-it-works) for details. 476 | 477 | - The library tested in SBCL, but may work in other CL implementations too. The browser code will be executed in JSCL environment, where not all of the standard CL library functions are implemented yet, so you have to respect JCSL limitations on browser-side. 478 | 479 | - All the function parameters and their results must be serializable via standard LISP reader/writer, you cannot return, for example, hash-table object from browser-side function to backend, and put a hash-table as a parameter to browser-side function when calling it on backend. But you can use any allowed data types while you are still on backend or browser-side, if a b-s function will be called only by another b-s functions it can return any objects. Also, you can pass a lambdas as arguments of b-s functions, they will be compiled and executed on browser-side. The backend functions can be passed as parameter to bs-functions, they will work on the backend, while called on brower-side, but you will get a security warning during compilation. 480 | 481 | - DOM and MOP objects are specially serialized on browser-side and passed to backend as `omg::remote-object` instances. They can be sent back and used as parameters within `remote-exec`, for example. The `omg::remote-object` instances are belongs to their sessions, so you cannot send, for example, a DOM object, created in one browser to another. The `omg::remote-object` instances itself are "black boxes" for the backend, you can only store them and pass to browser-side functions as parameters. 482 | 483 | - Lists can be passed as parameters to b-s functions, but they must be implicitly constructed with LIST function, quotes and backquotes cannot be used: 484 | 485 | ``` 486 | (some-bs-function (list a b c)) ;; will work 487 | (some-bs-function '(a b c)) ;; will not work 488 | ``` 489 | 490 | This is because the CL macros cannot distinct function calls and lists, constructed by quotation and quasiquotations. The second line will be treated as `(some-bs-function (a b c))`. 491 | 492 | - There is no error propagation yet between browser and backend. If bs-function causes a error, `nil` will be returned. 493 | 494 | - Hygienic macros _must_ use `gensym2` instead of `gensym` 495 | 496 | ## How it works 497 | 498 | There are the following macros to define browser-side functions, macros and variables: 499 | 500 | - `defun-f` 501 | - `defmacro-f` and `def-local-macro-f` 502 | - `defvar-f` 503 | - `defparameter-f` 504 | 505 | Also you can define RPC-functions, with 506 | 507 | - `defun-r` 508 | 509 | ### Browser-side functions 510 | 511 | `defun-f` has similar syntax as a `defun`, but defines macro with the same name, instead of function. The macro has to check its arguments and evaluate only some of them on backend, passing the rest to the browser-side as is. For example: 512 | 513 | ``` 514 | (some-bs-function "value1" ;; will be passed as is 515 | (some-backend-function) ;; will be evaluated on backend and the result will be passed as a parameter 516 | (another-bs-function) ;; will be passed as is and evaluated on browser-side 517 | #'another-bs-function ;; will be passed as is 518 | (lambda (x) (+ x 1)) ;; will be passed as is and evaluated on browser-side 519 | #'another-backend-function) ;; will be automatically converted to RPC-call, security warning will be printed 520 | ``` 521 | 522 | Just after websocket connection, the browser-side has no declared symbols and functions. When you trying to execute `(some-bs-function)` the symbol `some-bs-function` will be undeclared (in browser) and the library will ask backend for the symbol via synchronous XHR query and will get it as an already compiled to JS code. You can change this behavior by setting the `omg::*local-compile*` variable to `nil`, after that the CL code will be sent as is and compiled in browser before execution. This can provide a bit more compatibility, but code compilation will be much slower. The `omg::*local-compile*` may be changed on-the-fly without browser page reloading. 523 | 524 | The library determines which symbols must be fetched from backend just by their packages: if the package still not exists, it will be created on-the-fly with `defpackage`, `cl` and `jscl` packages will be used. All created packages will be marked as _remote_ and the library will try to fetch unknown symbols from that packages from the backend. This is the reason, why you cannot define browser-side functions just in `CL-USER`. 525 | 526 | ### Browser-side macros 527 | 528 | Browser-side macros are called while code is compiled to JS and must be evaluated on the browser side. So, if you are use such macros while the `omg::*local-compile*` is set to `T` (by default), JSCL will parse the code and execute code of each macro in the browser, get the results and finish the compilation using them. This means that while local compilation is enabled, macro expansion will be rather expensive, especially, if you are using recursive macros. Also, all of the macro output must be transferred from the browser to the host, so you cannot use just `(gensym)` to generate temporary symbols, they are must be interned to be properly transferred. Intern all of your symbols manually or just use helper function `(gensym2)` from OMGUI package. 529 | 530 | You can disable this behavior by setting `omg::*disable-remote-macro*` to `t`, or by using `def-local-macro-f` - in this case the code of macros will be executed locally (on the backend). 531 | 532 | ### Browser-side variables and parameters 533 | 534 | You can declare browser-side variables and parameters with `defvar-f` and `defparameter-f`. They a similar to standard `defvar` and `defparameter`, but the symbols will be available to browser-side functions. This is one-way availability: if the variable will be changed on browser-side, backend will see no update, also, the data will not be updated on other connected browsers. If you are changing such variable or parameter on the backend, the changes will be seen only for newly connected browsers or by browser, which are not fetched they yet. 535 | 536 | ### RPC functions 537 | 538 | Due to security reasons, you can call only some specially marked functions of backend from browser side. You can declare them with `defun-r` macro, which acts as standard `defun`, but places the function name in the list of allowed RPC functions. The RPC function can be simply called on browser-side as any other function. 539 | 540 | Also, you can asynchronously call any RPC function using `async-bind` macro: 541 | 542 | ``` 543 | (async-bind (res (some-rpc-function arg1 arg2)) 544 | (jslog res)) ;; The code will be executed asynchronously after RPC call completion 545 | 546 | (async-bind ((r1 r2 r3) (some-rpc-function arg1 arg2)) ;; multiple return values 547 | (jslog r1 r2 r3)) 548 | ``` 549 | 550 | 551 | ### CLOS 552 | 553 | The preliminary CLOS support is added. You can use `defclass-f`, `defmethod-f` and `defgeneric-f` to create browser-side classes, methods and generics. May be buggy, please report all bugs found. Browser-side methods cannot be invoked directly from the host, use `remote-exec` instead. The CLOS implementation is JSCL is very old and may be obsolete, see JSCL documentation and issues on github. For example there is problems with accessors setf expanders. 554 | 555 | #### Mirrored objects 556 | 557 | You can declare specific classes and create instances on backend, using `defclass-m` macro, which is defined in `omgutil` package: 558 | 559 | ``` 560 | (defclass-m avatar () 561 | ((xxx :initarg :xxx) 562 | (yyy :initarg :yyy 563 | :browser-side t) 564 | (zzz :initarg :zzz 565 | :mirrored t)) 566 | :scope :session) 567 | 568 | (defmethod-r xxx ((obj avatar)) 569 | (slot-value obj 'xxx)) 570 | 571 | (defparameter a (make-instance 'avatar :xxx 10 :yyy 20 :zzz 30)) 572 | 573 | (remote-exec `(jslog (xxx ,q))) 574 | ``` 575 | 576 | Here is a local variable `a`, contains an instance of `avatar` class. This instance can be transferred to the browser-side, where an instance with the same class name will be created. On browser-side only methods marked with `:browser-side t` can be accessible (an they cannot be accessed on backend). All other slots are directly accessible only at backend side. The `defmethod-r` is like `defun-r`, creates a method on the backend, which can be called on browser-side: `(jslog (xxx ,q)))` and executed on the backend with instance `a` in `obj` parameter, so it can be used to access value of the slot `xxx`. 577 | 578 | You also can define browser-side methods with `defmethod-f` and they are completely independed from local methods. So, you can define `(defmethod initialize-instance :after ((obj avatar) ...` and `(defmethod-f initialize-instance :after ((obj avatar) ...` simultaneously, one will work on backend, while another will work on frontends. 579 | 580 | The mirrored class can inherit other classes, both normal an browser-side ones (like `omg-widget`). The backend class will inherit only local classes from the given list, while browser-side will inherit only classes, declared with `defclass-f` and `defclass-m`. 581 | 582 | Each class can have a `:scope` option defined to increase instance security. If the scope is `:session`, the instance can be used only within a (browser) session, where it was created. If you will try to send the object into browser with different session, a error will be raised. The default scope is `:auto`, which is same as `:session` if the instance was created within a session, and will work with any session, if no current session on instance creation time. Also, you can provide an arbitrary function as a parameter of `:scope`, each instance will work in sessions, where the function returns the same value. For example, you can provide a function, returning current user ID, and your instances will be shared with session, where the same user is logged in. 583 | 584 | **WARNING:** the single backend instance can have multiple (one per session) browser-side siblings, they will be created any time, when you use this instance as a parameter for browser-side function. When you create an instance on backend, you can provide initargs also for browser-side slots, like `:yyy 20` in the example. This parameters will be supplied each time when the new browser-side instance is created. Also, you can hook `initialize-instance` method with `defmethod-f`, to perform data synchronization between browser-side and backend instances, if needed. The library itself don't provide any synchronization service, it will only guarantee the connection between backend and frontend instances. 585 | 586 | Slots marked with `:mirrored t` will present both on backend and browser sides. All instances, created on browser-side, will load values on that slots from the backend. But, only on creation time, and there are no backward (browser-to-backend) synchronization. 587 | 588 | The method `(sync-slot (m-object slot))` can be called both on backend and in a browser to synchronize slot value with backend instance. If it called on backend, instances in all active sessions will be updated. 589 | 590 | #### Data synchronization between objects 591 | 592 | The `OMG` library provides a special m-class `data-sync`, defined in `omgutil` package. This class provides a notification mechanism for browser-side instances of mirrored objects. This class don't provides any real syncronization and even don't specify data storage itself. After each data update, you must call `sync-data` method on backend providing the m-instance as a parameter. If the browser loses it's server connection, the `sync-data` method will be called after reconnection for all instances of `data-sync` which needed. To make it useful, you have to subclass `data-sync` class, providing a data storage slots and addind `sync-data :after` browser-side method, to perform a real data synchronization. 593 | 594 | 595 | ### Sessions 596 | 597 | Each connected browser starts a new _session_ which is determined by unique random symbol - _session ID_. When RPC-function is called from browser-side, it will be executed in the session context, so, it will execute all bs-functions in the specific browser. You can implicitly set the current session by executing a code inside `with-session` macro: 598 | 599 | ``` 600 | (with-session (find-session 'ASDXCASA) ;; find a session object by ID 601 | (some-bs-function)) ;; will be called in session 'ASDXCASA 602 | ``` 603 | 604 | If you are executing bs-function without session, it will be executed in **ALL** connected browsers and a list of results will be returned. 605 | 606 | The library provides some other utility functions to work with sessions: 607 | 608 | - `(set-debug-session session)` - execute this function to mark specific _session_ as **debug**. 609 | - `(in-debug-session code)` - execute a code in the debug session. If there are no active debug session a warning will be printed and code will not executed. 610 | 611 | Sometimes you need to return from RPC function immediately to not block JS execution and do some work in background. In this case use `thread-in-session` macro: 612 | 613 | ``` 614 | (thread-in-session 615 | ;; This code will be executed in a separate thread, but within current session 616 | ) 617 | ``` 618 | 619 | To define global server-side variable, which value will be different for different sessions, use `def-session-var` macro: 620 | 621 | ``` 622 | (def-session-var *search-in-progress* nil) 623 | ``` 624 | 625 | The macro will create a symbol-macro with name `*search-in-progress*` and a hash table to store values for each session. Now you can use `*search-in-progress*` as a normal setf-able variable. 626 | 627 | ### Boot functions 628 | 629 | Just after connection, the some boot code will be executed in browser. You can control this using the following functions: 630 | 631 | - `(add-to-boot code)` - add some code to boot sequence. This function can be called more then once to to codes which will be executed sequentally in the order of addition. The code must be a lisp form, for _example: 632 | 633 | ``` 634 | (add-to-boot '(jslog "Hi!")) ;; print "Hi!" to JS console. 635 | ``` 636 | 637 | If you want to execute some backend code, use RPC call: 638 | 639 | ``` 640 | (defun-r my-boot () 641 | (print "New browser is connected!") 642 | (set-debug-session (current-session-id))) ;; Mark the session as debug 643 | (add-to-boot '(my-boot)) 644 | ``` 645 | 646 | - `(rm-from-boot code)` - remove code from boot sequence. 647 | 648 | - `(set-boot code)` - set a boot code with clearing all of the previous added code 649 | 650 | ### REMOTE-EXEC function 651 | 652 | You can use `(remote-exec cmd [nowait])` function to execute any CL code `cmd` in the browser. This function has optional argument `nowait` - set it to `T` if you are not needed to return value(s) and the function will return nil immediately. If there is a timeout occurred while waiting a response, a error condition will be raised, when you call it within a session context. If no current session is set, the code will be executed in all connected browsers and list of return values will be returned. You can change remote-exec timeout by setting the `omg::*remote-exec-timeout*` (in seconds), which is 600 by default. 653 | 654 | Each time, when timeout occurred in remote-exec, the internal counter in session object is increased. You can obtain this counter value from browser-side with function `(omgutil:get-timeouts)` and reset it with `(omgutil:reset-timeouts)`. This allows you to check, does the server tried to communicate with the browser during disconnection. 655 | 656 | ### Adding a custom HTML into default document body 657 | 658 | The default HTML page returned for "/" just contains the main js script link, but you can add any extra HTML into document body, for example to display "Loading..." message: 659 | 660 | ``` 661 | (add-to-root-html "The page is loading, please wait...") 662 | (add-to-root-head "My application") 663 | (add-to-boot '(remove-element (js-get-element-by-id "loadBanner"))) 664 | ``` 665 | 666 | Also you can use `(set-root-html str)` to set root html with clearing the old one. 667 | 668 | ### User URI handler 669 | 670 | If the library cannot serve http request it will respond with `404` error by default. You can redirect this requests to your function by setting `omg::*user-uri-handler*` variable: 671 | 672 | ``` 673 | (setf omg::*user-uri-handler* 674 | (lambda (env) 675 | (let ((uri (getf env :REQUEST-URI))) 676 | `(200 (:content-type "text/plain") 677 | (,(format nil "The ~A URI was requested." uri)))))) 678 | ``` 679 | 680 | Also you can define a custom responder for a specific path (relative to the `omg::*root-path*`): 681 | 682 | ``` 683 | (add-serve-path "mypage" 684 | `(200 (:content-type "text/html; charset=utf-8") 685 | ("My custom page") 686 | ``` 687 | 688 | ### PWA mode 689 | 690 | The library can be used to create Progressive Web App (PWA), just by adding one single function call: 691 | 692 | ``` 693 | (make-pwa (:name "Application Name" :short-name "Application Short Name" :display "standalone" :theme-color "#000000" :background-color "#ffffff" :icon-path "/path/to/icon/file.png") 694 | ``` 695 | 696 | All of the arguments are optional (default values will be used). Only `.png` `.jpeg` and `.gif` image formats of icon file are accepted. 697 | 698 | ### ServiceWorker 699 | 700 | **WARNING:** The ServiceWorker code is in early experimental state, the ServiceWorker can lose all it context sometimes. This will be fixed later. 701 | 702 | You can install and use ServiceWorker, just create a service-worker object (must be executed on browser-side): 703 | 704 | ``` 705 | (make-instance 'service-worker) 706 | ``` 707 | 708 | Or just execute a code in a service-worker (the service-worker instance will be created automatically, if needed) with the followin macro: 709 | 710 | ``` 711 | (in-service-worker 712 | ((jscl::oget (jscl::%js-vref "self") "console" "log") "Hello!")) 713 | ``` 714 | 715 | **NB:** The ServiceWorker is executed in a separate context, so you cannot use any symbols and functions from your main code. Also, the ServiceWorker cannot use syncronous XHR, so it cannot fetch any symbols from backend. So, when you executing a code, all needed functions will be compiled locally and sent to the browser during a call. This means, for example, what if you update a function, which is referenced in the code inside `in-service-worker` macro, you have to recompile all functions, where `in-service-worker` macro using this function has a place, or refresh browser page to promote the changes to the service worker code. 716 | 717 | You can use ServiceWorker to catch and handle network requests with the following macro: 718 | 719 | ``` 720 | (set-service-worker-uri-handler (uri req event) 721 | (cond ((equal (uri-path uri) "/my-path") 722 | (jslog "Request:" req) 723 | (respond-with "SOME DATA")) 724 | (t (default-action))))) 725 | ``` 726 | 727 | In the following macro the utility functions `jslog`, `respond-with` and `default-action` are pre-defined, for your convenience. You can use this macro multiple times, to add several handlers, just don't forget to call `(default-action)` if the request is not handled. 728 | 729 | ### Classic WebWorker 730 | 731 | **NB:** To use Web Workers you have to open your web-page via SSL. 732 | 733 | You can run (almost) any code in a separate WebWorker threads, utilizing poor JS multiprocessing capabilities. The macro `omgui:run-in-web-worker` doing the job: 734 | 735 | ``` 736 | (run-in-web-worker (make-instance 'classic-worker) 737 | (jslog "I'm in the worker!")) 738 | ``` 739 | 740 | The first parameter is a `classic-worker` instance or `nil`. In the second case a free webworker (if any) will be got from the pool or a new one will be started (and will go into the pool after). The macro returns the `classic-worker` instance itself. 741 | The code inside the macro will be executed in a webworker context, but all global and local variables will be available to it. This is one-way availability, any changes performed in main context (if you are not using the caching, see below) will be visible in workers, but if you modify a variable in a worker, it will not be modified in other contexts. After the modification the variable will be "detached" from the main context and worker will not see any its changes anymore. 742 | 743 | The function `test` will print "3" in console: 744 | ``` 745 | (defparameter-f x 1) 746 | 747 | (defun-f test () 748 | (let ((y 2)) ;; Yes, local variables are also visible! 749 | (run-in-web-worker nil 750 | (jslog (+ x y))))) 751 | ;; Here the execution continues, without waiting for worker code completion 752 | ``` 753 | 754 | To get return values from the webworker, you have to register a callback function with `bind-exit-values-for` macro: 755 | 756 | ``` 757 | (bind-exit-values-for (x y z) 758 | (run-in-web-worker nil 759 | (values 1 2 3))) 760 | (jslog x y z) ;; The "1 2 3" will be printed when the worker ends execution 761 | ``` 762 | 763 | You can call main thread lambdas from a webworker, but you have to register them before with `register-main-lambda` and pass: 764 | 765 | ``` 766 | (let ((l1 (lambda (x y) 767 | (jslog "Adding" x "and" y) ;; This will be printed in main thread 768 | (+ x y)))) 769 | (register-main-lambda l1) 770 | (run-in-web-worker nil 771 | (jslog "The main thread returns:" (funcall l1 1 2)))) 772 | ``` 773 | 774 | Ofcourse, the only way to pass data to such lambda is parameters, it will be executed in real main-thread context, all varaibles, modified in the worker, will not be visible. 775 | 776 | #### Data transferring and caching 777 | 778 | The variables visibility between main thread and webworker is achieved by implicit data transfer from main thread to webworker, when you trying to access a variable. This may be an expensive process when data is large, and there are some limitations. The only numbers, strings, symbols, conses (and lists), arrays and MOP-objects are transferred. Lambdas (except ones, registered with `register-main-lambda`) and DOM-objects will be replaced by `nil`, all other types will cause a error. MOP instances are just transferred as a set of their slots, so a new MOP object will be created in webworker (with `allocate-instance`) and all its slots will be filled by the data. Conses, lists, arrays and strings are re-created each time when transferred, so, if you modify their parts, the modifications will gone if you are not using caching. 779 | 780 | You can cache the data by yourself: 781 | 782 | ``` 783 | (let ((x '(1 2 3 4 5))) 784 | (run-in-web-worker nil 785 | (let ((x x)) ;; The caching, by creating a new variable 786 | (setf (car x) 100) ;; The modification will persist 787 | (format t "~A" x))) ;; (100 2 3 4 5) will be printed as expected 788 | (run-in-web-worker nil 789 | (setf (car x) 100) 790 | (format t "~A" x))) ;; (1 2 3 4 5) will be printed here, because x will be requested each time from the main thread 791 | ``` 792 | 793 | Or you can use `cache-vars` pseudo-function as a first element of the code: 794 | 795 | ``` 796 | (let ((x '(1 2 3 4 5))) 797 | (run-in-web-worker nil 798 | (cache-vars x) ;; Instruct the system to cache x variable 799 | (setf (car x) 100) 800 | (format t "~A" x))) ;; (100 2 3 4 5) will be printed 801 | ``` 802 | 803 | Also you can use `(cache-vars t)` to cache all variables. 804 | 805 | The `classic-worker` instance will have no internal state by default, all variables, cached or not, will be reset each time, when you use the same instance multiple times. You can disable this behavior, by setting `:persistent-cache t` when creating the instance: 806 | 807 | ``` 808 | (let ((ww (make-instance 'classic-worker :persistent-cache t)) 809 | (x 100)) 810 | (bind-exit-values-for () ;; Use just to execute a code when worker completes 811 | (run-in-web-worker ww 812 | (jslog x) ;; 100 will be printed 813 | (setf x 200)) 814 | (progn 815 | (setf x 300) 816 | (run-in-web-worker ww 817 | (jslog x))))) ;; 200 will be printed 818 | ``` 819 | 820 | The caching can improve the performance drastically sometimes. 821 | **NB:** with `:persistent-cache t` ALL variables, even local ones, will be cached and saved within the worker state. If you call the same code next time, it will ignore any changes in local variables. If you want to avoid *permanent* cache of the variable, you can add it to the `(cache-vars)` list. It will be cached temporarely, only while the `run-in-web-worker` code is executing, but not on the next call of the same `run-in-web-worker` block. 822 | 823 | If you can inherit your class from `dont-transfer` superclass, it instances will not be transferred to the webworkers contexts, a `nil` values will be transferred instead. This may be useful, if your objects, which needs to be transferred, references some instances, which is not. 824 | 825 | Also, two useful macros are presented: 826 | 827 | ``` 828 | (when-worker-free ww 829 | (some-code)) ;; The code will be executed when worker will finish the job (if any) 830 | 831 | (when-worker-ready ww 832 | (some-code)) ;; The code will be executed when worker is spawned 833 | ``` 834 | 835 | You can kill the webworker with method `kill`: 836 | 837 | ``` 838 | (bind-exit-values-for () 839 | (run-in-web-worker ww 840 | (some-code)) 841 | (kill ww)) ;; Kill the worker after completion 842 | ``` 843 | 844 | **WARINING:** The WebWorker code is not well tested, so bugs (especially in different browsers) may exists. Use with caution! Also, be careful with main thread lambdas - if such lambda throws an exception, the worker will hang, consuming some CPU permanently (al least in the current Firefox). Chrome has strange issues with massive parallel worker jobs, they are much slower when running in Firefox. All other browsers are not tested yet, sorry. 845 | 846 | ### Binary serialization/deserialization 847 | 848 | The `omgui` package introduces two browser-side functions for serialization/deserialization almost any lisp objects. Now supported object types are `integer` (32 bit), `real` (32 bit), `symbol`, `cons/list`, `vector/array` and `mop-object`. Data stored in `ArrayBuffer`/`SharedArrayBuffer` objects to save it, for example, in `indexedDB`. JS-objects and lambdas are stored as `nil` values. 849 | Example: 850 | 851 | ``` 852 | (let* ((buf (jscl::make-new (winref "ArrayBuffer") (* 1024 1024))) ;; Allocate 1 MB buffer 853 | (len (store-to-buffer my-object buf :start 0))) ;; start offset can be provided, amount of data stored is returned 854 | (format t "Loaded data: ~A (~A bytes used)" (load-from-buffer buf) len)) ;; load data back and show it with amount of used memory in bytes 855 | ``` 856 | 857 | If there is not enough room in the buffer supplied to store an object, `store-to-buffer` will just return a needed size, so you can allocate a 1-byte buffer, call `store-to-buffer`, to determine a needed buffer size, allocate a new buffer of that size and call `store-to-buffer` again. 858 | 859 | **NB:** store/load functions retains object equality, but only within a single store/load calls. So, you can store a list, containing multiple references to one mop-object, for example, and, after loading, all the references in the returned list will point to the same object. But, if you call `load-from-buffer` again, all references will point to another instance in the returned list. 860 | 861 | If you have to store/load huge objects, you may prevent interface freezes by making all the process asynchronous by using `:background`, `progress-cb` abd `final-cb` options of `store-to-buffer` and `load-from-buffer` functions. When you specify `:background t` option, the process will be executed in background with 0.1 sec chunks (you can supply another time chunk value with `:background 0.5` for example), after each chunk finishing the function provided with `progress-cb` will be called with single argm equal to current load/store position (in bytes). When the process is done, `final-cb` function will be called. The arguments will be an `ArrayBuffer` (for store-to-buffer) or the loaded object (for `load-from-buffer`) and the last position (in bytes). 862 | 863 | When you loading a MOP object, which class was changed, new slots will be initialized via `:initform` or `initfunction`. For each loaded MOP-object the method `(mop-object-loaded obj)` will be called, so you can hook it to perform all needed initialization. 864 | 865 | ### indexedDB 866 | 867 | There are some useful macros in `omgui` package to work with IndexedDB: 868 | 869 | `setup-indexed-db` (the code will be executed only when database is not exists): 870 | ``` 871 | (setup-indexed-db (db "MyDatabase") 872 | (make-instance 'idb-object-store :connection db :name "table1")) 873 | (make-instance 'idb-object-store :connection db :name "table2" :key "MyKey" :auto-increment t)) 874 | ``` 875 | 876 | `indexed-db-add` / `indexed-db-put` - add/modify an object to the store: 877 | ``` 878 | (indexed-db-add "MyDatabase" "table1" key val ;; Key must be a string, val can be any object, suitable for binary serialization (see above) 879 | :when-ok (lambda () 880 | (jslog "The data is saved!"))))))))))) 881 | :when-err (lambda () 882 | (jslog "The data is not saved!"))))))))))) 883 | :raw nil ;; If t, the load-from-buffer will not be called and object will be returned as is 884 | ``` 885 | 886 | `indexed-db-get` - get a value for a key: 887 | ``` 888 | (indexed-db-get (val ("MyDatabase" "table1" key raw)) ;; if raw is t, the store-to-buffer will not be called before object saving 889 | (jslog "Value loaded:" val)) ;; will be called asynchronously, when data is retrieved. 890 | ``` 891 | 892 | `indexed-db-delete` - delete a key from the store: 893 | ``` 894 | (indexed-db-delete ("MyDatabase" "table1" key)) 895 | (jslog "The key is deleted!")) ;; will be called asynchronously 896 | ``` 897 | 898 | `indexed-db-get-all-keys` - get e list of all keys in the store 899 | ``` 900 | (indexed-db-get-all-keys (lst ("MyDatabase" "table1")) 901 | (jslog "The keys are:") ;; will be called asynchronously 902 | (map nil #'jslog lst)) 903 | ``` 904 | 905 | `if-idb-key` - execute a code when the key exists/not exists: 906 | ``` 907 | (if-idb-key ("MyDatabase" "table1" key) 908 | (jslog "Key exists!") ;; will be called asynchronously if the key is exists 909 | (jslog "Key not exists!")) ;; will be called asynchronously if the key is not exists 910 | ``` 911 | 912 | ## OMG daemon mode 913 | 914 | **WARNING:** the following functionality is in early alpha version now, it will work only in POSIX compatible environments (Linux, MacOS X). 915 | 916 | OMGlib allows developers to work with code via REPL, but all of the changes are applied immediately, so, you need two copies of your code -- local development version and production one, which is updated less frequently. Each production code update causes a server restart, so all connected clients will lose they connections and will have to reconnect. After the reconnection, browser still has functions from previous version, which may lead to problems. 917 | 918 | OMGlib offers a better way to maintain version updating. The special daemon `omgdaemon` is spawned and works as a reverse-proxy, which accepts http connections and, basing on special cookie `OMGVERSION`, connects clients to specific versions. Here is one special version with name `"devel"`, where developer(s) can do any development works, using swank connection via standard port 4008\. When the version will be good enough to be pushed into production, the `(commit-production)` function is called and lisp image is saved to disk and gets an unique version name. After that, all new connections will be redirected to this version and new `"devel"` version will be spawned again. If there was previous versions with clients connected, they will receive notification (the `(commit-notify new-version)` function will be called) so they can offer version update to the clients. Also, the browser-side function `(ensure-last-version)` can be called at boot-time, to check is it a latest version and perform page reload to proceed to the top version if necessary. 919 | 920 | The following code can be used to work in `omgdaemon` environment: 921 | 922 | ``` 923 | (ql:quickload :omgdaemon) ;; load omgdaemon system 924 | 925 | (defpackage :my-package 926 | (:use cl omg omgui jscl omgdaemon daemonui)) ;; Import omgdaemon 927 | 928 | (defparameter-f *page-shown* nil) 929 | 930 | (defun-f my-boot () ;; this function will be called after the first WebSocket connection 931 | (if (not *page-shown*) ;; The page is just loaded 932 | (progn 933 | (register-hash-cb "#devel" ;; The way to proceed to "devel" version using #devel hash 934 | (lambda () 935 | (if (not (equal (get-my-version) "devel")) ;; If the version is not a "devel" already 936 | (progn 937 | (setf (jscl::oget (jscl::%js-vref "document") "cookie") 938 | (format nil "~A=devel" (get-omg-cookie-name))) ;; set the version cookie 939 | (allow-page-close) 940 | ((jscl::oget (jscl::%js-vref "location") "reload") t))))) ;; Hard reload! 941 | (ensure-last-version) 942 | (setf *page-shown* t) 943 | (init-gui)))) ;; Show page contents 944 | 945 | (defun-f show-commit-notify (cookie-name version) ;; Show a notification if a new version is available 946 | (show-notification 947 | (create-element "div" :|innerHTML| "New version available!" 948 | :|style.color| "red") 949 | (create-element "div" 950 | :append-element "Save you work and click " 951 | :append-element (create-element "a" 952 | :|href| "#" 953 | :|onclick| 954 | (lambda (ev) 955 | (setf (jscl::oget (jscl::%js-vref "document") "cookie") 956 | (format nil "~A=~A" cookie-name version)) 957 | (allow-page-close) 958 | ((jscl::oget (jscl::%js-vref "location") "reload") t) 959 | nil) 960 | :append-element "here") 961 | :append-element " to proceed to new version.") 962 | :period 600) ;; Remind every 10 minutes 963 | nil) 964 | 965 | (defun commit-notify (version) 966 | (remote-exec `(show-commit-notify ,+omg-version-cookie+ ,version)) 967 | nil) 968 | 969 | ;; omg-init will be called after version spawn 970 | 971 | (defvar old-init #'omg-init) ;; Save the default init function 972 | 973 | (defun omg-init (port) 974 | ;; Put here all your initialization -- connect to the database, etc... 975 | (funcall old-init port)) 976 | 977 | (add-to-boot '(my-boot)) ;; Add #'mu-boot to the boot sequence 978 | ``` 979 | 980 | You can use standadrd slime/swank to connect to the `devel` image and perform any REPL work. 981 | 982 | ## Making an `omgdaemon` image 983 | 984 | The `omgdaemon` image can be built with the following command: 985 | 986 | ``` 987 | sbcl --eval "(require :omg)" --eval "(omgdaemon:make-omg-daemon 8080)" 988 | ``` 989 | 990 | where `8080` is a port where proxy will accept HTTP connections. The daemon will store version images in `.omg` subdirectory. 991 | 992 | ## Using docker container 993 | 994 | The most convinient way to run `omgdaemon` is to put it into a docker container. You can build a docker image with the following command: 995 | 996 | ``` 997 | sbcl --eval "(require :omg)" --eval "(omgdaemon::make-docker-image)" --quit 998 | ``` 999 | 1000 | `(omgdaemon::make-docker-image)` accepts two keys - `:tag` for name of the new image (default "omgdaemon") and `:sbcl-version` (default "2.3.1" for now`). The image can be started in the following way to serve on port `7575` on `localhost` and port 4008 for swank-server: 1001 | 1002 | ``` 1003 | docker run -d -p 127.0.0.1:7575:8081 -p 127.0.0.1:4008:4008 omgdaemon 1004 | ``` 1005 | --------------------------------------------------------------------------------