id
int64
0
45.1k
file_name
stringlengths
4
68
file_path
stringlengths
14
193
content
stringlengths
32
9.62M
size
int64
32
9.62M
language
stringclasses
1 value
extension
stringclasses
6 values
total_lines
int64
1
136k
avg_line_length
float64
3
903k
max_line_length
int64
3
4.51M
alphanum_fraction
float64
0
1
repo_name
stringclasses
779 values
repo_stars
int64
0
882
repo_forks
int64
0
108
repo_open_issues
int64
0
90
repo_license
stringclasses
8 values
repo_extraction_date
stringclasses
146 values
sha
stringlengths
64
64
__index_level_0__
int64
0
45.1k
exdup_ids_cmlisp_stkv2
listlengths
1
47
4,270
germinal.asd
jfmcbrayer_germinal/germinal.asd
(in-package :cl-user) (defpackage germinal-asd (:use :cl :asdf)) (in-package :germinal-asd) (defsystem germinal :version "1.0.0" :author "Jason McBrayer" :license "AGPL3" :depends-on ( :alexandria :babel :usocket :usocket-server :bordeaux-threads :cl+ssl :str :trivial-mimes :ppath :osicat :cl-interpol :quri :cl-ppcre :cl-fad :local-time :uax-15 ) :components ((:file "package") (:file "server") (:file "middleware") (:file "util") (:file "classes") ) :description "A Gemini protocol server." )
843
Common Lisp
.asd
34
13.588235
42
0.431931
jfmcbrayer/germinal
40
2
0
AGPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
f02f2dddfccf3a2819a885d18316e4470da8860e65feb1faaa34683776f825ea
4,270
[ -1 ]
4,277
germinal.service
jfmcbrayer_germinal/germinal.service
[Unit] Description=Germinal, a gemini server [Service] ExecStart=/usr/local/share/germinal/germinal.ros Type=simple Restart=always RestartSec=10 User=germinal PrivateTmp=yes NoNewPrivileges=yes ProtectSystem=strict ProtectHome=yes [Install] WantedBy=multi-user.target
271
Common Lisp
.l
14
18.142857
48
0.885827
jfmcbrayer/germinal
40
2
0
AGPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
ec628bd977d2638f1850d1dce21110ff214f07c724a4e041be36a33630a4c610
4,277
[ -1 ]
4,279
germinal.ros
jfmcbrayer_germinal/germinal.ros
#!/bin/sh #|-*- mode:common-lisp -*-|# #| exec ros -Q -- $0 "$@" |# (progn ;;init forms (ros:ensure-asdf) #+quicklisp(ql:quickload '(germinal swank) :silent t) ) (defpackage :ros.script.germinal (:use :cl)) (in-package :ros.script.germinal) (declaim (optimize (debug 3))) (defvar *germinal-server* nil) (defvar *germinal-server-thread* nil) (defvar *swank-server* nil) (setf germinal:*germinal-server-name* "localhost" germinal:*germinal-cert* "localhost.crt" germinal:*germinal-cert-key* "localhost.key" germinal:*germinal-root* "/home/jmcbray/Documents/var-gemini" germinal:*germinal-pathname-blacklist* '(".git" "dont-read-me")) ;; Set default content type for files without a file extension (setf (gethash nil mimes:*mime-db*) "text/gemini") (setf germinal:*germinal-routes* '((".*" . germinal:gemini-serve-file-or-directory))) (defun start-server () (setf *swank-server* (swank:create-server :port 4006 :dont-close t)) (multiple-value-setq (*germinal-server-thread* *germinal-server*) (germinal:start :background t))) (defun stop-server () (when (and *germinal-server-thread* (bt:thread-alive-p *germinal-server-thread*)) (bt:destroy-thread *germinal-server-thread*) (swank:stop-server *swank-server*) (setf *germinal-server* nil) (setf *germinal-server-thread* nil) (setf *swank-server* nil))) (defun restart-server () (stop-server) (start-server)) (defun main (&rest argv) (declare (ignorable argv)) (start-server) (loop do (sleep 10))) ;;; vim: set ft=lisp lisp:
1,579
Common Lisp
.l
46
30.978261
70
0.690289
jfmcbrayer/germinal
40
2
0
AGPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
87ac3b7d05cc78997482fdf44011b267a454daabddaceb0bfdb02cbcd6551e19
4,279
[ -1 ]
4,294
omgdaemon.lisp
hemml_OMGlib/omgdaemon.lisp
(defpackage :omgdaemon (:use cl omg inferior-shell iolib log4cl trivial-dump-core) (:export *omg-version* ;; Current version name (string) *omg-last-version* ;; Last production version name (string) omg-init ;; Init function, called after version startup. ;; Can be redefined, but must call (setf omg::*port* port) and (start-server) ;; The port is supplied as a parameter commit-devel ;; Save development version image commit-production ;; Commit the image as a production version make-omg-daemon ;; Dump daemon image, specify proxy port commit-notify ;; The fucntion called on versions when new production version commited version-set-sym ;; Set symbol value in server (version) context +omg-version-cookie+ ;; cookie name +devel-version+)) ;; development version name (in-package :omgdaemon) (if (not (find-package :hunchentoot)) (require :hunchentoot)) (defvar *main-st-i* nil) ;; Streams and lock for devel<->daemon communications (defvar *main-st-o* nil) (defvar *main-lock* nil) (defvar *start-lock* nil) (defvar +app_prefix+ "omg_app_") ;; Prefix for dumped version images (defvar +devel-version+ "devel") ;; Name of development version (defvar +omg-images-path+ (merge-pathnames (make-pathname :directory '(:relative ".omg")))) ;; path to store version images (defvar +proxy-chunk-size+ 65536) ;; Buffer size for internal proxy (defvar +omg-version-cookie+ "OMGVERSION") ;; Internal proxy cookie name (defvar +version-cookie-prefix+ (concatenate 'string +omg-version-cookie+ "=")) ;; Cookie prefix, just to speed-up cookie extraction process (defvar *forks* (make-hash-table :test #'equal)) ;; Hash to store started versions data: I/O streams and fds, pid, etc (defvar *start-locks* (make-hash-table :test #'equal)) ;; Hash to store locks, preventing multiple starups of a version (defvar *omg-version* +devel-version+) ;; Current version name (string), default to devel (defvar *omg-last-version* +devel-version+) ;; Current version name (string), default to devel (defvar +nl-code+ (char-code #\Newline)) (defvar +cr-lf+ (trivial-utf-8:string-to-utf-8-bytes (format nil "~C~C" #\Return #\Newline))) (defvar *prevent-devel-startup* nil) ;; Setf to T to temporary prevent development version startup, use to avoid race condition while new version commit (defun disable-debugger () (setf *debugger-hook* (lambda (c h) (declare (ignore h)) (log:error "Error found, while debugger is disabled: ~A" c) (uiop:quit)))) (defun omg-init (port) ;; Called at version startup (setf omg::*port* port) (restart-server :address "127.0.0.1")) (defvar +keyword-pkg+ (find-package "KEYWORD")) (defvar +nil-str+ (write-to-string (list nil))) (defun get-cmd-res (cmd) ;; Eval cmd and return results as a readable string (let* ((r1 (ignore-errors (multiple-value-list (eval cmd)))) (res (if r1 r1 (list nil))) (str (let ((*package* +keyword-pkg+)) (write-to-string res))) (re1 (ignore-errors (multiple-value-bind (r l) (read-from-string str) (declare (ignore r)) (if (= l (length str)) str +nil-str+))))) (if re1 re1 +nil-str+))) (defparameter *server-set-list* nil) (defparameter *server-set-sem* nil) (defun version-set-sym (var val) ;; Set symbol value in server (version) context (push (cons var val) *server-set-list*) (bt:signal-semaphore *server-set-sem*)) (defun run-main () ;; toplevel function, called after image startup. Waiting and executing commands from proxy (setf omg::*giant-hash-lock* (bt:make-lock)) (let* ((args (uiop:command-line-arguments)) (fds (mapcar #'parse-integer args)) (st-i (swank/backend:make-fd-stream (parse-integer (car args)) :UTF-8)) ;; I/O FDs are supplied as parameters (st-o (swank/backend:make-fd-stream (parse-integer (cadr args)) :UTF-8)) (eofv (gensym))) (loop for i from 4 to 2048 when (and (not (position i fds)) (osicat-posix:fd-open-p i)) do (log:debug "Closing FD ~A" i) (osicat-posix:close i)) ;; For security reasons closing all unneeded file descriptors (if (caddr args) ;; For devel version two additional FDs are supplied, to execute commands in proxy process (setf *main-st-i* (swank/backend:make-fd-stream (parse-integer (caddr args)) :UTF-8))) (if (cadddr args) (setf *main-st-o* (swank/backend:make-fd-stream (parse-integer (cadddr args)) :UTF-8))) (if (cddr args) (progn (setf *main-lock* (bt:make-lock)) (setf *debugger-hook* #'swank:swank-debugger-hook) (setf *server-set-sem* (bt:make-semaphore)) (bt:make-thread ;; process symbol-set requests to set symbol values in the server (version) context (lambda () (loop do (progn (bt:wait-on-semaphore *server-set-sem* :timeout 1) (if *server-set-list* (ignore-errors (progn (map nil (lambda (kv) (set (car kv) (cdr kv))) *server-set-list*) (setf *server-set-list* nil))))))))) (disable-debugger)) (loop while (and (open-stream-p st-i) (open-stream-p st-o)) do (let* ((cmd (ignore-errors (read st-i nil eofv))) (res (if (and cmd (not (equal cmd eofv))) (get-cmd-res cmd)))) (if (or (not cmd) (equal cmd eofv)) (uiop:quit)) (format st-o "~A~%" res) (force-output st-o))) (uiop:quit))) (defun version-file-path (version) ;; Return a pathname for version image (if (or (position #\/ version) ;; Version name included into filename, so it cannot include "/" symbol (= 0 (length version))) (error (format nil "Invalid version name: \"~A\"" version))) (merge-pathnames (make-pathname :name (format nil "~A~A" +app_prefix+ version)) +omg-images-path+)) (defun version-path-p (path) ;; Check is a path a version image path (and (equal (directory-namestring path) (directory-namestring +omg-images-path+)) (equal (ignore-errors (subseq (file-namestring path) 0 (length +app_prefix+))) +app_prefix+))) (defun kill-all-threads () (loop while (cdr (bt:all-threads)) do (progn (map nil (lambda (thr) (if (not (equal thr (bt:current-thread))) (bt:destroy-thread thr))) (bt:all-threads)) (if (cdr (bt:all-threads)) (sleep 1))))) (defun makimg (path) ;; save lisp image (ensure-directories-exist path) (ignore-errors (kill-server)) (let* ((ostream (make-string-output-stream :element-type 'extended-char)) (istream (make-string-input-stream "")) (*standard-output* ostream) (*error-output* ostream) (*standard-input* istream)) (kill-all-threads) (save-executable path #'run-main))) (defun make-tmp-version (version) ;; construct a temporary version name (used while image dump, just to prevent current image damage) (format nil "tmp_~A" version)) (defun tmp-version-p (version) (equal "tmp_" (subseq version 0 4))) (defun get-version-info (version) ;; Return an alist with version info -- streams, fds, pid, etc. Returns NIL if process not alive. (let* ((frk (omg::gethash-lock version *forks*)) (pid (if frk (cdr (assoc :pid frk))))) (if (and pid (not (ignore-errors (osicat-posix:kill pid 0)))) ;; Check process alive, using signal 0 (progn (log:info "Process ~A of version ~A died" pid version) (osicat-posix:waitpid pid) (return-from get-version-info nil))) frk)) (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) (log:debug "CMD to ~A: ~A" version cmd) (let ((frk (if version (get-version-info version)))) (if (or (not version) frk) (let ((st-i (if frk (cdr (assoc :in frk)) *main-st-i*)) (st-o (if frk (cdr (assoc :out frk)) *main-st-o*)) (lock (if frk (cdr (assoc :lock frk)) *main-lock*))) (bt:with-lock-held (lock) (format st-o "~A~%" (let ((*package* (find-package "KEYWORD"))) (write-to-string cmd))) (force-output st-o) (if (not no-wait) (apply #'values (ignore-errors (read st-i)))))) (error (format nil "Cannot find forked version ~A" version))))) (defun commit (version) ;; Save image as a version (if (not (equal *omg-version* +devel-version+)) (error "Only development version can be commited!")) (let ((tmpv (make-tmp-version version))) (send-cmd-to nil `(wait-for-commit-version ,tmpv ,version ,(osicat-posix:getpid))) (send-cmd-to nil `(send-cmd-to ,+devel-version+ '(progn (setf omgdaemon::*omg-version* ,version) (makimg (version-file-path ,tmpv))) :no-wait t)) (swank:stop-server 4008) (map nil (lambda (conn) (ignore-errors (close (swank::connection.socket-io conn)))) swank::*connections*))) (defun commit-devel () ;; Save development version image (if (not (equal *omg-version* +devel-version+)) (error "Only development version can be commited!")) (commit +devel-version+)) (defun get-top-version () ;; Return latest (by write time) production version, or "devel" if no production versions yet (let* ((files (remove-if (lambda (path) (let ((fname (file-namestring path))) (or (equal (subseq fname (length +app_prefix+)) +devel-version+) (tmp-version-p fname)))) (remove-if-not #'version-path-p (directory (merge-pathnames (make-pathname :name :wild :type :wild) +omg-images-path+))))) (tvf (car (sort (mapcar #'cons files (mapcar #'file-write-date files)) #'> :key #'cdr)))) (if tvf (subseq (file-namestring (car tvf)) (length +app_prefix+)) +devel-version+))) (defun commit-production () ;; Commit the image as a production version (if (not (equal *omg-version* +devel-version+)) (error "Only development version can be commited!")) (loop for version = (omg::random-string 8) ;; Generate random string as a version name for path = (version-file-path version) when (not (probe-file path)) return (commit version))) (defun kill-version (version) ;; Kill version process (let* ((inf (get-version-info version)) (pid (cdr (assoc :pid inf))) (fds (cdr (assoc :fds inf)))) (if inf (progn (log:info "Killing version ~A" version) (bt:make-thread (lambda () (if (and (equal version +devel-version+) *prevent-devel-startup*) ;; Don't try to restart development version while image saved (loop for i below 60 while *prevent-devel-startup* do (sleep 1))) (loop for i below 5 while (ignore-errors (osicat-posix:kill pid 0)) do (sleep 1)) (if (ignore-errors (osicat-posix:kill pid 0)) (progn (log:info "Version ~A not died, sending SIGTERM!" version) (ignore-errors (osicat-posix:kill pid osicat-posix:sigterm)) (loop for i below 5 while (ignore-errors (osicat-posix:kill pid 0)) do (sleep 1)) (if (get-version-info version) (progn (log:info "Version ~A not died, sending SIGKILL!" version) (ignore-errors (osicat-posix:kill pid osicat-posix:sigkill)))))) (osicat-posix:waitpid pid) (log:info "Version ~A killed!" version)) :name "kill-version") (log:info "Trying to quit version ~A..." version) (send-cmd-to version '(bt:make-thread (lambda () (sleep 1) (osicat-posix:exit 0)))) (map nil #'osicat-posix:close fds) (remhash version *forks*) (log:info "Version ~A unregistered" version))))) (defun posix-fork () ;; Adopted from https://gitlab.common-lisp.net/qitab/poiu/blob/master/fork.lisp #+(and allegro os-unix) (excl.osi:fork) #+(and clisp os-unix) (funcall (find-symbol* 'fork "LINUX")) #+(and clozure os-unix) (ccl:external-call "fork" :int) #+(and sbcl os-unix) (progn (sb-ext:gc) (sb-posix:fork)) #-(and os-unix (or allegro clisp clozure sbcl)) (error "Fork not implemented, sorry")) (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 (let* ((frk (get-version-info version)) (port (cdr (assoc :port frk)))) (and port (not (find-port:port-open-p port)) (or no-cmd (equal 3 (send-cmd-to version '(+ 1 2))))))) (defun wait-for-version-startup (version &optional (timeout 30)) ;; Wait up to 30 seconds (default) for version startup (loop for i below timeout while (not (version-alive-p version)) do (sleep 1))) (defparameter *swank-comm-style* :spawn) (defun run-version (version) ;; Start a version (if (get-version-info version) (log:info "The version ~A is already alive!" version) (let* ((path (version-file-path version)) (is-dev (equal version +devel-version+))) (if (and is-dev *prevent-devel-startup*) ;; Don't try to restart development version while image saved (loop for i below 60 while *prevent-devel-startup* do (sleep 1))) (if (probe-file path) (let* ((pip1 (multiple-value-list (osicat-posix:pipe))) (pip2 (multiple-value-list (osicat-posix:pipe))) (dpip1 (if is-dev (multiple-value-list (osicat-posix:pipe)))) (dpip2 (if is-dev (multiple-value-list (osicat-posix:pipe)))) (st-i (swank/backend:make-fd-stream (car pip1) :UTF-8)) (st-o (swank/backend:make-fd-stream (cadr pip2) :UTF-8)) (st-di (if is-dev (swank/backend:make-fd-stream (car dpip1) :UTF-8))) (st-do (if is-dev (swank/backend:make-fd-stream (cadr dpip2) :UTF-8))) (fds `(,@pip1 ,@pip2 ,@(if is-dev `(,@dpip1 ,@dpip2)))) ;; Collect all FDs which we need to close after process termination) (name (namestring path)) (port (find-port:find-port))) (let ((pid (osicat-posix:fork))) ;; fork-exec, to preserve open FDs (if (= pid 0) (let* ((args `(,name ,(format nil "~A" (car pip2)) ,(format nil "~A" (cadr pip1)) ,@(if is-dev `(,(format nil "~A" (car dpip2)) ,(format nil "~A" (cadr dpip1)))))) (argc (+ 2 (length args)))) (cffi:with-foreign-object (argv :pointer argc) (iolib/syscalls:bzero argv (* argc (iolib/syscalls:sizeof :pointer))) (loop for s in args and i below (length args) do (setf (cffi:mem-aref argv :pointer i) (cffi:foreign-string-alloc s))) (iolib/syscalls:execv name argv))) (let ((dev-thr (if is-dev ;; for development version we need to start sawnk server and process incoming commands (bt:make-thread (lambda () (wait-for-version-startup version) (send-cmd-to version `(progn (setf swank::*loopback-interface* "0.0.0.0") (setf swank::*globally-redirect-io* t) (bt:make-thread (lambda () (swank:create-server :port 4008 :dont-close t :style ,*swank-comm-style*))))) (loop while (and (open-stream-p st-di) (open-stream-p st-do)) do (let* ((eofv (gensym)) (cmd (ignore-errors (read st-di nil eofv))) (res (if (and cmd (not (equal cmd eofv))) (get-cmd-res cmd)))) (if (or (not cmd) (equal cmd eofv)) (return)) (format st-do "~A~%" res) (force-output st-do)))) :name "devel processing")))) (unwind-protect (progn (setf (omg::gethash-lock version *forks*) `((:out . ,st-o) (:in . ,st-i) (:fds . ,fds) (:pid . ,pid) (:port . ,port) (:lock . ,(bt:make-lock)))) ;; The lock needed to prevent parallel command processing (because streams are sequental) (send-cmd-to version `(progn (setf omgdaemon::*omg-version* ,version) ;; Allow the process to know its version (setf omgdaemon::*omg-last-version* ,(get-top-version)) (omg-init ,port))) (if is-dev (send-cmd-to version `(setf hunchentoot:*catch-errors-p* nil))) (wait-for-version-startup version) (if (version-alive-p version) (log:info "Version [~A] spawned!" version) (error (format nil "Cannot spawn version [~A]" version)))) (if (not (version-alive-p version)) (progn (if dev-thr (bt:destroy-thread dev-thr)) (kill-version version)))))))) (error (format nil "Cannot find image file for version ~A" version)))))) (defun restart-version (version) (log:info "Restarting version ~A" version) (ignore-errors (kill-version version)) (run-version version)) (defun ensure-version-working (version &key no-cmd) ;; If the version not spawned, start it (bt:with-lock-held ((bt:with-lock-held (*start-lock*) (let ((l (gethash version *start-locks*))) (if l l (setf (gethash version *start-locks*) (bt:make-lock)))))) (let ((tim0 (get-universal-time))) (loop while (and (not (version-alive-p version :no-cmd no-cmd)) (< (- (get-universal-time) tim0) 120)) do (log:info "Version ~A not responding" version) (when (and (equal version +devel-version+) *prevent-devel-startup*) (loop for i below 60 while *prevent-devel-startup* do (sleep 1))) (restart-version version) (loop for i below 10 while (not (version-alive-p version)) do (sleep 1))) (version-alive-p version)))) (defun commit-notify (version) (declare (ignore version))) (defun wait-for-commit-version (tv v pid) ;; The function called (on proxy) by development version just before image dump (bt:make-thread ;; Wait, process with PID termination and tename tv image to v (lambda () (setf *prevent-devel-startup* t) (unwind-protect (let ((tv-path (version-file-path tv)) (v-path (version-file-path v)) (link-ok nil)) (osicat-posix:waitpid pid) (when (ensure-version-working tv) (kill-version tv) (if (probe-file v-path) (delete-file v-path)) (rename-file tv-path v-path) (if (not (equal v +devel-version+)) ;; For production commit, we also have to replace development version (let ((dev-path (version-file-path +devel-version+))) (unwind-protect (progn (rename-file dev-path tv-path) (osicat-posix:link v-path dev-path) (setf link-ok t) (delete-file tv-path) (map nil (lambda (vers) (bt:make-thread (lambda () (log:debug "Sending cmd to: ~A ~A" vers v) (ignore-errors (send-cmd-to vers `(ignore-errors (setf omgdaemon::*omg-last-version* ,v) (commit-notify ,v))) (log:debug "Cmd to ~A sent!" vers)))) (sleep 1)) (bt:with-lock-held (omg::*giant-hash-lock*) (loop for vers being each hash-key of *forks* when vers collect vers)))) (if (not link-ok) (rename-file tv-path dev-path))))))) (setf *prevent-devel-startup* nil))) :name "wait-for-commit") nil) (defmacro buf-append (b1 b2) (let ((bl1 (gensym)) (b1t (gensym)) (b2t (gensym))) `(let* ((,b1t ,b1) (,b2t ,b2) (,bl1 (array-dimension ,b1t 0))) (adjust-array ,b1t (list (+ ,bl1 (array-dimension ,b2t 0)))) (replace ,b1t ,b2t :start1 ,bl1) ,b1t))) (defun version-available (version) ;; Check if version image exists (probe-file (version-file-path version))) (defvar *proxy-port* 80) (defclass ring-buffer () (buf (buf-size :initform +proxy-chunk-size+ :initarg :size) (start :initform 0) (end :initform 0))) (defmethod initialize-instance :after ((b ring-buffer) &key &allow-other-keys) (with-slots (buf buf-size) b (setf buf (make-array (list buf-size) :element-type '(unsigned-byte 8))))) (defmethod get-space ((b ring-buffer) &optional size) (with-slots (start end buf buf-size) b (let ((end1 (if (and (= end buf-size) (> start 0)) 0 end))) (if size (values buf end1 (min (+ end1 size) (if (<= start end1) buf-size (1- start)))) (values buf end1 (if (<= start end1) buf-size (1- start))))))) (defmethod allocate-space ((b ring-buffer) size) (with-slots (start end buf buf-size) b (when (< size 0) (error (format nil "Trying to allocate ~A btyes" size))) (let ((end1 (if (and (= end buf-size) (> start 0)) 0 end))) (when (> (+ end1 size) (if (<= start end1) buf-size (1- start))) (error "Buffer overrrun!")) (setf end (+ end1 size)) (when (and (= end buf-size) (> start 0)) (setf end 0))))) (defmethod data-available ((b ring-buffer)) (with-slots (start end buf buf-size) b (if (<= start end) (values buf start end) (values buf start buf-size)))) (defmethod deallocate-space ((b ring-buffer) size) (with-slots (start end buf buf-size) b (when (< size 0) (error (format nil "Trying to deallocate ~A btyes" size))) (when (> (+ start size) (if (<= start end) end buf-size)) (error "Buffer underrun!")) (incf start size) (when (= start buf-size) (setf start 0) (when (= end buf-size) (setf end 0))))) (defmethod empty-p ((b ring-buffer)) (with-slots (start end) b (= start end))) (defmethod full-p ((b ring-buffer)) (with-slots (start end buf-size) b (not (if (<= start end) (or (< end buf-size) (> start 0)) (< end start))))) ; (defmethod extend-buf ((b ring-buffer)) ; (with-)) (defvar *active-connections* (make-hash-table)) (defclass async-conn () ((write-buf :initform (make-instance 'ring-buffer)) (read-buf :initform (make-instance 'ring-buffer)) (base :initarg :base :initform (error "IOLIB base must be specified!")) (conn :initarg :conn) (fin :initform nil) (connected :initform nil) (readed :initform 0) (written :initform 0) (write-registered :initform nil) (conn-id :initform "[unknown ip:port]"))) (defclass selector-conn (async-conn) ((last-pos :initform 0) (cookie-found :initform nil) (cookie-sent-state :initform :waiting-end-of-hdrs) (cur-str-len :initform 0) (version-id))) (defmacro wait-for (base pred &rest code) (let ((fn (gensym)) (dt (gensym))) `(let ((,dt 0.01)) (labels ((,fn () (if ,pred (progn ,@code) (progn (setf ,dt (min 5.0 (* 1.1 ,dt))) (add-timer ,base #',fn ,dt :one-shot t))))) (,fn))))) (defvar *version-spawn-threads* (make-hash-table :test #'equalp)) (defmethod connect-to-version ((c selector-conn) &optional (version (get-top-version))) (with-slots (cookie-found base last-pos version-id) c (log:debug "Connecting to version ~A" version) (setf cookie-found t) (let ((frk (get-version-info version))) (when (and (not frk) (not (gethash version *version-spawn-threads*))) (setf (gethash version *version-spawn-threads*) (bt:make-thread (lambda () (unwind-protect (loop for i below 5 until (ignore-errors (ensure-version-working version)) when (not (version-alive-p version)) do (let ((v1 (get-top-version))) (when (not (gethash v1 *version-spawn-threads*))) (when (not (equal v1 version)) (log:info "Cannot start version ~A, trying with ~A" version v1) (remhash version *version-spawn-threads*) (setf version v1) (if (gethash v1 *version-spawn-threads*) (return) (setf (gethash v1 *version-spawn-threads*) (bt:current-thread)))))) (remhash version *version-spawn-threads*))) :name (format nil "starting version ~A" version))))) (let ((t0 (get-universal-time))) (wait-for base (or (> (- (get-universal-time) t0) 60) (get-version-info version)) (let ((frk (get-version-info version))) (if frk (let ((vrs (make-socket :connect :active :address-family :internet :type :stream :ipv6 nil))) (connect vrs +ipv4-loopback+ :port (cdr (assoc :port frk)) :wait nil) (wait-for base (socket-connected-p vrs) (let ((vrs-conn (make-instance 'async-conn :conn vrs :base base))) (setf version-id version) (log:debug "Connected to version ~A" version) (attach c vrs-conn) (attach vrs-conn c)))) (log:debug "Cannot wait more for version ~A" version))))))) (defmethod push-to ((c selector-conn) buf &key (start 0) (end (array-dimension buf 0))) (with-slots (cookie-sent-state cur-str-len write-buf version-id) c (cond ((eql cookie-sent-state :cookie-sent) (call-next-method)) ((eql cookie-sent-state :send-a-cookie) (let* ((cookie-hdr (trivial-utf-8:string-to-utf-8-bytes (format nil "Set-cookie: ~A~A~C~C" +version-cookie-prefix+ version-id #\return #\newline))) (cookie-len (array-dimension cookie-hdr 0))) (multiple-value-bind (buf1 start1 end1) (get-space write-buf cookie-len) (when (>= (- end1 start1) cookie-len) (replace buf1 cookie-hdr :start1 start1 :start2 0 :end1 (+ start1 cookie-len) :end2 cookie-len) (allocate-space write-buf cookie-len) (register-write c) (setf cookie-sent-state :cookie-sent))) (return-from push-to 0))) ((eql cookie-sent-state :waiting-end-of-hdrs) (let ((lpos start)) (multiple-value-bind (buf1 start1 end1) (get-space write-buf (- end start)) (let ((cw (min (- end start) (- end1 start1)))) (when (> cw 0) (let ((end (+ start cw))) (loop for pos = (position +nl-code+ buf :start lpos :end end) when (and pos (= pos (1+ lpos))) do (log:debug "End of headers found, injecting a cookie header") (replace buf1 buf :start1 start1 :start2 start :end1 (+ start1 (- lpos start)) :end2 (+ start (- lpos start))) (allocate-space write-buf (- lpos start)) (register-write c) (setf cookie-sent-state :send-a-cookie) (return-from push-to (- lpos start)) when pos do (setf lpos (1+ pos)) (setf cur-str-len 0) when (not pos) do (incf cur-str-len (- end lpos)) (return-from push-to (call-next-method)))))))))))) (defmethod try-read :after ((c selector-conn)) (with-slots (connected last-pos read-buf cookie-found) c (when (and (not connected) (not cookie-found)) (if (full-p read-buf) (close-conn c) (multiple-value-bind (buf start end) (data-available read-buf) (declare (ignore start)) (loop for pos = (position +nl-code+ buf :start last-pos :end end) while pos do (let* ((s (trivial-utf-8:utf-8-bytes-to-string buf :start last-pos :end (1- pos))) (cp (position #\: s))) (when (and cp (string-equal s "cookie" :end1 cp)) (let* ((p (search +version-cookie-prefix+ s :start2 cp)) (ps (if p (+ p (length +version-cookie-prefix+)))) (pe (if p (position #\; s :start ps))) (pe2 (if pe pe (length s))) (val (if p (subseq s ps pe2)))) (when val (log:debug "Version cookie found: [~A]" val) (return (connect-to-version c val))))) (when (= 0 (length s)) (return (connect-to-version c))) (setf last-pos (1+ pos))))))))) (defmethod attach ((from async-conn) (to async-conn)) (with-slots (connected) from (setf connected to) (feed-connected from))) (defmethod close-conn ((c async-conn) &key close abort) (with-slots (conn base connected written readed conn-id) c (let ((fd (socket-os-fd conn))) (ignore-errors (remove-fd-handlers base fd :read t :write t :error t)) (log:debug "Closing connection to ~A (abort: ~A close: ~A) W: ~A R: ~A" conn-id abort close written readed) (if abort (close conn :abort t) (if close (close conn)))) (remhash c *active-connections*))) (defmethod try-write ((c async-conn)) (with-slots (conn base fin write-registered write-buf written conn-id) c (handler-case (progn (if (not (empty-p write-buf)) (multiple-value-bind (buf start end) (data-available write-buf) (let ((wb (send-to conn buf :start start :end end))) (log:debug "~A Written ~A bytes" conn-id wb) (incf written wb) (deallocate-space write-buf wb))) (progn (ignore-errors (remove-fd-handlers base (socket-os-fd conn) :write t)) (setf write-registered nil))) (when (and fin (empty-p write-buf)) (log:debug "Finalized connection ~A, closing" conn-id) (close-conn c :close t))) (socket-connection-reset-error () (log:debug "Client ~A: connection reset by peer" conn-id) (close-conn conn)) (isys:ewouldblock () (log:debug "write-some-bytes: ewouldblock")) (isys:epipe () (log:debug "Client ~A got hangup on write" conn-id) (close-conn conn))))) (defmethod fin ((c async-conn) &optional err) (with-slots (fin base conn connected read-buf) c (when (not fin) (when err (log:debug "~A" err)) (ignore-errors (remove-fd-handlers base (socket-os-fd conn) :read t)) (setf fin t) (try-write c)))) (defmethod register-write ((c async-conn)) (with-slots (conn base write-registered) c (when (not write-registered) (when (socket-connected-p conn) (set-io-handler base (socket-os-fd conn) :write (lambda (&rest args) (declare (ignore args)) (try-write c))) (setf write-registered t))))) (defmethod push-to ((c async-conn) buf &key (start 0) (end (array-dimension buf 0))) (with-slots (write-buf) c (multiple-value-bind (buf1 start1 end1) (get-space write-buf (- end start)) (let ((cw (min (- end start) (- end1 start1)))) (when (> cw 0) (replace buf1 buf :start1 start1 :start2 start :end1 (+ start1 cw) :end2 (+ start cw)) (allocate-space write-buf cw) (register-write c)) cw)))) (defmethod feed-connected ((c async-conn)) (with-slots (connected read-buf base fin conn) c (when (not (empty-p read-buf)) (let ((conn-dt 0.01))7 (labels ((schedule-push () (setf conn-dt (min 5.0 (* conn-dt 1.1))) (add-timer base #'try-push conn-dt :one-shot t)) (try-push () (when connected (with-slots (write-buf) connected (if (empty-p read-buf) (when fin (fin connected)) (multiple-value-bind (buf start end) (data-available read-buf) (when (not (full-p write-buf)) (let ((cw (push-to connected buf :start start :end end))) (when (> cw 0) (deallocate-space read-buf cw)))) (schedule-push))))))) (try-push)))))) (defmethod try-read ((c async-conn)) (with-slots (fin conn base read-buf connected readed conn-id) c (when (and (not fin) (not (full-p read-buf))) (handler-case (multiple-value-bind (buf start end) (get-space read-buf) (when (> end start) (multiple-value-bind (buf rb) (receive-from conn :buffer buf :start start :end end) (declare (ignore buf)) (when (= 0 rb) (error 'end-of-file)) (log:debug "~A Readed ~A bytes" conn-id rb) (incf readed rb) (allocate-space read-buf rb) (feed-connected c)))) (socket-connection-reset-error () (fin c (format nil "Client ~A: connection reset by peer" conn-id))) (end-of-file () (fin c (format nil "Client ~A produced end-of-file on a read" conn-id))))))) (defmethod initialize-instance :after ((c async-conn) &key &allow-other-keys) (when (not (slot-boundp c 'conn)) (error "Connection must be specified!")) (with-slots (conn base conn-id) c (set-io-handler base (socket-os-fd conn) :read (lambda (&rest args) (declare (ignore args)) (try-read c))) (ignore-errors (multiple-value-bind (ip port) (remote-name conn) (setf conn-id (format nil "~A:~A" ip port))))) (setf (omg::gethash-lock c *active-connections*) (get-universal-time))) (defun proxy (port) ;; Start a proxy server (let ((ebase (make-instance 'event-base))) (unwind-protect (handler-case (with-open-socket (srv :connect :passive :address-family :internet :type :stream :ipv6 nil) ;;:external-format 'unsigned-byte) (log:debug "Created socket: ~A[fd=~A]" srv (socket-os-fd srv)) (bind-address srv +ipv4-unspecified+ :port port :reuse-addr t) (log:debug "Bound socket: ~A" srv) (listen-on srv :backlog 5) (log:info "Listening on socket bound to: ~A:~A" (local-host srv) (local-port srv)) (set-io-handler ebase (socket-os-fd srv) :read (lambda (fd ev exc) (declare (ignorable ev exc)) (let ((conn (accept-connection srv :wait t))) (log:debug "Connection accepted:" conn) (wait-for ebase (socket-connected-p conn) (with-slots (conn-id) (make-instance 'selector-conn :conn conn :base ebase) (log:info "Connection from ~A" conn-id)))))) (log:info "Entering loop!") (loop do (ignore-errors (event-dispatch ebase)) (sleep 1))) (socket-address-in-use-error () (log:info "Cannot start omgdaemon serever, address already in use!"))) (progn (log:debug "Finalize!") (loop for c being each hash-key of *active-connections* do (close-conn c :abort t)) (close ebase))))) (defun run-daemon () ;; Toplevel function for daemon startup (setf omg::*giant-hash-lock* (bt:make-lock)) (let ((devel-path (version-file-path +devel-version+))) (if (not (probe-file devel-path)) ;; If this is a first start, dump development version image (let ((pid (posix-fork))) (if (> pid 0) (osicat-posix:waitpid pid) (makimg devel-path)))) (bt:start-multiprocessing) (setf *main-lock* (bt:make-lock)) (setf *start-lock* (bt:make-lock)) (loop while (not (ensure-version-working +devel-version+))) (disable-debugger) (loop do (proxy *proxy-port*) do (log:info "Proxy exited, restarting...") (sleep 1)))) (defun make-omg-daemon (port &key (swank-comm-style :spawn)) ;; Dump daemon image, specify proxy port (swank-loader:init :delete nil ; delete any existing SWANK packages :reload nil ; reload SWANK, even if the SWANK package already exists :load-contribs nil) (setf *proxy-port* port) (setf swank::*globally-redirect-io* t) (setf *swank-comm-style* swank-comm-style) (loop for i below 20 ;; Wait for swank shutdown while (position-if (lambda (s) (search "swank" s :test #'char-equal)) (mapcar #'bt:thread-name (bt:all-threads))) do (progn (log:info "Waiting for swank shutdown...") (sleep 1))) (if (position-if (lambda (s) (search "swank" s :test #'char-equal)) (mapcar #'bt:thread-name (bt:all-threads))) (log:info "SWANK NOT DEAD!!1111")) (kill-all-threads) (disable-debugger) (save-executable (merge-pathnames (make-pathname :name "omgdaemon")) #'run-daemon)) (defun make-docker-image (&key (tag 'omgdaemon) (sbcl-version "2.4.7")) (with-input-from-string (fd (format nil "FROM debian RUN apt-get update && apt-get dist-upgrade -y RUN apt-get install -y sbcl cl-quicklisp git build-essential ziproxy libzstd-dev libfixposix-dev RUN cd /root && git clone -b sbcl-~A https://git.code.sf.net/p/sbcl/sbcl sbcl-sbcl &&\\ cd sbcl-sbcl && ./make.sh --fancy --prefix=/usr && ./install.sh && cd / &&\\ rm -fr /root/sbcl-sbcl RUN adduser omg RUN su -l omg -c 'ziproxy -d ; sbcl --load \"/usr/share/common-lisp/source/quicklisp/quicklisp.lisp\" \\ --eval \"(quicklisp-quickstart:install :proxy \\\"http://127.0.0.1:8080/\\\")\" --non-interactive' RUN su -l omg -c 'mkdir -p /home/omg/quicklisp/local-projects && cd /home/omg/quicklisp/local-projects &&\\ git clone --recurse-submodules https://github.com/hemml/OMGlib.git' RUN su -l omg -c 'ziproxy -d ; cd /home/omg && sbcl --eval \"(load \\\"/home/omg/quicklisp/setup.lisp\\\")\"\\ --eval \"(ql:quickload :omgdaemon)\" --eval \"(omgdaemon:make-omg-daemon 8081)\" --non-interactive' EXPOSE 8081 4008 CMD ziproxy -d ; while true; do su -l omg -c 'cd /home/omg && ./omgdaemon' ; sleep 1 ; done" sbcl-version)) (run `(docker build :tag ,tag :pull :no-cache -) :input fd))) (defun update-omg () (run '(and (cd "/home/omg/quicklisp/local-projects/OMGlib") (git pull :rebase))) (require :omg))
41,517
Common Lisp
.lisp
777
40.383526
152
0.548886
hemml/OMGlib
43
1
0
GPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
7b9e9b0d498b9e66616fabe78925d0900df3881e75dbfa03c0ced3c3601f680e
4,294
[ -1 ]
4,295
daemonui.lisp
hemml_OMGlib/daemonui.lisp
(defpackage :daemonui (:use cl omg omgdaemon) (:export ensure-last-version get-omg-cookie-name get-my-version)) (in-package :daemonui) (defun-r need-reload () (and (not (equal *omg-version* +devel-version+)) (not (equal *omg-version* *omg-last-version*)))) (defun-r get-omg-cookie-name () +omg-version-cookie+) (defun-r get-last-version () *omg-last-version*) (defun-r get-my-version () *omg-version*) (defun-f ensure-last-version () (if (need-reload) (progn (setf (jscl::oget (jscl::%js-vref "document") "cookie") (format nil "~A=~A" (get-omg-cookie-name) (get-last-version))) ((jscl::oget (jscl::%js-vref "location") "reload") t))))
720
Common Lisp
.lisp
21
29.238095
76
0.626263
hemml/OMGlib
43
1
0
GPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
2e2ac781dfa57e10ea776111cfed57724634e450cf05792aa2094fcaa8fa1154
4,295
[ -1 ]
4,296
example.lisp
hemml_OMGlib/example.lisp
;; Load this file via (load "example.lisp") in the REPL and open http://localhost:7500 in the browser (require :omg) (defpackage :my-test (:use cl omg omgui jscl)) (in-package :my-test) ;; (setf omg::*ssl-cert* "sslcert.pem") ;; (setf omg::*ssl-key* "sslkey.pem") ;; (setf omg::*port* 7500) (defun-f play-yt (video-id) (add-youtube-player (append-element (create-element "div")) :video-id video-id :width 800 :onready (lambda (ev) ((jscl::oget ev "target" "mute")) ;; respect autoplay restrictions ((jscl::oget ev "target" "playVideo")) (jslog "Starting playback")) :onstatechange (lambda (ev) (if (equal (jscl::oget ev "data") (jscl::oget (jscl::%js-vref "YT") "PlayerState" "PLAYING")) (progn (jslog "Playback started!") (execute-after 10.0 ;; Pause video after 10 sec. playback (lambda () ((jscl::oget ev "target" "pauseVideo"))))))))) (defun-f up1 (s) (string-upcase s)) (defun-r up2 (s) (string-upcase s)) (defun-r my-boot () (print "BOOT!") (set-debug-session (current-session-id))) (add-to-boot '(my-boot)) ;; call my-boot just after connection (restart-server) ;; (re)start a server on default port 7500 ;; execute this via SLIME after browser connection: (in-debug-session (print (modal-dialog "The header" "The modal dialog test" :lines (list :line1 (list "Upcase on backend:" :filter #'up2) :line2 (list "Upcase on frontend:" :filter #'up1) :pass (list "Upcase on frontend:" :type "password") :line3 "Enter something:" :buttons (list (list "OK" #'dialog-ok) (list "Cancel" #'close-current-dialog)))))) (play-yt "vla6vpa1-Bk")
2,287
Common Lisp
.lisp
45
33.155556
109
0.471961
hemml/OMGlib
43
1
0
GPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
6e3bcb396fc848fec7820692f18587365095b495089690f20e35ec99ec23f866
4,296
[ -1 ]
4,297
omgui.lisp
hemml_OMGlib/omgui.lisp
(defpackage :omgui (:use cl omg jscl bordeaux-threads) (:export add-event-handler add-event-listener add-style add-youtube-player append-element async-bind allow-page-close bind-exit-values-for browser-case cache-vars check-element classic-worker close-current-dialog create-element dialog-ok disable-back-button disable-scroll dont-transfer dragabble-list dragabble-list-elements dragabble-list-insert dragabble-list-insert-position element-width element-height enable-back-button enable-scroll ensure-element execute-after find-widget gensym2 get-dialog-data get-element-id idb-object-store if-idb-key in-service-worker indexed-db-add indexed-db-put indexed-db-get indexed-db-delete indexed-db-get-all-keys is-nan js-get-element-by-id jsceil jsfloor jstrunc jsln jslog jsmax jsmin js-parse-float jssin jscos jstan jsasin jsacos jsatan jsatan2 jsrandom jssort kill load-js-script local-storage make-dialog make-dragabble-list make-js-function make-js-object make-pwa make-svg make-tab-form modal-dialog now oget-bind on-element-remove page-width page-height parent-element prevent-page-close register-hash-cb register-main-lambda remove-element rm-event-handler run-in-web-worker service-worker session-storage set-service-worker-uri-handler setup-indexed-db show-notification visible-width visible-height visible-left visible-top when-worker-free when-worker-ready winref with-promise with-self set-service-worker-uri-handler respond-with default-action uri-path store-to-buffer load-from-buffer)) (in-package :omgui) (defvar *default-icon* nil) (defun-f winref (name) (jscl::oget (jscl::%js-vref "self") name)) (defun-f is-nan (n) (funcall (winref "isNaN") n)) (defun-f js-parse-float (s) (funcall (winref "Number") (jscl::lisp-to-js s))) (defun-f local-storage (key &optional def) (let ((vl ((jscl::oget (winref "localStorage") "getItem") (jscl::lisp-to-js key)))) (if (jscl::js-null-p vl) def vl))) (defun-f (setf local-storage) (val key) ((jscl::oget (winref "localStorage") "setItem") (jscl::lisp-to-js key) val)) (defun-f session-storage (key &optional def) (let ((vl ((jscl::oget (winref "sessionStorage") "getItem") (jscl::lisp-to-js key)))) (if (jscl::js-null-p vl) def vl))) (defun-f (setf session-storage) (val key) ((jscl::oget (winref "sessionStorage") "setItem") (jscl::lisp-to-js key) val)) (def-local-macro-f async-bind (vcmd &rest cod) (let* ((res (gensym)) (rst (gensym)) (vrs (car vcmd)) (ll (if (listp vrs) `(,(car vrs) &optional ,@(cdr vrs) &rest ,rst) `(,vrs &rest ,rst)))) `(progn (funcall (jscl::oget (jscl::%js-vref "OMG") "AsyncRPC2") (jscl::omg-write-to-string ',(omg::get-id omg::*current-session*) ',(intern (package-name *package*)) (list ',(caadr vcmd) (list ,@(cdadr vcmd)))) (lambda (,res) (destructuring-bind ,ll ,res ,@cod))) nil))) (defun-f make-svg (&rest cod) (labels ((process-cmd (cmd args) (let* ((symname (symbol-name cmd)) (symdown (string-downcase symname)) (el ((jscl::oget (jscl::%js-vref "document") "createElementNS") "http://www.w3.org/2000/svg" (if (equal symname (string-upcase symname)) symdown symname)))) ((jscl::oget el "setAttribute") "xmlns" "http://www.w3.org/2000/svg") (process-cmd-tail el args))) (process-cmd-tail (el cod) (if cod (cond ((symbolp (car cod)) (let* ((path (js-string-split (symbol-name (car cod)) #\.)) (obj (deep-oget-1 el path)) (fld (car (last path)))) (if (> (length path) 1) (jscl::oset (cadr cod) obj fld) ((jscl::oget el "setAttribute") (symbol-name (car cod)) (cadr cod))) (process-cmd-tail el (cddr cod)))) ((listp (car cod)) (progn ((jscl::oget el "appendChild") (process-cmd (caar cod) (cdar cod))) (process-cmd-tail el (cdr cod)))) ((stringp (car cod)) (let ((txt ((jscl::oget (jscl::%js-vref "document") "createTextNode") (car cod)))) ((jscl::oget el "appendChild") txt) (process-cmd-tail el (cdr cod)))) (t (progn ((jscl::oget el "appendChild") (car cod)) (process-cmd-tail el (cdr cod))))) el))) (process-cmd :svg cod))) (defun-f system-font () "The system font for dialogs, etc. Defined as a function because functions are automatically updated in browsers." "1.2em Gill Sans,Gill Sans MT,Calibri,sans-serif") (defun-f jslog (&rest args) "Log function for js" (apply (jscl::oget (jscl::%js-vref "console") "log") args) nil) (defun-f jsrandom () "Return a random number in 0..1 range" (funcall (jscl::oget (jscl::%js-vref "Math") "random"))) (defun-f jsfloor (x) "Math.floor function" ((jscl::oget (jscl::%js-vref "Math") "floor") x)) (defun-f jsceil (x) "Math.ceil function" ((jscl::oget (jscl::%js-vref "Math") "ceil") x)) (defun-f jstrunc (x) "Math.trunc function" ((jscl::oget (jscl::%js-vref "Math") "trunc") x)) (defun-f jsln (arg) "Math.log function" ((jscl::oget (jscl::%js-vref "Math") "log") arg)) (defun-f jssin (arg) "Math.sin function" ((jscl::oget (jscl::%js-vref "Math") "sin") arg)) (defun-f jscos (arg) "Math.cos function" ((jscl::oget (jscl::%js-vref "Math") "cos") arg)) (defun-f jstan (arg) "Math.tan function" ((jscl::oget (jscl::%js-vref "Math") "tan") arg)) (defun-f jsasin (arg) "Math.asin function" ((jscl::oget (jscl::%js-vref "Math") "asin") arg)) (defun-f jsacos (arg) "Math.acos function" ((jscl::oget (jscl::%js-vref "Math") "acos") arg)) (defun-f jsatan (arg) "Math.atan function" ((jscl::oget (jscl::%js-vref "Math") "atan") arg)) (defun-f jsatan2 (y x) "Math.atan2 function" ((jscl::oget (jscl::%js-vref "Math") "atan2") y x)) (defun-f jsmin (&rest args) "Math.min function" (apply (jscl::oget (jscl::%js-vref "Math") "min") args)) (defun-f jsmax (&rest args) "Math.max function" (apply (jscl::oget (jscl::%js-vref "Math") "max") args)) (defun-f js-get-element-by-id (id) "Get DOM object by ID (must not be called on host!)" ((jscl::oget (jscl::%js-vref "document") "getElementById") id)) (defun-f jssort (arr &optional (fn (lambda (x y) (> x y)))) "Sort an array" ((jscl::oget arr "sort") fn)) (defun-f check-element (id) "Check if element with ``id'' exists in DOM" (not (jscl::js-null-p (js-get-element-by-id id)))) (defun-f random-id () "Get an unique random string to use as a DOM id" (let* ((chrs "ABCDEFGHIJKLMOPQRSTUVWXYZ") (id (map 'string (lambda (x) (declare (ignore x)) (char chrs (jsfloor (* (jsrandom) (length chrs))))) (make-string 8)))) (if (check-element id) (random-id) id))) (defun-f get-element-id (el) "Returns an id of the element el" (let ((id (jscl::oget el "id"))) (if (> (length id) 0) id (let ((nid (random-id))) (setf (jscl::oget el "id") nid) nid)))) (defun-f js-string-split (path ch) "Split a string path by the character ch, much, much fater then JSCL function" (let* ((pos (position ch path)) (p0 (subseq path 0 pos))) (cons p0 (if pos (js-string-split (subseq path (+ pos 1)) ch) (list))))) (defun-f deep-oget-1 (el path) "Get a value of el.the.list.of.the.property.path" (if (cdr path) (deep-oget-1 (jscl::oget el (car path)) (cdr path)) el)) (defun-f create-element (typ &rest args) "Create and return a DOM element type ``typ'' and specified attributes: (create-element \"A\" '|href| \"http://google.com\")" (let ((el ((jscl::oget (jscl::%js-vref "document") "createElement") typ))) (loop for (k v) on args by (function cddr) do (labels ((app-el (nel) (append-element (if (stringp v) ((jscl::oget (jscl::%js-vref "document") "createTextNode") nel) nel) el))) (cond ((equal k :append-element) (app-el v)) ((equal k :append-elements) (map nil #'app-el v)) ((equal k :add-style) (add-style el v)) ((equal (symbol-name k) (string-upcase (symbol-name k))) ((jscl::oget el "setAttribute") (symbol-name k) v)) (t (let* ((path (js-string-split (symbol-name k) #\.)) (obj (deep-oget-1 el path)) (fld (car (last path)))) (jscl::oset v obj fld)))))) el)) (defun-f append-element (el &optional parent) "Append the element el as a child to the parent" (let ((el1 (if (stringp el) ((jscl::oget (jscl::%js-vref "document") "createTextNode") el) el))) (if parent ((jscl::oget parent "appendChild") el1) ((jscl::oget (jscl::%js-vref "document") "body" "appendChild") el1)) el1)) (defun-f parent-element (el) "Get parent of the element el" (jscl::oget el "parentNode")) (defun-f remove-element (el) "Remove the element el from it's parent children" ((jscl::oget (parent-element el) "removeChild") el)) (defun-f element-width (el) "Get element width in pixels" (jscl::oget el "clientWidth")) (defun-f element-height (el) "Get element height in pixels" (jscl::oget el "clientHeight")) (defun-f page-width () "Get the browser page width" (jsmax (jscl::oget (jscl::%js-vref "document") "body" "scrollWidth") (jscl::oget (jscl::%js-vref "document") "documentElement" "scrollWidth") (jscl::oget (jscl::%js-vref "document") "body" "offsetWidth") (jscl::oget (jscl::%js-vref "document") "documentElement" "offsetWidth") (jscl::oget (jscl::%js-vref "document") "documentElement" "clientWidth"))) (defun-f page-height () "Get the browser page height" (jsmax (jscl::oget (jscl::%js-vref "document") "body" "scrollHeight") (jscl::oget (jscl::%js-vref "document") "documentElement" "scrollHeight") (jscl::oget (jscl::%js-vref "document") "body" "offsetHeight") (jscl::oget (jscl::%js-vref "document") "documentElement" "offsetHeight") (jscl::oget (jscl::%js-vref "document") "documentElement" "clientHeight"))) (defun-f visible-width () "Get the browser page visible width" (jscl::oget (jscl::%js-vref "document") "body" "clientWidth")) (defun-f visible-height () "Get the browser page visible height" (jscl::oget (jscl::%js-vref "document") "body" "clientHeight")) (defun-f visible-left () "Get the browser page left coordinate" (jscl::oget (jscl::%js-vref "document") "body" "scrollLeft")) (defun-f visible-top () "Get the browser page top coordinate" (jscl::oget (jscl::%js-vref "document") "body" "scrollTop")) (defparameter-f *scroll-disabled* nil) (defun-f disable-scroll () "Disable browser page scroll" (if (not *scroll-disabled*) (progn (setf (jscl::oget (jscl::%js-vref "document") "body" "style" "overflow") "hidden") (setf *scroll-disabled* t) t))) (defun-f enable-scroll () "Enable browser page scroll" (if *scroll-disabled* (progn (setf (jscl::oget (jscl::%js-vref "document") "body" "style" "overflow") "") (setf *scroll-disabled* nil) t))) (defun-f curtain () "Create a curtain, to shadow elements while modal dialog active" (create-element "div" :|style.opacity| "80%" :|style.background| "white" :|style.width| (page-width) :|style.height| (page-height) :|style.position| "absolute" :|style.top| "0" :|style.left| "0" :|class| "blurbg" :|zIndex| 100000)) (defun-f dialog-frame () "Create a modal dialog outer frame" (create-element "div" :|style.opacity| "0" :|style.border| "0.1em solid black" :|style.border-radius| "0.5em" :|style.padding| "0" :|style.overflowX| "hidden" :|style.width| "auto" :|style.background| "#fffff0" :|style.display| "inline-block" :|style.font| (system-font) :|style.boxShadow| "0.5em 0.5em 1em gray" :|style.position| "absolute" :|omgwidget| "dialog" :|zIndex| 200000)) (defun-f dialog-header (header) "Create a modal dialog header" (let* ((hdr (create-element "div" :|style.width| "auto" :|style.background| "#a0f0a0" :|style.padding| "0.5em" :|style.minHeight| "1em" :|innerHTML| (if header header ""))) (close-btn (create-element "div" :|style.width| "0.75em" :|style.height| "0.75em" :|style.margin| "0" :|style.borderRadius| "0.2em" :|style.background| "red" :|style.float| "right" :|style.boxShadow| "0 0 0.5em grey" :|style.cursor| "pointer" :|title| "close" :|onclick| #'close-current-dialog))) (append-element close-btn hdr) hdr)) (defun-f execute-after (tim cb) "Schedule an execution of cb after tim seconds" (funcall (jscl::%js-vref "setTimeout") cb (* tim 1000.0))) (defparameter-f *dialog-stack* nil) (defun-f form-line (key txt &optional params) "Create modal dialog table line" (let* ((row (create-element "div" :|style.display| "table-row" :|style.width| "auto")) (c1 (create-element "div" :|style.display| "table-cell" :|style.padding| "0.3em" :|style.width| "auto" :|style.text-align| "right" :|style.fontWeight| "lighter" :|style.verticalAlign| "bottom" :|innerHTML| txt)) (c2 (create-element "div" :|style.display| "table-cell" :|style.padding| "0.3em" :|style.width| "50%" :|style.verticalAlign| "bottom")) (typ (getf params :type)) (def1 (getf params :default)) (def (if def1 def1 "")) (inp (create-element "input" :|type| (if typ typ "text") :|value| def :|style.font| "inherit" :|style.fontStyle| "italic" :|style.fontWeight| "lighter" :|style.width| "100%")) (last-val def) (cb (getf params :filter)) (current-dialog (car *dialog-stack*)) (data (cdr (assoc :data current-dialog)))) (if (not (assoc key data)) (progn (push (cons key def) data) (setf (cdr (assoc :data current-dialog)) data))) (labels ((tcb (ev) ;; the callback is called after every field update (execute-after 0 (lambda () (let ((val (jscl::oget inp "value"))) (if (not (equal last-val val)) (let ((new-val (if cb (funcall cb val) val)) (current-dialog (car *dialog-stack*)) (data (cdr (assoc :data current-dialog)))) (setf last-val (if (stringp new-val) new-val val)) (if (stringp new-val) (let ((selection-start (jscl::oget inp "selectionStart")) (selection-end (jscl::oget inp "selectionEnd"))) (setf (jscl::oget inp "value") new-val) (if (not (assoc key data)) (push (cons key new-val) data) (setf (cdr (assoc key data)) new-val)) (setf (cdr (assoc :data current-dialog)) data) ;; JSCL bug workaround ((jscl::oget inp "setSelectionRange") selection-start selection-end)))))))) t)) (setf (jscl::oget inp "onchange") #'tcb) (setf (jscl::oget inp "onkeyup") #'tcb) (setf (jscl::oget inp "onkeydown") #'tcb) (setf (jscl::oget inp "onpaste") #'tcb) (setf (jscl::oget inp "ondrop") #'tcb)) (append-element inp c2) (append-element c1 row) (append-element c2 row) row)) (defun-f form-button-row (btns) "Create a row with buttons for dialog" (let* ((row (create-element "div" :|style.display| "table-caption" :|style.width| "auto" :|style.captionSide| "bottom")) (cl (create-element "div" :|style.display| "flex" :|style.width| "100%" :|style.height| "100%" :|style.text-align| "center" :|style.justifyContent| "center" :|style.alignItems| "center" :|style.paddingBottom| "0.5em"))) (map nil (lambda (b) (cond ((listp b) (append-element (create-element "button" :|innerHTML| (car b) :|style.marginBottom| "0.3em" :|style.marginLeft| "1em" :|style.marginRight| "1em" :|onclick| (lambda (ev) (funcall (eval (cadr b))))) cl)))) btns) (append-element cl row) row)) (defun-f dialog-table (lines) "Create modal dialog table" (let ((tbl (create-element "div" :|style.display| "table" :|style.width| "auto" :|style.padding| "1em"))) (loop for (k v) on lines by (function cddr) do (if (equal k :buttons) (append-element (form-button-row v) tbl) (if (listp v) (cond ((stringp (car v)) (append-element (form-line k (car v) (cdr v)) tbl))) (append-element (form-line k v) tbl)))) tbl)) (defparameter *dialog-wait-list* (make-hash-table)) (defun-r dialog-wl-send (id dat) (let ((sem (gethash id *dialog-wait-list*))) (if sem (progn (setf (gethash id *dialog-wait-list*) (remove-if (lambda (x) (equal (car x) 'dialog-id)) dat)) (signal-semaphore sem)))) nil) (defun-f close-current-dialog (&optional ev no-sem) (let ((current-dialog (pop *dialog-stack*))) (if (assoc :scroll-disabled current-dialog) (enable-scroll)) (let* ((outer (cdr (assoc :outer current-dialog))) (curtain (cdr (assoc :curtain current-dialog))) (dat (cdr (assoc :data current-dialog))) (id (assoc 'dialog-id dat))) (if outer (remove-element outer)) (if curtain (remove-element curtain)) (if (and (cdr id) (not no-sem)) (dialog-wl-send (cdr id) nil))))) (defun-f get-dialog-data () (cdr (assoc :data (car *dialog-stack*)))) (defun-f make-dialog (header-text dialog-text &key lines id) "Create modal dialog with header, text and lines. " (let* ((curtain (curtain)) (outer (dialog-frame))) (setf *dialog-stack* (cons (list (cons :scroll-disabled (disable-scroll)) (cons :curtain curtain) (cons :outer outer) (cons :data (list (cons 'dialog-id id)))) *dialog-stack*)) (let* ((hdr (dialog-header header-text)) (tbl (dialog-table lines)) (txt (create-element "div" :|innerHTML| dialog-text :|style.fontWeight| "lighter" :|style.marginTop| "1em" :|style.marginLeft| "1em" :|style.marginRight| "1em" :|style.width| "auto"))) (append-element hdr outer) (if dialog-text (append-element txt outer)) (append-element tbl outer) (append-element curtain) (append-element outer) (setf (jscl::oget outer "style" "left") (jscl::concat (write-to-string (+ (visible-left) (jsfloor (/ (- (visible-width) (element-width outer)) 2)))) "px")) (setf (jscl::oget outer "style" "top") (jscl::concat (write-to-string (+ (visible-top) (jsfloor (/ (- (visible-height) (element-height outer)) 2)))) "px")) (setf (jscl::oget outer "style" "opacity") "100%") (get-element-id curtain)))) (defun-f dialog-ok () (let* ((current-dialog (car *dialog-stack*)) (dat (cdr (assoc :data current-dialog))) (id (assoc 'dialog-id dat))) (close-current-dialog nil t) (if id (dialog-wl-send (cdr id) dat)))) (defmacro modal-dialog (header-text dialog-text &key lines) `(if (current-session-id) (let* ((id (intern (symbol-name (omg::random-key *dialog-wait-list*)) :omgui)) (sem (make-semaphore)) (ht ,header-text) (dt ,dialog-text) (lins ,lines)) (setf (gethash id *dialog-wait-list*) sem) (if (remote-exec `(make-dialog ,ht ,dt :lines ',lins :id ',id)) (progn (wait-on-semaphore sem) (let ((res (gethash id *dialog-wait-list*))) (remhash id *dialog-wait-list*) res)))))) (defun-f load-js-script (src &optional onload) (let ((el (create-element "script" :|src| src))) (if onload (setf (jscl::oget el "onload") onload)) (append-element el))) (defun-f make-js-function (name code) (setf (jscl::oget (jscl::%js-vref "self") name) code)) (defun-f make-js-object (&rest plist) (let ((obj (jscl::new))) (loop for (k v) on plist by #'cddr do (setf (jscl::oget obj (symbol-name k)) v)) obj)) (defun-f allow-page-close () (setf *disable-page-unload* nil) nil) (defparameter-f *disable-back* nil) (defparameter-f *backcnt* 0) (defparameter-f *fback* t) (defparameter-f *onpopstate-installed* nil) (defun-f disable-back-button (&optional cb) (if (not *onpopstate-installed*) (progn ((jscl::oget (jscl::%js-vref "history") "pushState") "" "" (jscl::oget (jscl::%js-vref "self") "location" "href")) ((jscl::oget (jscl::%js-vref "history") "back")) (setf *onpopstate-installed* t) (setf (jscl::oget (jscl::%js-vref "self") "onpopstate") (lambda (ev) (let ((bcnt *backcnt*) ;; JSCL bug workaround (fb *fback*)) (setf *backcnt* (+ 1 *backcnt*)) (if *disable-back* ((jscl::oget (jscl::%js-vref "history") "forward"))) (if (equal bcnt 1) (progn (if (and cb (not fb)) (funcall cb)) (setf *fback* nil) (setf *backcnt* 0)))))))) (setf *disable-back* t) nil) (defun-f enable-back-button () (setf *disable-back* nil) ((jscl::oget (jscl::%js-vref "history") "back")) nil) (defparameter-f *beforeunload-installed* nil) (defparameter-f *disable-page-unload* nil) (defun-f prevent-page-close () (if (not *beforeunload-installed*) (progn ((jscl::oget (jscl::%js-vref "self") "addEventListener") "beforeunload" (lambda (ev) (if *disable-page-unload* (progn ((jscl::oget ev "preventDefault")) (setf (jscl::oget ev "returnValue") ""))))) (setf *beforeunload-installed* t))) (setf *disable-page-unload* t) nil) (defparameter-f *youtube-js-loaded* nil) (defun-f add-youtube-player (element &key onready onstatechange onqualitychange onratechange onerror onapichange width height video-id) (let ((cfg (make-js-object :|events| (make-js-object :|onReady| (lambda (ev) (setf *youtube-js-loaded* t) (if onready (funcall onready ev))) :|onStateChange| (lambda (ev) (if onstatechange (funcall onstatechange ev))) :|onPlaybackQualityChange| (lambda (ev) (if onqualitychange (funcall onqualitychange ev))) :|onPlaybackRateChange| (lambda (ev) (if onratechange (funcall onratechange ev))) :|onError| (lambda (ev) (if onerror (funcall onerror ev))) :|onApiChange| (lambda (ev) (if onapichange (funcall onapichange ev))))))) (if width (setf (jscl::oget cfg "width") width)) (if height (setf (jscl::oget cfg "height") height)) (if video-id (setf (jscl::oget cfg "videoId") video-id)) (labels ((make-player () (jscl::make-new (jscl::oget (jscl::%js-vref "YT") "Player") element cfg))) (if (not *youtube-js-loaded*) (progn (make-js-function "onYouTubeIframeAPIReady" (lambda () (jslog "YouTube API loaded") (setf *youtube-js-loaded* t) (make-player))) (load-js-script "https://www.youtube.com/iframe_api")) (make-player)))) nil) (defparameter-f *hash-change-cbs* nil) (defun-f register-hash-cb (hsh cb) (labels ((mcb (&optional ev) (let* ((hs (jscl::oget (jscl::%js-vref "location") "hash")) (cb (assoc hs *hash-change-cbs* :test #'equal))) (if cb (funcall (cdr cb)))))) (let ((need-mcb (not *hash-change-cbs*))) (push (cons hsh cb) *hash-change-cbs*) (if need-mcb (progn (setf (jscl::oget (jscl::%js-vref "self") "onhashchange") #'mcb) (mcb))))) nil) (defun-f gensym2 (&rest args) (intern (symbol-name (apply #'gensym args)))) ;; use: ;; (browser-case ;; (:safari (jslog "Safari detected!")) ;; ((:firefox :chrome) (jslog "FF or Chrome!")) ;; (:opera (jslog "Opera!")) ;; (:edge (jslog "Edge!"))) ;; (t (jslog "Unknown browser!")) (defmacro-f browser-case (&rest cod) (let ((agent (gensym2)) (browser (gensym2))) `(let* ((,agent (string-downcase (jscl::oget (jscl::%js-vref "navigator") "userAgent"))) (,browser (cond ((or (search "chrome" ,agent) (search "chromium" ,agent) (search "crios" ,agent)) :chrome) ((or (search "firefox" ,agent) (search "fxios" ,agent)) :firefox) ((search "safari" ,agent) :safari) ((search "opr" ,agent) :opera) ((search "edg" ,agent) :edge) (t nil)))) (cond ,@(mapcar (lambda (c) `(,(if (listp (car c)) `(or ,@(mapcar (lambda (s) `(equal ,browser ,s)) (car c))) (if (equal t (car c)) (car c) `(equal ,browser ,(car c)))) ,@(cdr c))) cod))))) (defparameter-f *style-cache* nil) (defun-f add-style (el css-text) (let* ((sid (assoc css-text *style-cache* :test #'equal)) (chrs "ABCDEFGHIJKLMOPQRSTUVWXYZ") (clsid (if sid (cdr sid) (map 'string (lambda (x) (declare (ignore x)) (char chrs (jsfloor (* (jsrandom) (length chrs))))) (make-string 8))))) (if (not sid) (progn (append-element (create-element "style" :|innerHTML| (jscl::concat "." clsid css-text)) (jscl::oget (jscl::%js-vref "document") "head")) (push (cons css-text clsid) *style-cache*))) ((jscl::oget el "classList" "add") clsid))) (defparameter-f *notification-container* nil) (defun-f element-on-page-p (el) (or (equal el (jscl::%js-vref "document")) (and (not (jscl::js-null-p el)) (element-on-page-p (jscl::oget el "parentNode"))))) (defparameter-f *global-observer-handlers* nil) (defun-f on-element-remove (el cb) (if (not *global-observer-handlers*) (let ((obs (jscl::make-new (winref "MutationObserver") (lambda (&rest args) (let ((rems nil)) (map nil (lambda (eh) (if (not (element-on-page-p (car eh))) (if (not (funcall (cdr eh) (car eh))) (push eh rems)))) *global-observer-handlers*) (setf *global-observer-handlers* (remove-if (lambda (x) (position x rems :test #'equal)) *global-observer-handlers*)) nil))))) ((jscl::oget obs "observe") (jscl::oget (jscl::%js-vref "document") "body") (make-js-object :|childList| t)))) (push (cons el cb) *global-observer-handlers*)) (defun-f show-notification (header body &key period check) (let* ((frame (create-element "div" :|style.border| "1pt solid black" :|style.position| "relative" :|style.margin| "0.5em" :|style.background| "white" :|style.width| "15em" :|style.borderRadius| "0.2em" :|style.minHeight| "5em" :|style.boxShadow| "0 0 1em grey" :|style.right| 0 :|omgwidget| "notification")) (head-line (create-element "div" :|style.left| 0 :|style.right| 0 :|style.top| 0 :|style.padding| "0.25em" :|style.position| "relative" :|style.font| (omgui::system-font))) (close-btn (create-element "div" :|style.borderRadius| "0.2em" :|style.background| "red" :|style.right| "0.25em" :|style.top| "0.25em" :|style.width| "0.5em" :|style.aspectRatio| 1 :|style.boxShadow| "0 0 0.5em grey" :|style.cursor| "pointer" :|style.position| "absolute" :|title| "close" :|onclick| (lambda (ev) (remove-element frame)))) (body-cont (create-element "div" :|style.padding| "0.25em" :|style.font| (omgui::system-font))) (ncont (if *notification-container* *notification-container* (create-element "div" :|style.position| "absolute" :|style.right| 0 :|style.top| 0)))) (if (not *notification-container*) (progn (setf *notification-container* ncont) (append-element ncont))) (append-element header head-line) (append-element close-btn head-line) (append-element head-line frame) (append-element body body-cont) (append-element body-cont frame) (append-element frame ncont) (if period (on-element-remove frame (lambda (el) (if (or (not check) (funcall check)) (progn (execute-after period (lambda () (append-element frame ncont))) t) nil)))))) (defun-f find-widget (ev &optional type) (labels ((get-wg (el) (let ((w (jscl::oget el "omgwidget"))) (if (and w (or (not type) (equal w type))) el (let ((par (jscl::oget el "parentNode"))) (if (and par (not (jscl::js-null-p par))) (get-wg par))))))) (get-wg (jscl::oget ev "target")))) (def-local-macro-f ensure-element (e &rest body) (let ((fn (gensym)) (e1 (gensym))) `(labels ((,fn () (let ((,e1 ,e)) (if (and ,e1 (> (jscl::oget ,e1 "clientWidth") 0)) (progn ,@body) (execute-after 0.1 #',fn))))) (,fn)))) (defparameter-f *global-event-handlers* nil) (defun-f add-event-handler (path handler) (let ((handlers (assoc path *global-event-handlers* :test #'equal))) (if (not handlers) (let* ((path-l (omgui::js-string-split path #\.)) (obj (omgui::deep-oget-1 (jscl::%js-vref "self") (butlast path-l)))) (setf (jscl::oget obj (car (last path-l))) (lambda (ev) (map nil (lambda (cb) (funcall cb ev)) (cdr (assoc path *global-event-handlers* :test #'equal))))) (push (cons path (list handler)) *global-event-handlers*)) (push handler (cdr handlers))))) (defun-f rm-event-handler (path handler) (setf *global-event-handlers* (mapcar (lambda (hnd) (if (equal path (car hnd)) (cons path (remove-if (lambda (h) (equal h handler)) (cdr hnd))) hnd)) *global-event-handlers*))) (defun-f make-tab-form (tab-list) (let* ((tab-div (create-element "div" :|style.display| "flex" :|style.position| "relative")) (content (create-element "div" :|style.padding| "1em" :|style.borderLeft| "1px solid gray" :|style.borderRight| "1px solid gray" :|style.borderBottom| "1px solid gray")) (outer (create-element "div" :append-element tab-div :append-element content)) (tbs nil)) (map nil (lambda (tab num) (append-element (let ((tb (create-element "div" :|style.borderTop| "1px solid gray" :|style.borderLeft| "1px solid gray" :|style.borderRight| "1px solid gray" :|style.borderBottom| (if (= 0 num) "none" "1px solid gray") :|style.background| (if (= 0 num) "#ffffff" "#f0f0f0") :|style.paddingTop| "0.25em" :|style.paddingBottom| "0.25em" :|style.paddingLeft| "1em" :|style.paddingRight| "1em" :|style.borderRadius| "0.5em 0.5em 0 0" :|style.display| "inline-block" :append-element (create-element "a" :|href| "#" :append-element (car tab) :|onclick| (lambda (ev) (map nil (lambda (tab) (setf (jscl::oget (cdr tab) "style" "display") "none") (setf (jscl::oget (cdr tab) "style" "display") "none")) tab-list) (map nil (lambda (th tn) (setf (jscl::oget th "style" "background") (if (= tn num) "#ffffff" "#f0f0f0")) (setf (jscl::oget th "style" "borderBottom") (if (= tn num) "none" "1px solid gray"))) tbs (loop for i below (length tbs) collect i)) (setf (jscl::oget (cdr tab) "style" "display") "block") nil))))) (setf tbs `(,@tbs ,tb)) (setf (jscl::oget (cdr tab) "style" "display") (if (= num 0) "block" "none")) (append-element (cdr tab) content) tb) tab-div)) tab-list (loop for i below (length tab-list) collect i)) (append-element (create-element "div" :|style.display| "inline-block" :|style.width| "auto" :|style.borderBottom| "1px solid gray" :|style.flexGrow| 1) tab-div) outer)) (defun-f make-dragabble-list (elements &key (outer-type "div") reorder-cb on-drag insert-el) (let* ((trans "all 0.5s linear") (insert-gizmo (if insert-el (create-element outer-type :|style.position| "absolute" :|style.right| "100%" :|style.z-index| 20 :|style.display| "block" :|style.visibility| (if elements "hidden" "visible") :|style.transition| "opacity 0.5s linear" :append-element insert-el))) (insert-gizmo-width nil) (inner (create-element "div" :|style.position| "relative")) (moving-el nil) (moving-el-height nil) (moving-el-num nil) (max-top nil) (last-shift nil) (els-pos nil) (els-mid nil) (element-stack nil) (client-y0 nil) (page-y0 nil) (cur-top nil) (last-min-pos nil)) (if insert-el (progn (add-style insert-gizmo ":hover {cursor: pointer;}") (setf (jscl::oget insert-gizmo "onmouseover") (lambda (ev) (if (and (not moving-el) last-min-pos) (progn (setf (jscl::oget inner"omg-insert-position") last-min-pos) (loop for i from (max 0 last-min-pos) to (min last-min-pos (- (length element-stack) 1)) do (progn (setf (jscl::oget (nth i element-stack) "style" "transition") "all 0.1s linear") (setf (jscl::oget (nth i element-stack) "style" "transform") (if (< i last-min-pos) "translateY(-0.5em)" "translateY(0.5em)")))))))) (setf (jscl::oget insert-gizmo "onmouseout") (lambda (ev) (if (and (not moving-el) last-min-pos) (progn (setf (jscl::oget inner "omg-insert-position") nil) (map nil (lambda (el) (setf (jscl::oget el "style" "transform") "translateY(0)")) element-stack))))) (append-element insert-gizmo inner) (setf (jscl::oget inner "omg-insert-position") nil))) (labels ((set-els-pos () (setf els-pos (mapcar (lambda (el) (let ((top (jscl::oget el "offsetTop"))) (cons top (+ top (jscl::oget el "offsetHeight"))))) element-stack)) (setf els-mid (mapcar (lambda (pos) (* 0.5 (+ (car pos) (cdr pos)))) els-pos))) (up-handler (ev) (if moving-el (progn (setf (jscl::oget moving-el "style" "top") 0) (if insert-el (setf (jscl::oget insert-gizmo "style" "display") "block")) (map nil (lambda (el) (if (not (equal el moving-el)) (progn (setf (jscl::oget el "style" "transition") "none") (setf (jscl::oget el "style" "transform") "translateY(0)")) (setf (jscl::oget el "style" "transform") (format nil "translateY(~Apx)" (- cur-top (car (nth last-shift els-pos))))))) element-stack) (let ((el moving-el)) (execute-after 0.1 (lambda () (setf (jscl::oget el "style" "scale") "100%") (setf (jscl::oget el "style" "boxShadow") "0 0 0") (setf (jscl::oget el "style" "zIndex") 10) (setf (jscl::oget el "style" "transform") "translateY(0)")))) (if (and (not (equal moving-el-num last-shift)) (not (and reorder-cb (not (funcall reorder-cb moving-el-num last-shift inner))))) (progn (remove-element moving-el) (if (> last-shift moving-el-num) (if (not (equal last-shift (- (length element-stack) 1))) ((jscl::oget inner "insertBefore") moving-el (nth (+ last-shift 1) element-stack)) (append-element moving-el inner)) ((jscl::oget inner "insertBefore") moving-el (nth last-shift element-stack))) (if (> last-shift moving-el-num) (setf element-stack `(,@(subseq element-stack 0 moving-el-num) ,@(subseq element-stack (+ 1 moving-el-num) (+ last-shift 1)) ,moving-el ,@(subseq element-stack (+ last-shift 1)))) (setf element-stack `(,@(subseq element-stack 0 last-shift) ,moving-el ,@(subseq element-stack last-shift moving-el-num) ,@(subseq element-stack (+ 1 moving-el-num))))) (setf (jscl::oget inner "omg-list-elements") (mapcar (lambda (el) (jscl::oget el "omg-orig-element")) element-stack)))) (setf moving-el nil) (setf last-shift nil) (set-els-pos)))) (move-handler (ev) (let* ((x1 (jscl::oget ev "pageX")) (y1 (jscl::oget ev "pageY"))) (if moving-el (progn (setf cur-top (max 0 (min max-top (+ (- y1 page-y0) client-y0)))) (setf (jscl::oget moving-el "style" "top") (format nil "~Apx" (- cur-top client-y0))) ((jscl::oget (funcall (winref "getSelection")) "empty")) ((jscl::oget ev "stopPropagation")) (let* ((mid (+ cur-top (* 0.5 moving-el-height))) (pos (position-if (lambda (el) (and (> mid (car el)) (< mid (cdr el)))) els-pos))) (if (and pos (not (equal pos last-shift))) (let ((ls1 (if last-shift last-shift pos))) (loop for i from (max 0 (min (- ls1 1) pos)) to (min (- (length element-stack) 1) (max (+ ls1 1) pos)) do (setf (jscl::oget (nth i element-stack) "style" "transform") (format nil "translateY(~Apx)" (cond ((and (>= i pos) (< i moving-el-num)) moving-el-height) ((and (<= i pos) (> i moving-el-num)) (- moving-el-height)) (t 0))))) (setf last-shift pos) (if on-drag (funcall on-drag moving-el pos))))) nil) (if (and insert-el insert-gizmo-width) (let* ((rect ((jscl::oget inner "getBoundingClientRect"))) (top (+ (jscl::oget rect "top") (winref "scrollY"))) (left (+ (jscl::oget rect "left") (winref "scrollX"))) (y1 (- y1 top)) (minpos (if els-mid (if (< y1 (car els-mid)) '(0 . 0) (if (> y1 (car (last els-mid))) `(,(cdar (last els-pos)) . ,(length els-mid)) (loop for i below (length els-mid) when (< y1 (nth i els-mid)) return `(,(cdr (nth (- i 1) els-pos)) . ,i))))))) (if (and (< x1 (+ left (* 0.5 (jscl::oget rect "width")))) (> x1 (- left (* 2 insert-gizmo-width)))) (if (not (equal (jscl::oget insert-gizmo "style" "display") "block")) (progn (setf (jscl::oget insert-gizmo "style" "display") "block") (setf (jscl::oget insert-gizmo "style" "visibility") "visible") (setf (jscl::oget insert-gizmo "style" "opacity") 0) (ensure-element insert-gizmo (setf (jscl::oget insert-gizmo "style" "opacity") 1))) (progn (if (not (equal last-min-pos (cdr minpos))) (progn (setf (jscl::oget insert-gizmo "style" "top") (car minpos)) (setf last-min-pos (cdr minpos)))))) (if (and els-mid (equal (jscl::oget insert-gizmo "style" "display") "block")) (progn (setf (jscl::oget insert-gizmo "style" "opacity") 0) (execute-after 0.5 (lambda () (setf (jscl::oget insert-gizmo "style" "display") "none"))))))))))) (make-rec (el) (let* ((rec (create-element "div" :|style.position| "relative" :|style.transition| trans :|style.zIndex| 10 :append-element el))) (setf (jscl::oget rec "omg-orig-element") el) (setf (jscl::oget rec "onmousedown") (lambda (ev) (if (equal (jscl::oget ev "button") 0) (progn (if insert-el (setf (jscl::oget insert-gizmo "style" "display") "none")) (setf moving-el rec) (setf moving-el-num (position rec element-stack)) (setf (jscl::oget rec "style" "scale") "101%") (setf (jscl::oget rec "style" "boxShadow") "0 0 1em 0.2em #909090") (setf (jscl::oget rec "style" "zIndex") 100) (setf client-y0 (- (jscl::oget ((jscl::oget rec "getBoundingClientRect")) "top") (jscl::oget ((jscl::oget inner "getBoundingClientRect")) "top"))) (setf cur-top client-y0) (setf page-y0 (jscl::oget ev "pageY")) (setf max-top (- (jscl::oget inner "offsetHeight") (jscl::oget rec "offsetHeight"))) (set-els-pos) (setf moving-el-height (jscl::oget ((jscl::oget rec "getBoundingClientRect")) "height")) ;;(jscl::oget rec "offsetHeight")) (map nil (lambda (el) (setf (jscl::oget el "style" "transition") trans)) element-stack) (setf (jscl::oget rec "style" "transition") "all 0.1s linear"))))) rec))) (setf element-stack (mapcar (lambda (el) (let ((rec (make-rec el))) (append-element rec inner) rec)) elements)) (ensure-element inner (set-els-pos)) (setf (jscl::oget inner "omg-list-elements") elements) (setf (jscl::oget inner "omg-insert-fn") (lambda (el pos) (let ((rec (make-rec el))) (setf (jscl::oget rec "style" "transition") "none") (setf (jscl::oget rec "style" "visibility") "hidden") (setf (jscl::oget rec "style" "opacity") 0) (append-element rec inner) (ensure-element rec (let ((h (jscl::oget ((jscl::oget rec "getBoundingClientRect")) "height"))) (remove-element rec) (loop for i below (length element-stack) for el = (nth i element-stack) do (progn (setf (jscl::oget el "style" "transition") "none") (if (>= i pos) (setf (jscl::oget el "style" "transform") (format nil "translateY(~Apx)" (- h)))))) (if (>= pos (length element-stack)) (append-element rec inner) ((jscl::oget inner "insertBefore") rec (nth pos element-stack))) (setf element-stack `(,@(subseq element-stack 0 pos) ,rec ,@(subseq element-stack pos))) (setf (jscl::oget inner "omg-list-elements") (mapcar (lambda (el) (jscl::oget el "omg-orig-element")) element-stack)) (execute-after 0.1 (lambda () (setf (jscl::oget rec "style" "transition") trans) (setf (jscl::oget rec "style" "visibility") "visible") (setf (jscl::oget rec "style" "opacity") 1) (map nil (lambda (el) (setf (jscl::oget el "style" "transition") trans) (setf (jscl::oget el "style" "transform") "translateY(0)")) element-stack) (execute-after 0.5 (lambda () (set-els-pos)))))))))) (ensure-element insert-gizmo (setf insert-gizmo-width (jscl::oget ((jscl::oget insert-gizmo "getBoundingClientRect")) "width"))) (add-event-handler "document.onmouseup" #'up-handler) (add-event-handler "document.onmousemove" #'move-handler) (on-element-remove inner (lambda (el) (rm-event-handler "document.onmouseup" #'up-handler) (rm-event-handler "document.onmousemove" #'move-handler))) inner))) (defun-f dragabble-list-elements (inner) (jscl::oget inner "omg-list-elements")) (defun-f dragabble-list-insert-position (inner) (if (dragabble-list-elements inner) (jscl::oget inner "omg-insert-position") 0)) (defun-f dragabble-list-insert (inner el &optional pos) (funcall (jscl::oget inner "omg-insert-fn") el (if pos pos (dragabble-list-insert-position inner)))) (defvar-f *worker-cache* nil) (defparameter-f *current-service-worker* nil) (defun-r get-js-path () (format nil "~A~A" omg::*root-path* omg::*js-path*)) (defun-r get-sw-path () (format nil "~A~A" omg::*root-path* omg::*service-worker-path*)) (defun-r get-ww-path () (format nil "~A~A" omg::*root-path* omg::*web-worker-path*)) (defun-r get-root-path () omg::*root-path*) (defclass-f webworker () ((worker :accessor worker) (ready :initform nil :accessor ready) (busy :initform nil :accessor busy) (persistent-cache :initform nil :initarg :persistent-cache :accessor persistent-cache) (return-handlers :accessor return-handlers :initform nil))) (defclass-f classic-worker (webworker) ()) (defclass-f service-worker (webworker) ()) (defparameter-f *web-workers-pool* nil) (def-local-macro-f when-worker-ready (ww &rest code) (let ((wwait (gensym))) `(labels ((,wwait () (if (ready ,ww) (progn ,@code) (execute-after 0.1 #',wwait)))) (,wwait)))) (def-local-macro-f when-worker-free (ww &rest code) (let ((wwait (gensym))) `(when-worker-ready ,ww (labels ((,wwait () (if (busy ,ww) (execute-after 0.1 #',wwait) (progn ,@code)))) (,wwait))))) (defmethod-f msg ((ww webworker) data &key transfer) (when-worker-ready ww (if (worker ww) (if transfer ((jscl::oget (worker ww) "postMessage") (make-js-object :|code| data) transfer) ((jscl::oget (worker ww) "postMessage") (make-js-object :|code| data)))))) (defmethod-f initialize-instance :after ((ww webworker) &rest args) (labels ((wait-ww (timeout) (if (and (slot-boundp ww 'worker) (not (ready ww))) (setf (jscl::oget (worker ww) "onmessage") (lambda (ev) (cond ((equal (jscl::oget ev "data") "BOOT") ((jscl::oget (worker ww) "postMessage") (make-js-object :|code| (format nil "~Aself.OMG.Base='~A' ; OMG.session_id='~A' ; self.postMessage('BOOT DONE');" (if (persistent-cache ww) "self.OMG.PersistentCache=true ; " "") (jscl::oget (winref "self") "OMG" "Base") (jscl::oget (winref "self") "OMG" "session_id")) :|cache| (jscl::oget (winref "OMG") "FetchCache")))) ((equal (jscl::oget ev "data") "BOOT DONE") (setf (slot-value ww 'ready) t) (setf (jscl::oget (worker ww) "onmessage") (lambda (ev)))) (t (error "Invalid init message from worker"))))) (execute-after timeout (lambda () (wait-ww (* 2 timeout))))))) (wait-ww 0.1))) (defmethod-f initialize-instance :before ((ww service-worker) &key &allow-other-keys) ((jscl::oget ((jscl::oget (winref "navigator") "serviceWorker" "register") (get-sw-path) (make-js-object :|scope| (get-root-path))) "then") (lambda (reg) ((jscl::oget reg "update")) (labels ((wait-sw (timeout) (if (jscl::js-null-p (jscl::oget (winref "navigator") "serviceWorker")) (execute-after timeout (lambda () (wait-sw (* timeout 2)))) (progn (setf (slot-value ww 'worker) (jscl::oget (winref "navigator") "serviceWorker" "controller")) (setf (slot-value ww 'ready) t) (setf *current-service-worker* ww))))) (setf (jscl::oget (winref "navigator") "serviceWorker" "oncontrollerchange") (lambda (ev) (jslog "Controller changed!") (wait-sw 0.1))) (wait-sw 0.1))))) (defmethod-f initialize-instance :before ((ww classic-worker) &rest args) (push ww *worker-cache*) (setf (slot-value ww 'worker) (jscl::make-new (jscl::%js-vref "Worker") (jscl::lisp-to-js ((jscl::oget (winref "OMG") "get_ww_js_url")))))) (defmethod-f kill ((ww webworker)) (if (worker ww) ((jscl::oget (worker ww) "terminate"))) (setf *worker-cache* (remove-if (lambda (w) (equal w ww)) *worker-cache*))) (defmethod-f kill ((ww service-worker) &optional (try-count 20)) (if *current-service-worker* ((jscl::oget ((jscl::oget (jscl::%js-vref "navigator") "serviceWorker" "getRegistration") (get-root-path)) "then") (lambda (reg) ((jscl::oget reg "unregister")) (setf *current-service-worker* nil))) (if (> try-count 0) (execute-after 0.5 (lambda () (kill ww (- try-count 1)))) (jslog "Service Worker not spawned yet, cannot kill"))) nil) (def-local-macro-f in-service-worker (&rest code) (let ((js (omg::compile-to-js `(progn ,@code) *package* :recursive t)) (fn (gensym))) `(progn (if *current-service-worker* (msg *current-service-worker* ,js) (labels ((,fn () (if *current-service-worker* (msg *current-service-worker* ,js) (execute-after 0.2 #',fn)))) (make-instance 'service-worker) (,fn))) nil))) (defvar-f *linefeed* (format nil "~%")) (defparameter-f *main-lambdas* nil) (defun-f register-main-lambda (l) (let ((id (gensym2))) (push (cons id l) *main-lambdas*))) (defun-f compile-js (code) (setf (jscl::oget (winref "OMG") "disableLIL") t) (prog1 (jscl::with-compilation-environment (jscl::compile-toplevel code t t)) (setf (jscl::oget (winref "OMG") "disableLIL") nil))) (defclass-f dont-transfer () ()) (defun-f store-to-buffer (obj buf &key (start 0) respect-transfer background progress-cb final-cb) (let ((last-id 100) (obj-hash (make-hash-table)) (len (jscl::oget buf "byteLength")) (lambda-stack nil) (t0 (now)) (dt (if (numberp background) background 0.1))) (macrolet ((ps (&rest code) `(push (lambda () ,@code) lambda-stack)) (psp (&rest code) `(ps (pop lambda-stack) ,@code)) (check-id (typ &rest cod) `(let* ((old-id (gethash obj obj-hash)) (obj-id (if old-id old-id (setf (gethash obj obj-hash) (incf last-id))))) (if (not old-id) (progn ,@cod) (store-id-set ,typ 0 obj-id))))) (labels ((store-id (id l &optional (id1 l)) (multiple-value-bind (d r) (floor l 4) (if (<= (+ 8 l start) len) (let ((idb (jscl::make-new (winref "Int32Array") buf start 2))) (setf (jscl::oget idb 0) id) (setf (jscl::oget idb 1) id1))) (+ 8 l start (if (> r 0) (- 4 r) 0)))) (store-id-set (id l &optional (id1 l)) (setf start (store-id id l id1))) (sing-val (id typ obj) (let ((start1 (store-id id 4))) (if (<= start1 len) (let ((b1 (jscl::make-new (winref typ) buf (+ start 8) 1))) (setf (jscl::oget b1 0) obj))) (setf start start1))) (store-val (obj) (typecase obj (integer (sing-val 0 "Int32Array" obj)) ;; 0 - integer (real (sing-val 1 "Float32Array" obj)) ;; 1 - real (string (let* ((enc (jscl::make-new (winref "TextEncoder"))) (sb ((jscl::oget enc "encode") obj)) (bl (jscl::oget sb "byteLength")) (start1 (store-id 2 bl))) ;; 2 - string (if (<= start1 len) (let ((rb (jscl::make-new (winref "Uint8Array") buf (+ start 8) bl))) (loop for i below bl do (setf (jscl::oget rb i) (jscl::oget sb i))))) (setf start start1))) (null (store-id-set 4 0 0)) ;; 4 - NIL is CONS, 0 for NIL (symbol (store-id-set 3 0) ;; 3 - symbol (psp (store-val (symbol-name obj))) (psp (store-val (package-name (symbol-package obj))))) (jscl::mop-object (if (and respect-transfer (typep obj (find-class 'dont-transfer))) (store-id-set 4 0 0) (check-id 6 ;; 6 - CLOS object, class and alist of slots follows (let ((slts (remove-if #'null (mapcar (lambda (slot) (let ((name (getf slot :name))) (if (slot-boundp obj name) (cons name (slot-value obj name))))) (jscl::class-slots (class-of obj)))))) (store-id-set 6 0 obj-id) (psp (store-val slts)) (psp (store-val (class-name (class-of obj)))))))) (list (check-id 4 ;; 4 -- cons (store-id-set 4 0 obj-id) (psp (store-val (cdr obj))) (psp (store-val (car obj))))) (vector (check-id 5 (store-id-set 5 0 obj-id) ;; 5 - array, array dims follows (let ((i 0) (lar (length obj))) (ps (if (< i lar) (store-val (aref obj i)) (pop lambda-stack)) (incf i)) (psp (store-val (list (length obj))))))) (array (check-id 5 (store-id-set 5 0 obj-id) (let ((i 0) (lar (apply #'* (array-dimensions obj)))) (ps (if (< i lar) (store-val (aref obj i)) (pop lambda-stack)) (incf i)) (psp (store-val (array-dimensions obj)))))) (jscl::js-object (store-id-set 4 0 0)) ;; JS objects are not serializable, store NIL instead (function (let ((ml (car (rassoc obj *main-lambdas*)))) (if ml (progn (store-id-set 7 0 0) ;; 7 -- main thread lambda, symbol key follow (psp (store-val ml))) (store-id-set 4 0 0)))) ;; other lambdas are not serializable, store NIL instead) (t (error (format nil "Don't know, how to serialize ~A" (type-of obj))))))) (psp (store-val obj)) (if background (labels ((doit () (setf t0 (now)) (loop while (and lambda-stack (< (- (now) t0) dt)) do (funcall (car lambda-stack))) (if progress-cb (funcall progress-cb start)) (if lambda-stack (execute-after 0 #'doit) (if final-cb (funcall final-cb start))))) (if progress-cb (funcall progress-cb start)) (execute-after 0 #'doit)) (loop while lambda-stack do (funcall (car lambda-stack)))) start)))) (defun-f load-from-buffer (buf &key (start 0) background progress-cb final-cb) (let ((len (jscl::oget buf "byteLength")) (obj-hash (make-hash-table)) (exit-flg nil) (lambda-stack (list (if background (lambda (obj) (if progress-cb (funcall progress-cb start)) (if final-cb (funcall final-cb obj start)) (setf exit-flg t)) (lambda (obj) (return-from load-from-buffer (values obj start)))))) (dt (if (numberp background) background 0.1))) (labels ((ld () (let ((t0 (now))) (loop while (and (<= start (- len 8)) (or (not background) (< (- (now) t0) dt))) do (let* ((idb (jscl::make-new (winref "Int32Array") buf start 2)) (typ (jscl::oget idb 0)) (b2 (jscl::oget idb 1))) (labels ((cur-lam (obj) (funcall (car lambda-stack) obj)) (eob () (error "End of the buffer reached!") (return-from load-from-buffer (values nil start))) (sing-val (typ) (if (> (+ start 4) len) (eob)) (incf start 4) (cur-lam (jscl::oget (jscl::make-new (winref typ) buf (- start 4) 1) 0)))) (macrolet ((ps (&rest code) `(push (lambda (obj) ,@code) lambda-stack)) (psp (&rest code) `(ps (pop lambda-stack) ,@code))) (incf start 8) (case typ (0 (sing-val "Int32Array")) ;; integer (1 (sing-val "Float32Array")) ;; real (2 (if (<= (+ start b2) len) ;; string (multiple-value-bind (x r) (floor b2 4) (let ((s1 start)) (incf start (+ b2 (if (> r 0) (- 4 r) 0))) (cur-lam ((jscl::oget (jscl::make-new (winref "TextDecoder")) "decode") ((jscl::oget (jscl::make-new (winref "Uint8Array") buf s1 b2) "slice")))))) (eob))) (3 ;; symbol (let (pkg) (psp (cur-lam (intern obj (find-package pkg)))) (psp (setf pkg obj)))) (4 ;; cons (if (= b2 0) (cur-lam nil) ;; nil (multiple-value-bind (obj fnd) (gethash b2 obj-hash) (if fnd (cur-lam obj) (let ((cns (cons nil nil))) (setf (gethash b2 obj-hash) cns) (psp (setf (cdr cns) obj) (cur-lam cns)) (psp (setf (car cns) obj))))))) (5 ;; array (multiple-value-bind (obj fnd) (gethash b2 obj-hash) (if fnd (cur-lam obj) (let (arr len (cnt 0) (b22 b2)) (ps (if (< cnt len) (setf (aref arr cnt) obj)) (incf cnt) (when (>= cnt len) (pop lambda-stack) (cur-lam arr))) (psp (setf arr (make-array obj)) (setf len (apply #'* obj)) (setf (gethash b22 obj-hash) arr)))))) (6 ;; MOP object (multiple-value-bind (obj fnd) (gethash b2 obj-hash) (if fnd (cur-lam obj) (let (inst (b22 b2)) (psp (map nil (lambda (slt) (setf (slot-value inst (car slt)) (cdr slt))) obj) (cur-lam inst)) (psp (setf inst (allocate-instance (find-class obj))) (setf (gethash b22 obj-hash) inst)))))) (7 ;; main thread lambda (psp (cur-lam (jscl::js-to-lisp ;; without js-to-lisp it is not working (WHY?!!!) (let* ((cur-buf-len (* 1024 1024 128)) (req-buf (jscl::make-new (winref "SharedArrayBuffer") cur-buf-len))) (lambda (&rest args) (labels ((stor-all (ofs) (let ((siz (store-to-buffer (cons obj args) req-buf :start ofs))) (if (> siz cur-buf-len) (progn (setf cur-buf-len (* 2 cur-buf-len)) (setf req-buf (jscl::make-new (winref "SharedArrayBuffer") cur-buf-len)) (stor-all ofs))))) (try-fetch (rc) (let ((ibuf (jscl::make-new (winref "Int32Array") req-buf 0 2))) (setf (jscl::oget ibuf 0) 0) (setf (jscl::oget ibuf 1) rc) (funcall (winref "postMessage") req-buf) ((jscl::oget (jscl::%js-vref "Atomics") "wait") ibuf 0 0) (let ((res-len (jscl::oget ibuf 0))) (if (> res-len 0) (if (> res-len (jscl::oget req-buf "byteLength")) (progn (setf cur-buf-len res-len) (setf req-buf (jscl::make-new (winref "SharedArrayBuffer") cur-buf-len)) (store-to-buffer sym req-buf :start 8) (try-fetch 3)) (return-from try-fetch (load-from-buffer req-buf :start 4)))))))) (stor-all 8) (apply #'values (try-fetch 2)))))))))))))))) (lp () (when (not exit-flg) (ld) (if progress-cb (funcall progress-cb start)) (execute-after 0 #'lp)))) (if background (progn (if progress-cb (funcall progress-cb start)) (lp)) (progn (ld) (error "End of the buffer!")))) (values nil nil))) (defun-f get-free-worker () (let* ((w1 (car (remove-if (lambda (w) (busy w)) *web-workers-pool*))) (w (if w1 w1 (make-instance 'classic-worker)))) (if (not w1) (push w *web-workers-pool*)) w)) (defparameter-f *main-thread-result-cache* nil) (def-local-macro-f run-in-web-worker (ww1 &rest code) (let* ((sym (gensym)) (req-buf (gensym)) (req-buf2 (gensym)) (ibuf (gensym)) (ev (gensym)) (res-len (gensym)) (cur-buf-len (gensym)) (rvals (gensym)) (v0 (gensym)) (ww (gensym)) (hl (gensym)) (cache-lst (gensym)) (cache-all (gensym)) (cache-h (gensym)) (tmp-cache-h (gensym)) (lam (gensym)) (val (gensym)) (fnd (gensym)) (fhandler (gensym)) (req-code (gensym)) (alt-buf (gensym)) (local-symbols (remove-if #'null (mapcar #'jscl::binding-name (remove-if-not #'null (cadr jscl::*environment*) :key #'jscl::binding-declarations)) :key #'symbol-package)) (jscode (let ((jscl::*environment* (jscl::copy-lexenv jscl::*environment*))) (setf (cadr jscl::*environment*) (remove-if #'null (cadr jscl::*environment*) :key #'jscl::binding-declarations)) (omg::compile-to-js `(progn (if (and (jscl::oget (winref "OMG") "PersistentCache") (not (jscl::oget (winref "OMG") "VarCache"))) (setf (jscl::oget (winref "OMG") "VarCache") (make-hash-table))) (let* ((,cache-lst ',(if (and (listp (car code)) (equal 'cache-vars (caar code))) (cdar code))) (,cache-all (position t ,cache-lst)) (,cur-buf-len (* 1024 1024 128)) (,req-buf (jscl::make-new (winref "SharedArrayBuffer") ,cur-buf-len)) (,req-buf2 (jscl::make-new (winref "SharedArrayBuffer") ,cur-buf-len)) (,cache-h (if (jscl::oget (winref "OMG") "PersistentCache") (jscl::oget (winref "OMG") "VarCache") (make-hash-table))) (,tmp-cache-h (make-hash-table))) (labels ((,fhandler (,sym &optional (,req-code 0) ,alt-buf) (labels ((try-fetch () (let ((,ibuf (jscl::make-new (winref "Int32Array") (if ,alt-buf ,req-buf2 ,req-buf) 0 2))) (store-to-buffer ,sym (if ,alt-buf ,req-buf2 ,req-buf) :start 8) (setf (jscl::oget ,ibuf 0) 0) (setf (jscl::oget ,ibuf 1) ,req-code) (funcall (winref "postMessage") (if ,alt-buf ,req-buf2 ,req-buf)) ((jscl::oget (jscl::%js-vref "Atomics") "wait") ,ibuf 0 0) (let ((,res-len (jscl::oget ,ibuf 0))) (if (> ,res-len (jscl::oget (if ,alt-buf ,req-buf2 ,req-buf) "byteLength")) (progn (setf ,cur-buf-len ,res-len) (setf ,req-buf (jscl::make-new (winref "SharedArrayBuffer") ,cur-buf-len)) (setf ,req-buf2 (jscl::make-new (winref "SharedArrayBuffer") ,cur-buf-len)) (try-fetch)) (load-from-buffer (if ,alt-buf ,req-buf2 ,req-buf) :start 4)))))) (multiple-value-bind (,val ,fnd) (gethash ,sym ,tmp-cache-h) (if ,fnd ,val (multiple-value-bind (,val ,fnd) (gethash ,sym ,cache-h) (if ,fnd ,val (let ((,val (try-fetch))) (if (and (jscl::oget (winref "OMG") "PersistentCache") (not (position ,sym ',local-symbols)) (not (position ,sym ,cache-lst))) (setf (jscl::oget ,sym "value") ,val) (if (position ,sym ,cache-lst) (setf (gethash ,sym ,tmp-cache-h) ,val) (if (or ,cache-all (jscl::oget (winref "OMG") "PersistentCache")) (setf (gethash ,sym ,cache-h) ,val)))) ,val)))))))) (setf (jscl::oget (winref "OMG") "FValueFetchHandler") (lambda (,sym) (if (not (or (eq ,sym 'store-to-buffer) (eq ,sym 'load-from-buffer))) (let* ((,val (,fhandler ,sym 4 t))) (if (stringp ,val) ,val))))) (setf (jscl::oget (winref "OMG") "symbolValueFetchHandler") #',fhandler)) (let ((,rvals (multiple-value-list (progn ,@(if (and (listp (car code)) (equal 'cache-vars (caar code))) (cdr code) code))))) (labels ((try-store () (let ((,res-len (store-to-buffer ,rvals ,req-buf :start 8 :respect-transfer t))) (if (> ,res-len (jscl::oget ,req-buf "byteLength")) (progn (setf ,cur-buf-len ,res-len) (setf ,req-buf (jscl::make-new (winref "SharedArrayBuffer") ,cur-buf-len)) (try-store)))))) (try-store) (let ((,ibuf (jscl::make-new (winref "Int32Array") ,req-buf 0 2))) (setf (jscl::oget ,ibuf 1) 1) (funcall (winref "postMessage") ,req-buf)))))) *package*)))) `(let ((,ww (if ,ww1 ,ww1 (get-free-worker)))) (when-worker-ready ,ww (setf (jscl::oget (worker ,ww) "onmessage") (lambda (,ev) (let* ((,req-buf (jscl::oget ,ev "data")) (,ibuf (jscl::make-new (winref "Int32Array") ,req-buf 0 2)) (,v0 (jscl::oget ,ibuf 1))) (case ,v0 (0 (let* ((,sym (load-from-buffer ,req-buf :start 8)) ;; 0 -- symbol requested (,res-len (store-to-buffer (case ,sym ,@(mapcar (lambda (sym) `(,sym ,sym)) local-symbols) (t (symbol-value ,sym))) ,req-buf :start 4 :respect-transfer t))) ; (format t "REQ: ~A" ,sym) ((jscl::oget (jscl::%js-vref "Atomics") "store") ,ibuf 0 ,res-len) ((jscl::oget (jscl::%js-vref "Atomics") "notify") ,ibuf 0))) (1 (let ((,rvals (load-from-buffer ,req-buf :start 8)) ;; 0 -- return values arrived (,hl (return-handlers ,ww))) (setf (slot-value ,ww 'return-handlers) nil) (setf (slot-value ,ww 'busy) nil) (setf (jscl::oget (worker ,ww) "onmessage") (lambda (ev))) (map nil (lambda (l) (apply l ,rvals)) ,hl))) (2 (if (not *main-thread-result-cache*) ;; 2 -- execute a lambda (setf *main-thread-result-cache* (make-hash-table))) (let* ((,sym (load-from-buffer ,req-buf :start 8)) (,lam (cdr (assoc (car ,sym) *main-lambdas*)))) (if ,lam (let ((,val (multiple-value-list (apply ,lam (cdr ,sym))))) (setf (gethash (car ,sym) *main-thread-result-cache*) ,val) ((jscl::oget (jscl::%js-vref "Atomics") "store") ,ibuf 0 (store-to-buffer ,val ,req-buf :start 4 :respect-transfer t)) ((jscl::oget (jscl::%js-vref "Atomics") "notify") ,ibuf 0)) (progn ((jscl::oget (jscl::%js-vref "Atomics") "store") ,ibuf 0 -1) ((jscl::oget (jscl::%js-vref "Atomics") "notify") ,ibuf 0) (error "Unregistered main thread lambda execution requested!"))))) (3 (let ((,sym (load-from-buffer ,req-buf :start 8))) ;; 3 -- send the result again ((jscl::oget (jscl::%js-vref "Atomics") "store") ,ibuf 0 (store-to-buffer (gethash ,sym *main-thread-result-cache*) ,req-buf :start 4 :respect-transfer t)) (remhash ,sym *main-thread-result-cache*) ((jscl::oget (jscl::%js-vref "Atomics") "notify") ,ibuf 0))) (4 (let* ((,sym (load-from-buffer ,req-buf :start 8))) ;; 4 -- send a value from FetchCache ((jscl::oget (jscl::%js-vref "Atomics") "store") ,ibuf 0 (store-to-buffer (jscl::oget (winref "OMG") "FetchCache" (format nil "~A::~A" (package-name (symbol-package ,sym)) (symbol-name ,sym))) ,req-buf :start 4)) ((jscl::oget (jscl::%js-vref "Atomics") "notify") ,ibuf 0))))))) (setf (slot-value ,ww 'busy) t) (msg ,ww ,jscode)) ,ww))) (def-local-macro-f bind-exit-values-for (args ww &rest code) (let ((ww1 (gensym))) `(let ((,ww1 ,ww)) (setf (slot-value ,ww1 'return-handlers) (cons (lambda (,(car args) &optional ,@(cdr args)) ,@code) (return-handlers ,ww1))) ,ww1))) (defmacro-f set-service-worker-uri-handler (uri-req-event &rest code) (let ((ev (gensym2)) (opts (gensym2)) (body (gensym2)) (options (gensym2)) (args (gensym2)) (uri (gensym2)) (old-handler (gensym2)) (unused-args (list (gensym2) (gensym2) (gensym2)))) `(in-service-worker (let ((,old-handler (jscl::oget (jscl::%js-vref "self") "OMG" "fetchHandler"))) (setf (jscl::oget (jscl::%js-vref "self") "OMG" "fetchHandler") (lambda (,ev) (apply (lambda (,@uri-req-event &optional ,@unused-args) (labels ((respond-with (&optional ,body ,options) (let ((,opts (jscl::new))) (loop for (k v) on ,options by #'cddr do (setf (jscl::oget obj (symbol-name k)) v)) ((jscl::oget ,ev "respondWith") (jscl::make-new (jscl::%js-vref "Response") ,body ,opts)))) (jslog (&rest ,args) (apply (jscl::oget (jscl::%js-vref "self") "console" "log") ,args)) (default-action () (funcall ,old-handler ,ev)) (uri-path (,uri) (jscl::oget (jscl::make-new (jscl::oget (jscl::%js-vref "self") "URL") (jscl::lisp-to-js ,uri)) "pathname"))) ,@code)) (list (jscl::oget ,ev "request" "url") (jscl::oget ,ev "request") ,ev)))))))) (defvar-f *pwa-mode* nil) (defun make-pwa (&key (name "Application") (short-name "app") (display "standalone") (theme-color "#000000") (background-color "#ffffff") icon-path) (setf *pwa-mode* t) (let* ((manifest-path (format nil "~A.json" (omg::random-string 20))) (icon-path (if icon-path (if (equal (type-of icon-path) 'pathname) icon-path (parse-namestring icon-path)))) (icon-ext (if icon-path (pathname-type icon-path) "png")) (icon-type (media-types:extension-media-type icon-ext)) (icon-size (if icon-path (cond ((equal icon-type "image/png") (let ((png (pngload:load-file icon-path :decode nil))) (format nil "~Ax~A" (pngload:get-metadata png :width) (pngload:get-metadata png :height)))) ((equal icon-type "image/jpeg") (multiple-value-bind (h w ncomp trans) (cl-jpeg:jpeg-file-dimensions icon-path) (declare (ignore ncomp)) (declare (ignore trans)) (format nil "~Ax~A" w h))) ((equal icon-type "image/gif") (let ((gif (skippy:load-data-stream icon-path))) (format nil "~Ax~A" (skippy:width gif) (skippy:height gif)))) (t (error (format nil "Unsupported icon format: ~A" icon-type)))) "512x512")) (icon-url-path (format nil "~A.~A" (omg::random-string 20) icon-ext))) (add-serve-path manifest-path `(200 (:content-type "text/javascript; charset=utf-8") (,(format nil "{\"name\":\"~A\",\"short_name\":\"~A\",\"display\":\"~A\",\"start_url\":\"~A\",\"theme_color\":\"~A\",\"background_color\":\"~A\",\"icons\"\: [{\"src\": \"~A~A\",\"sizes\": \"~A\",\"type\": \"~A\"}]}" name short-name display omg::*root-path* theme-color background-color omg::*root-path* icon-url-path icon-size icon-type)))) (add-serve-path icon-url-path `(200 (:content-type ,icon-type) ,(if icon-path icon-path *default-icon*))) (add-to-root-html-head (format nil " <title>~A</title> <meta name=\"viewport\" content=\"width=device-width, user-scalable=no\"/> <link rel=\"manifest\" href=\"~A~A\" /> " name omg::*root-path* manifest-path)) (add-to-root-html-head (format nil "<link rel=\"icon\" href=\"~A~A\" type=\"~A\" />" omg::*root-path* icon-url-path icon-type)) (pushnew '(make-instance 'service-worker) omg::*pre-boot-functions*))) (defclass-f idb-connection () ((connection :initarg :connection :accessor connection))) (defclass-f idb-object-store () ((name :initarg :name :accessor name :initform nil) (conn :initarg :connection :accessor conn :initform nil) (key :initarg :key :accessor key :initform nil) (auto-increment :initarg :auto-increment :accessor auto-increment :initform nil) (trans :initarg :trans :initform nil :accessor trans) (stor :initarg :trans :initform nil :accessor stor))) (defclass-f idb-transaction () ((stores :initarg :stores :accessor stores :initform nil) (mode :initarg :mode :accessor mode :initform :readonly) (durability :initarg :durability :accessor durability :initform :default) (conn :initarg :connection :accessor conn :initform (error "Please, specify a connection for idb-transaction!")) (trans :accessor trans))) (defmethod-f initialize-instance :after ((tr idb-transaction) &rest args) (setf (slot-value tr 'stores) (map 'vector #'jscl::lisp-to-js (let ((str (stores tr))) (if str (if (stringp str) (list str) str) (store-names (conn tr)))))) (setf (slot-value tr 'trans) ((jscl::oget (connection (conn tr)) "transaction") (stores tr) (case (mode tr) (:readonly "readonly") (:readwrite "readwrite") (:readwriteflush "readwriteflush") (t (error (format nil "Invalid mode for idb-transaction: ~A, must be :readonly, :readwrite or :readwriteflush!" (mode tr))))) (make-js-object :|durability| (case (durability tr) (:default "default") (:strict "strict") (:relaxed "relaxed") (t (error (format nil "Invalid durability for idb-transaction: ~A, must be :default, :strict or :relaxed" (durability tr))))))))) (defmethod-f close ((c idb-connection)) ((jscl::oget (connection c) "close"))) (defmethod-f store-names ((c idb-connection)) (jscl::oget (connection c) "objectStoreNames")) (defmethod-f create ((s idb-object-store)) ((jscl::oget (connection (conn s)) "createObjectStore") (name s) (apply #'make-js-object `(,@(if (key s) `(:|keyPath| ,(key s))) ,@(if (auto-increment s) `(:|autoIncrement| t)))))) (defmethod-f initialize-instance :after ((s idb-object-store) &rest args) (if (and (not (conn s)) (not (trans s))) (error "Please specify a connection for idb-object-store!") (when (trans s) (setf (slot-value s 'conn) (conn (trans s))) (if (not (name s)) (if (= 1 (length (stores (trans s)))) (setf (slot-value s 'name) (jscl::js-to-lisp (aref (stores (trans s)) 0))) (error "Please, specify a name for idb-object-store! The transaction belongs to multiple stores!"))) (setf (slot-value s 'stor) ((jscl::oget (trans (trans s)) "objectStore") (jscl::lisp-to-js (name s)))) (setf (slot-value s 'key) (jscl::oget (stor s) "keyPath")))) (if (not (name s)) (error "Please, specify a name for idb-object-store!")) (loop for name across (store-names (conn s)) when (equal (jscl::js-to-lisp name) (name s)) return t finally (setf (slot-value s 'stor) (create s)))) (defmethod-f add ((s idb-object-store) key data &key when-ok when-err put raw) (let* ((len (if raw (jscl::oget data "byteLength") (omgui::store-to-buffer data (jscl::make-new (winref "SharedArrayBuffer") 1)))) (buf (if raw data (jscl::make-new (winref "ArrayBuffer") len)))) (if (not raw) (omgui::store-to-buffer data buf)) (let ((req ((jscl::oget (stor s) (if put "put" "add")) buf key))) (if when-ok (setf (jscl::oget req "onsuccess") (lambda (ev) (funcall when-ok)))) (setf (jscl::oget req "onerror") (lambda (ev) (if when-err (funcall when-err (jscl::oget req "error" "message")) (error (format nil "IDB add error: ~A" (jscl::oget req "error" "message"))))))))) (defmethod-f get ((s idb-object-store) key cb &optional err raw) (let ((req ((jscl::oget (stor s) "get") key))) (setf (jscl::oget req "onsuccess") (lambda (ev) (let ((res (jscl::oget req "result"))) (funcall cb (if raw res (if res (omgui::load-from-buffer res))))))) (setf (jscl::oget req "onerror") (lambda (ev) (if err (funcall err (jscl::oget req "error" "message")) (error (format nil "idb get error: ~A" (jscl::oget req "error" "message")))))))) (defmethod-f idb-delete ((s idb-object-store) key &key when-ok when-err) (let ((req ((jscl::oget (stor s) "delete") key))) (if when-ok (setf (jscl::oget req "onsuccess") (lambda (ev) (funcall when-ok)))) (setf (jscl::oget req "onerror") (lambda (ev) (if when-err (funcall when-err (jscl::oget req "error" "message")) (error (format nil "IDB delete error: ~A" (jscl::oget req "error" "message")))))))) (defmethod-f get-all-keys ((s idb-object-store) cb &optional err) (let ((req ((jscl::oget (stor s) "getAllKeys")))) (setf (jscl::oget req "onsuccess") (lambda (ev) (funcall cb (map 'vector #'jscl::js-to-lisp (jscl::oget req "result"))))) (setf (jscl::oget req "onerror") (lambda (ev) (if err (funcall err (jscl::oget req "error" "message")) (error (format nil "get-all-keys error: ~A" (jscl::oget req "error" "message")))))))) (def-local-macro-f with-indexed-db (conn-name-version &rest code) (let* ((conn (car conn-name-version)) (name (cadr conn-name-version)) (version (caddr conn-name-version)) (version (if version version 1)) (req (gensym)) (err (gensym)) (ev (gensym))) `(let ((,req ((jscl::oget (winref "indexedDB") "open") ,name ,version)) (,err nil)) (setf (jscl::oget ,req "onerror") (lambda (,ev) (error (format nil "Error when opening database ~A: ~A" ,name (jscl::oget ,req "error" "message"))))) (setf (jscl::oget ,req "onsuccess") (lambda (,ev) (if (not ,err) (let ((,conn (make-instance 'idb-connection :connection (jscl::oget ,req "result")))) ,@code (close ,conn))))) (setf (jscl::oget ,req "onupgradeneeded") (lambda (,ev) (setf ,err t) (if (= ,version 1) (format t "Database ~A does not exists" ,name) (format t "Database upgrade not yet implemented")) ((jscl::oget (jscl::oget ,req "result") "close")))) ,req))) (def-local-macro-f setup-indexed-db (conn-name-version &rest code) (let* ((conn (car conn-name-version)) (name (cadr conn-name-version)) (version (caddr conn-name-version)) (version (if version version 1)) (req (gensym)) (err (gensym)) (ev (gensym))) `(let ((,req ((jscl::oget (winref "indexedDB") "open") ,name ,version)) (,err nil)) (setf (jscl::oget ,req "onerror") (lambda (,ev) (error (format nil "Error when opening database ~A: ~A" ,name (jscl::oget ,req "error" "message"))))) (setf (jscl::oget ,req "onsuccess") (lambda (,ev) (let ((,conn (jscl::oget ,req "result"))) ((jscl::oget ,conn "close"))))) (setf (jscl::oget ,req "onupgradeneeded") (lambda (,ev) (let ((,conn (make-instance 'idb-connection :connection (jscl::oget ,req "result")))) ,@code)))))) (defun-f indexed-db-add (db store key val &key when-ok when-err raw) (with-indexed-db (conn db) (let* ((tr (make-instance 'idb-transaction :connection conn :stores store :mode :readwrite)) (st (make-instance 'idb-object-store :trans tr))) (add st key val :when-ok when-ok :when-err when-err :raw raw)))) (defun-f indexed-db-put (db store key val &key when-ok when-err raw) (with-indexed-db (conn db) (let* ((tr (make-instance 'idb-transaction :connection conn :stores store :mode :readwrite)) (st (make-instance 'idb-object-store :trans tr))) (add st key val :when-ok when-ok :when-err when-err :put t :raw raw)))) (def-local-macro-f indexed-db-get (val-db-store-key-raw &rest code) (let* ((conn (gensym)) (tr (gensym)) (st (gensym)) (val (car val-db-store-key-raw)) (db-store-key (cadr val-db-store-key-raw)) (db (car db-store-key)) (store (cadr db-store-key)) (key (caddr db-store-key)) (raw (caddr val-db-store-key-raw))) `(with-indexed-db (,conn ,db) (let* ((,tr (make-instance 'idb-transaction :connection ,conn :stores ,store :mode :readonly)) (,st (make-instance 'idb-object-store :trans ,tr))) (get ,st ,key (lambda (,val) ,@code) nil ,raw))))) (def-local-macro-f indexed-db-delete (db-store-key &rest code) (let* ((conn (gensym)) (tr (gensym)) (st (gensym)) (db (car db-store-key)) (store (cadr db-store-key)) (key (caddr db-store-key))) `(with-indexed-db (,conn ,db) (let* ((,tr (make-instance 'idb-transaction :connection ,conn :stores ,store :mode :readwrite)) (,st (make-instance 'idb-object-store :trans ,tr))) (idb-delete ,st ,key :when-ok (lambda () ,@code)))))) (def-local-macro-f indexed-db-get-all-keys (val-db-store &rest code) (let* ((conn (gensym)) (tr (gensym)) (st (gensym)) (val (car val-db-store)) (db-store (cadr val-db-store)) (db (car db-store)) (store (cadr db-store))) `(with-indexed-db (,conn ,db) (let* ((,tr (make-instance 'idb-transaction :connection ,conn :stores ,store :mode :readonly)) (,st (make-instance 'idb-object-store :trans ,tr))) (get-all-keys ,st (lambda (,val) ,@code)))))) (def-local-macro-f if-idb-key (db-store-key true &optional false) (let* ((conn (gensym)) (tr (gensym)) (st (gensym)) (val (gensym)) (db (car db-store-key)) (store (cadr db-store-key)) (key (caddr db-store-key))) `(with-indexed-db (,conn ,db) (let* ((,tr (make-instance 'idb-transaction :connection ,conn :stores ,store :mode :readonly)) (,st (make-instance 'idb-object-store :trans ,tr))) (get ,st ,key (lambda (,val) (if ,val ,true ,false))))))) (def-local-macro-f with-self (var &rest code) `(let (,var) (setf ,var (progn ,@code)))) (def-local-macro-f oget-bind (vars el keys &rest code) (let* ((o (gensym)) (innr `(let (,@(mapcar (lambda (v k) `(,v (jscl::oget ,(if (listp el) o el) ,k))) vars keys)) ,@code))) (if (listp el) `(let ((,o (jscl::oget ,@el))) ,innr) innr))) (defun-f now () (/ (get-internal-real-time) internal-time-units-per-second)) (defun-f add-event-listener (event fn &key passive once capture element) (let ((options (make-js-object :|once| once :|passive| passive :|capture| capture))) (if element ((jscl::oget element "addEventListener") event fn options) (funcall (winref "addEventListener") event fn options)))) (def-local-macro-f with-promise (p &key then catch) (let ((pv (gensym))) `(let* ((,pv ,p) ,@(if then `((,pv ((jscl::oget ,pv "then") ,then)))) ,@(if catch `((,pv ((jscl::oget ,pv "catch") ,catch))))) ,pv))) (eval-when (:compile-toplevel) (with-open-file (fd (merge-pathnames (make-pathname :name "default_icon.png") (asdf:system-source-directory :omg)) :element-type '(unsigned-byte 8)) (setf *default-icon* (make-array `(,(file-length fd)) :element-type '(unsigned-byte 8))) (read-sequence *default-icon* fd)))
108,255
Common Lisp
.lisp
2,094
32.031996
241
0.435251
hemml/OMGlib
43
1
0
GPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
35378056aad0a67aeaa5ce4fb651bf5c7e4bf7e7ebb4ba36504d9242917f6b2d
4,297
[ -1 ]
4,298
omgutil.lisp
hemml_OMGlib/omgutil.lisp
(defpackage omgutil (:use omg cl) (:export defclass-m ;; define a both-side class sync-slot ;; slot syncronization method for mirrored instances data-sync ;; a class for objects which needs a data syncronization sync-data) ;; method called if data synchronization needed for data-sync clacc (:import-from omg defclass-m mirrored-object sync-all-data omg-id sync-slot-r sync-slot gethash-lock scope *session-list* *current-session* *m-scope-funcs*)) (in-package :omgutil) (defvar-f *data-sync-objects* nil) (defclass-f mirrored-object () ((omg-id :initarg :omg-internal-id))) (defmethod-f initialize-instance :after ((obj mirrored-object) &key &rest args) (setf (jscl::oget (jscl::%js-vref "self") "OMG" "objectRegistry" (slot-value obj 'omg-id)) obj) (setf (jscl::oget obj "omgObjId") (slot-value obj 'omg-id))) (defclass-m data-sync () ((data-epoch :mirrored t :initform 0 :accessor data-epoch))) (defmethod-f sync-data ((obj data-sync)) (sync-slot obj 'data-epoch)) (defmethod sync-data ((obj data-sync)) (incf (data-epoch obj)) (let ((scf (gethash-lock (class-name (class-of obj)) *m-scope-funcs*))) (loop for *current-session* being the hash-values of *session-list* do (if (equal (slot-value obj 'scope) (funcall scf obj)) (remote-exec `(sync-data ,obj)))))) (defun-f sync-all-data () (map nil (lambda (obj) (let ((new-epoch (sync-slot-r obj 'data-epoch))) (if (not (= (data-epoch obj) new-epoch)) (progn (sync-data obj) (setf (slot-value obj 'data-epoch) new-epoch))))) *data-sync-objects*)) (defmethod-f initialize-instance :after ((obj data-sync) &key &rest args) (pushnew obj *data-sync-objects*))
2,036
Common Lisp
.lisp
47
34.276596
102
0.579798
hemml/OMGlib
43
1
0
GPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
acc9c77a1a6d1422b3fe5504ed7217d907a56bc5ac91942a81a204d513395ada
4,298
[ -1 ]
4,299
omgwidgets.lisp
hemml_OMGlib/omgwidgets.lisp
(defpackage :omgwidgets (:use cl omg jscl omgui omgutil) (:export omg-widget root render-widget redraw editable-field input-size value ok cancel val modal-dialog-window progress-bar width height bg-style fg-style set-progress list-view elements current-position transfer-chunk list-view-element-class graph xmin xmax ymin ymax adjust xticks yticks xdelta ydelta xcaption ycaption show-scales plots need-rescale add-plot remove-plot remove-all-plots preserve-aspect-ratio rescale rescale-auto make-curve plot color parent func-plot func tabular-plot table matrix-plot nx ny palette matrix norm)) (in-package :omgwidgets) (defclass-f omg-widget () ((root :accessor root) (id :initform (omgui::random-id) :accessor id))) (defclass-f editable-field (omg-widget) ((root :initform (create-element "span" :|style.textDecorationStyle| "dashed" :|style.textDecorationLine| "underline" :|style.textDecorationThicknes| "1.75pt" :|style.color| "blue" :|title| "change" :add-style ":hover {cursor:pointer;}")) (input-size :initarg :input-size :initform 20 :accessor input-size) (value :initarg :value :initform "" :accessor val) (ok :initarg :ok :initform (lambda (val) (declare (ignore val)) (setf (slot-value w 'value) val) val) :reader ok-callback) (cancel :initarg :cancel :initform (lambda (w) (declare (ignore w))) :reader cancel-callback) (edt-blk :accessor edt-blk :initform nil))) (defclass-f modal-dialog-window (omg-widget) ((mdw-curtain :accessor mdw-curtain))) (defclass-f progress-bar (omg-widget) ((width :accessor width :initarg :width :initform "20em") (height :accessor height :initarg :height :initform "1em") (bg-style :accessor bg-style :initarg :bg-style :initform '(:|style.border| "1px solid black" :|style.background| "white")) (fg-style :accessor fg-style :initarg :fg-style :initform '(:|style.background| "blue")) (value :accessor value :initarg :value :initform 0) (bar :accessor bar))) (defclass-m list-view (omg-widget data-sync) ((elements :accessor elements :initform nil) (current-position :accessor current-position :initform 150 :mirrored t) (transfer-chunk :initform 50 :accessor transfer-chunk :browser-side t) (mean-height :browser-side t :initform nil :accessor mean-height) (f-elements :accessor f-elements :initform nil :browser-side t) (list-view-element-class :browser-side t :initform 'list-view-element :accessor list-view-element-class) (root :initform (create-element "div") :accessor root))) (defclass-f list-view-element (omg-widget) ((loaded :initform nil :accessor loaded :initarg :loaded) (pos :initform (error "Position must be defined!") :accessor pos :initarg :pos))) (defclass-f graph (omg-widget) ((xmin :initarg :xmin :initform -1 :accessor xmin) (xmax :initarg :xmax :initform 1 :accessor xmax) (ymin :initarg :ymin :initform -1 :accessor ymin) (ymax :initarg :ymax :initform 1 :accessor ymax) (adjust :initarg :adjust :initform t :accessor adjust) (xticks :initarg :xticks :initform 5 :accessor xticks) (yticks :initarg :yticks :initform 5 :accessor yticks) (xdelta :initarg :xdelta) (ydelta :initarg :ydelta) (xcaption :initarg :xcaption :initform nil :accessor xcaption) (ycaption :initarg :ycaption :initform nil :accessor ycaption) (show-scales :initarg :scales :initform '(:bottom :left) :accessor show-scales) (graph :accessor graph) (plots :initform (list) :accessor plots) (preserve-aspect-ratio :initform nil :initarg :preserve-aspect-ratio :accessor preserve-aspect-ratio) (need-rescale :initform nil :accessor need-rescale))) (defclass-f graph-scale (omg-widget) ((root :initform nil) (parent :initarg :graph :initform (error "Parent graph must be supplied!") :accessor parent) (pos :initarg :position :accessor pos :initform (error "Scale position must be provided!")))) (defclass-f plot (omg-widget) ((root :initform nil) (color :initform "red" :initarg :color :accessor color) (parent :accessor parent))) (defclass-f func-plot (plot) ((func :initarg :func :initform (error "Function must be provided for func-plot!") :accessor func) (last-ymin :initform nil :accessor last-ymin) (last-ymax :initform nil :accessor last-ymax))) (defclass-f tabular-plot (plot) ((table :initarg :table :initform (error "Table must be provided for tabular-plot!") :accessor table))) (defclass-f matrix-plot (plot) ((nx) (ny) (xmin :accessor xmin :initarg :xmin :initform (error "matrix-plot bounds must bi defined!")) (xmax :accessor xmax :initarg :xmax :initform (error "matrix-plot bounds must bi defined!")) (ymin :accessor ymin :initarg :ymin :initform (error "matrix-plot bounds must bi defined!")) (ymax :accessor ymax :initarg :ymax :initform (error "matrix-plot bounds must bi defined!")) (palette :initarg :palette :initform (lambda (x) (list x x x)) :accessor palette) (matrix :initarg :matrix :initform (error "Matrix must be provided for matrix-plot!") :accessor matrix) (norm :initarg :norm :initform nil :accessor norm))) ;;;;;;;;;;;;;;;;; render-widget ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defgeneric-f render-widget (w)) (defmethod-f render-widget ((w omg-widget)) (root w)) (defmethod-f render-widget ((w editable-field)) (setf (jscl::oget (root w) "onclick") (lambda (ev) (declare (ignore ev)) (to-edit-state w))) (setf (jscl::oget (root w) "innerHTML") (val w)) (root w)) (defmethod-f render-widget ((w modal-dialog-window)) (append-element (setf (slot-value w 'mdw-curtain) (create-element "div" :|style.opacity| "80%" :|style.background| "white" :|style.width| (page-width) :|style.height| (page-height) :|style.position| "absolute" :|style.top| "0" :|style.left| "0" :|style.zIndex| 100000))) (setf (slot-value w 'root) (create-element "div" :|style.visibility| "hidden" :|style.width| "auto" :|style.display| "inline-block" :|style.position| "absolute" :|style.zIndex| 200000)) (ensure-element (root w) (setf (jscl::oget (root w) "style" "left") (format nil "~Apx" (max 0 (+ (visible-left) (jsfloor (/ (- (visible-width) (element-width (root w))) 2)))))) (setf (jscl::oget (root w) "style" "top") (format nil "~Apx" (max 0 (+ (visible-top) (jsfloor (/ (- (visible-height) (element-height (root w))) 2)))) "px")) (setf (jscl::oget (root w) "style" "visibility") "visible")) (root w)) (defmethod-f render-widget ((b progress-bar)) (setf (slot-value b 'root) (apply #'create-element `("div" ,@(bg-style b) :|style.width| ,(width b) :|style.height| ,(height b) :|style.position| "relative" :append-element ,(make-svg :|viewBox| "0 0 100 100" :|style.width| "100%" :|style.height| "100%" :|style.left| "0" :|style.top| "0" :|style.display| "block" :|style.position| "absolute" :|preserveAspectRatio| "none" '(:|defs| (:|linearGradient| :|id| "boxgrad" :|x1| "0" :|x2| "1" (:|stop| :|offset| "0%" :|stop-color| "white") (:|stop| :|offset| "50%" :|stop-color| "#e0e0e0") (:|stop| :|offset| "100%" :|stop-color| "white") (:|animate| :|attributeName| "x1" :|values| "-1;1" :|dur| "1s" :|repeatCount| "indefinite") (:|animate| :|attributeName| "x2" :|values| "0;2" :|dur| "1s" :|repeatCount| "indefinite"))) '(:|rect| :|x| 0 :|y| 0 :|width| "100%" :|height| "100%" :|fill| "url('#boxgrad')")) :append-element ,(setf (slot-value b 'bar) (apply #'create-element `("div" ,@(fg-style b) :|style.height| "100%" :|style.position| "absolute" :|style.left| 0 :|style.top| 0 :|style.width| ,(format nil "~A%" (jsfloor (* 100 (value b)))))))))) (root b)) (defmethod-f render-widget ((e list-view-element)) (setf (slot-value e 'root) (if (loaded e) (render-widget (loaded e)) (create-element "div" :|style.position| "relative" :|style.left| 0 :|style.right| 0 :|style.height| "1em" :|style.marginTop| "0.2em" :|style.background| "#f0f0f0")))) (defmethod-f render-widget ((l list-view)) (let ((el (create-element "div" :append-elements (mapcar #'render-widget (slot-value l 'f-elements))))) (ensure-element el (onscroll l (f-elements l) (current-position l)) (let ((scroll-tim nil)) (setf (jscl::oget (parent-element el) "onscroll") (lambda (ev) (if scroll-tim (funcall (jscl::%js-vref "clearTimeout") scroll-tim)) (setf scroll-tim (execute-after 0.1 (lambda () (onscroll l))))))) (let ((cur-el (nth (current-position l) (f-elements l)))) (if cur-el (setf (jscl::oget (parent-element el) "scrollTop") (- (jscl::oget (slot-value cur-el 'root) "offsetTop") (jscl::oget ((jscl::oget (parent-element el) "getBoundingClientRect")) "top")))))) (setf (slot-value l 'root) el))) (defmethod-f render-widget ((g graph)) (setf (slot-value g 'graph) (apply #'create-element `("div" :|style.width| "100%" ,@(if (not (preserve-aspect-ratio g)) (list :|style.height| "100%") (list :|style.aspectRatio| (/ (- (xmax g) (xmin g)) (- (ymax g) (ymin g))))) :|style.position| "relative" :|style.left| 0 :|style.top| 0 :|style.overflow| "hidden" :|style.boxSizing| "border-box"))) (let* ((scales (show-scales g)) (top-scale (position :top scales)) (bottom-scale (position :bottom scales)) (left-scale (position :left scales)) (right-scale (position :right scales)) (xcap (xcaption g)) (ycap (ycaption g))) (setf (slot-value g 'root) (apply #'create-element `("table" :|style.width| "100%" :|style.height| ,(if (preserve-aspect-ratio g) "fit-content" "100%") :|style.borderSpacing| 0 :|style.padding| "1em" :append-elements ,(if top-scale (list (create-element "tr" :|style.height| "1px" :append-elements (if ycap (list (create-element "td"))) :append-elements (if left-scale (list (create-element "td" :|style.height| "inherit" :|style.width| "inherit"))) :append-element (create-element "td" :|style.height| "inherit" :|style.width| "inherit" :|style.padding| 0 :|style.position| "relative" ; :|style.height| "max-content" :append-element (render-widget (make-instance 'graph-scale :graph g :position :top))) :append-elements (if right-scale (list (create-element "td")))))) :append-element ,(create-element "tr" :|style.height| "1px" :append-elements (if ycap (list (create-element "td" :|style.paddingRight| "1em" :|style.height| "inherit" :append-element (create-element "span" :|style.writingMode| "vertical-lr" :|style.writingMode| "sideways-lr" :append-element ycap)))) :append-elements (if left-scale (list (create-element "td" :|style.padding| 0 :|style.position| "relative" :|style.height| "inherit" :|style.width| "inherit" :append-element (render-widget (make-instance 'graph-scale :graph g :position :left))))) :append-element (create-element "td" :|style.padding| 0 :|style.borderSpacing| 0 :|style.width| "100%" :|style.height| "100%" :append-element (create-element "div" :|style.width| "100%" :|style.height| "100%" :|style.position| "relative" :|style.boxSizing| "border-box" :|style.background| "white" :|style.boxShadow| "black 0px 0px 0px 1px" :append-element (graph g))) :append-elements (if right-scale (list (create-element "td" :|style.padding| 0 :|style.position| "relative" :|style.height| "inherit" :|style.width| "inherit" :append-element (render-widget (make-instance 'graph-scale :graph g :position :right)))))) :append-elements ,(if bottom-scale (list (create-element "tr" :|style.height| "1px" :append-elements (if ycap (list (create-element "td"))) :append-elements (if left-scale (list (create-element "td"))) :append-element (create-element "td" :|style.height| "inherit" :|style.width| "inherit" :|style.padding| 0 :|style.position| "relative" ; :|style.height| "max-content" :append-element (render-widget (make-instance 'graph-scale :graph g :position :bottom))) :append-elements (if right-scale (list (create-element "td")))))) :append-elements ,(if xcap (list (create-element "tr" :|style.height| "1px" :append-elements (if ycap (list (create-element "td"))) :append-elements (if left-scale (list (create-element "td"))) :append-element (create-element "td" :|align| "center" :|style.height| "inherit" :|style.width| "inherit" :|style.padding| 0 :append-element xcap) :append-elements (if right-scale (list (create-element "td")))))))))) (ensure-element (graph g) (loop for p in (plots g) do (if (not (and (root p) (jscl::oget (root p) "isConnected"))) (append-element (render-widget p) (graph g))))) (rescale-auto g) (root g)) (defmethod-f render-widget ((s graph-scale)) (setf (slot-value s 'root) (labels ((trnk (x delta) (let* ((dg (floor (/ (jsln delta) (jsln 10)))) (digits (if (< dg 1) (+ (if (< dg 0) (- dg) dg) 1) 0))) (/ (jstrunc (* (expt 10 digits) x)) (expt 10 digits))))) (let* ((g (parent s)) (adjust (adjust g)) (pos (pos s)) (horizontal (or (equal :top pos) (equal :bottom pos))) (min (if horizontal (xmin g) (ymin g))) (max (if horizontal (xmax g) (ymax g))) (delta (if horizontal (xdelta g) (ydelta g))) (ft (if adjust (* delta (jsceil (/ min delta))) min))) (create-element "div" :|style.position| "relative" ;;:|style.inset| 0 (if horizontal :|style.width| :|style.height|) "100%" ; :|style.background| "green" :|style.display| "flex" :|style.flexFlow| (if horizontal "row" "column") :append-elements (let* ((ticks (funcall (if horizontal #'identity #'reverse) (loop for x100 from (* 100 ft) to (* 100 max) by (* 100 delta) for x = (/ x100 100) collect (cons x (if horizontal (/ (- x min) (- max min)) (- 1 (/ (- x min) (- max min)))))))) (tick-pos (mapcar #'cdr ticks)) (tick-val (mapcar #'car ticks))) (mapcar (lambda (x1 x2 v) (create-element "div" (if horizontal :|style.width| :|style.height|) (format nil "~A%" (* 100 (- x2 x1))) (if horizontal :|style.height| :|style.width|) "100%" :|style.overflow| "visible" :|style.position| "relative" :append-element (create-element "div" (if horizontal :|style.width| :|style.height|) "0px" (if horizontal :|style.height| :|style.width|) "0.5em" :|style.position| "absolute" (if horizontal :|style.right| :|style.bottom|) "-0.5px" (if horizontal :|style.borderRight| :|style.borderBottom|) "1px solid black" (case pos (:left :|style.right|) (:right :|style.left|) (:top :|style.bottom|) (:bottom :|style.top|)) 0) :append-element (create-element "div" :|innerHTML| (format nil "~A" (trnk v delta)) (if horizontal :|style.width| :|style.height|) "max-content" (if horizontal :|style.left| :|style.top|) "100%" :|style.translate| (format nil "~A ~A" (if horizontal (if (< v 0) "calc(-50% - 0.2em)" "-50%") "0") (if horizontal "0" "-50%")) :|style.position| "relative" (case pos (:left :|style.paddingRight|) (:right :|style.paddingLeft|) (:top :|style.paddingBottom|) (:bottom :|style.paddingTop|)) (if horizontal "0.5em" "0.6em") :|style.textAlign| (case pos (:left "right") (:right "left") (:top "bottom") (:bottom "top"))))) (cons 0 tick-pos) tick-pos tick-val))))))) (defmethod-f render-widget ((p plot)) (setf (slot-value p 'root) (let* ((g (parent p)) (xmin (xmin g)) (xmax (xmax g)) (ymin (ymin g)) (ymax (ymax g))) (make-svg :|viewBox| (format nil "~A ~A ~A ~A" xmin ymin (- xmax xmin) (- ymax ymin)) :|style.width| "100%" :|style.height| "100%" :|style.left| "0" :|style.top| "0" :|style.display| "block" :|style.position| "absolute" :|preserveAspectRatio| "none" (make-curve p))))) ;;;;;;;;;;;;;;;; redraw ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defgeneric-f redraw (omg-widget)) (defmethod-f redraw ((w omg-widget)) (if (slot-boundp w 'root) (let* ((old-root (root w)) (new-root (render-widget w)) (parent (parent-element old-root))) (if (and old-root (jscl::oget old-root "isConnected") (not (eql old-root new-root))) (progn ((jscl::oget parent "insertBefore") new-root old-root) (remove-element old-root))) new-root))) ;;;;;;;;;;;;;; editable-field ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod-f to-edit-state ((w editable-field)) (let ((ok-button (create-element "button" :|innerHTML| "update" :|style.marginLeft| "1em")) (cancel-button (create-element "button" :|innerHTML| "cancel" :|style.marginLeft| "1em")) (edit-fld (create-element "input" :|type| "text" :|value| (val w) :|size| (input-size w)))) (setf (jscl::oget ok-button "onclick") (lambda (ev) (let ((res (funcall (ok-callback w) (jscl::oget edit-fld "value")))) (if res (progn (setf (slot-value w 'value) res) (to-show-state w)))))) (setf (jscl::oget cancel-button "onclick") (lambda (ev) (to-show-state w) (if (cancel-callback w) (funcall (cancel-callback w) w)))) (setf (slot-value w 'edt-blk) (create-element "span" :|style.display| "inline-block" :append-elements `(,edit-fld ,cancel-button ,ok-button))) (setf (jscl::oget (root w) "style" "display") "none") ((jscl::oget (parent-element (root w)) "insertBefore") (edt-blk w) (root w)) ((jscl::oget edit-fld "focus")))) (defmethod-f to-show-state ((w editable-field)) (setf (jscl::oget (root w) "innerHTML" ) (val w)) (setf (jscl::oget (root w) "style" "display") "inline-block") (if (edt-blk w) (remove-element (edt-blk w)))) ;;;;;;;;;;;;;; modal-dialog-window ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod-f close ((w modal-dialog-window)) (remove-element (mdw-curtain w)) (remove-element (root w))) ;;;;;;;;;;;;;; progress-bar ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod-f set-progress ((b progress-bar) val) (setf (slot-value b 'value) (min 1 (max 0 val))) (setf (jscl::oget (bar b) "style" "width") (format nil "~A%" (* 100 (value b)))))0 ;;;;;;;;;;;;;; list-view ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod-f initialize-instance :after ((l list-view) &key &rest args) (sync-data l)) (defmethod-r elements-length ((l list-view)) (length (elements l))) (defmethod-r get-elements ((l list-view) from to) (subseq (elements l) from to)) (defmethod-r get-element ((l list-view) num) (nth num (elements l))) (defmethod-f sync-data :after ((l list-view)) (setf (slot-value l 'f-elements) (let* ((cs (transfer-chunk l)) (ps (current-position l)) (start (max 0 (- ps cs))) (el (elements-length l)) (end (min (- el 1) (+ ps cs cs))) (iitms (get-elements l start (+ end 1))) (ec (list-view-element-class l))) (append (loop for i from 0 below start collect (make-instance ec :pos i)) (loop for i from start below (+ end 1) collect (make-instance ec :pos i :loaded (nth (- i start) iitms))) (loop for i from (+ end 1) below el collect (make-instance ec :pos i))))) (redraw l)) (defmethod-f onscroll ((l list-view) &optional (cdl (f-elements l)) first-passed) (if cdl (let* ((eh (jscl::oget (root (car cdl)) "clientHeight")) (tc (transfer-chunk l)) (scroll-top (jscl::oget (parent-element (root l)) "scrollTop")) (ofs (- scroll-top (* 3 tc eh))) (bot (+ ofs (jscl::oget (parent-element (root l)) "clientHeight") (* 3 tc eh))) (bnd (jscl::oget ((jscl::oget (parent-element (root l)) "getBoundingClientRect")) "top")) (stk nil) (rem nil) (first-el nil)) (loop for el on cdl do (let* ((e (car el)) (r (root e)) (rtop (- (jscl::oget r "offsetTop") bnd))) (setf rem el) (if (and (> rtop (- scroll-top bnd)) (not first-el)) (setf first-el (pos e))) (if (> rtop bot) (loop-finish) (if (and (>= rtop ofs) (not (loaded e))) (progn (push e stk) (if (>= (length stk) (transfer-chunk l)) (loop-finish))))))) (if (and (not first-passed) first-el) (setf (slot-value l 'current-position) first-el)) (if stk (map nil (lambda (e i) (setf (slot-value e 'loaded) i) (redraw e)) (reverse stk) (get-elements l (pos (car (last stk))) (+ 1 (pos (car stk)))))) (if (and stk rem) (execute-after 0.01 (lambda () (onscroll l rem first-el))))))) (defmethod-f sync-slot :after ((l list-view) slot) (if (equal slot 'elements) (redraw l))) ;;;;;;;;;;;;;; list-view ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defgeneric make-curve (p)) (defmethod-f make-curve ((p plot)) (error "Please subclass plot and define the make-curve method!")) (defmethod-f make-curve ((p tabular-plot)) (let* ((g (parent p)) (ymin (ymin g)) (ymax (ymax g)) (tbl (table p))) `(path :|stroke| ,(color p) :|stroke-width| "1px" :|vector-effect| "non-scaling-stroke" :|fill| "none" :|d| ,(apply #'jscl::concat (cons (format nil "M~A,~A " (caar tbl) (+ ymin (- ymax (cdar tbl)))) (loop for i in (cdr tbl) collect (format nil "L~A,~A " (car i) (+ ymin (- ymax (cdr i)))))))))) (defmethod-f make-curve ((p func-plot)) (let* ((g (parent p)) (xmin (xmin g)) (xmax (xmax g)) (ymin (ymin g)) (ymax (ymax g)) (grf (graph g)) (wi (jscl::oget grf "clientWidth")) (he (jscl::oget grf "clientWidth"))) (setf (slot-value p 'last-ymin) (setf (slot-value p 'last-ymax) (funcall (func p) xmin))) `(path :|stroke| ,(color p) :|stroke-width| "1px" :|vector-effect| "non-scaling-stroke" :|fill| "none" :|d| ,(apply #'jscl::concat (cons (format nil "M~A,~A " xmin (+ ymin (- ymax (funcall (func p) xmin)))) (loop for i from 1 to wi collect (let* ((x (+ xmin (* (- xmax xmin) (/ i wi)))) (f (funcall (func p) x))) (setf (slot-value p 'last-ymin) (jsmin f (last-ymin p))) (setf (slot-value p 'last-ymax) (jsmax f (last-ymax p))) (format nil "L~A,~A " x (+ ymin (- ymax f)))))))))) (defmethod-f make-curve ((p matrix-plot)) (let* ((g (parent p)) (ymin (ymin g)) (ymax (ymax g)) (canv (create-element "canvas" :|width| (nx p) :|height| (ny p))) (ctx ((jscl::oget canv "getContext") "2d")) (idat ((jscl::oget ctx "getImageData") 0 0 (nx p) (ny p))) (dat (jscl::oget idat "data")) (mt (matrix p)) (nx (nx p)) (ny (ny p)) (min-cf (if (norm p) (loop for i below (* nx ny) minimize (aref mt i)) 0.0)) (max-cf (if (norm p) (loop for i below (* nx ny) maximize (aref mt i)) 1.0)) (delta-cf (if (and (norm p) (< min-cf max-cf)) (/ 1.0 (- max-cf min-cf)) 1.0))) (loop for i below nx do (loop for j below ny do (let* ((adr (+ i (* nx j))) (colors (funcall (palette p) (* delta-cf (- (aref mt adr) min-cf)))) (idx (* 4 adr))) (setf (aref dat (+ idx 3)) 255) (loop for o below 3 do (setf (aref dat (+ idx o)) (* 255 (- 1.0 (nth o colors)))))))) ((jscl::oget ctx "putImageData") idat 0 0) `(image :|width| ,(- (xmax p) (xmin p)) :|height| ,(- (ymax p) (ymin p)) :|x| ,(xmin p) :|y| ,(- (+ (ymax g) (ymin g)) (ymax p)) :|preserveAspectRatio| "none" :|style.imageRendering| "pixelated" ; :|transform| ,(format nil "translate(~A ~A)" (xmin p) (ymin p)) :|href| ,((jscl::oget canv "toDataURL") "image/bmp")))) (defgeneric xmin (p)) (defgeneric xmax (p)) (defgeneric ymin (p)) (defgeneric ymax (p)) (defmethod-f xmin ((p plot)) (xmin (parent p))) (defmethod-f xmax ((p plot)) (xmax (parent p))) (defmethod-f ymin ((p plot)) (ymin (parent p))) (defmethod-f ymax ((p plot)) (ymax (parent p))) (defmethod-f xmin ((p tabular-plot)) (apply #'min (mapcar #'car (table p)))) (defmethod-f xmax ((p tabular-plot)) (apply #'max (mapcar #'car (table p)))) (defmethod-f ymin ((p tabular-plot)) (apply #'min (mapcar #'cdr (table p)))) (defmethod-f ymax ((p tabular-plot)) (apply #'max (mapcar #'cdr (table p)))) (defmethod-f ymin ((p func-plot)) (if (last-ymin p) (last-ymin p) (ymin (parent p)))) (defmethod-f ymax ((p func-plot)) (if (last-ymax p) (last-ymax p) (ymax (parent p)))) (defmethod-f nx ((p matrix-plot)) (car (array-dimensions (matrix p)))) (defmethod-f ny ((p matrix-plot)) (cadr (array-dimensions (matrix p)))) (defmethod-f add-plot ((g graph) (p plot) &key rescale) (if (position p (plots g)) (remove-element (root p))) (setf (slot-value p 'parent) g) (pushnew p (slot-value g 'plots)) (if rescale (setf (slot-value g 'need-rescale) t)) (if (slot-boundp g 'graph) (ensure-element (graph g) (if (not (jscl::oget (root p) "isConnected")) (append-element (render-widget p) (graph g))) (rescale-auto g)))) (defmethod-f remove-plot ((p plot)) (setf (slot-value (parent p) 'plots) (loop for pl in (plots (parent p)) when (not (eql p pl)) collect pl)) (if (and (root p) (jscl::oget (root p) "isConnected")) (remove-element (root p)))) (defmethod-f remove-all-plots ((g graph)) (map nil (lambda (p) (if (and (root p) (jscl::oget (root p) "isConnected")) (remove-element (root p)))) (plots g)) (setf (slot-value g 'plots) (list)) (redraw g)) (defmethod-f rescale ((g graph) &key xmin xmax ymin ymax xdelta ydelta) (macrolet ((upd (&rest vl) `(progn ,@(mapcar (lambda (v) `(if ,v (setf (slot-value g ',v) ,v))) vl)))) (upd xmin xmax ymin ymax xdelta ydelta) (redraw g))) (defmethod-f rescale-auto ((g graph)) (if (need-rescale g) (let* ((plots (plots g)) (xmin (apply #'min (mapcar #'xmin plots))) (xmax (apply #'max (mapcar #'xmax plots))) (ymin (apply #'min (mapcar #'ymin plots))) (ymax (apply #'max (mapcar #'ymax plots))) (xadd (* 0.01 (- ymax ymin))) (yadd (* 0.01 (- ymax ymin)))) (setf (slot-value g 'need-rescale) nil) (if (and (> xadd 0) (> yadd 0)) (rescale g :xmin (- xmin xadd) :xmax (+ xmax xadd) :ymin (- ymin yadd) :ymax (+ ymax yadd)))))) (defun-f guess-delta (dx nt) (let* ((delta (/ dx nt)) (dgl (jsfloor (/ (jsln delta) (jsln 10)))) (d1 (expt 10 dgl))) (cond ((< (/ dx d1) (1+ nt)) d1) ((< (/ dx (* 2 d1)) (1+ nt)) (* 2 d1)) ((< (/ dx (* 2.5 d1)) (1+ nt)) (* 2.5 d1)) ((< (/ dx (* 5 d1)) (1+ nt)) (* 5 d1)) (t (* 10 d1))))) (defmethod-f xdelta ((g graph)) (if (slot-boundp g 'xdelta) (slot-value g 'xdelta) (guess-delta (- (xmax g) (xmin g)) (xticks g)))) (defmethod-f ydelta ((g graph)) (if (slot-boundp g 'ydelta) (slot-value g 'ydelta) (guess-delta (- (ymax g) (ymin g)) (yticks g))))
38,794
Common Lisp
.lisp
780
30.733333
144
0.426414
hemml/OMGlib
43
1
0
GPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
76cc95820fe7ffc8d8e0ddc6a1ef22e77111eee0c05988230f38f3336a9df91f
4,299
[ -1 ]
4,300
omg.lisp
hemml_OMGlib/omg.lisp
(defpackage :omg (:use cl clack websocket-driver bordeaux-threads trivial-utf-8 parallel) (:import-from :event-emitter #:emit) (:export add-to-boot ;; add a code to boot sequence set-boot ;; set boot code add-to-root-html ;; add a text to html body add-to-root-html-head ;; add a text to html head add-serve-path ;; add custom handler for specific URI (relative to *root-path*) set-root-html ;; set html body set-root-head ;; set html head rm-from-boot ;; remove a code from boot sequence start-server ;; start a http(s)-server kill-server ;; kill a http(s)-server restart-server ;; restart a http(s)-server defclass-f ;; define a browser-side class defun-f ;; define a browser-side function defmacro-f ;; define a browser-side macro def-local-macro-f ;; define a browser-side macro, but executing locally defmethod-f ;; define a browser-side method defmethod-r ;; define a rpc method for both-side classess defgeneric-f ;; define a browser-side generic defvar-f ;; define a browser-side variable defparameter-f ;; define a browser-side parameter defconstant-f ;; define a browser-side constant defun-r ;; define a RPC-function def-session-var ;; define server-side session var remote-exec ;; execute a code in browser(s) with-session ;; execute e code block on the specific browser find-session ;; find session object by ID current-session-id ;; get ID of current session (returns NIL if no session) set-debug-session ;; mark current session as "debug" in-debug-session ;; execute code in debug session thread-in-session)) ;; spawn thread in current session (in-package :omg) (defconstant |sid-length| 10) ;; the length for all random IDs generated (defvar *local-compile* t) ;; if T -- compile all lisp code to JS on the server side ;; can be altered without page reloading or server restart ;; Here are the paths for all HTTP(s) queries (the page reload required after change): (defvar *root-path* "/") ;; must be started with "/" (defvar *html-path* "") ;; the path (relative to *root-path*) for simple html page with injcetced js (defvar *js-path* "j") ;; the path of js for injection (relative to *root-path*) (defvar *ws-path* "s") ;; websocket path (relative to *root-path*) (defvar *rpc-path* "r") ;; rpc call path (relative to *root-path*) without multiple values support, for compatibility only, will be removed (defvar *rpc-path-m* "m") ;; rpc call path (relative to *root-path*) (defvar *gimme-path* "g") ;; the path to query undefined symbols and functions (relative to *root-path*) (defvar *takit-path* "t") ;; the auxilary path, nedded to return macro expansion results if *local-compile* is set (defvar *service-worker-path* "sw") ;; path to the service worker code (defvar *web-worker-path* "ww") ;; path to the web worker code (defvar *port* 7500) ;; default server port (defvar *use-wss* nil) ;; if T -- use wss:// protocol for websocket (defvar *ssl-key* nil) ;; SSL key path (defvar *ssl-cert* nil) ;; SSL cert path (defvar *giant-hash-lock* nil) ;; A giant lock to make hashes thread safe (defvar *omg-thread-list* nil) (defvar *cross-origin* t) ;; Enable (by default) Cross-orign headers (defun gethash-lock (key hash) (apply #'values (if *giant-hash-lock* (bt:with-lock-held (*giant-hash-lock*) (multiple-value-list (gethash key hash))) (multiple-value-list (gethash key hash))))) (defun (setf gethash-lock) (val key hash) (if *giant-hash-lock* (bt:with-lock-held (*giant-hash-lock*) (setf (gethash key hash) val)) (setf (gethash key hash) val))) ;; If we have both SSL key and SSL cert, start server with SSL support (defun has-ssl-p () (and *ssl-key* *ssl-cert*)) ;; If our server serves SSL, use wss:// or you may enforce wss:// protocol with *use-wss* ;; if you are behind reverse proxy with SSL (defun use-wss-p () (or *use-wss* (has-ssl-p))) (defun random-string (len) "Generate a random stgring of length len" (let ((chrs "ABCDEFGHIJKLMOPQRSTUVWXYZ")) (map 'string (lambda (x) (declare (ignore x)) (char chrs (random (length chrs)))) (make-sequence 'string len)))) (defun random-symbol (len) "Make a random symbol" (intern (random-string len) :omg)) (defun random-key (h &optional (len 10)) "Make a random hash-table key" (let ((k (random-symbol len))) (if (nth-value 1 (gethash-lock k h)) (random-key h len) k))) (defvar *exportable-expressions* (make-hash-table)) ;; All exportable functions are here (defvar *rpc-functions* (make-hash-table)) ;; The allowed RPC functions registry (defvar *gimme-wait-list* (make-hash-table)) ;; The temporary storage for gimme-threads, ;; waiting compilation results ;; FIXME: periodic cleanup procedure needed! (defvar *takit-wait-list* (make-hash-table)) ;; The temporary storage for compilation threads, ;; waiting for macro expansion results from browser side ;; FIXME: periodic cleanup procedure needed! (defvar *in-f-macro* nil) ;; If T -- do not convert -f function calls to (remote-exec ...) (don't change manually!!!) (defvar *exported-function-names* nil) ;; list of browser-side functions (defvar *exported-classes-methods* (make-hash-table)) ;; methods for browser-side classess, which are not in omg packages (defvar *accessor-classes* (make-hash-table)) (defvar *local-lambdas* (make-hash-table)) ;; list of unnamed functions, passed as arguments to browser-side ones ;; used by exec-local-lambda RPC-function to determine what lambda to execute (defun is-system-pkg (pkg) (or (equal pkg (find-package :common-lisp)) (equal pkg (find-package :common-lisp-user)) (equal pkg (find-package :keyword)) (equal pkg (find-package :cl)) (equal pkg (find-package :cl-user)) (equal pkg (find-package :jscl)) (equal pkg (find-package :jscl/loop)))) (defun register-rpc (name &optional (def 'defun)) (remhash name *exportable-expressions*) (setf (gethash-lock name *rpc-functions*) t) (setf (gethash-lock name *exportable-expressions*) `(,def ,name (&rest argl) (apply #'values ((jscl::oget (jscl::%js-vref "self") "OMG" "RPC2") (let ((*package* (find-package ,(package-name *package*)))) (jscl::omg-write-to-string (intern (jscl::oget (jscl::%js-vref "self") "OMG" "session_id") :OMG) (intern ,(package-name *package*)) (list ',name argl)))))))) (defmacro defun-r (name args &rest body) "Define a server-side function and allow to call it from browser side" `(progn (register-rpc ',name) (defun ,name ,args ,@body))) (defun-r exec-local-lambda (idargs) (let ((h (gethash-lock (car idargs) *local-lambdas*))) (if h (apply h (cdr idargs)) nil))) ;; return nil if function not found. FIXME: must return an error object! (defun f-eval (arg) "Smart-eval -- evaluate everything, but expotrable expressions, lambdas and function names" (cond ((and (symbolp arg) (or (boundp arg) (fboundp arg)) (gethash-lock arg *exportable-expressions*)) arg) ((and (consp arg) (equal (car arg) 'function) ;; in-browser function name (gethash-lock (cadr arg) *exportable-expressions*)) arg) ((and (listp arg) (fboundp (car arg))) (cond ((equal (car arg) 'lambda) ;; lambdas are always evaluates in browser arg) ((gethash-lock (car arg) *exportable-expressions*) ;; browser-side function (cons (car arg) (mapcar #'f-eval (cdr arg)))) ((equal (car arg) 'CONS) `(quote (,(f-eval (cadr arg)) . (f-eval (caddr arg))))) ((equal (car arg) 'LIST) `(list ,@(mapcar #'f-eval (cdr arg)))) ((equal (car arg) 'QUOTE) arg) (t (let ((res (eval (cons (car arg) (mapcar #'f-eval (cdr arg)))))) (if (listp res) (list 'quote (mapcar #'f-eval res)) (f-eval res)))))) ((and (symbolp arg) (boundp arg)) (eval arg)) ((functionp arg) (let ((f (find (nth-value 2 (function-lambda-expression arg)) *exported-function-names*))) (if f `(symbol-function (quote ,f)) ;; browser-side function (let ((id (random-key *local-lambdas*))) (warn "Passing a local function as a parameter of browser-side function is dangerous!") (setf (gethash-lock id *local-lambdas*) arg) `(lambda (&rest args) (exec-local-lambda (cons ',id args))))))) (t arg))) (defun get-all-sup (cls) (let ((scls (caddr (gethash-lock cls *exportable-expressions*)))) (if scls (append scls (mapcan #'get-all-sup scls))))) (defparameter *disable-remote-macro* nil) (defmacro make-def-macro-f (op1) "Just a macro to generate macros for f-functions and f-macros definintions (defun-f, defmacro-f, etc...)" (let ((op (if (equal op1 'def-local-macro) 'defmacro op1))) `(defmacro ,(read-from-string (format nil "~a-f" op1)) (name args &rest body) (let* ((op ',op) (clos-args (if (and (equal 'defmethod op) (not (listp args))) (cons args (car body)) args)) (is-setf (and (listp name) (equal (car name) 'setf))) (ex-sym (if is-setf (intern (format nil "(SETF_~A)" (symbol-name (cadr name))) *package*) name)) (f-form `(,op ,name ,args ,@body)) (macro-hook (if (equal ',op 'defmacro) ;; Macro require an injection into JSCL lexenv (let ((ar (gensym))) `((jscl::%compile-defmacro ',name (lambda (,ar) ; (exec-remote-macro ',name ,ar))))))) ,(if (or *disable-remote-macro* (equal ',op1 'def-local-macro)) `(apply (lambda ,args ,@body) ,ar) `(exec-remote-macro ',name ,ar)))))))) (lam (if is-setf (gensym))) (args2 (if is-setf (mapcar (lambda (a) (declare (ignore a)) `(quote ,(gensym))) args))) (asym (gensym)) (a2sym (gensym)) (bdsym (gensym))) `(progn ,@macro-hook (remhash ',ex-sym *rpc-functions*) ;; Unregister possible RPC function with the same name (remote-unintern ',ex-sym) ;; unintern the function in all connected browsers ,(cond (is-setf `(let* ((,asym ',args) (,bdsym ',body) (,a2sym (list ,@args2)) (,lam (lambda ,(cdr args) (values (list ,@(cdr args2)) (list ,@(cdr args)) (list ,(car args2)) `(apply (lambda ,,asym ,@,bdsym) (list ,@,a2sym)) (list ',(cdr name) ,@(cdr args2)))))) (if (assoc ',(cadr name) jscl::*setf-expanders*) (setf (cdr (assoc ',(cadr name) jscl::*setf-expanders*)) ,lam) (push (cons ',(cadr name) ,lam) jscl::*setf-expanders*)))) ((or (equal ',op 'defmethod) (equal ',op 'defgeneric)) `(let* ((classes (remove-duplicates (remove-if-not (lambda (cls) (gethash-lock cls *exportable-expressions*)) (mapcar #'cadr (remove-if-not #'listp ',clos-args)))))) (if (not (find ',name *exported-function-names*)) (progn (push ',name *exported-function-names*) (setf (gethash-lock ',ex-sym *exportable-expressions*) (list 'progn ',f-form))) (let* ((defs (cdr (gethash-lock ',ex-sym *exportable-expressions*))) (pos (position ',clos-args defs :test #'tree-equal ;; FIXME: need to compare lambda lists here, not just to use #'tree-equal :key (lambda (l) (if (listp (caddr l)) (caddr l) (cons (caddr l) (cadddr l))))))) (setf (gethash-lock ',ex-sym *exportable-expressions*) (if pos `(progn ,@(subseq defs 0 pos) ,',f-form ,@(subseq defs (+ pos 1))) `(progn ,@defs ,',f-form))))) (labels ((replace-method (cls) (setf (gethash-lock cls *exported-classes-methods*) (cons ',f-form (remove-if (lambda (rec) (and (equal 'defmethod (car rec)) (equal ',name (cadr rec)) (or (and (listp (caddr rec)) (tree-equal (caddr rec) ',clos-args)) (and (symbolp (caddr rec)) (tree-equal (cons (caddr rec) (cadddr rec)) ',clos-args))))) (gethash-lock cls *exported-classes-methods*)))))) (if (and classes (is-system-pkg (symbol-package ',name))) (progn (jscl::with-compilation-environment ;; We need to compile specific methods locally to proper setup jscl clos environment (jscl::compile-toplevel (jscl::ls-read-from-string (omg-write-to-string ',f-form)))) (map nil #'replace-method classes) (remote-update-methods ',name classes))) (if (intersection (gethash-lock ',name *accessor-classes*) (concatenate 'list classes (mapcan #'get-all-sup classes))) (map nil #'replace-method classes))))) (t `(progn (setf (gethash-lock ',ex-sym *exportable-expressions*) ',f-form) (defmacro ,name (&rest args) (if *in-f-macro* `',(cons ',name (mapcar #'f-eval args)) (let ((*in-f-macro* t)) ;; Evaluate all -f functions and macros on the browser-side `(remote-exec ',(cons ',name (mapcar #'f-eval args)))))) (if (not (find ',name *exported-function-names*)) (push ',name *exported-function-names*))))) ',name))))) (defmacro make-var-macro-f (op) "A macro for variables-parameters-constants definitions" `(defmacro ,(read-from-string (format nil "~a-f" op)) (name val) (let* ((op ',op) (f-form `(,op ,name ,val))) `(progn (remhash ',name *rpc-functions*) (setf (gethash-lock ',name *exportable-expressions*) ',f-form) (,op ,name ,val) (remote-unintern ',name))))) (defvar *classes-f-slots* (make-hash-table)) (defvar *classes-f-superclasses* (make-hash-table)) (defmacro defclass-f (name sup slots) (let ((f-form `(defclass ,name ,sup ,slots)) (tmp (gensym))) (setf (gethash name *classes-f-slots*) slots) (setf (gethash name *classes-f-superclasses*) sup) `(let ((,tmp (jscl::with-compilation-environment ;; We need to compile defclass locally (jscl::compile-toplevel (jscl::ls-read-from-string (omg-write-to-string ',f-form)))))) ;; to proper setup jscl compilation environment (declare (ignore ,tmp)) (setf (gethash-lock ',name *exportable-expressions*) ',f-form) (if (not (gethash-lock ',name *exported-classes-methods*)) (setf (gethash-lock ',name *exported-classes-methods*) (list))) (map nil (lambda (rec) (mapcan (lambda (s) (let ((r (getf (cdr rec) s))) (if r (setf (gethash-lock r *accessor-classes*) (remove-duplicates (cons ',name (gethash-lock r *accessor-classes*))))))) '(:accessor :reader :writer))) ',slots) (remote-rdefclass ',name)))) (make-def-macro-f defun) ;; defun-f (make-def-macro-f defmacro) ;; defmacro-f (make-def-macro-f def-local-macro) ;; defmacro-f (make-def-macro-f defmethod) ;; defmethod-f (make-def-macro-f defgeneric) ;; defgeneric-f (make-var-macro-f defvar) ;; defvar-f (make-var-macro-f defparameter) ;; defparameter-f (make-var-macro-f defconstant) ;; defconstant-f (defvar *extra-html* "") (defvar *extra-head* "") (defun get-root-html () "Return a somple HTML with JS injected." (concatenate 'string "<html><head>" *extra-head* "<script src='" *root-path* *js-path* "' type='text/javascript'></script></head><body>" *extra-html* "</body></html>")) (defun add-to-root-html (html) (setf *extra-html* (concatenate 'string *extra-html* html))) (defun add-to-root-html-head (html) (setf *extra-head* (concatenate 'string *extra-head* html))) (defun set-root-html (html) (setf *extra-html* html)) (defun set-root-head (html) (setf *extra-head* html)) (defun get-main-js () "Return the JS code, including JSCL and OMG parts glued." (concatenate 'string "(()=>{" jscl::*jscl-js* " var OMG = Object.create(null) self.OMG=OMG OMG.session_id=false OMG.PersistentCache=false OMG.inWorker=(typeof window==='undefined') OMG.inServiceWorker=(OMG.inWorker&&(typeof XMLHttpRequest==='undefined')) OMG.FetchCache={} OMG.objectRegistry={} OMG.ww_js_url=false OMG.get_ww_js_url=()=>{ if(!OMG.ww_js_url) { let xhr=new XMLHttpRequest() xhr.open('GET', OMG.Base+'" *root-path* *web-worker-path* "', false) xhr.send() if (xhr.status === 200) { OMG.ww_js_url=URL.createObjectURL(new Blob([xhr.response], {'type' : 'application/javascript'})) } else { throw new Error('Cannot fetch webworker js!') } } return OMG.ww_js_url } OMG.get_session_id=()=>{ if(OMG.session_id) return 'OMG::'+OMG.session_id return 'OMG::NO-SESSION' } OMG.find_object=(id)=>{ if(id in OMG.objectRegistry) return OMG.objectRegistry[id] return false } OMG.register_object=(obj)=>{ const find_rnd_key=()=>{ const id=parseInt((Math.random() + 1).toString().substring(3)+'0') if(id in OMG.objectRegistry) find_rnd_key() return id } const obj_id=('omgObjId' in obj)?obj.omgObjId:find_rnd_key() obj.omgObjId=obj_id OMG.objectRegistry[obj_id]=obj return obj_id } OMG.MOPr=jscl.packages.JSCL.symbols['MOP-OBJECT-PRINTER'].fvalue OMG.WrStr=jscl.packages.CL.symbols['WRITE-STRING'].fvalue OMG.in_omg_write=false jscl.packages.JSCL.symbols['MOP-OBJECT-PRINTER'].fvalue=(values,form,stream)=>{ if(OMG.in_omg_write) { const obj_id=OMG.register_object(form) return OMG.WrStr(values,jscl.internals.js_to_lisp('#'+obj_id+'Ё'),stream) } return OMG.MOPr(values,form,stream) } OMG.WRAux=jscl.packages.JSCL.symbols['WRITE-AUX'].fvalue jscl.packages.JSCL.symbols['WRITE-AUX'].fvalue=(values,form,stream,known_objects,object_ids)=>{ if(OMG.in_omg_write) { const is_js=jscl.packages.JSCL.symbols['JS-OBJECT-P'].fvalue(null,form) if(is_js && typeof(is_js)==='object' && 'name' in is_js && is_js.name==='T') { const obj_id=OMG.register_object(form) return OMG.WrStr(values,jscl.internals.js_to_lisp('#'+obj_id+'Ё'),stream) } } return OMG.WRAux(values,form,stream,known_objects,object_ids) } if(!OMG.inWorker) { OMG.URL=new URL(document.currentScript.src) OMG.Path=OMG.URL.pathname.replace(/\\/[^\\\/]+$/,'') OMG.HostPath=(OMG.URL.username?(OMG.URL.username+ (OMG.URL.password?(':'+OMG.URL.password):'')+'@'):'')+ OMG.URL.host+ OMG.Path OMG.Base=OMG.URL.protocol+'//'+OMG.HostPath OMG.WS='" (if (use-wss-p) "wss://" "ws://") "'+OMG.HostPath+'" *root-path* *ws-path* "' } jscl.packages['COMMON-LISP-USER'] = jscl.packages.CL; if(!OMG.inServiceWorker) { OMG.root_ws=undefined OMG.InFetch={} OMG.OriginalSymbolValue=jscl.internals.symbolValue jscl.internals.symbolValue=(symbol)=>{ if(symbol.package) { const full_name=symbol.package.packageName+'::'+symbol.name if(symbol.value===undefined&&symbol.package.omgPkg&&!OMG.InFetch[full_name]) { //console.log('SYMVALUE FETCH:', full_name) if(OMG.symbolValueFetchHandler) return OMG.symbolValueFetchHandler(symbol) OMG.InFetch[full_name]=true let xhr=new XMLHttpRequest() xhr.open('POST', OMG.Base+'" *root-path* *gimme-path* "', false) xhr.send(OMG.get_session_id()+' '+ jscl.packages.CL.symbols['*PACKAGE*'].value.packageName+ ' '+full_name) if (xhr.status === 200) { eval(xhr.response) } else { throw new Error('Cannot fetch symbol '+symbol.name) } } } return OMG.OriginalSymbolValue(symbol) } OMG.OriginalIntern=jscl.internals.intern OMG.Fetch=(sym, eval_fn=eval)=>{ const full_name=sym.package.packageName+'::'+sym.name //console.log('FVALUE FETCH:',full_name) if(!OMG.InFetch[full_name]) { OMG.InFetch[full_name]=true let xhr=new XMLHttpRequest() xhr.open('POST', OMG.Base+'" *root-path* *gimme-path* "', false) xhr.send(OMG.get_session_id()+' '+ jscl.packages.CL.symbols['*PACKAGE*'].value.packageName+ ' '+full_name) if (xhr.status === 200) { //console.log(xhr.response) eval_fn(xhr.response) OMG.FetchCache[full_name]=xhr.response OMG.InFetch[full_name]=false } else { OMG.InFetch[full_name]=false throw new Error('Cannot fetch symbol '+sym.package.packageName+'::'+sym.name) } } else { console.log('Already in fetch:',sym.name) } } OMG.FetchWithCache=(sym, eval_fn=eval)=>{ //return OMG.Fetch(sym, eval_fn) const full_name=sym.package.packageName+'::'+sym.name if(full_name in OMG.FetchCache) { //console.log('CACHED1:',full_name) eval_fn(OMG.FetchCache[full_name]) } else { OMG.Fetch(sym, eval_fn) } } OMG.FetchFvalue=(sym)=>{ let isFetched=false const full_name=sym.package.packageName+'::'+sym.name const ffv=(...args)=>{ if(isFetched||sym.package.symbols[sym.name].fvalue!=ffv) return sym.fvalue.apply(null,args) OMG.FetchWithCache(sym) //,(x)=>{if(sym.package.symbols[sym.name].fvalue==ffv){return eval(x)}}) isFetched=true sym.fvalue=sym.package.symbols[sym.name].fvalue return sym.fvalue.apply(null,args) } return ffv } OMG.InMakePackage=false OMG.MakePackage=(package_name)=>{ if(!OMG.InMakePackage) { OMG.InMakePackage=true jscl.evaluateString('(DEFPACKAGE :'+package_name+' (:USE :CL :JSCL))') OMG.InMakePackage=false jscl.packages[package_name].omgPkg=true } } jscl.internals.intern=(name, package_name)=>{ if(package_name && !(package_name in jscl.packages)) { OMG.MakePackage(package_name) } let sym=OMG.OriginalIntern(name, package_name) const full_name=package_name+'::'+name if('package' in sym&&sym.package.omgPkg&&sym.value===undefined&& !jscl.internals.fboundp(sym)&&!OMG.InFetch[full_name]) { sym.fvalue=OMG.FetchFvalue(sym) } return sym } OMG.RPC=(cmd)=>{ // will be removed let xhr=new XMLHttpRequest() xhr.open('POST', OMG.Base+'" *root-path* *rpc-path* "', false) xhr.send(cmd) if (xhr.status === 200) { return eval(xhr.response) } else { throw new Error('Cannot call RPC') } } OMG.RPC2=(cmd)=>{ let xhr=new XMLHttpRequest() xhr.open('POST', OMG.Base+'" *root-path* *rpc-path-m* "', false) xhr.send(cmd) if (xhr.status === 200) { return eval(xhr.response) } else { throw new Error('Cannot call RPC') } } OMG.AsyncRPC=(cmd, cb)=>{ // will be removed let xhr=new XMLHttpRequest() xhr.open('POST', OMG.Base+'" *root-path* *rpc-path* "', true) xhr.onload=function (e) { if (xhr.readyState === 4) { if (xhr.status === 200) { cb(eval(xhr.response)) } else { throw new Error('Cannot call RPC') } } } xhr.onerror = function (e) { throw new Error('Cannot call RPC') } xhr.send(cmd) } OMG.AsyncRPC2=(cmd, cb)=>{ let xhr=new XMLHttpRequest() xhr.open('POST', OMG.Base+'" *root-path* *rpc-path-m* "', true) xhr.onload=function (e) { if (xhr.readyState === 4) { if (xhr.status === 200) { cb(eval(xhr.response)) } else { throw new Error('Cannot call RPC') } } } xhr.onerror = function (e) { throw new Error('Cannot call RPC') } xhr.send(cmd) } OMG.OriginalFP=jscl.packages.CL.symbols['FIND-PACKAGE'].fvalue jscl.packages.CL.symbols['FIND-PACKAGE'].fvalue=(values,pkg)=>{ let res=OMG.OriginalFP(values,pkg) if(!OMG.InMakePackage&&typeof(res)==='object'&&res.name==='NIL'&&res.package.packageName==='CL') { OMG.MakePackage(jscl.internals.lisp_to_js(pkg)) res=OMG.OriginalFP(values,pkg ) } return res } OMG.disableLIL=false OMG.OriginalLIL=jscl.packages.JSCL.symbols['LOOKUP-IN-LEXENV'].fvalue jscl.packages.JSCL.symbols['LOOKUP-IN-LEXENV'].fvalue=(mv,name,lexenv,ns)=>{ let res=OMG.OriginalLIL(mv,name,lexenv,ns) if(!OMG.disableLIL && ns.name==='FUNCTION' && 'package' in name && name.package.omgPkg && 'name' in res && res.name==='NIL') { OMG.FetchWithCache(name) res=OMG.OriginalLIL(mv,name,lexenv,ns) } return res } OMG.OriginalGSE=jscl.packages.JSCL.symbols['!GET-SETF-EXPANSION'].fvalue jscl.packages.JSCL.symbols['!GET-SETF-EXPANSION'].fvalue=(mv,fn)=>{ const set_name = '(SETF_'+fn.car.name+')' if('car' in fn && 'name' in fn.car && 'package' in fn.car && fn.car.package.omgPkg && !(set_name in fn.car.package.symbols)) { OMG.FetchWithCache({'package':fn.car.package, 'name':set_name}) } return OMG.OriginalGSE(mv,fn) } OMG.OriginalCAMUC=jscl.packages.JSCL.symbols['COMPUTE-APPLICABLE-METHODS-USING-CLASSES'].fvalue jscl.packages.JSCL.symbols['COMPUTE-APPLICABLE-METHODS-USING-CLASSES'].fvalue=(mv,gf,clss)=>{ let res=OMG.OriginalCAMUC(mv,gf,clss) if ('name' in res && res.name=='NIL') { OMG.FetchWithCache(gf.cdr.cdr.car[0]) res=OMG.OriginalCAMUC(mv,gf,clss) } return res } OMG.OriginalFC=jscl.packages.JSCL.symbols['!FIND-CLASS'].fvalue jscl.packages.JSCL.symbols['!FIND-CLASS'].fvalue=(mv,cls,arg2)=>{ if('package' in cls && cls.package.omgPkg && !cls.package.symbols[cls.name].omgClass) { cls.package.symbols[cls.name].omgClass=true OMG.Fetch(cls) } return OMG.OriginalFC(mv,cls,arg2) } OMG.OriginalFC1=jscl.packages.CL.symbols['FIND-CLASS'].fvalue jscl.packages.CL.symbols['FIND-CLASS'].fvalue=(mv,cls,arg2)=>{ if('package' in cls && cls.package.omgPkg && !cls.package.symbols[cls.name].omgClass) { cls.package.symbols[cls.name].omgClass=true OMG.FetchWithCache(cls) } return OMG.OriginalFC1(mv,cls,arg2) } OMG.make_conn=()=>{ console.log('Connecting to host') OMG.root_ws=new WebSocket(OMG.WS) OMG.root_ws.onopen=()=>{ console.log('Socket connected') if(OMG.session_id) OMG.root_ws.send('!!SESID:'+OMG.session_id) } OMG.root_ws.onclose=(ev)=>{ console.log('Socket closed ('+(ev.wasClean?'normally':'by error')+'), reconnecting') delete(OMG.root_ws) setTimeout(OMG.make_conn,1000) } OMG.root_ws.onerror=(err)=>{ console.log('Socket error ('+err.message+')') OMG.root_ws.close() } OMG.root_ws.onmessage=function (ev) { const cmd=ev.data; setTimeout(()=>{eval(cmd)},1) } } if(!OMG.inWorker) { if(document.readyState==='complete') { OMG.make_conn() } else { document.addEventListener('DOMContentLoaded',()=>{ OMG.make_conn() }) } } } else { // Automake packages for Service Worker OMG.InMakePackage=false OMG.MakePackage=(package_name)=>{ if(!OMG.InMakePackage) { OMG.InMakePackage=true jscl.evaluateString('(DEFPACKAGE :'+package_name+' (:USE :CL :JSCL))') OMG.InMakePackage=false jscl.packages[package_name].omgPkg=true } } OMG.OriginalIntern=jscl.internals.intern jscl.internals.intern=(name, package_name)=>{ if(package_name && !(package_name in jscl.packages)) { OMG.MakePackage(package_name) } return OMG.OriginalIntern(name, package_name) } } })() ")) (defvar *current-session* nil) ;; The current session, usually set by remote-exec (defvar *session-list* (make-hash-table)) ;; The store for session objects, keys are session-ids (defvar *current-res* nil) ;; The key for gimme-wait-list hash, denotes the place where to store result for ;; current gimme request (defvar *in-rpc* nil) ;; If T -- we are in RPC call, all remote-execs must be done via takit-mechanism (defun current-session-id () (if *current-session* (get-id *current-session*))) (defclass omg-session () ((socket :initarg :socket :initform (error "socket required") :reader socket) (ses-id :initform (random-symbol |sid-length|) :reader get-id) (last-active :initform (get-universal-time) :reader last-active) (wait-list :initform (make-hash-table) :reader wait-list) (disconnected-at :initform nil :accessor disconnected-at) (session-ws :initarg :ws :initform (error "Session WS required") :accessor session-ws)) (:documentation "The session object, holding the session socket, the wait-list holding semaphores and storing result data from remote-exec calls")) (defvar *remote-objects* (make-hash-table)) (defclass remote-object () ((session :initarg :session :initform nil :accessor session) (id :initarg :id :initform (error "ID is required") :accessor id))) (defmethod initialize-instance :after ((obj remote-object) &key &allow-other-keys) (setf (session obj) *current-session*)) (defparameter *in-omg-writer* nil) (defmethod print-object ((obj remote-object) s) (if *in-omg-writer* (write `((jscl::oget (jscl::%js-vref "self") "OMG" "find_object") ,(id obj)) :stream s) (format s "#<REMOTE-JS-OBJECT ~A ~A>" (if (session obj) (get-id (session obj)) nil) (id obj)))) (defun omg-data-to-compile-form (form) (cond ((consp form) (list 'cons (omg-data-to-compile-form (car form)) (omg-data-to-compile-form (cdr form)))) ((symbolp form) (list 'quote form)) (t form))) (defmethod print-m-slots-init (obj nvar s) nil) (defvar *m-initialized* nil) (defvar *m-classess* (list)) (defun scope-session (obj scope) (if (and (equal scope :auto) (slot-boundp obj 'scope) (not (slot-value obj 'scope))) nil *current-session*)) (defvar *m-scopes* (make-hash-table)) (defvar *m-scope-funcs* (make-hash-table)) (defmacro defclass-m (name superclasses slots &rest options) (labels ((is-f-slot (slt) (and (getf (cdr slt) :browser-side) (not (getf (cdr slt) :mirrored)))) (is-m-slot (slt) (getf (cdr slt) :mirrored)) (is-o-slot (slt) (and (not (is-f-slot slt)) (not (is-m-slot slt)))) (clr-bs (slt) (remf (cdr slt) :browser-side) (remf (cdr slt) :mirrored)) (fcls (cls) (find-class cls nil))) (let* ((f-super (remove-if (lambda (cls) (and (fcls cls) (not (position cls *m-classess*)))) superclasses)) (o-super (remove-if-not #'fcls superclasses)) (f-slots (remove-if-not #'is-f-slot slots)) (m-slots (remove-if-not #'is-m-slot slots)) (o-slots (remove-if-not #'is-o-slot slots)) (all-f-slots (labels ((get-f-slts (cls) (append (gethash cls *classes-f-slots*) (mapcan #'get-f-slts (gethash cls *classes-f-superclasses*))))) (remove-duplicates (append f-slots (get-f-slts name)) :key #'car))) (f-args (remove-if #'null (mapcar (lambda (slt) (getf (cdr slt) :initarg)) all-f-slots))) (has-m-super (notany #'null (mapcar (lambda (cls) (position cls *m-classess*)) superclasses))) (class-scope (getf options :scope (let ((vrs (remove-duplicates (remove-if #'null (mapcar (lambda (cls) (gethash-lock cls *m-scopes*)) o-super))))) (if vrs (if (cdr vrs) (error (format nil "No default scope defined for m-class ~A and multiple different scopes found for superclasses" name)) (car vrs)) :auto))))) (setf (gethash name *classes-f-superclasses*) f-super) ;; defclass-f macros may not be evaluated immediately (push name *m-classess*) (map nil #'clr-bs f-slots) (map nil #'clr-bs o-slots) (map nil #'clr-bs m-slots) `(progn (defclass ,name ,o-super (,@o-slots ,@m-slots (omg-id) (f-init) (scope))) (defclass-f ,name (,@(if (not has-m-super) '(mirrored-object)) ,@f-super) (,@f-slots ,@m-slots)) (setf (gethash-lock ',name *m-scopes*) ,class-scope) (setf (gethash-lock ',name *m-scope-funcs*) (lambda (obj) ,(cond ((functionp class-scope) `(funcall ,class-scope obj)) ((or (equal :session class-scope) (equal :auto class-scope)) `(scope-session obj ,class-scope)) (t (error (format nil "Invalid m-class scope: ~A" class-scope)))))) (defmethod initialize-instance :around ((obj ,name) &rest args &key &allow-other-keys) ,(if (equal class-scope :session) `(if (equal *current-session* nil) (error "Trying to create instance with :sesson scope while not in session"))) (setf (slot-value obj 'scope) (funcall (gethash-lock ',name *m-scope-funcs*) obj)) (let ((id (+ 1 (* 10 (random 100000000000000))))) (setf (gethash-lock id *remote-objects*) obj) (setf (slot-value obj 'omg-id) id) (setf (slot-value obj 'f-init) (loop for arg in args by #'cddr when (position arg ',f-args) append (list arg (getf args arg))))) (call-next-method)) (defmethod-f sync-slot ((obj ,name) slot) (setf (slot-value obj slot) (sync-slot-r obj slot))) ,@(mapcar (lambda (slt) `(progn (defmethod-r sync-slot-r ((obj ,name) (slot (eql ',(car slt)))) (slot-value obj slot)) (defmethod sync-slot ((obj ,name) (slot (eql ',(car slt)))) (let ((slt-name ',(car slt)) (scf (gethash-lock ',name *m-scope-funcs*))) (loop for *current-session* being the hash-values of *session-list* do (if (equal (slot-value obj 'scope) (funcall scf obj)) (remote-exec `(sync-slot ,obj ',slt-name) :nowait))))))) m-slots) (defmethod print-m-slots-init :around ((obj ,name) nvar s) `(,@(if (next-method-p) (call-next-method)) ,@(mapcar (lambda (slt) `(setf (slot-value ,nvar ',(car slt)) ,(omg-data-to-compile-form (slot-value obj (car slt))))) ',m-slots))) (defmethod print-object ((obj ,name) s) (if *in-omg-writer* (let ((name ',name) (obj-id (slot-value obj 'omg-id)) (f-init (slot-value obj 'f-init))) (if (equal (slot-value obj 'scope) (funcall (gethash-lock ',name *m-scope-funcs*) obj)) (write `(let* ((ovar ((jscl::oget (jscl::%js-vref "self") "OMG" "find_object") ,obj-id))) (if ovar ovar (let ((nvar (make-instance ',name :omg-internal-id ,obj-id ,@f-init))) ,@(print-m-slots-init obj 'nvar s) nvar))) :stream s) (error "Trying to send an instance to invalid scope"))) (format s "#<~A ~A>" ',name (slot-value obj 'omg-id)))))))) (defmacro defmethod-r (name args &rest body) `(progn (defmethod ,name ,args ,@body) (register-rpc ',name 'defmethod))) (defun find-session (sid) "Return session object with specific ID" (gethash-lock sid *session-list*)) (defmacro with-session (sess &rest body) "Execute commands inside session sess" `(let ((*current-session* ,sess)) ,@body)) (defvar *debug-session-id* nil) (defun set-debug-session (sid) (setf *debug-session-id* sid) nil) (defmacro in-debug-session (&rest body) (let ((ses (gensym))) `(let ((,ses (find-session *debug-session-id*))) (if ,ses (with-session ,ses ,@body) (warn "Cannot find debug session!"))))) (defmacro def-session-var (vr &optional init) (let ((h (gentemp)) (def (gentemp))) `(progn (defvar ,h (make-hash-table)) (defparameter ,def ,init) (define-symbol-macro ,vr (gethash (current-session-id) ,h ,def))))) (defun remote-unintern (sym) "Unintern the symbol within all active sessions, mandatory to reflect symbol redefinition. The next try to intern the symbol in browser-side will cause new symbol fetch." (loop for s being the hash-values of *session-list* do (let* ((sym-name (symbol-name sym)) (sym-pkg (package-name (symbol-package sym))) (cmd (format nil "if(\"~A\" in jscl.packages && \"~A\" in jscl.packages[\"~A\"].symbols) { delete(OMG.InFetch[\"~A:~A\"]) delete(OMG.FetchCache[\"~A::~A\"]) jscl.packages[\"~A\"].symbols[\"~A\"].fvalue=OMG.FetchFvalue(OMG.OriginalIntern(\"~A\", \"~A\")) jscl.packages[\"~A\"].symbols[\"~A\"].value=undefined}" sym-pkg sym-name sym-pkg sym-pkg sym-name sym-pkg sym-name sym-pkg sym-name sym-name sym-pkg sym-pkg sym-name))) (send-text (socket s) cmd)))) (defun remote-rdefclass (cls) (loop for s being the hash-values of *session-list* do (let* ((cls-name (symbol-name cls)) (cls-pkg (package-name (symbol-package cls))) (cmd (format nil "if(\"~A\" in jscl.packages && \"~A\" in jscl.packages[\"~A\"].symbols && \"omgClass\" in jscl.packages[\"~A\"].symbols[\"~A\"]) { delete(OMG.InFetch[\"~A:~A\"]) OMG.Fetch(jscl.packages[\"~A\"].symbols[\"~A\"])}" cls-pkg cls-name cls-pkg cls-pkg cls-name cls-pkg cls-name cls-pkg cls-name))) (send-text (socket s) cmd)))) (defun remote-update-methods (method classess) (loop for s being the hash-values of *session-list* do (let* ((mathod-name (symbol-name method)) (mathod-pkg (package-name (symbol-package method))) (cmd (format nil "~{{~A}~}" (mapcar (lambda (cls-name cls-pkg) (format nil "if(\"~A\" in jscl.packages && \"~A\" in jscl.packages[\"~A\"].symbols && \"omgClass\" in jscl.packages[\"~A\"].symbols[\"~A\"] && \"~A\" in jscl.packages && \"~A\" in jscl.packages[\"~A\"].symbols) { OMG.Fetch(jscl.packages[\"~A\"].symbols[\"~A\"]) }" cls-pkg cls-name cls-pkg cls-pkg cls-name mathod-pkg mathod-name mathod-pkg mathod-pkg mathod-name)) (mapcar #'symbol-name classess) (mapcar #'package-name (mapcar #'symbol-package classess)))))) (send-text (socket s) cmd)))) ;; From LISP Cookbook (defun replace-all (string part replacement &key (test #'char=)) "Returns a new string in which all the occurences of the part is replaced with replacement." (with-output-to-string (out) (loop with part-length = (length part) for old-pos = 0 then (+ pos part-length) for pos = (search part string :start2 old-pos :test test) do (write-string string out :start old-pos :end (or pos (length string))) when pos do (write-string replacement out) while pos))) (defun put-wl-result (res key) (let* ((gwl (gethash-lock key *gimme-wait-list*)) (sem (cdr (assoc :sem gwl))) (time (cdr (assoc :time gwl)))) (setf (gethash-lock key *gimme-wait-list*) `((:result . ,res) (:time . ,time))) (signal-semaphore sem))) (defun omg-write-to-string (&rest forms) (let ((*in-omg-writer* t) (*print-circle* t)) (with-output-to-string (s) (map nil (lambda (f) (write f :stream s)) (copy-tree forms))))) ;; copy-tree to avoid SBCL or SLIME bug with (*print-circle* t) (defun compile-to-js (code pkg &key recursive) "Return JS for the code, pkg is current package for compilation context." (let* ((*package* pkg) (c0 (if recursive (let ((seen (make-hash-table))) (labels ((get-rec (cod) (cond ((symbolp cod) (if (not (gethash cod seen)) (let ((e (gethash-lock cod *exportable-expressions*))) (when e (setf (gethash cod seen) t) (cons e (get-rec e)))))) ((listp cod) (mapcan #'get-rec cod)) (t nil)))) (get-rec code))))) (c1 (omg-write-to-string `(let ((*package* (find-package ,(package-name pkg))) (*print-circle* t)) ,@c0 ,code))) (code (if *local-compile* (jscl::with-compilation-environment (let ((jscl::*macroexpander-cache* (make-hash-table :test #'eq))) ;; workaround for JSCL macroexpander race condition (jscl::compile-toplevel (let ((jscl::*labelled-objects* nil)) ;; workaround for JSCL reader race condition (jscl::ls-read-from-string c1)) t t))) c1)) (rcode (if *local-compile* (replace-all (replace-all (replace-all (replace-all code "\\" "\\\\") (string #\linefeed) "\\n") (string #\return) "\\\\r") "\"" "\\\"") (replace-all (replace-all code (string #\linefeed) " ") (string #\return) " "))) (res (if *local-compile* (concatenate 'string "jscl.internals.lisp_to_js(jscl.internals.globalEval(\"" rcode "\"))") (concatenate 'string "jscl.evaluateString(" rcode ")")))) res)) (defun omg-read (s) (let ((*readtable* (copy-readtable)) (*read-eval* nil)) (set-dispatch-macro-character #\# #\Ё (lambda (st subch infix) (declare (ignore subch st)) (let ((fnd (gethash-lock infix *remote-objects*))) (if fnd fnd (setf (gethash-lock infix *remote-objects*) (make-instance 'remote-object :id infix :session *current-session*)))))) (read s))) (defun omg-read-from-string (s) (with-input-from-string (st s) (omg-read st))) (defun takit (key res) "The handler for takit-requests. This requests are used to return macro expansion results from browser-side" (let* ((sem-dat-sym (gethash-lock key *takit-wait-list*))) (if (and sem-dat-sym (assoc :sem sem-dat-sym)) (let ((newsem (make-semaphore))) (setf (gethash-lock key *takit-wait-list*) `((:result . ,res) ,(assoc :time sem-dat-sym))) (setf (gethash-lock key *gimme-wait-list*) `((:sem . ,newsem) (:time . ,(get-universal-time)) ,(assoc :symbol sem-dat-sym))) (signal-semaphore (cdr (assoc :sem sem-dat-sym))) (if (wait-on-semaphore newsem :timeout 600) `(200 (:content-type "text/plain; charset=utf-8") (,(cdr (assoc :result (gethash-lock key *gimme-wait-list*))))) `(500 (:content-type "text/plain; charset=utf-8") (,"Timeout")))) `(404 (:content-type "text/plain; charset=utf-8") (""))))) (defun gimme (sym) "The handler for gimme-requests, which are used to request unknown symbols from the server-side." (multiple-value-bind (datp fnd) (gethash-lock sym *exportable-expressions*) (if fnd (let* ((auto-funcs (if (and (listp datp) (equal 'defclass (car datp))) (remove-duplicates (gethash-lock sym *exported-classes-methods*))))) (if datp (let* ((dat (if (boundp sym) (list (car datp) (cadr datp) (let ((sv (symbol-value sym))) (if (listp sv) `(quote ,sv) sv))) datp)) (sem (make-semaphore)) (key (random-key *gimme-wait-list* |sid-length|))) (setf (gethash-lock key *gimme-wait-list*) `((:sem . ,sem) (:time . ,(get-universal-time)) (:symbol . ,sym))) (push (bt:make-thread (lambda () (put-wl-result (format nil "{~A};~{{~A}~^;~}" (compile-to-js dat (symbol-package sym)) (mapcar (lambda (f) (compile-to-js f (symbol-package sym))) auto-funcs)) key)) :initial-bindings `((*current-res* . ',key) (*current-session* . ,*current-session*))) *omg-thread-list*) (if (wait-on-semaphore sem :timeout 600) (let ((res (cdr (assoc :result (gethash-lock key *gimme-wait-list*))))) (remhash key *gimme-wait-list*) (multiple-value-bind (x fnd) (gethash key *takit-wait-list*) (declare (ignore x)) (if (not fnd) (unintern key))) `(200 (:content-type "text/plain; charset=utf-8") (,res))) `(500 (:content-type "text/plain; charset=utf-8") ("Timeout")))))) `(404 (:content-type "text/plain; charset=utf-8") (""))))) (defun rpc-wrapper (op args pkg &optional mv) "The wrapper for RPC requests, used to allow call browser-side functions from RPC funcs." (let* ((sem (make-semaphore)) (key (random-key *gimme-wait-list* |sid-length|))) (setf (gethash-lock key *gimme-wait-list*) `((:sem . ,sem) (:time . ,(get-universal-time)) (:symbol . ,(intern "omg-rpc-symbol" pkg)))) (push (bt:make-thread (lambda () (let ((res (multiple-value-list (apply op args)))) (put-wl-result (compile-to-js (omg-data-to-compile-form (if mv res (car res))) pkg) key))) :initial-bindings `((*current-res* . ',key) (*current-session* . ,*current-session*) (*in-rpc* . t))) *omg-thread-list*) (if (wait-on-semaphore sem :timeout 600) (let ((res (cdr (assoc :result (gethash-lock key *gimme-wait-list*))))) (remhash key *gimme-wait-list*) (unintern key) `(200 (:content-type "text/plain; charset=utf-8") (,res))) `(500 (:content-type "text/plain; charset=utf-8") ("Server timeout"))))) (defun exec-remote-macro (name args) "Execute in a browser a code of the macro with the specific name and argments. Called by JSCL compiler while compling lisp code to JS. We have to execute macros on the browser-side, because all side-effects, produced by macros, must have a place in the browser." (if *current-res* (let* ((cur-res *current-res*) (sem-tim-sym (gethash-lock cur-res *gimme-wait-list*)) (sem (cdr (assoc :sem sem-tim-sym))) (sym (cdr (assoc :symbol sem-tim-sym))) (takit-sem (make-semaphore)) (mcod (compile-to-js `(jscl::omg-write-to-string (apply (lambda ,@(cddr (gethash-lock name *exportable-expressions*))) ',args)) (symbol-package sym)))) (setf (gethash-lock cur-res *takit-wait-list*) `((:sem . ,takit-sem) (:time . ,(get-universal-time)) (:symbol . ,sym))) (setf (gethash-lock cur-res *gimme-wait-list*) `((:result . ,(format nil (concatenate 'string "xhr=new XMLHttpRequest();xhr.open('POST','" *root-path* *takit-path* "',false);" "xhr.send(OMG.get_session_id()+' '+" "\"" (package-name (symbol-package sym)) "\"+" "' OMG::~A '+(~A));if(xhr.status===200){eval(xhr.response);}else" "{throw new Error('Cannot fetch symbol (takit fails).');}") (symbol-name cur-res) mcod)) (assoc :time sem-tim-sym))) (signal-semaphore sem) (if (wait-on-semaphore takit-sem :timeout 600) (let ((macro-res (cdr (assoc :result (gethash-lock cur-res *takit-wait-list*))))) (remhash cur-res *takit-wait-list*) (unintern cur-res) macro-res) (error "Remote macro timeout"))) (remote-exec `(apply (lambda ,@(cddr (gethash-lock name *exportable-expressions*))) ',args)))) (defun remote-exec (cmd &optional nowait) "Execute the code on the browser-side. If the *current-session* set, the code will be executed within the specific session, otherwise, the code will be executed in all sessions and all the return values are returned as a list. If the nowait is T, the function will retrurn NIL immediately, without waiting result from the remote side." (if *in-rpc* (let* ((cur-res *current-res*) (sem-tim-sym (gethash-lock *current-res* *gimme-wait-list*)) (sem (cdr (assoc :sem sem-tim-sym))) (takit-sem (make-semaphore)) (mcod (compile-to-js (if nowait cmd `(jscl::omg-write-to-string ,cmd)) *package*))) (setf (gethash-lock cur-res *takit-wait-list*) `((:sem . ,takit-sem) (:time . ,(get-universal-time)) ,(assoc :symbol sem-tim-sym))) (setf (gethash-lock cur-res *gimme-wait-list*) `((:result . ,(format nil (concatenate 'string "xhr=new XMLHttpRequest();xhr.open('POST','" *root-path* *takit-path* "',false);" "xhr.send(OMG.get_session_id()+' '+" "jscl.packages.CL.symbols['*PACKAGE*'].value.packageName+" "' OMG::~A '+(~A));if(xhr.status===200){eval(xhr.response);}else" "{throw new Error('Cannot fetch symbol (takit fails).');}") (symbol-name cur-res) mcod)) ,(assoc :time sem-tim-sym))) (signal-semaphore sem) (if (wait-on-semaphore takit-sem :timeout 600) (let ((res (cdr (assoc :result (gethash-lock cur-res *takit-wait-list*))))) (remhash cur-res *takit-wait-list*) (unintern cur-res) res) (error "Timeout"))) (flet ((exec () (let* ((wlist (wait-list *current-session*)) (sock (socket *current-session*)) (sock-state (ready-state sock)) (key (random-key wlist |sid-length|)) (sem (if nowait nil (make-semaphore))) (rcmd (compile-to-js (if nowait cmd `(jscl::omg-write-to-string (multiple-value-list ,cmd))) *package*)) (pkgname (package-name *package*)) (pkg-hook (if *local-compile* "" (format nil "jscl.evaluateString(\"(IN-PACKAGE :~A)\")" pkgname))) (jscmd (if nowait (format nil "~A;~A;" pkg-hook rcmd) (format nil "OMG.root_ws.send((\"^~A\"));~A;OMG.root_ws.send((\"~~~A\"+~A));" (symbol-name key) pkg-hook (symbol-name key) rcmd))) (timeout-chunk 5)) (if (equal sock-state :open) (progn (if (not nowait) (setf (gethash-lock key wlist) (list (current-thread) sem nil nil))) (send-text sock jscmd) (if (not nowait) (labels ((get-res (&key (timeout 600) retry) (if (wait-on-semaphore sem :timeout timeout-chunk) (let ((ret (let ((*read-eval* nil)) (omg-read-from-string (caddr (gethash-lock key wlist)))))) (remhash key wlist) (unintern key) (if *current-session* (setf (slot-value *current-session* 'last-active) (get-universal-time))) (values ret nil)) (if (and (or retry (cadddr (gethash-lock key wlist))) (> timeout 0) (equal (ready-state (socket *current-session*)) :open)) (multiple-value-call #'get-res :timeout (- timeout timeout-chunk)) (values nil t))))) (multiple-value-call #'get-res :retry t)) (values nil nil))) (progn (if (equal sock-state :closed) (emit :close sock)) (values nil t)))))) (if *current-session* (multiple-value-bind (r timeout) (exec) (if (not timeout) (apply #'values r) (error "Timeout in remote-exec"))) (mapcar #'car (remove-if #'null (par-map (lambda (s) (with-session s (exec))) (loop for s being the hash-values of *session-list* when (equal :open (ready-state (socket s))) collect s)))))))) (defvar *pre-boot-functions* nil) (defvar *boot-functions* nil) (defun add-to-boot (f) (push f *boot-functions*)) (defun set-boot (f) (setf *boot-functions* (list f))) (defun rm-from-boot (f) (delete f *boot-functions*)) (defvar-f *boot-done* nil) (in-package :omg) (defun boot-f () "The boot code, will be executed on the browser-side just after the page is loaded and socket connected." (if *current-session* (setf (slot-value *current-session* 'last-active) (get-universal-time))) (remote-exec `(if (not *boot-done*) (progn (defun jscl::omg-write-to-string (&rest forms) (with-output-to-string (s) (let ((*print-circle* t)) (setf (jscl::oget (jscl::%js-vref "self") "OMG" "in_omg_write") t) (map nil (lambda (f) (print f s)) forms) (setf (jscl::oget (jscl::%js-vref "self") "OMG" "in_omg_write") (jscl::lisp-to-js nil)) s))) (setf (jscl::oget (jscl::%js-vref "self") "OMG" "session_id") ,(symbol-name (get-id *current-session*))) (setf *boot-done* t) ,@*pre-boot-functions* ,@*boot-functions* nil) (if (fboundp 'sync-all-data) (sync-all-data))) :nowait)) (defun make-ws (env) "Return the websocket for the new session. Also, creates the session object." (let* ((ws (websocket-driver.server:make-server env)) (ses (make-instance 'omg-session :socket ws :ws ws)) (sid (get-id ses)) (sock-thread (bt:current-thread))) (setf (gethash-lock sid *session-list*) ses) (on :open ws (lambda () (push (bt:make-thread (lambda () (let ((*current-session* ses) (*package* (find-package :omg))) (if *current-session* (setf (slot-value *current-session* 'last-active) (get-universal-time))) (boot-f))) :name (concatenate 'string (symbol-name sid) "-BOOT")) *omg-thread-list*))) (on :error ws (lambda (error) (format t "WS error: ~S~%" error))) (on :message ws (lambda (msg) (if (and (> (length msg) 8) (equal (subseq msg 0 8) "!!SESID:")) (let* ((new-sid (intern (subseq msg 8) :omg)) (new-ses (gethash new-sid *session-list*))) (if new-ses (progn (setf (disconnected-at ses) 0) (setf (disconnected-at new-ses) nil) (setf (slot-value new-ses 'socket) ws) (remhash (get-id ses) *session-list*) (setf ses new-ses) (setf sid new-sid)) (progn (remhash (get-id ses) *session-list*) (setf (slot-value ses 'ses-id) new-sid) (setf sid new-sid) (setf (gethash-lock new-sid *session-list*) ses)))) (let* ((m (subseq msg 0 1)) (rid (intern (subseq msg 1 (+ |sid-length| 1)) :omg)) (val (subseq msg (+ |sid-length| 1)))) (if ses (setf (slot-value ses 'last-active) (get-universal-time))) (cond ((equal m "~") (let* ((wlist (wait-list ses)) (trsem (gethash-lock rid wlist))) (when trsem (setf (caddr trsem) val) (signal-semaphore (cadr trsem))))) ((equal m "^") (let* ((wlist (wait-list ses)) (trsem (gethash-lock rid wlist))) (when trsem (setf (cadddr trsem) t))))))))) (on :close ws (lambda (&key code reason) (format t "WS closed (~a ~a)~%" code reason) (setf (disconnected-at ses) (get-universal-time)) (setf (session-ws ses) nil) (when (and sock-thread (not (equal sock-thread (bt:current-thread)))) (bt:destroy-thread sock-thread)))) ws)) (defun get-str-from (s len) (let ((*read-eval* nil) (tseq (make-array (list len) :element-type '(unsigned-byte 8)))) (read-sequence tseq s) (utf-8-bytes-to-string tseq))) (in-package :omg) (defun get-service-worker-js () (concatenate 'string " self.Deno=1; // Just a fake to disable JSCL worker code " (get-main-js) " self.addEventListener('install', (e)=>{ console.log('Service worker installed!') return self.skipWaiting() }) self.addEventListener('activate', (e)=>{ console.log('Service worker activated!') return self.clients.claim() }) self.addEventListener('message', (currentEvent)=>{ jscl.internals.globalEval(currentEvent.data.code) }) OMG.fetchHandler=(ev)=>{return} self.addEventListener('fetch', function(e) { OMG.fetchHandler(e) }) ")) (defun get-worker-js () (concatenate 'string " self.Deno=1; // Just a fake to disable JSCL worker code " (get-main-js) " self.addEventListener('message', (currentEvent)=>{ if('cache' in currentEvent.data) { OMG.FetchCache=currentEvent.data.cache } jscl.internals.globalEval(currentEvent.data.code) }) self.postMessage('BOOT') ")) (defvar *user-uri-handler* (lambda (env) (declare (ignore env)) '(404 (:content-type "text/plain") ("File not found")))) (defvar *serve-paths* (make-hash-table :test #'equal)) (defun add-serve-path (path result) (setf (gethash path *serve-paths*) result)) (defun serv (env) (let ((uri (getf env :REQUEST-URI)) (*read-eval* nil)) (cond ((equal uri (concatenate 'string *root-path* *service-worker-path*)) `(200 (:content-type "text/javascript; charset=utf-8" :cache-control "no-store" ,@(if *cross-origin* '(:Cross-Origin-Opener-Policy "same-origin" :Cross-Origin-Embedder-Policy "require-corp"))) (,(get-service-worker-js)))) ((equal uri (concatenate 'string *root-path* *web-worker-path*)) `(200 (:content-type "text/javascript; charset=utf-8" ,@(if *cross-origin* '(:Cross-Origin-Opener-Policy "same-origin" :Cross-Origin-Embedder-Policy "require-corp"))) (,(get-worker-js)))) ((equal uri (concatenate 'string *root-path* *js-path*)) `(200 (:content-type "text/javascript; charset=utf-8" :connection "Close") (,(get-main-js)))) ((equal uri (concatenate 'string *root-path* *html-path*)) `(200 (:content-type "text/html; charset=utf-8" ,@(if *cross-origin* '(:Cross-Origin-Opener-Policy "same-origin" :Cross-Origin-Embedder-Policy "require-corp"))) (,(get-root-html)))) ((and (equal uri (concatenate 'string *root-path* *rpc-path*)) ;; will be removed (getf env :content-length)) (with-input-from-string (s (omg::replace-all (get-str-from (getf env :raw-body) (getf env :content-length)) "\\n" (make-string 1 :initial-element #\newline))) (let* ((session-id (intern (symbol-name (omg-read s)) :omg)) (*current-session* (find-session session-id)) (*package* (find-package (omg-read s))) (cmd (omg-read s)) (op (car cmd)) (args (cadr cmd))) (if (and (not (equal session-id 'no-session)) *current-session*) (setf (slot-value *current-session* 'last-active) (get-universal-time))) (if (gethash-lock op *rpc-functions*) (rpc-wrapper op args *package*) `(404 (:content-type "text/plain; charset=utf-8") ("")))))) ((and (equal uri (concatenate 'string *root-path* *rpc-path-m*)) (getf env :content-length)) (with-input-from-string (s (omg::replace-all (get-str-from (getf env :raw-body) (getf env :content-length)) "\\n" (make-string 1 :initial-element #\newline))) (let* ((session-id (intern (symbol-name (omg-read s)) :omg)) (*current-session* (find-session session-id)) (*package* (find-package (omg-read s))) (cmd (omg-read s)) (op (car cmd)) (args (cadr cmd))) (if (and (not (equal session-id 'no-session)) *current-session*) (setf (slot-value *current-session* 'last-active) (get-universal-time))) (if (gethash-lock op *rpc-functions*) (rpc-wrapper op args *package* t) `(404 (:content-type "text/plain; charset=utf-8") ("")))))) ((and (equal uri (concatenate 'string *root-path* *gimme-path*)) (getf env :content-length)) (let ((str (get-str-from (getf env :raw-body) (getf env :content-length)))) (with-input-from-string (s str) (let* ((session-id (intern (symbol-name (omg-read s)) :omg)) (*current-session* (find-session session-id)) (*package* (find-package (omg-read s))) (sym (omg-read s))) (if (and *current-session* (not (equal session-id 'no-session))) (setf (slot-value *current-session* 'last-active) (get-universal-time))) (if (symbolp sym) (gimme sym)))))) ((and (equal uri (concatenate 'string *root-path* *takit-path*)) (getf env :content-length)) (let ((str (get-str-from (getf env :raw-body) (getf env :content-length)))) (with-input-from-string (s str) (let* ((session-id (intern (symbol-name (omg-read s)) :omg)) (*current-session* (find-session session-id)) (*package* (find-package (omg-read s)))) (if (and *current-session* (not (equal session-id 'no-session))) (setf (slot-value *current-session* 'last-active) (get-universal-time))) (takit (omg-read s) (omg-read s)))))) ((equal uri (concatenate 'string *root-path* *ws-path*)) (let ((ws (make-ws env))) (lambda (responder) (declare (ignorable responder)) (start-connection ws)))) (t (if (equal (string>= uri *root-path*) (length *root-path*)) (let ((res (gethash (subseq uri (length *root-path*)) *serve-paths*))) (if res res (funcall *user-uri-handler* env))) (funcall *user-uri-handler* env)))))) (defvar *serv* nil) (defvar *last-args* nil) (defparameter *wl-timeout* 600) (defparameter *session-timeout* (* 60 60 24)) (defun start-server (&rest args) (if args (setf *last-args* args)) (start-multiprocessing) ;; bordeaux-threads requirement (if (not *giant-hash-lock*) (setf *giant-hash-lock* (bt:make-lock))) (setf *serv* (ignore-errors (apply #'clack:clackup `(,#'serv :port ,*port* :ssl ,(has-ssl-p) :ssl-key-file ,*ssl-key* :ssl-cert-file ,*ssl-cert* :debug nil :use-default-middlewares nil ,@*last-args*)))) (if *serv* (push (bt:make-thread (lambda () (loop do (ignore-errors (let ((tim (get-universal-time))) (labels ((clwl (h) (map nil (lambda (x) (let ((t1 (cdr (assoc :time (gethash-lock x h))))) (if (and t1 (> (- tim t1) *wl-timeout*)) (progn (remhash x h) (unintern x))))) (loop for k being each hash-key of h collect k)))) (map nil #'clwl (list *gimme-wait-list* *takit-wait-list*)) (map nil (lambda (sid) (let* ((ses (gethash-lock sid *session-list*)) (ws (session-ws ses))) (when ws (when (equal (ready-state ws) :closed) (emit :close ws)) (ignore-errors (send-ping ws)) (when (equal (ready-state ws) :closing) (ignore-errors (close-connection ws)))) (if (and (disconnected-at ses) (> (- (get-universal-time) (disconnected-at ses)) *session-timeout*)) (progn (maphash (lambda (k v) (if (and (car v) (not (equal (current-thread) (car v))) (thread-alive-p (car v))) (destroy-thread (car v))) (unintern k)) (wait-list ses)) (map nil (lambda (id) (remhash id *remote-objects*)) (loop for obj being each hash-value of *remote-objects* when (equal (session obj) ses) collect (id obj))) (remhash sid *session-list*) (remove-all-listeners (session-ws ses)) (unintern sid))))) (loop for k being each hash-key of *session-list* collect k)) (setf *omg-thread-list* (remove-if-not #'bt:thread-alive-p *omg-thread-list*))) (sleep 60)))))) *omg-thread-list*) (warn "Server not started!"))) (defun kill-server () (loop for s being each hash-value of *session-list* when (equal (ready-state (socket s)) :open) do (ignore-errors (close-connection (socket s)))) (map nil #'clrhash (list *gimme-wait-list* *takit-wait-list* *session-list*)) (map nil #'bt:destroy-thread (remove-if-not #'bt:thread-alive-p *omg-thread-list*)) (setf *omg-thread-list* nil) (if *serv* (clack::stop *serv*))) (defun restart-server (&rest args) (progn (kill-server) (apply #'start-server args))) (defmacro thread-in-session (&rest code) `(push (bt:make-thread (lambda () ,@code) :initial-bindings (list (cons '*current-session* *current-session*))) *omg-thread-list*))
75,893
Common Lisp
.lisp
1,512
35.490079
156
0.51127
hemml/OMGlib
43
1
0
GPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
05fed8be2e70c1cdca8a25fc7b34b6c7c1cd47263350c365ab344dd211d57d50
4,300
[ -1 ]
4,301
omg.asd
hemml_OMGlib/omg.asd
(defsystem "omg" :description "A Common Lisp library to build fully dynamic web interfaces" :version "0.2.0" :author "Pavel Kaygorodov <[email protected]>" :licence "GPLv3" :homepage "https://github.com/hemml/OMGlib" :source-control "https://github.com/hemml/OMGlib.git" :depends-on ("clack" "websocket-driver-server" "bordeaux-threads" "trivial-utf-8" "media-types" "hunchentoot" "pngload" "skippy" "cl-jpeg" "cl-parallel") :build-operation "static-program-op" :components ((:static-file "README.md") (:static-file "LICENSE") (:file "omg") (:file "omgui" :depends-on ("omg")) (:file "omgutil" :depends-on ("omg")) (:file "omgwidgets" :depends-on ("omg" "omgui")))) (defparameter *jscl-dir* (merge-pathnames (make-pathname :directory '(:relative "jscl")) (asdf:system-source-directory :omg))) (load (merge-pathnames (make-pathname :name "jscl.lisp") *jscl-dir*)) (defparameter jscl::*jscl-js* (make-array '(0) :element-type 'base-char :fill-pointer 0 :adjustable t)) ;; Adopted from jscl.lisp: (let ((jscl::*features* (list* :jscl :jscl-xc jscl::*features*)) (jscl::*package* (find-package "JSCL")) (jscl::*default-pathname-defaults* *jscl-dir*)) (setq jscl::*environment* (jscl::make-lexenv)) (jscl::with-compilation-environment (jscl::with-output-to-string (jscl::out jscl::*jscl-js*) (format jscl::out "(function(){~%") (format jscl::out "'use strict';~%") (jscl::write-string (jscl::read-whole-file (jscl::source-pathname "prelude.js")) jscl::out) (jscl::do-source input :target (jscl::!compile-file input jscl::out :print nil)) (jscl::dump-global-environment jscl::out) (jscl::!compile-file "src/toplevel.lisp" jscl::out :print nil) (format jscl::out "})();~%"))))
1,889
Common Lisp
.asd
35
46.571429
111
0.628649
hemml/OMGlib
43
1
0
GPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
1a023baf6c2de13fdc12559e94a49d06dcee5c5df8f81db6d5b77b1fae034eb3
4,301
[ -1 ]
4,302
omgdaemon.asd
hemml_OMGlib/omgdaemon.asd
(defsystem "omgdaemon" :description "A deployment system for omg-based apps" :version "0.0.1" :author "Pavel Kaygorodov <[email protected]>" :licence "GPLv3" :homepage "https://github.com/hemml/OMGlib" :source-control "https://github.com/hemml/OMGlib.git" :depends-on ("omg" "bordeaux-threads" "trivial-utf-8" "swank" "osicat" "uiop" "find-port" "inferior-shell" "iolib" "log4cl" "trivial-dump-core" "cffi") :components ((:static-file "README.md") (:static-file "LICENSE") (:file "omgdaemon") (:file "daemonui" :depends-on ("omgdaemon"))))
596
Common Lisp
.asd
12
43.583333
153
0.650685
hemml/OMGlib
43
1
0
GPL-3.0
9/19/2024, 11:26:12 AM (Europe/Amsterdam)
2a0a47439064221417d3427a0e82d835a2ffb70d760853c4e39f388e730be5aa
4,302
[ -1 ]
4,325
tangram-packages.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/tangram-packages.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: CL-USER; Base: 10 -*- (in-package :CL-USER) ;;; ;;; Define Packages ;;; (export '(transform-xy-list psgraph tree-reverse tree-remove tree-collect-if tree-find tree-find-if tflatten my-round => <=> kill run blank-line-p with-standard-output-to-file concept-name intervall-intersects-p circle-intervall-intersects-p lies-in-circle-intervall-p circle-intervall-length rad-to-deg deg-to-rad +2pi+ +pi/2+ recode-german-characters zerop-eps =-eps <=-eps >=-eps one-of xor defun-memo defmethod-memo reset-memo yes no ensure-list circle-subseq mynconc my-format pushend make-cyclic get-lambda-args set-equal set-disjoint fac n-over-k k-out-of-n compute-all-subsets power prod perm permutations forcecdr stringsubst-char-with-string string-substitute build-elem-pairs-in-list vector-orientation splice-in reorder loop-over-avl-tree insert-into-avl-tree delete-from-avl-tree find-in-avl-tree print-avl-tree)) (defpackage tangram-persistence-manager (:use common-lisp) (:shadow #:defclass #:defstruct) (:export #:defpersistentclass #:defpersistentstruct #:initialize-loaded-persistent-object #:make-object-persistent #:load-persistent-object #:print-persistence-manager-info #:user-write-constructor #:user-write-component-constructor #:user-write-initializer #:user-write-component-initializer #:user-fill-object #:user-read-component-object #:user-create-empty-object)) (defpackage tangram-geometry (:use common-lisp-user common-lisp tangram-persistence-manager) (:export infinit geom-thing geom-point geom-line geom-chain-or-polygon geom-chain geom-polygon geom-aggregate bounding-box bounding-box-mixin delete-object polygon chain make-circle make-arc make-point p make-line l make-polygon poly make-chain chain make-aggregate agg make-bounding-box bb poly-from-xy-list chain-from-xy-list get-xy-list bounding-box-p bound-to ;id mark-value mark-object x y det det-0-vecs bb-width bb-height p1 p2 centroid p1-of p2-of centroid-of pmin ; BB pmax ; BB radius ; BB segments point-list has-parts ; nur fuer Aggregate ! part-of point-=-p point->=-p point-<=-p line-=-p joins-p parallel-p upright-p primary-p ; Primaerobjekt <=> keine Master component-p common-root-p get-all-masters ; fuer alle Objekte ! get-all-components get-direct-components ; fuer alle Objekte ! get-already-present-direct-master ; fuer alle Objekte ! get-topmost-master get-topmost-common-master get-direct-common-master get-direct-common-master-from-list for-each-master-holds-p for-each-component-holds-p for-some-master-holds-p for-some-component-holds-p calculate-bounding-box invalidate-bounding-box calculate-bounding-box-for-complex-object calculate-centroid calculate-intersection-point calculate-intersection-line angle-difference distance-between* distance-between-point-and-line distance-between distance-between-xy length-of-line point-truly-inside-box-p point-truly-inside-box-p* point-inside-box-p point-inside-box-p* point-truly-outside-box-p point-truly-outside-box-p* point-outside-box-p point-outside-box-p* box-overlaps-box-p box-overlaps-box-p* enlarged-box-overlaps-box-p box-truly-overlaps-box-p box-truly-overlaps-box-p* box-touches-box-p box-touches-box-p* box-inside-box-p box-inside-box-p* box-truly-inside-box-p box-truly-inside-box-p* line-intersects-box-border-p line-intersects-box-border-p* normalize angle-between angle-between* distance-and-orientation distance-and-orientation* global-orientation make-matrix reset translate scale rotate compose with-matrix with-translation with-scaling with-rotation with-no-matrix-at-all proportional-2-point fixed-sy-2-point lies-on-p lies-on-p* inside-p inside-p* outside-p outside-p* intersects-p crosses-p crosses-p* crossed-by-p touches-p covers-p covered-by-p overlaps-p congruent-p 0d-touches-p 1d-touches-p 1d-intersects-p equal-p inside-epsilon-p inside-epsilon-p* calculate-relation inverse get-epsilon-enclosure-relevant-points get-epsilon-enclosure-relevant-points* segment-list-ok-p ;; Symbole (werden von calculate-relation geliefert) borders bordered-by disjoint lies-on crosses crossed-by touches 0d-intersects 1d-intersects intersects inside contains covers covered-by overlaps congruent calculate-relation calculate-rcc-relation inverse-rcc-relation orientation decode-ccw orientate-counterclockwise orientate-clockwise affected-by-matrix-p insert-new-border-points )) (defpackage tangram (:use common-lisp-user common-lisp clim clim-lisp tangram-persistence-manager tangram-geometry) (:SHADOW CLIM:COLOR) (:shadowing-import-from tangram-geometry POLYGON MAKE-POINT MAKE-LINE MAKE-POLYGON WITH-TRANSLATION WITH-SCALING WITH-ROTATION) (:shadowing-import-from clim PATHNAME TRUENAME BOOLEAN INTERACTIVE-STREAM-P))
6,257
Common Lisp
.lisp
294
15.081633
76
0.671883
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
e7476b6d3f3438f929e7ccdcf7f708b0f7940390118a2f2d74f78f227c20bbce
4,325
[ -1 ]
4,326
define-system.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/define-system.lisp
;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: CL-USER -*- (cl:in-package :cl-user) ;;; ---------------------------------------------------------------------- ;;; ;;; Portable system declaration expanding into vendor-specific versions. ;;; ;;; DEFINE System = DEFsystem Is Now Expanded System ;;; ;;; ---------------------------------------------------------------------- ;;; Make load-system and compile-system available in cl-user. ;;; Both systems accept a system-name (symbol or string) as a parameter. ;;; Please notice that in some native defsystems, symbols used for ;;; system names might be package-sensitive. ;;; Therefore it is recommended that cl-user is used for defsystem definitions. #+:Genera (import '(scl:load-system scl:compile-system) 'fcl-user) #+:MCL (if (or (fboundp 'load-system) (fboundp 'compile-system)) (warn "The function definitions of load-system and/or compile-system will be overwritten.") (when (y-or-n-p "Do you want to do this? ") (setf (symbol-function 'load-system) #'load-unit) (setf (symbol-function 'compile-system) #'compile-unit))) (defun load-system-definition (system-name) (let ((name (if (symbolp system-name) (string-downcase (symbol-name system-name)) (string-downcase system-name)))) (load-logical-pathname-translations name) (load (concatenate 'string name ":system-declarations;" name "-sysdcl.lisp")))) (defmacro define-system (name (&key (pretty-name (symbol-name name)) default-pathname (subsystem nil)) components) #+(or :Allegro :mcl :Lispworks) (declare (ignore subsystem #+(or :mcl :Lispworks) pretty-name)) (labels ((host-substring (logical-pathname) (let ((position (position #\: logical-pathname))) (if position (subseq logical-pathname 0 position) nil))) #+:Allegro (system-loading-code (components) (let ((systems (remove-if #'stringp (flatten-serial-parallel-descriptions components)))) (mapcar #'(lambda (system-name) `(unless (find-system ',system-name) (load-system-definition ',system-name))) systems))) #+(or :Allegro :Genera :mcl :Lispworks) (flatten-serial-parallel-descriptions (description) (if (consp description) (mapcan #'flatten-serial-parallel-descriptions (rest description)) (list description)))) (unless default-pathname (error "A default pathname must be supplied in a system definition.")) (let ((logical-host (host-substring default-pathname)) #+(or :Genera :mcl) (systems-depending-on (remove-if-not #'symbolp (flatten-serial-parallel-descriptions components)))) (unless logical-host (error "Systems must be given a logical pathname as default pathname.")) `(progn #+:Allegro ,@(system-loading-code components) (load-logical-pathname-translations ,logical-host) #+:Allegro (excl:defsystem ,name (:default-pathname ,default-pathname :pretty-name ,pretty-name) ,components) #+:Lispworks (lw:defsystem ,name (:default-pathname ,(string-upcase default-pathname)) :members ,(mapcar #'(lambda (component) (if (symbolp component) `(,component :type :system) component)) (flatten-serial-parallel-descriptions components)) :rules ((:in-order-to :compile :all (:requires (:load :previous))))) #+:Genera (,(if subsystem 'sct:defsubsystem 'sct:defsystem) ,name (:default-pathname ,default-pathname :pretty-name ,pretty-name) ,@(mapcar #'(lambda (system) `(:module ,system (,system) (:type :system))) systems-depending-on) ,components) #+:mcl (cc:defunit ,name (:depends-on . ,systems-depending-on) (:source-pathname ,default-pathname) (:binary-pathname ,default-pathname) ; not default (:components . ,(remove-if #'symbolp (flatten-serial-parallel-descriptions components)))))))) #| (define-system :test (:default-pathname "test:default;" :pretty-name "Test" :subsystem t) (:serial (:parallel :bar :bvyy) "test1" "test2")) |#
4,233
Common Lisp
.lisp
120
29.9
95
0.643489
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
9b620eb0904296e7c25671cb90125a493b0e37a9952f0d68c78a0f80b1f8374b
4,326
[ -1 ]
4,327
deliver.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/deliver.lisp
;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: CL-USER -*- (in-package :cl-user) (load-all-patches) #+:mswindows (setf (logical-pathname-translations "tangram") '(("**;*.*" "C:\\Users\\micha\\Desktop\\GIT\\Common-Lisp-Tangram-Solver\\src\\**\\*.*"))) #-:mswindows (setf (logical-pathname-translations "tangram") '(("**;*.*" "/home/mwessel/tangram/src/**/*.*"))) ;;; ;;; ;;; (require "clim") (load "tangram:define-system.lisp") (load "tangram:tangram-sysdcl.lisp") (defun csys (system &rest args) (apply #'compile-system system args) (apply #'load-system system args)) (csys "tangram" :force-p t) (deliver 'tangram::tangram #-:mswindows "/home/mwessel/temp/tangram" #+:mswindows "c:\\temp\\tangram.exe" 4 :packages-to-keep '(tangram-geometry tangram-persistence-manager cl-user tangram) :interface :capi :multiprocessing t ) (quit)
930
Common Lisp
.lisp
31
25.903226
95
0.64059
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
e10e07052673528819a191ce53e5e2785e724dc654e4e3e60aa07e7fc1770726
4,327
[ -1 ]
4,328
tangram-sysdcl.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/tangram-sysdcl.lisp
;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: CL-USER -*- (in-package :cl-user) (setf (logical-pathname-translations "tangram") '(("**;*.*" "C:\\Users\\micha\\Desktop\\GIT\\Common-Lisp-Tangram-Solver\\src\\**\\*.*"))) ;;; ;;; ;;; (require "clim") (load "tangram:define-system.lisp") ;;; ;;; ;;; (define-system tangram-aux (:default-pathname "tangram:tools;") (:serial "aux8")) (define-system tangram-persistence (:default-pathname "tangram:persistence;") (:serial "persistence2")) (define-system tangram-geometry (:default-pathname "tangram:geometry;") (:serial "geometry" "box-relations" "predicates" "rcc-predicates" "relations")) ;;; ;;; ;;; (define-system tangram-main (:default-pathname "tangram:main;") (:serial tangram-aux tangram-persistence "covering4")) (define-system tangram-gui (:default-pathname "tangram:gui;") (:serial tangram-aux tangram-persistence "gui-aux" "gui3")) (define-system tangram (:default-pathname "tangram:") (:serial "tangram-packages" #+:linux "tangram-templates" tangram-aux tangram-persistence tangram-geometry tangram-main tangram-gui)) ;;; ;;; ;;; (compile-system "tangram" :force-p t) (load-system "tangram")
1,249
Common Lisp
.lisp
49
22.489796
95
0.682513
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
365993a953fa8aeb6b4cf319a23423e72622ed81b8ee2b8814ee73732ad8bead
4,328
[ -1 ]
4,329
box-relations.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/geometry/box-relations.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: TANGRAM-GEOMETRY; Base: 10 -*- (in-package tangram-geometry) (defgeneric point-truly-inside-box-p (point box) (:documentation "Determine if point is contained by box. If point lies on the border of the box, returns NIL.")) (defgeneric point-inside-box-p (point box) (:documentation "Determine if point is contained by box. If point lies on the border of the box, returns T.")) (defgeneric point-truly-outside-box-p (point box) (:documentation "Determine if point is outside box. If point lies on the border of the box, returns NIL.")) (defgeneric point-outside-outside-box-p (point box) (:documentation "Determine if point is outside box. If point lies on the border of the box, returns T.")) (defgeneric box-inside-box-p (box1 box2) (:documentation "Determine whether box1 is inside box2. If box1 touches box2 from the inside, returns T.")) (defgeneric box-truly-inside-box-p (box1 box2) (:documentation "Determine whether box1 is inside box2. If box1 touches box2 from the inside, returns NIL.")) (defgeneric box-overlaps-box-p (box1 box2) (:documentation "Determine whether box1 overlaps box2. If only the borders intersect, but not their interiors, returns T.")) (defgeneric box-truly-overlaps-box-p (box1 box2) (:documentation "Determine whether box1 overlaps box2. If only the borders intersect, but not their interiors, returns NIL.")) (defgeneric box-touches-box-p (box1 box2) (:documentation "Determine whether box1 touches box2. This is the case, if only the borders of the boxes intersect, but not their interiors.")) (defgeneric line-intersects-box-border-p (line box) (:documentation "Determine whether line intersects the border of box. Intersections between the interior and the line will be ignorerd.")) (defgeneric enlarged-box-overlaps-box-p (obj box r) (:documentation "Enlarge box in all directions by R and determine wheter box and the bounding box of obj are overlapping.")) ;;; ;;; BOX-Relationen ;;; (defun point-inside-box-p* (x y box) (and (<= (x (pmin box)) x (x (pmax box))) (<= (y (pmin box)) y (y (pmax box))))) (defmethod point-inside-box-p ((point geom-point) (box bounding-box-mixin)) (point-inside-box-p* (x point) (y point) box)) (defun point-truly-inside-box-p* (x y box) (and (< (x (pmin box)) x (x (pmax box))) (< (y (pmin box)) y (y (pmax box))))) (defmethod point-truly-inside-box-p ((point geom-point) (box bounding-box-mixin)) (point-truly-inside-box-p* (x point) (y point) box)) (defun point-outside-box-p* (x y box) (or (>= x (x (pmax box))) (<= x (x (pmin box))) (>= y (y (pmax box))) (<= y (y (pmin box))))) (defmethod point-outside-box-p ((point geom-point) (box bounding-box-mixin)) (point-outside-box-p* (x point) (y point) box)) (defun point-truly-outside-box-p* (x y box) (or (> x (x (pmax box))) (< x (x (pmin box))) (> y (y (pmax box))) (< y (y (pmin box))))) (defmethod point-truly-outside-box-p ((point geom-point) (box bounding-box-mixin)) (point-truly-outside-box-p* (x point) (y point) box)) ;;; ;;; ;;; (defun box-inside-box-p* (xmin1 ymin1 xmax1 ymax1 xmin2 ymin2 xmax2 ymax2) (and (>= xmin1 xmin2) (>= ymin1 ymin2) (<= xmax1 xmax2) (<= ymax1 ymax2))) (defmethod box-inside-box-p ((box1 bounding-box-mixin) (box2 bounding-box-mixin)) (box-inside-box-p* (x (pmin box1)) (y (pmin box1)) (x (pmax box1)) (y (pmax box1)) (x (pmin box2)) (y (pmin box2)) (x (pmax box2)) (y (pmax box2)))) ;;; ;;; ;;; (defun box-truly-inside-box-p* (xmin1 ymin1 xmax1 ymax1 xmin2 ymin2 xmax2 ymax2) (and (> xmin1 xmin2) (> ymin1 ymin2) (< xmax1 xmax2) (< ymax1 ymax2))) (defmethod box-truly-inside-box-p ((box1 bounding-box-mixin) (box2 bounding-box-mixin)) (box-truly-inside-box-p* (x (pmin box1)) (y (pmin box1)) (x (pmax box1)) (y (pmax box1)) (x (pmin box2)) (y (pmin box2)) (x (pmax box2)) (y (pmax box2)))) ;;; ;;; ;;; (defun box-overlaps-box-p* (xmin1 ymin1 xmax1 ymax1 xmin2 ymin2 xmax2 ymax2) (and (<= xmin2 xmax1) (<= ymin2 ymax1) (>= xmax2 xmin1) (>= ymax2 ymin1))) (defmethod box-overlaps-box-p ((box1 bounding-box-mixin) (box2 bounding-box-mixin)) (box-overlaps-box-p* (x (pmin box1)) (y (pmin box1)) (x (pmax box1)) (y (pmax box1)) (x (pmin box2)) (y (pmin box2)) (x (pmax box2)) (y (pmax box2)))) ;;; ;;; ;;; (defun box-truly-overlaps-box-p* (xmin1 ymin1 xmax1 ymax1 xmin2 ymin2 xmax2 ymax2) (and (< xmin2 xmax1) (< ymin2 ymax1) (> xmax2 xmin1) (> ymax2 ymin1))) (defmethod box-truly-overlaps-box-p ((box1 bounding-box-mixin) (box2 bounding-box-mixin)) (box-truly-overlaps-box-p* (x (pmin box1)) (y (pmin box1)) (x (pmax box1)) (y (pmax box1)) (x (pmin box2)) (y (pmin box2)) (x (pmax box2)) (y (pmax box2)))) ;;; ;;; ;;; (defun box-touches-box-p* (xmin1 ymin1 xmax1 ymax1 xmin2 ymin2 xmax2 ymax2) (and (not (box-truly-overlaps-box-p* xmin1 ymin1 xmax1 ymax1 xmin2 ymin2 xmax2 ymax2)) (box-overlaps-box-p* xmin1 ymin1 xmax1 ymax1 xmin2 ymin2 xmax2 ymax2))) (defmethod box-touches-box-p ((box1 bounding-box-mixin) (box2 bounding-box-mixin)) (box-touches-box-p* (x (pmin box1)) (y (pmin box1)) (x (pmax box1)) (y (pmax box1)) (x (pmin box2)) (y (pmin box2)) (x (pmax box2)) (y (pmax box2)))) ;;; ;;; ;;; (defun line-intersects-box-border-p* (x1 y1 x2 y2 b) (let ((xmin (x (pmin b))) (ymin (y (pmin b))) (xmax (x (pmax b))) (ymax (y (pmax b)))) (labels ((code (x y) (let ((bit1 (< x xmin)) (bit2 (> x xmax)) (bit3 (< y ymin)) (bit4 (> y ymax))) (values bit1 bit2 bit3 bit4)))) (multiple-value-bind (c1 c2 c3 c4) (code x1 y1) (multiple-value-bind (ca cb cc cd) (code x2 y2) (and (not (or (and c1 ca) ; ein gemeinsames Bit ? (OR ...) => VOLLSTAENDIG UNSICHTBAR (and c2 cb) (and c3 cc) (and c4 cd))) (=> (not (or c1 c2 c3 c4 ca cb cc cd)) ; vollst. innen (or (= x1 xmin) ; liegt auf Rand ? (= x1 xmax) (= x2 xmin) (= x2 xmax) (= y1 ymin) (= y1 ymax) (= y2 ymin) (= y2 ymax))))))))) (defmethod line-intersects-box-border-p ((line geom-line) (box bounding-box-mixin)) (and (=> (and (bounding-box-p line) (bounding-box-p box)) (box-overlaps-box-p line box)) (line-intersects-box-border-p* (x (p1 line)) (y (p1 line)) (x (p2 line)) (y (p2 line)) box))) ;;; ;;; ;;; (defmethod enlarged-box-overlaps-box-p ((box1 bounding-box-mixin) (box2 bounding-box-mixin) r) (box-overlaps-box-p* (- (x (pmin box1)) r) (- (y (pmin box1)) r) (+ (x (pmax box1)) r) (+ (y (pmax box1)) r) (x (pmin box2)) (y (pmin box2)) (x (pmax box2)) (y (pmax box2))))
7,232
Common Lisp
.lisp
203
30.197044
102
0.615619
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
18c6aed214520d00f3b4d19060bb86dad37f393bf0fb4574ed0c5d3782f5be16
4,329
[ -1 ]
4,330
predicates.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/geometry/predicates.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: TANGRAM-GEOMETRY; Base: 10 -*- (in-package tangram-geometry) ;;; ;;; Basis-Prädikate ;;; (defun intersects-p* (xs1 ys1 xe1 ye1 xs2 ys2 xe2 ye2) (let* ((a (ccw* xs1 ys1 xe1 ye1 xs2 ys2)) (b (ccw* xs1 ys1 xe1 ye1 xe2 ye2)) (c (ccw* xs2 ys2 xe2 ye2 xs1 ys1)) (d (ccw* xs2 ys2 xe2 ye2 xe1 ye1))) (and (<= (* a b) 0.0) (<= (* c d) 0.0)))) (defun crosses-p* (xs1 ys1 xe1 ye1 xs2 ys2 xe2 ye2) (let* ((a (ccw* xs1 ys1 xe1 ye1 xs2 ys2)) (b (ccw* xs1 ys1 xe1 ye1 xe2 ye2)) (c (ccw* xs2 ys2 xe2 ye2 xs1 ys1)) (d (ccw* xs2 ys2 xe2 ye2 xe1 ye1))) (when (and (<= (* a b) 0.0) (<= (* c d) 0.0)) ; Schnitt liegt vor (not (or (zerop a) (zerop b) (zerop c) (zerop d) (zerop (ccw* xe1 ye1 xs1 ys1 xs2 ys2)) (zerop (ccw* xe1 ye1 xs1 ys1 xe2 ye2)) (zerop (ccw* xe2 ye2 xs2 ys2 xs1 ys1)) (zerop (ccw* xe2 ye2 xs2 ys2 xe1 ye1))))))) (defmethod lies-on-p* (x y (line geom-line)) (or (zerop (ccw* (x (p1 line)) (y (p1 line)) (x (p2 line)) (y (p2 line)) x y)) (zerop (ccw* (x (p2 line)) (y (p2 line)) (x (p1 line)) (y (p1 line)) x y)))) (defmethod-memo lies-on-p* (x y (poly-or-chain geom-chain-or-polygon)) ((x y poly-or-chain (trafo-id *matrix*))) (some #'(lambda (segment) (lies-on-p* x y segment)) (segments poly-or-chain))) ;;; ;;; LIES-ON ;;; (defmethod lies-on-p ((point1 geom-point) (point2 geom-point)) (point-=-p point1 point2)) (defmethod lies-on-p ((point geom-point) (line geom-line)) (or (zerop (ccw (p1 line) (p2 line) point)) (zerop (ccw (p2 line) (p1 line) point)))) (defmethod-memo lies-on-p ((point geom-point) (poly-or-chain geom-chain-or-polygon)) ((point poly-or-chain (trafo-id *matrix*))) (some #'(lambda (segment) (lies-on-p point segment)) (segments poly-or-chain))) (defmethod lies-on-p ((l1 geom-line) (l2 geom-line)) (and (lies-on-p (p1 l1) l2) (lies-on-p (p2 l1) l2))) #| (defmethod-memo lies-on-p ((line geom-line) (poly geom-polygon)) ((line poly-or-chain)) (or (some #'(lambda (segment) (equal-p line segment)) (segments poly)) (and (intersects-p line poly) (not (one-part-is-inside-p line poly)) (not (one-part-is-outside-p line poly))))) |# (defmethod-memo lies-on-p ((line geom-line) (poly geom-polygon)) ((line poly (trafo-id *matrix*))) (or (some #'(lambda (segment) (lies-on-p line segment)) (segments poly)) (and (lies-on-p (p1 line) poly) (lies-on-p (p2 line) poly) (or (every #'(lambda (point) (lies-on-p point line)) (get-points-between poly (p1 line) (p2 line))) (every #'(lambda (point) (lies-on-p point line)) (get-points-between poly (p2 line) (p1 line))))))) (defmethod-memo lies-on-p ((line geom-line) (chain geom-chain)) ((line chain (trafo-id *matrix*))) (or (some #'(lambda (segment) (lies-on-p line segment)) (segments chain)) (and (lies-on-p (p1 line) chain) (lies-on-p (p2 line) chain) (every #'(lambda (point) (lies-on-p point line)) (get-points-between chain (p1 line) (p2 line)))))) (defmethod-memo lies-on-p ((poly-or-chain1 geom-chain-or-polygon) (poly-or-chain2 geom-chain-or-polygon)) ((poly-or-chain1 poly-or-chain2 (trafo-id *matrix*))) (every #'(lambda (segment) (lies-on-p segment poly-or-chain2)) (segments poly-or-chain1))) ;;; ;;; INTERSECTS ;;; (defmethod intersects-p ((point1 geom-point) (point2 geom-point)) (point-=-p point1 point2)) (defmethod intersects-p ((point geom-point) (line geom-line)) (lies-on-p point line)) (defmethod intersects-p ((line geom-line) (point geom-point)) (lies-on-p point line)) (defmethod intersects-p ((point geom-point) (poly-or-chain geom-chain-or-polygon)) (lies-on-p point poly-or-chain)) (defmethod intersects-p ((poly-or-chain geom-chain-or-polygon) (point geom-point)) (lies-on-p point poly-or-chain)) (defmethod intersects-p ((l1 geom-line) (l2 geom-line)) (and (=> (and (bounding-box-p l1) (bounding-box-p l2)) (box-overlaps-box-p l1 l2)) (let* ((l1p1 (p1 l1)) (l2p1 (p1 l2)) (l1p2 (p2 l1)) (l2p2 (p2 l2)) (a (ccw l1p1 l1p2 l2p1)) (b (ccw l1p1 l1p2 l2p2)) (c (ccw l2p1 l2p2 l1p1)) (d (ccw l2p1 l2p2 l1p2))) (and (<= (* a b) 0.0) (<= (* c d) 0.0))))) (defmethod-memo intersects-p ((line geom-line) (poly-or-chain geom-chain-or-polygon)) ((line poly-or-chain (trafo-id *matrix*))) (and (=> (and (bounding-box-p line) (bounding-box-p poly-or-chain)) (box-overlaps-box-p line poly-or-chain)) (some #'(lambda (segment) (intersects-p line segment)) (segments poly-or-chain)))) (defmethod intersects-p ((poly-or-chain geom-chain-or-polygon) (line geom-line)) (intersects-p line poly-or-chain)) (defmethod-memo intersects-p ((poly-or-chain1 geom-chain-or-polygon) (poly-or-chain2 geom-chain-or-polygon)) ((poly-or-chain1 poly-or-chain2 (trafo-id *matrix*))) (some #'(lambda (segment) (intersects-p segment poly-or-chain2)) (segments poly-or-chain1))) ;;; ;;; CROSSES ;;; (defmethod crosses-p ((l1 geom-line) (l2 geom-line)) ;; "X" oder "+" (and (=> (and (bounding-box-p l1) (bounding-box-p l2)) (box-truly-overlaps-box-p l1 l2)) (let* ((l1p1 (p1 l1)) (l2p1 (p1 l2)) (l1p2 (p2 l1)) (l2p2 (p2 l2)) (a (ccw l1p1 l1p2 l2p1)) (a1 (ccw l1p2 l1p1 l2p1)) (b (ccw l1p1 l1p2 l2p2)) (b1 (ccw l1p2 l1p1 l2p2)) (c (ccw l2p1 l2p2 l1p1)) (c1 (ccw l2p2 l2p1 l1p1)) (d (ccw l2p1 l2p2 l1p2)) (d1 (ccw l2p2 l2p1 l1p2))) (and (not (or (zerop a) (zerop a1) (zerop b) (zerop b1) (zerop c) (zerop c1) (zerop d) (zerop d1))) (<= (* a b) 0) (<= (* c d) 0))))) (defmethod crossed-by-p ((l1 geom-line) (l2 geom-line)) (crosses-p l2 l1)) ;;; ;;; TOUCHES ;;; (defmethod touches-p ((l1 geom-line) (l2 geom-line)) ;; z.B. meets ("--"), aber auch "T" oder "\/" (and (=> (and (bounding-box-p l1) (bounding-box-p l2)) (box-overlaps-box-p l1 l2)) (let ((l1p1-l2 (lies-on-p (p1 l1) l2)) (l1p2-l2 (lies-on-p (p2 l1) l2)) (l2p1-l1 (lies-on-p (p1 l2) l1)) (l2p2-l1 (lies-on-p (p2 l2) l1))) (or ;; "T"-Faelle (and l1p1-l2 (not l1p2-l2) (not l2p1-l1) (not l2p2-l1)) (and (not l1p1-l2) l1p2-l2 (not l2p1-l1) (not l2p2-l1)) (and (not l1p1-l2) (not l1p2-l2) l2p1-l1 (not l2p2-l1)) (and (not l1p1-l2) (not l1p2-l2) (not l2p1-l1) l2p2-l1) ;; "--" und "\/"-Faelle (and (joins-p l1 l2) ;; 1d-Schnitte ausschliessen (not (or (and l1p1-l2 l1p2-l2) (and l2p1-l1 l2p2-l1)))))))) ;;; ;;; 1D-INTERSECTS ;;; (defmethod 1d-intersects-p ((l1 geom-line) (l2 geom-line)) ;; overlaps, contains, covers, equal + Inverse (and (=> (and (bounding-box-p l1) (bounding-box-p l2)) (box-overlaps-box-p l1 l2)) (let ((l1p1-l2 (lies-on-p (p1 l1) l2)) (l1p2-l2 (lies-on-p (p2 l1) l2)) (l2p1-l1 (lies-on-p (p1 l2) l1)) (l2p2-l1 (lies-on-p (p2 l2) l1))) (or (and l1p1-l2 (not l1p2-l2) l2p1-l1 (not l2p2-l1) ; overlaps-faelle (not (point-=-p (p1 l1) (p1 l2)))) ; touches ausschliessen (and l1p1-l2 (not l1p2-l2) (not l2p1-l1) l2p2-l1 (not (point-=-p (p1 l1) (p2 l2)))) (and (not l1p1-l2) l1p2-l2 l2p1-l1 (not l2p2-l1) (not (point-=-p (p2 l1) (p1 l2)))) (and (not l1p1-l2) l1p2-l2 (not l2p1-l1) l2p2-l1 (not (point-=-p (p2 l1) (p2 l2)))) (and l1p1-l2 l1p2-l2 (not l2p1-l1) (not l2p2-l1)) ; l1 contains l2 (and (not l1p1-l2) (not l1p2-l2) l2p1-l1 l2p2-l1) (and l1p1-l2 l1p2-l2 l2p1-l1 l2p2-l1) ; equal (and l1p1-l2 (not l1p2-l2) l2p1-l1 l2p2-l1) ; l1 covers l2 (and (not l1p1-l2) l1p2-l2 l2p1-l1 l2p2-l1) (and l1p1-l2 l1p2-l2 l2p1-l1 (not l2p2-l1)) ; l2 covers l1 (and l1p1-l2 l1p2-l2 (not l2p1-l1) l2p2-l1))))) ;;; ;;; Bestimme, ob bzgl. der von "line" erzeugten Halbebenen alle ;;; gegebenen Strecken auf einer Seite (bzw. in einer der Halbebenenen) ;;; liegen. ;;; (defmethod-memo one-one-side-of-p ((segments list) (line geom-line)) ((segments line (trafo-id *matrix*))) (let ((ccws (mapcar #'(lambda (x) (ccw (p1 line) (p2 line) x)) (apply #'append (mapcar #'point-list segments))))) (or (every #'(lambda (x) (not (minusp x))) ccws) (every #'(lambda (x) (not (plusp x))) ccws)))) ;;; ;;; Inside-Relation ;;; (defparameter *cur-line* ; willkuerlich gewaehlt (l (p 0 0 :affected-by-matrix-p nil) ;;; WICHTIG!!! (p 1 1 :affected-by-matrix-p nil) :affected-by-matrix-p nil :bounding-box-p nil)) (defparameter *test-beam* ; willkuerlich gewaehlt (l (p 0 0 :affected-by-matrix-p nil) (p 1 1 :affected-by-matrix-p nil) :affected-by-matrix-p nil :bounding-box-p nil)) #| int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy) { int i, j, c = 0; for (i = 0, j = nvert-1; i < nvert; j = i++) { if ( ((verty[i]>testy) != (verty[j]>testy)) && (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ) c = !c; } return c; } |# #| (defun-memo count-intersections* (x y polygon) ((x y polygon (trafo-id *matrix*))) (let* ((points (t-list polygon)) (count 0)) (dolist (point points) (if (not (eq (> ( y point) y) ((verty[i]>testy) != (verty[j]>testy)) && (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ) c = !c; |# (defun-memo count-intersections* (x y polygon) ((x y polygon (trafo-id *matrix*))) (let* ((points (point-list polygon)) (count 0) (from-point nil) (cur-point nil) (mark-point '?) (flag nil)) (setf (x (p1 *test-beam*)) x (y (p1 *test-beam*)) y (x (p2 *test-beam*)) +big-int+ (y (p2 *test-beam*)) +big-int2+) (loop until (eq mark-point 'stop) do ; einmal ganz rum (setf cur-point (first points) points (rest points)) (when (null points) (setf points (point-list polygon))) (when (eq cur-point mark-point) (setf mark-point 'stop)) (cond ((and (= y (y cur-point)) ; Zeit sparen... (<= x (x cur-point)) (lies-on-p cur-point *test-beam*)) (setf flag t)) (t (if (not from-point) ; noch kein erster Pkt. gefunden (progn (setf mark-point cur-point) ; merken => einmal rum! (setf flag nil) (setf from-point cur-point)) (progn (cond (flag ; es lagen Punkte zwischen from-point und cur-point a.d. Teststrahl (when (or (<= (y from-point) y (y cur-point)) (>= (y from-point) y (y cur-point))) (incf count))) (t ; es lagen keine Pkt. a.d. Teststrahl (setf (p1 *cur-line*) from-point) (setf (p2 *cur-line*) cur-point) (let ((p1c (p1 *cur-line*)) (p2c (p2 *cur-line*)) (p1t (p1 *test-beam*)) (p2t (p2 *test-beam*))) (when (not (and (= (x p1c) (x p2c) x))) (when (intersects-p* (x p1c) (y p1c) (x p2c) (y p2c) (slot-value p1t 'x) (slot-value p1t 'y) (slot-value p2t 'x) (slot-value p2t 'y)) (incf count)))))) (setf flag nil) (setf from-point cur-point)))))) count)) (defun count-intersections (point polygon) (count-intersections* (x point) (y point) polygon)) ;;; ;;; ACHTUNG: ALLE INSIDE/OUTSIDE-RELATIONEN SIND "TRULY"-INSIDE => RAND GEHOERT NICHT DAZU !!! ;;; (defmethod-memo inside-p* (x y (polygon geom-polygon)) ((x y polygon (trafo-id *matrix*))) (and (=> (bounding-box-p polygon) (point-truly-inside-box-p* x y polygon)) (not (lies-on-p* x y polygon)) (oddp (count-intersections* x y polygon)))) (defmethod inside-p ((point geom-point) (polygon geom-polygon)) (inside-p* (x point) (y point) polygon)) (defmethod contains-p ((polygon geom-polygon) (point geom-point) ) (inside-p point polygon)) (defmethod-memo outside-p* (x y (polygon geom-polygon)) ((x y polygon (trafo-id *matrix*))) (or (and (bounding-box-p polygon) (point-truly-outside-box-p* x y polygon)) (and (not (lies-on-p* x y polygon)) (evenp (count-intersections* x y polygon))))) (defmethod outside-p ((point geom-point) (polygon geom-polygon)) (outside-p* (x point) (y point) polygon)) ;;; ;;; ;;; (defmethod-memo inside-p ((line geom-line) (poly geom-polygon)) ((line poly (trafo-id *matrix*))) (and (=> (and (bounding-box-p line) (bounding-box-p poly)) (box-truly-inside-box-p line poly)) (not (intersects-p line poly)) (inside-p (p1 line) poly) (inside-p (p2 line) poly))) (defmethod contains-p ((poly geom-polygon) (line geom-line)) (inside-p line poly)) (defmethod-memo outside-p ((line geom-line) (poly geom-polygon)) ((line poly (trafo-id *matrix*))) (or (and (bounding-box-p line) (bounding-box-p poly) (not (box-overlaps-box-p line poly))) (and (not (intersects-p line poly)) (outside-p (p1 line) poly) (outside-p (p2 line) poly)))) ;;; ;;; ;;; (defmethod-memo inside-p ((poly-or-chain geom-chain-or-polygon) (poly geom-polygon)) ((poly-or-chain poly (trafo-id *matrix*))) (and (=> (and (bounding-box-p poly-or-chain) (bounding-box-p poly)) (box-truly-inside-box-p poly-or-chain poly)) (every #'(lambda (segment) (inside-p segment poly)) (segments poly-or-chain)))) (defmethod contains-p ((poly geom-polygon) (poly-or-chain geom-chain-or-polygon)) (inside-p poly-or-chain poly)) (defmethod-memo outside-p ((poly-or-chain geom-chain-or-polygon) (poly geom-polygon)) ((poly-or-chain poly (trafo-id *matrix*))) (or (and (bounding-box-p poly-or-chain) (bounding-box-p poly) (not (box-overlaps-box-p poly-or-chain poly))) (every #'(lambda (segment) (outside-p segment poly)) (segments poly-or-chain)))) ;;; ;;; Approximation: ist ein Teil einer Linie innerhalb eines Polygons enthalten? ;;; Bzw. gibt es einen echten Schnitt mit dem Inneren des Polygon? ;;; Gibt es hierfür einen effizienten Algorithmus? ;;; Hier zählt der Rand vom Polygon *NICHT* als Inneres!!! ;;; (defconstant +granularity+ 20) (defmethod-memo one-part-is-inside-p ((line geom-line) (poly geom-polygon)) ((line poly (trafo-id *matrix*))) (or (inside-p (p1 line) poly) (inside-p (p2 line) poly) (one-part-is-inside-p* (x (p1 line)) (y (p1 line)) (x (p2 line)) (y (p2 line)) poly (/ (+ (expt (- (x (p1 line)) (x (p2 line))) 2) (expt (- (y (p1 line)) (y (p2 line))) 2)) +granularity+)))) (defun-memo one-part-is-inside-p* (x1 y1 x2 y2 poly delta) ((x1 y1 x2 y2 poly (trafo-id *matrix*))) (let ((xm (float (/ (+ x1 x2) 2))) (ym (float (/ (+ y1 y2) 2)))) ;; BUG IN LISPWORKS!!!!! WITH RATIOS IT DOESN'T WORK - WRONG VALUE ON STACK!!!! (or (inside-p* xm ym poly) (unless (< (+ (expt (- x1 x2) 2) (expt (- y1 y2) 2)) delta) (or (one-part-is-inside-p* x1 y1 xm ym poly delta) (one-part-is-inside-p* xm ym x2 y2 poly delta)))))) ;;; ;;; Hier zählt der Rand des Polygons *NICHT* als Äußeres!!! ;;; (defmethod-memo one-part-is-outside-p ((line geom-line) (poly geom-polygon)) ((line poly (trafo-id *matrix*))) (or (and (not (lies-on-p (p1 line) poly)) (not (inside-p (p1 line) poly))) (and (not (lies-on-p (p2 line) poly)) (not (inside-p (p2 line) poly))) (one-part-is-outside-p* (x (p1 line)) (y (p1 line)) (x (p2 line)) (y (p2 line)) poly (/ (+ (expt (- (x (p1 line)) (x (p2 line))) 2) (expt (- (y (p1 line)) (y (p2 line))) 2)) +granularity+)))) (defun-memo one-part-is-outside-p* (x1 y1 x2 y2 poly delta) ((x1 y1 x2 y2 poly (trafo-id *matrix*))) (let ((xm (/ (+ x1 x2) 2)) (ym (/ (+ y1 y2) 2))) (or (and (not (inside-p* xm ym poly)) (not (lies-on-p* xm ym poly))) (unless (< (+ (expt (- x1 x2) 2) (expt (- y1 y2) 2)) delta) (or (one-part-is-outside-p* x1 y1 xm ym poly delta) (one-part-is-outside-p* xm ym x2 y2 poly delta)))))) ;;; ;;; Equal-Relation ;;; (defmethod equal-p ((obj1 geom-thing) (obj2 geom-thing)) nil) (defmethod equal-p ((obj1 geom-point) (obj2 geom-point)) (point-=-p obj1 obj2)) (defmethod equal-p ((obj1 geom-line) (obj2 geom-line)) (line-=-p obj1 obj2)) (defmethod-memo equal-for-complex-objects-p ((obj1 geom-thing) (obj2 geom-thing) (access-fn function)) ((obj1 obj2 (trafo-id *matrix*))) (and (= (length (funcall access-fn obj1)) (length (funcall access-fn obj2))) (every #'(lambda (i) (= 1 (count-if #'(lambda (j) (equal-p i j)) (funcall access-fn obj2)))) (funcall access-fn obj1)))) (defmethod-memo equal-p ((obj1 geom-chain-or-polygon) (obj2 geom-chain-or-polygon)) ((obj1 obj2 (trafo-id *matrix*))) (equal-for-complex-objects-p obj1 obj2 #'segments)) (defmethod-memo equal-p ((obj1 geom-aggregate) (obj2 geom-aggregate)) ((obj1 obj2 (trafo-id *matrix*))) (equal-for-complex-objects-p obj1 obj2 #'has-parts)) ;;; ;;; ;;; (defmethod get-segments-between ((chain-or-poly geom-chain-or-polygon) (s1 geom-line) (s2 geom-line)) ;;; bei einer Kette gibt's nur eine Richtung ;;; beim Polygon gibt es zwei!!! ;;; in dem Fall wird von s1 nach s2 gegangen (labels ((do-it (chain-or-poly s1 s2) (let ((current s1) (list (list s1))) (if (line-=-p s1 s2) list (loop (let ((next (find-if #'(lambda (x) (and (joins-p current x) (not (member x list :test #'line-=-p)))) (segments chain-or-poly)))) (unless next (return nil)) (push next list) (setf current next) (when (line-=-p next s2) (return list)))))))) (or (do-it chain-or-poly s1 s2) (do-it chain-or-poly s2 s1)))) (defmethod get-points-between ((chain-or-poly geom-chain-or-polygon) (p1 geom-point) (p2 geom-point)) (let* ((s1 (find-if #'(lambda (segment) (lies-on-p p1 segment)) (segments chain-or-poly))) (s2 (find-if #'(lambda (segment) (lies-on-p p2 segment)) (segments chain-or-poly)))) (when (and s1 s2) (let* ((segments (get-segments-between chain-or-poly s1 s2)) (point-list (mapcar #'point-list segments)) (points (apply #'append (mapcar #'(lambda (x y) (intersection x y :test #'point-=-p)) point-list (cdr point-list))))) (remove-if #'(lambda (x) (or (point-=-p x p1) (point-=-p x p2))) points)))))
20,814
Common Lisp
.lisp
542
29.905904
108
0.540906
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
cbb80eddc86c864e5dfa1333e38030be5a325304534aaf7831e2b31a1be1db35
4,330
[ -1 ]
4,331
rcc-predicates.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/geometry/rcc-predicates.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: TANGRAM-GEOMETRY; Base: 10 -*- (in-package tangram-geometry) ;;; ;;; Achtung - das sind Axproximationen! ;;; Für konvexe Polygone lassen sich einfacherere und ;;; korrekte Algorithmen angeben, die ohne die wichtigsten ;;; Funktionen "one-part-is-inside/outside-p*" auskommen ;;; (z.B. kann touches-p LINE x POLY gucken, ob alle Punkte ;;; des Polygons in nur einer der durch LINE geschaffenen ;;; Halbebene (Seite) liegen, etc.) Dann müsste man aber ;;; vorher auf Konvexität prüfen (ist das teuer?) ;;; ;;; ;;; Achtung: ein Objekt berührt sich eventuell selbst (reflexiv)! ;;; LINE X POLYGON, CHAIN x POLYGON, POLYGON x POLYGON ;;; (auch LINE X LINE im "intersects.lisp"-Modul) ;;; (defmethod touches-p ((obj1 geom-thing) (obj2 geom-thing)) ;;;(error "TOUCHES-P ~A ~A: Not well-defined!" obj1 obj2)) ) (defmethod touches-p ((line geom-line) (poly geom-polygon)) (and (intersects-p line poly) (or (lies-on-p line poly) (not (one-part-is-inside-p line poly))))) (defmethod touches-p ((poly geom-polygon) (line geom-line)) (touches-p line poly)) (defmethod touches-p ((chain1 geom-chain) (chain2 geom-chain)) ;;; (error "TOUCHES-P ~A ~A: Not well-defined!" chain1 chain2)) ) (defmethod-memo touches-p ((obj geom-chain) (poly geom-polygon)) ((obj poly (trafo-id *matrix*))) (and (intersects-p obj poly) (every #'(lambda (segment) (=> (intersects-p segment poly) (touches-p segment poly))) (segments obj)))) (defmethod touches-p ((poly geom-polygon) (obj geom-chain)) (touches-p obj poly)) (defmethod-memo touches-p ((poly1 geom-polygon) (poly2 geom-polygon)) ((poly1 poly2 (trafo-id *matrix*))) (and (not (eq poly1 poly2)) (intersects-p poly1 poly2) (every #'(lambda (segment) (=> (intersects-p segment poly2) (touches-p segment poly2))) (segments poly1)))) ;;; ;;; Achtung: ein Objekt "bedeckt" sich stets selbst (reflexiv)! ;;; Covered-by: LINE X POLYGON, CHAIN x POLYGON, POLYGON x POLYGON ;;; Covers: Inverse dazu ;;; (defmethod covered-by-p ((chain1 geom-chain) (chain2 geom-chain)) ;;; (error "COVERED-BY-P ~A ~A: Not well-defined!" chain1 chain2)) ) (defmethod covered-by-p ((obj1 geom-thing) (obj2 geom-thing)) ;;; (error "COVERED-BY-P ~A ~A: Not well-defined!" obj1 obj2)) ) (defmethod covers-p ((chain1 geom-chain) (chain2 geom-chain)) ;;; (error "COVERS-P ~A ~A: Not well-defined!" chain1 chain2)) ) (defmethod covers-p ((obj1 geom-thing) (obj2 geom-thing)) ;;; (error "COVERS-P ~A ~A: Not well-defined!" obj1 obj2)) ) (defmethod-memo covered-by-p ((line geom-line) (poly geom-polygon)) ((line poly (trafo-id *matrix*))) (and (intersects-p line poly) (or (lies-on-p line poly) (not (one-part-is-outside-p line poly))))) (defmethod covers-p ((poly geom-polygon) (line geom-line)) (covered-by-p line poly)) (defmethod-memo covered-by-p ((chain-or-poly geom-chain-or-polygon) (poly geom-polygon)) ((chain-or-poly poly (trafo-id *matrix*))) (and (not (eq chain-or-poly poly)) (intersects-p chain-or-poly poly) (every #'(lambda (segment) (=> (intersects-p segment poly) (covered-by-p segment poly))) (segments chain-or-poly)))) (defmethod covers-p ((poly geom-polygon) (chain-or-poly geom-chain-or-polygon)) (covered-by-p chain-or-poly poly)) ;;; ;;; CROSSES / CROSSED-BY (OD- bzw. 1D-Schnitte) ;;; LINE X LINE, LINE X POLYGON, CHAIN X POLYGON ;;; (auch LINE X LINE im "intersects.lisp"-Modul) ;;; (defmethod crosses-p ((obj1 geom-thing) (obj2 geom-thing)) ;;; (error "CROSSES-P ~A ~A: Not well-defined!" obj1 obj2)) ) (defmethod crossed-by-p ((obj1 geom-thing) (obj2 geom-thing)) ;;; (error "CROSSED-BY-P ~A ~A: Not well-defined!" obj1 obj2)) ) (defmethod crosses-p ((line geom-line) (poly geom-polygon)) (and (intersects-p line poly) (one-part-is-inside-p line poly))) (defmethod crossed-by-p ((poly geom-polygon) (line geom-line)) (crosses-p line poly)) (defmethod-memo crosses-p ((chain geom-chain) (poly geom-polygon)) ((chain poly (trafo-id *matrix*))) (some #'(lambda (segment) (crosses-p segment poly)) (segments chain))) (defmethod crossed-by-p ((poly geom-polygon) (chain geom-chain)) (crosses-p chain poly)) ;;; ;;; Achtung: ein Objekt überlappt sich nicht selbst! ;;; POLY X POLY ;;; (defmethod overlaps-p ((obj1 geom-thing) (obj2 geom-thing)) ;;; (error "OVERLAPS-P ~A ~A: Not well-defined!" obj1 obj2)) ) (defmethod-memo overlaps-p ((poly1 geom-polygon) (poly2 geom-polygon)) ((poly1 poly2 (trafo-id *matrix*))) (and (not (eq poly1 poly2)) (intersects-p poly1 poly2) (some #'(lambda (segment) (one-part-is-inside-p segment poly2)) (segments poly1)))) ;;; ;;; Kongruenz ;;; TOTAL ;;; (defmethod congruent-p ((obj1 geom-thing) (obj2 geom-thing)) nil) (defmethod congruent-p ((p1 geom-point) (p2 geom-point)) (point-=-p p1 p2)) (defmethod congruent-p ((l1 geom-line) (l2 geom-line)) (line-=-p l1 l2)) (defmethod-memo congruent-p ((obj1 geom-chain-or-polygon) (obj2 geom-chain-or-polygon)) ((obj1 obj2 (trafo-id *matrix*))) (or (equal-p obj1 obj2) (and (every #'(lambda (segment) (lies-on-p segment obj2)) (segments obj1)) (every #'(lambda (segment) (lies-on-p segment obj1)) (segments obj2)))))
5,617
Common Lisp
.lisp
136
36.235294
88
0.643277
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
4dbca79dda87ce792c6c54a4e382c9835ad27f9ec54f0709374f43cd1baba648
4,331
[ -1 ]
4,332
relations.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/geometry/relations.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: TANGRAM-GEOMETRY; Base: 10 -*- (in-package tangram-geometry) (defgeneric calculate-relation (obj1 obj2 &rest rest) (:documentation "Recognizes various spatial relationships between obj1 and obj2.")) ;;; ;;; ;;; (defun inverse (rel) (list 'inv rel)) ;;; ;;; (defmethod calculate-relation ((p1 geom-point) (p2 geom-point) &key (lod 0)) ;; LOD = "leve of detail" of the description (cond ((and (plusp lod) (eq p1 p2)) `(intersects ,@(when (plusp lod) `(0d ,@(when (plusp (1- lod)) `(equal ,@(when (plusp (- lod 2)) '(eq)))))))) ((point-=-p p1 p2) `(intersects ,@(when (plusp lod) `(0d ,@(when (plusp (1- lod)) `(equal)))))) (t '(disjoint)))) (defmethod calculate-relation ((p geom-point) (l geom-line) &key (lod 0)) (cond ((lies-on-p p l) `(intersects ,@(when (plusp lod) `(0d ,@(when (plusp (1- lod)) `(lies-on inside ,@(when (plusp (- lod 2)) (cond ((point-=-p (p1 l) p) `(is-endpoint ,@(when (plusp (- lod 3)) `((point-p1-relation ,(calculate-relation p (p1 l) :lod (- lod 4))))))) ((point-=-p (p2 l) p) `(is-endpoint ,@(when (plusp (- lod 3)) `((point-p2-relation ,(calculate-relation p (p2 l) :lod (- lod 4))))))))))))))) (t '(disjoint)))) (defmethod calculate-relation ((l geom-line) (p geom-point) &rest rest) (inverse (apply #'calculate-relation p l rest))) (defmethod calculate-relation ((p geom-point) (poly geom-polygon) &key (lod 0)) (cond ((lies-on-p p poly) `(intersects ,@(when (plusp lod) `(0d ,@(when (plusp (1- lod)) `(lies-on lies-on-border ,@(when (plusp (- lod 2)) (let ((res (remove-if-not #'(lambda (segment) (lies-on-p p segment)) (segments poly)))) `(,@(when (some #'(lambda (x) (point-=-p x p)) (point-list poly)) '(is-vertex-of)) ,@(when (and res (plusp (- lod 3))) `(point-segment-relations ,@(mapcar #'(lambda (segment) (calculate-relation p segment :lod (- lod 4))) res)))))))))))) ((inside-p p poly) `(intersects ,@(when (plusp lod) `(0d ,@(when (plusp (1- lod)) `(inside)))))) (t '(disjoint outside)))) (defmethod calculate-relation ((poly geom-polygon) (p geom-point) &rest rest) (inverse (apply #'calculate-relation p poly rest))) (defmethod calculate-relation ((p geom-point) (c geom-chain) &key (lod 0)) (cond ((lies-on-p p c) `(intersects ,@(when (plusp lod) `(0d ,@(when (plusp (1- lod)) `(lies-on ,@(when (plusp (- lod 2)) (when (some #'(lambda (x) (point-=-p x p)) (point-list c)) '(is-vertex-of))) ,@(when (plusp (- lod 3)) (cond ((point-=-p (p1 c) p) `(is-endpoint ,@(when (plusp (- lod 4)) `((point-p1-relation ,(calculate-relation p (p1 c) :lod (- lod 5))))))) ((point-=-p (p2 c) p) `(is-endpoint ,@(when (plusp (- lod 3)) `((point-p2-relation ,(calculate-relation p (p2 c) :lod (- lod 5))))))))) ,@(let ((res (remove-if-not #'(lambda (segment) (lies-on-p p segment)) (segments c)))) (when (and res (plusp (- lod 4))) `((point-segment-relations ,@(mapcar #'(lambda (segment) (calculate-relation p segment :lod (- lod 5))) res))))))))))) (t '(disjoint)))) (defmethod calculate-relation ((l geom-chain) (p geom-point) &rest rest) (inverse (apply #'calculate-relation p l rest))) ;;; ;;; ;;; (defmethod calculate-relation ((l1 geom-line) (l2 geom-line) &key (lod 0)) (if (and (bounding-box-p l1) (bounding-box-p l2) (not (box-overlaps-box-p l1 l2))) '(disjoint) (let* ((l1p1 (p1 l1)) (l2p1 (p1 l2)) (l1p2 (p2 l1)) (l2p2 (p2 l2)) (a (ccw l1p1 l1p2 l2p1)) (b (ccw l1p1 l1p2 l2p2)) (c (ccw l2p1 l2p2 l1p1)) (d (ccw l2p1 l2p2 l1p2))) (cond ((and (<= (* a b) 0.0) (<= (* c d) 0.0)) ; Schnitt liegt vor `(intersects ,@(when (plusp lod) (let* ((l1p1-l2 (lies-on-p (p1 l1) l2)) (l1p2-l2 (lies-on-p (p2 l1) l2)) (l2p1-l1 (lies-on-p (p1 l2) l1)) (l2p2-l1 (lies-on-p (p2 l2) l1)) (n (+ (if l1p1-l2 1 0) (if l1p2-l2 1 0) (if l2p1-l1 1 0) (if l2p2-l1 1 0)))) (let ((res (ecase n (0 `(0d ,@(when (plusp (1- lod)) '(crosses)))) ; X (1 `(0d ,@(when (plusp (1- lod)) '(touches)))) ; T (3 `(1d ,@(when (plusp (1- lod)) (if (and l1p1-l2 l1p2-l2) '(covered-by) '(covers))))) (4 `(1d ,@(when (plusp (1- lod)) `(equal ,@(when (and (eq l1 l2) (plusp (- lod 2))) '(eq)))))) (2 (cond ((joins-p l1 l2) `(0d ,@(when (plusp (1- lod)) '(touches)))) ; --, \/ ((and l1p1-l2 l1p2-l2) `(1d ,@(when (plusp (1- lod)) '(inside)))) ((and l2p1-l1 l2p2-l1) `(1d ,@(when (plusp (1- lod)) '(contains)))) (t `(1d ,@(when (plusp (1- lod)) '(overlaps))))))))) (if (plusp (- lod 2)) `(,@res (endpoint-line-relations ,(calculate-relation (p1 l1) l2 :lod (- lod 3)) ,(calculate-relation (p2 l1) l2 :lod (- lod 3)) ,(calculate-relation (p1 l2) l1 :lod (- lod 3)) ,(calculate-relation (p2 l2) l1 :lod (- lod 3)))) res)))))) (t '(disjoint)))))) (defmethod calculate-relation ((l geom-line) (c geom-chain) &key (lod 0)) (cond ((intersects-p l c) `(intersects ,@(when (plusp lod) `( ,@(if (some #'(lambda (x) (1d-intersects-p x l)) (segments c)) `(1d ,@(when (and (plusp (1- lod))) `( ,@(when (some #'(lambda (x) (line-=-p x l)) (segments c)) '(segment-of)) ,@(when (lies-on-p l c) '(lies-on))))) `(0d)))) ,@(when (plusp (- lod 2)) `((endpoint-chain-relations ,(calculate-relation (p1 l) c :lod (- lod 3)) ,(calculate-relation (p2 l) c :lod (- lod 3))))) ,@(let ((res (remove-if-not #'(lambda (segment) (intersects-p l segment)) (segments c)))) (when (and res (plusp (- lod 3))) (list (cons 'line-segment-relations (mapcar #'(lambda (segment) (calculate-relation l segment :lod (- lod 4))) res))))))) (t '(disjoint)))) (defmethod calculate-relation ((c geom-chain) (l geom-line) &rest rest) (inverse (apply #'calculate-relation l c rest))) (defmethod calculate-relation ((l geom-line) (p geom-polygon) &key (lod 0)) (declare (ignore rest)) (if (intersects-p l p) `(intersects ,@(when (plusp lod) (cond ((inside-p l p) `(inside ,@(when (plusp (1- lod)) `(1d)))) ((lies-on-p l p) `(lies-on lies-on-border ,@(when (plusp (1- lod)) `(1d)))) ((covered-by-p l p) `(covered-by ,@(when (plusp (1- lod)) `(1d)))) ((crosses-p l p) `(crosses ,@(when (plusp (1- lod)) `(1d)))) (t `(touches ,@(when (plusp (1- lod)) `( ,@(if (some #'(lambda (segment) (1d-intersects-p l segment)) (segments p)) '(1d) '(0d)))))))) ,@(when (plusp (- lod 2)) `((endpoint-polygon-relations ,(calculate-relation (p1 l) p :lod (- lod 3)) ,(calculate-relation (p2 l) p :lod (- lod 3))))) ,@(let ((res (remove-if-not #'(lambda (segment) (intersects-p l segment)) (segments p)))) (when (and res (plusp (- lod 3))) `((line-segment-relations ,@(mapcar #'(lambda (segment) (calculate-relation l segment :lod (- lod 4))) res)))))) '(disjoint))) (defmethod calculate-relation ((p geom-polygon) (l geom-line) &rest rest) (inverse (apply #'calculate-relation l p rest))) ;;; ;;; ;;; (defmethod calculate-relation ((c1 geom-chain) (c2 geom-chain) &key (lod 0)) (cond ((intersects-p c1 c2) `(intersects ,@(when (plusp lod) `( ,@(if (some #'(lambda (x) (some #'(lambda (y) (1d-intersects-p x y)) (segments c2))) (segments c1)) `(1d ,@(when (and (plusp (1- lod))) `( ,@(when (lies-on-p c1 c2) '(lies-on)))) ,@(when (and (plusp (- lod 2))) `( ,@(when (some #'(lambda (x) (some #'(lambda (y) (line-=-p x y)) (segments c2))) (segments c1)) '(common-segment))))) `(0d)))) ,@(when (plusp (- lod 2)) `((endpoint-chain-relations ,(calculate-relation (p1 c1) c2 :lod (- lod 3)) ,(calculate-relation (p2 c1) c2 :lod (- lod 3)) ,(calculate-relation (p1 c2) c1 :lod (- lod 3)) ,(calculate-relation (p2 c2) c1 :lod (- lod 3))))) ,@(let ((res (remove-if-not #'(lambda (segment) (intersects-p segment c2)) (segments c1)))) (when (and res (plusp (- lod 3))) (list (cons 'segment-chain-relations (mapcar #'(lambda (segment) (calculate-relation segment c2 :lod (- lod 4))) res))))))) (t '(disjoint)))) (defmethod calculate-relation ((c geom-chain) (p geom-polygon) &key (lod 0)) (declare (ignore rest)) (if (intersects-p c p) `(intersects ,@(when (plusp lod) (cond ((inside-p c p) `(inside ,@(when (plusp (1- lod)) `(1d)))) ((lies-on-p c p) `(lies-on lies-on-border ,@(when (plusp (1- lod)) `(1d)))) ((covered-by-p c p) `(covered-by ,@(when (plusp (1- lod)) `(1d)))) ((crosses-p c p) `(crosses ,@(when (plusp (1- lod)) `(1d)))) (t `(touches ,@(when (plusp (1- lod)) `( ,@(if (some #'(lambda (i) (some #'(lambda (j) (1d-intersects-p i j)) (segments p))) (segments c)) '(1d) '(0d)))))))) ,@(when (plusp (- lod 2)) `((endpoint-polygon-relations ,(calculate-relation (p1 c) p :lod (- lod 3)) ,(calculate-relation (p2 c) p :lod (- lod 3))))) ,@(let ((res (remove-if-not #'(lambda (segment) (intersects-p c segment)) (segments p)))) (when (and res (plusp (- lod 3))) `((chain-segment-relations ,@(mapcar #'(lambda (segment) (calculate-relation c segment :lod (- lod 4))) res)))))) '(disjoint))) (defmethod calculate-relation ((p geom-polygon) (c geom-chain) &rest rest) (inverse (apply #'calculate-relation c p rest))) ;;; ;;; ;;; (defmethod calculate-relation ((p1 geom-polygon) (p2 geom-polygon) &key (lod 0)) (declare (ignore lod)) (if (intersects-p p1 p2) `(intersects ,@(when (plusp lod) (cond ((inside-p p1 p2) `(inside ,@(when (plusp (1- lod)) `(2d)))) ((inside-p p2 p1) `(contains ,@(when (plusp (1- lod)) `(2d)))) ((covered-by-p p1 p2) `(covered-by ,@(when (plusp (1- lod)) `(2d)))) ((covered-by-p p2 p1) `(covers-p ,@(when (plusp (1- lod)) `(2d)))) ((overlaps-p p1 p2) `(overlaps ,@(when (plusp (1- lod)) `(2d)))) (t `(touches ,@(when (plusp (1- lod)) `( ,@(if (some #'(lambda (i) (some #'(lambda (j) (1d-intersects-p i j)) (segments p2))) (segments p1)) '(1d) '(0d)))))))) ,@(when (plusp (- lod 2)) `((segment-poly-relations ,@(mapcar #'(lambda (segment) (calculate-relation segment p2 :lod (- lod 3))) (segments p1)))))) 'disjoint)) ;;; ;;; ;;; (defun inverse-rcc-relation (rel) (labels ((lookup (rel) (ecase rel (:pp :ppi) (:ppi :pp) (:tpp :tppi) (:ntpp :ntppi) (:tppi :tpp) (:ntppi :ntpp) (:borders :bordered-by) (:bordered-by :borders) (:ec :ec) (:po :po) (:dc :dc) (:dr :dr) (:eq :eq)))) (if (consp rel) (mapcar #'lookup rel) (lookup rel)))) (defun-memo calculate-rcc-relation (a b) ((a b (trafo-id *matrix*))) ;;; zusätzlich erweitert um "borders/bordered-by" ;;; für lineale Features (typecase a (geom-point (typecase b (geom-point (cond ((point-=-p a b) :eq) (t :dc))) (geom-line (cond ((lies-on-p a b) :bordered-by) (t :dc))) (geom-chain (cond ((lies-on-p a b) :bordered-by) (t :dc))) (geom-polygon (cond ((inside-p a b) :ntpp) ((lies-on-p a b) :bordered-by) (t :dc))))) (geom-line (typecase b (geom-point (cond ((lies-on-p b a) :borders) (t :dc))) (geom-line (cond ((line-=-p a b) :eq) ((intersects-p a b) :po) (t :dc))) (geom-chain (cond ((lies-on-p a b) :bordered-by) ((intersects-p a b) :po) (t :dc))) (geom-polygon (cond ((intersects-p a b) (cond ((lies-on-p a b) :bordered-by) ((covered-by-p a b) :tpp) ((touches-p a b) :ec) (t :po))) ((inside-p a b) :ntpp) (t :dc))))) (geom-chain (typecase b (geom-point (cond ((lies-on-p b a) :borders) (t :dc))) (geom-line (cond ((lies-on-p b a) :borders) ((intersects-p a b) :po) (t :dc))) (geom-chain (cond ((congruent-p a b) :eq) ((lies-on-p a b) :bordered-by) ((lies-on-p b a) :borders) ((intersects-p a b) :po) (t :dc))) (geom-polygon (cond ((intersects-p a b) (cond ((lies-on-p a b) :bordered-by) ((covered-by-p a b) :tpp) ((touches-p a b) :ec) (t :po))) ((inside-p a b) :ntpp) (t :dc))))) (geom-polygon (typecase b (geom-point (cond ((lies-on-p b a) :borders) ((inside-p b a) :ntppi) (t :dc))) (geom-line (cond ((intersects-p a b) (cond ((lies-on-p b a) :borders) ((covered-by-p b a) :tppi) ((touches-p a b) :ec) (t :po))) ((inside-p b a) :ntppi) (t :dc))) (geom-chain (cond ((intersects-p a b) (cond ((lies-on-p b a) :borders) ((covered-by-p b a) :tppi) ((touches-p a b) :ec) (t :po))) ((inside-p b a) :ntppi) (t :dc))) (geom-polygon (cond ((congruent-p a b) :eq) ((intersects-p a b) (cond ((covered-by-p b a) :tppi) ((covered-by-p a b) :tpp) ((touches-p a b) :ec) (t :po))) ((inside-p b a) :ntppi) ((inside-p a b) :ntpp) (t :dc)))))))
23,521
Common Lisp
.lisp
554
20.268953
109
0.318102
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
79f1ff791163407132d8848ddd720893593b3b72536ae28c17f2204bb8198b2a
4,332
[ -1 ]
4,333
geometry.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/geometry/geometry.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: TANGRAM-GEOMETRY; Base: 10 -*- (in-package tangram-geometry) (defgeneric mark-obj (obj value) (:documentation "Mark object with value.")) (defgeneric x (point) (:documentation "Returns the x position of point with respect to *matrix*")) (defgeneric y (point) (:documentation "Returns the y position of point with respect to *matrix*")) (defgeneric point-=-p (point1 point2) (:documentation "Returns T if point1 and point2 have the same position.")) (defgeneric line-=-p (line1 line2) (:documentation "Returns T if line1 and line2 are congruent.")) (defgeneric point->=-p (point1 point2) (:documentation "Returns T if point1 is right and above point2.")) (defgeneric point-<=-p (point1 point2) (:documentation "Returns T if point1 is left and below point2.")) (defgeneric joins-p (line1 line2) (:documentation "Returns T, if line1 and line2 have a common point (point-=-p).")) (defgeneric parallel-p (line1 line2) (:documentation "Determine whether line1 and line2 are parallel.")) (defgeneric upright-p (line1 line2) (:documentation "Determine whether line1 and line2 are upright.")) (defgeneric delete-object (obj &key) (:method-combination progn) (:documentation "Delete object.")) (defgeneric centroid (obj) (:documentation "Returns the centroid of obj.")) (defgeneric ccw (point1 point2 point3) (:documentation "Counterclockwise way from point1 over point2 to point3. See Sedgewick for details!")) (defgeneric distance-between (obj1 obj2 &key sqrt sx sy) (:documentation "Calculate the smallest distance between obj1 and obj2.")) (defgeneric global-orientation (line) (:documentation "Calculate the angle between the x-axis and the line.")) (defgeneric calculate-intersection-point (line1 line2) (:documentation "Returns (x,y) intersection point (if a zero dimensional intersection between line1 and line2 holds).")) (defgeneric calculate-intersection-line (line1 line2) (:documentation "Returns (x1,y1,x2,y2) intersection line (if a one dimensional intersection between line1 and line2 holds).")) (defgeneric calculate-area (polygon) (:documentation "Calulates the area of the polygon.")) (defgeneric orientation (polygon) (:documentation "Calulates the orientation of the polygon.")) (defgeneric change-orientation (polygon) (:documentation "Change the orientation of the polygon.")) (defgeneric orientate-clockwise (polygon) (:documentation "Change the orientation of the polygon to clockwise.")) (defgeneric orientate-counterclockwise (polygon) (:documentation "Change the orientation of the polygon to counter-clockwise.")) (defgeneric insert-new-border-points (polygon-or-chain points) (:documentation "Create a new chain/polygon with additional points on the border of the original object.")) ;;; ;;; ;;; (defconstant +big-int+ 10000) (defconstant +big-int2+ 9000) (defparameter *matrix* nil) (defparameter *mark-counter* 0) (defun get-new-mark () (incf *mark-counter*)) ;;; ;;; ;;; (defpersistentclass bounding-box-mixin () ; abstrakt ((pmin :initarg :pmin :writer (setf pmin) :initform nil) (pmax :initarg :pmax :writer (setf pmax) :initform nil) (radius :initarg :radius :writer (setf radius) :initform nil) (last-trafo-id :accessor last-trafo-id :initarg :last-trafo-id :initform (if *matrix* (trafo-id *matrix*) -2)) (bounding-box-p :initform t :initarg :bounding-box-p :accessor bounding-box-p))) (defpersistentclass bounding-box (bounding-box-mixin) ; instantiierbar, aber NICHT TRANSFORMIERBAR !!! ((pmin :reader pmin) (pmax :reader pmax) (radius :reader radius))) ;;; ;;; ;;; (defvar *id-counter* 0) (defpersistentclass geom-thing () ; abstrakt ((part-of :initform nil :initarg :part-of :accessor part-of) (id :accessor id :initform (incf *id-counter*)) (class-of-internal-points :accessor class-of-internal-points :initarg :class-of-internal-points :initform 'geom-point) (affected-by-matrix-p :reader affected-by-matrix-p :initform t :initarg :affected-by-matrix-p) ;;; bei Punkten: T <=> nicht von Matrix beruehrt ;;; bei anderen Objekten: entscheidet, ob bei Bedarf neu erzeugte berechnete Punkte (centroid obj) ;;; das Flag gesetzt bekommen oder nicht (check-p :accessor check-p :initarg :check-p :initform t) (bound-to :accessor bound-to :initform nil) (cp-flag :accessor cp-flag :initform nil) (mark-value :accessor mark-value :initform nil) (error-flag :accessor error-flag :initform nil))) (defpersistentclass geom-point (geom-thing) ((x :writer (setf x) :initarg :x) (y :writer (setf y) :initarg :y) (centroid-of :accessor centroid-of :initarg :centroid-of :initform nil) (p1-of :accessor p1-of :initarg :p1-of :initform nil) (p2-of :accessor p2-of :initarg :p2-of :initform nil))) (defpersistentclass geom-line (geom-thing bounding-box-mixin) ((p1 :initarg :p1 :accessor p1) (p2 :initarg :p2 :accessor p2) (point-list :accessor point-list) (centroid-p :initform t :initarg :centroid-p :accessor centroid-p) (centroid :initform nil :initarg :centroid :writer (setf centroid)))) (defpersistentclass geom-chain-or-polygon (geom-thing bounding-box-mixin) ((segments :initarg :segments :accessor segments) (centroid :initform nil :initarg :centroid :writer (setf centroid)) (centroid-p :initform t :initarg :centroid-p :accessor centroid-p) (point-list :accessor point-list :initarg :point-list))) (defpersistentclass geom-polygon (geom-chain-or-polygon) ()) (defpersistentclass geom-chain (geom-chain-or-polygon) ((p1 :initarg :p1 :accessor p1) (p2 :initarg :p2 :accessor p2))) (defpersistentclass geom-aggregate (geom-thing bounding-box-mixin) ((has-parts :initarg :has-parts :accessor has-parts) (centroid-p :initform t :initarg :centroid-p :accessor centroid-p) (centroid :initform nil :initarg :centroid :writer (setf centroid)))) ;;; ;;; ;;; (defmethod trafo-id ((obj null)) -1) (defmethod pmin ((obj bounding-box-mixin)) (with-slots (pmin last-trafo-id) obj (unless (and pmin (= last-trafo-id (trafo-id *matrix*))) (recalculate-bounding-box obj)) pmin)) (defmethod pmax ((obj bounding-box-mixin)) (with-slots (pmax last-trafo-id) obj (unless (and pmax (= last-trafo-id (trafo-id *matrix*))) (recalculate-bounding-box obj)) pmax)) (defmethod radius ((obj bounding-box-mixin)) (with-slots (radius last-trafo-id) obj (unless (and radius (= last-trafo-id (trafo-id *matrix*))) (recalculate-bounding-box obj)) radius)) ;;; ;;; ;;; (defmethod bb-width ((obj bounding-box-mixin)) (- (x (pmax obj)) (x (pmin obj)))) (defmethod bb-height ((obj bounding-box-mixin)) (- (y (pmax obj)) (y (pmin obj)))) ;;; ;;; ;;; (defun check-for-centroid (obj) (with-slots (centroid) obj (unless centroid (calculate-centroid obj)) centroid)) (defmethod centroid ((obj geom-point)) obj) (defmethod centroid ((obj geom-line)) (check-for-centroid obj)) (defmethod centroid ((obj geom-chain-or-polygon)) (check-for-centroid obj)) (defmethod centroid ((obj geom-aggregate)) (check-for-centroid obj)) ;;; ;;; ;;; (defmethod print-object ((obj geom-thing) stream) (format stream "#<~A ~A>" (type-of obj) (id obj))) (defmethod print-object ((obj geom-point) stream) (format stream "#<~A ~A (~A,~A)>" (type-of obj) (id obj) (x obj) (y obj))) (defmethod print-object ((obj geom-line) stream) (format stream "#<~A ~A ((~A,~A)-(~A,~A)>" (type-of obj) (id obj) (x (p1 obj)) (y (p1 obj)) (x (p2 obj)) (y (p2 obj)))) #| (mapcar #'(lambda (x) (list (x x) (y x))) (point-list obj)))) |# (defmethod print-object ((obj geom-chain-or-polygon) stream) (format stream "#<~A ~A ~A>" (type-of obj) (id obj) (get-xy-list obj))) ;;; ;;; ;;; (defmethod mark-object ((obj geom-thing) value) (setf (mark-value obj) value)) ;;; ;;; ;;; (defmacro =-eps (x y) `(< (abs (- ,x ,y)) 0.01)) (defmethod point-=-p ((p1 geom-point) (p2 geom-point)) (or (eq p1 p2) (and (=-eps (x p1) (x p2)) (=-eps (y p1) (y p2))))) (defmethod point->=-p ((p1 geom-point) (p2 geom-point)) (and (>= (x p1) (x p2)) (>= (y p1) (y p2)))) (defmethod point-<=-p ((p1 geom-point) (p2 geom-point)) (and (<= (x p1) (x p2)) (<= (y p1) (y p2)))) ;;; ;;; ;;; (defmethod line-=-p ((l1 geom-line) (l2 geom-line)) (or (eq l1 l2) (and (point-=-p (p1 l1) (p1 l2)) (point-=-p (p2 l1) (p2 l2))) (and (point-=-p (p1 l1) (p2 l2)) (point-=-p (p2 l1) (p1 l2))))) (defmethod parallel-p ((line1 geom-line) (line2 geom-line)) (let ((dx1 (- (x (p1 line1)) (x (p2 line1)))) (dx2 (- (x (p1 line2)) (x (p2 line2)))) (dy1 (- (y (p1 line1)) (y (p2 line1)))) (dy2 (- (y (p1 line2)) (y (p2 line2))))) (or (zerop (- (* dx1 dy2) (* dx2 dy1))) (zerop (- (* dx2 dy1) (* dx1 dy2)))))) (defmethod upright-p ((line1 geom-line) (line2 geom-line)) (let ((dx1 (- (x (p1 line1)) (x (p2 line1)))) (dx2 (- (x (p1 line2)) (x (p2 line2)))) (dy1 (- (y (p1 line1)) (y (p2 line1)))) (dy2 (- (y (p1 line2)) (y (p2 line2))))) (zerop (+ (* dx1 dx2) (* dy1 dy2))))) (defmethod joins-p ((i geom-line) (j geom-line)) "joins-p(i,j) <=> haben mind. einen wertgleichen oder identischen Endpunkt" (or (and (point-=-p (p1 i) (p1 j))) (and (point-=-p (p1 i) (p2 j))) (and (point-=-p (p2 i) (p1 j))) (and (point-=-p (p2 i) (p2 j))))) ;;; ;;; ;;; (defmethod x ((point geom-point)) (with-slots (x y affected-by-matrix-p) point (let ((val (if (and *matrix* affected-by-matrix-p) (with-slots (a b tx) *matrix* (+ (* a x) (* b y) tx)) x))) (my-round val)))) (defmethod y ((point geom-point)) (with-slots (x y affected-by-matrix-p) point (let ((val (if (and *matrix* affected-by-matrix-p) (with-slots (c d ty) *matrix* (+ (* c x) (* d y) ty)) y))) (my-round val)))) ;;; ;;; ;;; (defvar *trafo-id* 0) (defpersistentclass matrix () ((trafo-id :accessor trafo-id :initform (incf *trafo-id*)) ; z.B. muss die BB nach Rotationen ; neuberechnet werden (=> Id aendert sich) (a :accessor a :initarg :a :initform 1) (b :accessor b :initarg :b :initform 0) (tx :accessor tx :initarg :tx :initform 0) (c :accessor c :initarg :c :initform 0) (d :accessor d :initarg :d :initform 1) (ty :accessor ty :initarg :ty :initform 0))) (defmacro make-matrix (&rest rest) `(make-instance 'matrix ,@rest)) (defmacro reset (matrix) `(with-slots (trafo-id a b tx c d ty) ,matrix (setf trafo-id (incf *trafo-id*)) (setf a 1 b 0 tx 0 c 0 d 1 ty 0) ,matrix)) (defmacro translate (matrix x y) `(with-slots (trafo-id tx ty) ,matrix (setf trafo-id (incf *trafo-id*)) (incf tx ,x) (incf ty ,y) ,matrix)) (defmacro scale (matrix sx sy) (let ((sx1 sx) (sy1 sy)) `(with-slots (trafo-id a b c d tx ty) ,matrix (setf trafo-id (incf *trafo-id*)) (psetf a (* a ,sx1) b (* b ,sx1) tx (* tx ,sx1) ty (* ty ,sy1) c (* c ,sy1) d (* d ,sy1)) ,matrix))) (defmacro rotate (matrix r) `(let ((rot ,r)) (with-slots (trafo-id a b c d tx ty) ,matrix (let ((pcos (cos rot)) (msin (- (sin rot))) (psin (sin rot))) (setf trafo-id (incf *trafo-id*)) (psetf a (+ (* a pcos) (* c msin)) b (+ (* b pcos) (* d msin)) tx (+ (* tx pcos) (* ty msin)) c (+ (* a psin) (* c pcos)) d (+ (* b psin) (* d pcos)) ty (+ (* tx psin) (* ty pcos))) ,matrix)))) (defmacro with-matrix ((matrix) &body body) `(let ((*matrix* ,matrix)) ,@body)) (defmacro with-no-matrix-at-all (&body body) `(let ((*matrix* nil)) ,@body)) ;;; ;;; ;;; (defmacro with-saved-matrix ((matrix) &body body) (let ((a (gensym)) (b (gensym)) (tx (gensym)) (c (gensym)) (d (gensym)) (ty (gensym))) `(let ((,a (a ,matrix)) (,b (b ,matrix)) (,c (c ,matrix)) (,d (d ,matrix)) (,tx (tx ,matrix)) (,ty (ty ,matrix))) (prog1 (progn ,@body) (with-slots (a b c d tx ty) ,matrix (setf a ,a b ,b c ,c d ,d tx ,tx ty ,ty)))))) (defmacro with-translation ((tx ty) &body body) `(if *matrix* (with-saved-matrix (*matrix*) (translate *matrix* ,tx ,ty) ,@body) (let ((*matrix* (make-matrix :tx ,tx :ty ,ty))) ,@body))) (defmacro with-scaling ((sx sy) &body body) `(if *matrix* (with-saved-matrix (*matrix*) (scale *matrix* ,sx ,sy) ,@body) (let ((*matrix* (make-matrix :a ,sx :d ,sy))) ,@body))) (defmacro with-rotation ((rot) &body body) `(if *matrix* (with-saved-matrix (*matrix*) (rotate *matrix* ,rot) ,@body) (let ((*matrix* (make-matrix))) (rotate *matrix* ,rot) ,@body))) ;;; ;;; (defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point)) (let* ((x0 (x p0)) (x1 (x p1)) (x2 (x p2)) (y0 (y p0)) (y1 (y p1)) (y2 (y p2))) (ccw* x0 y0 x1 y1 x2 y2))) (defun ccw* (x0 y0 x1 y1 x2 y2) (let* ((dx1 (- x1 x0)) (dy1 (- y1 y0)) (dx2 (- x2 x0)) (dy2 (- y2 y0))) (cond ((> (* dx1 dy2) (* dy1 dx2)) 1) ((< (* dx1 dy2) (* dy1 dx2)) -1) ((or (< (* dx1 dx2) 0) (< (* dy1 dy2) 0)) -1) ((< (+ (* dx1 dx1) (* dy1 dy1)) (+ (* dx2 dx2) (* dy2 dy2))) 1) (t 0)))) ;;; ;;; Konstruktoren ;;; (defun make-bounding-box (xmin ymin xmax ymax &rest initargs) ; BB als "eigenständiges" Objekt (apply #'make-instance 'bounding-box :xmin xmin :ymin ymin :xmax xmax :ymax ymax initargs)) (defun make-point (x y &rest initargs &key (class 'geom-point) &allow-other-keys) (apply #'make-instance class :x x :y y :allow-other-keys t initargs)) (defun make-line (p1 p2 &rest initargs &key (class 'geom-line) &allow-other-keys) (apply #'make-instance class :p1 p1 :p2 p2 initargs)) (defun make-chain (segment-list &rest initargs &key (class 'geom-chain) &allow-other-keys) (apply #'make-instance class :segments segment-list initargs)) (defun make-polygon (segment-list &rest initargs &key (class 'geom-polygon) &allow-other-keys) (apply #'make-instance class :segments segment-list initargs)) (defun make-aggregate (has-parts &rest initargs &key (class 'geom-aggregate) &allow-other-keys) (apply #'make-instance class :has-parts has-parts initargs)) ;;; ;;; ;;; (defun bb (xmin ymin xmax ymax &rest initargs) (apply #'make-bounding-box xmin ymin xmax ymax initargs)) (defun p (x y &rest initargs) (apply #'make-point x y initargs)) (defun l (p1 p2 &rest initargs) (apply #'make-line p1 p2 initargs)) (defun chain (segment-list &rest initargs) (apply #'make-chain segment-list initargs)) (defun chain-from-xy-list (xy-list &rest initargs) (let ((points (mapcar #'(lambda (c) (apply #'p (first c) (second c) initargs)) xy-list))) (apply #'chain (mapcar #'(lambda (p1 p2) (apply #'l p1 p2 initargs)) points (rest points)) initargs))) (defun poly (segment-list &rest initargs) (apply #'make-polygon segment-list initargs)) (defun poly-from-xy-list (xy-list &rest initargs &key normalize-p &allow-other-keys) (let* ((points (mapcar #'(lambda (c) (apply #'p (first c) (second c) initargs)) xy-list)) (newpoints (when normalize-p (break "Normalize! Really?") (list (first points)))) (points2 (when normalize-p (append points (list (first points) (second points)))))) ;;; "Normalisierung" (when normalize-p (mapc #'(lambda (x y z) (unless (or (zerop (ccw x z y)) (zerop (ccw z x y))) (push y newpoints))) points2 (cdr points2) (cddr points2)) (push (first points) newpoints)) (if normalize-p (apply #'poly (mapcar #'(lambda (p1 p2) (apply #'l p1 p2 initargs)) newpoints (rest newpoints)) initargs) (apply #'poly (mapcar #'(lambda (p1 p2) (apply #'l p1 p2 initargs)) points (rest points)) initargs)))) (defun agg (has-parts &rest initargs) (apply #'make-aggregate has-parts initargs)) ;;; ;;; ;;; (defun segment-list-ok-p (segments polygon-p must-be-simple-p) "Bedingung: mind. 2 Segmente, keine (wert)gleichen Strecken, keine Selbstueberschneidungen" (let ((first (first segments)) (last (first (last segments))) (n (length segments))) (and (>= n 2) (=> polygon-p (>= n 3)) (every #'(lambda (i) (= (count i segments) 1)) segments) (if (not polygon-p) (and (every #'(lambda (i j) (joins-p i j)) segments (rest segments)) (=> (> n 2) (not (joins-p (first segments) (first (last segments)))))) (and (every #'(lambda (i j) (joins-p i j)) (cons last segments) segments) (every #'(lambda (i) (= 2 (count-if #'(lambda (j) (and (not (eq i j)) (joins-p i j))) segments))) segments))) (=> must-be-simple-p (every #'(lambda (i) (let ((count ; Schnitte zaehlen (count-if #'(lambda (j) (and (not (eq i j)) (intersects-p i j))) segments))) (if (or (eq first i) (eq last i)) ; erstes od. letztes Segment ? (if (not polygon-p) (= count 1) (= count 2)) (= count 2)))) segments))))) ;;; ;;; ;;; (defun order-chain-segments (segments &key (adjust-segments-p t)) (unless (cdr segments) (error "More than one segment needed!")) (let* ((points (mapcan #'(lambda (s) (list (p1 s) (p2 s))) segments)) (end-points (remove-if-not #'(lambda (p) (= 1 (count-if #'(lambda (segment) (or (point-=-p p (p1 segment)) (point-=-p p (p2 segment)))) segments))) points)) (current (first end-points)) (new-segments nil)) (unless (cdr end-points) (error "Bad segments list!")) (loop while segments do (let ((seg (remove-if-not #'(lambda (x) (or (point-=-p current (p1 x)) (point-=-p current (p2 x)))) segments))) (when (or (not seg) (cddr seg)) (error "Bad segments list!")) (let ((seg (first seg))) (push seg new-segments) (setf segments (remove seg segments)) (cond ((point-=-p current (p1 seg)) (setf current (p2 seg))) ((point-=-p current (p2 seg)) (psetf current (p1 seg)) (when adjust-segments-p (psetf (p1 seg) (p2 seg) (p2 seg) (p1 seg)) (push seg (p1-of (p1 seg))) (push seg (p2-of (p2 seg))) (setf (point-list seg) (list (p1 seg) (p2 seg))) (setf (p1-of (p2 seg)) (delete seg (p1-of (p2 seg)))) (setf (p2-of (p1 seg)) (delete seg (p2-of (p1 seg)))))))))) (nreverse new-segments))) (defun order-poly-segments (segments &key p1 (adjust-segments-p t)) (unless (cddr segments) (error "More than one segment needed!")) (let* ((points (mapcan #'(lambda (s) (list (p1 s) (p2 s))) segments)) (current (or p1 (first points))) (new-segments nil)) (loop while segments do (let ((seg (remove-if-not #'(lambda (x) (or (point-=-p current (p1 x)) (point-=-p current (p2 x)))) segments))) (when (or (not seg) (cddr seg)) (error "Bad segments list!")) (let ((seg (first seg))) (push seg new-segments) (setf segments (remove seg segments)) (cond ((point-=-p current (p1 seg)) (setf current (p2 seg))) ((point-=-p current (p2 seg)) (psetf current (p1 seg)) (when adjust-segments-p (psetf (p1 seg) (p2 seg) (p2 seg) (p1 seg)) (push seg (p1-of (p1 seg))) (push seg (p2-of (p2 seg))) (setf (point-list seg) (list (p1 seg) (p2 seg))) (setf (p1-of (p2 seg)) (delete seg (p1-of (p2 seg)))) (setf (p2-of (p1 seg)) (delete seg (p2-of (p1 seg)))))))))) (nreverse new-segments))) ;;; ;;; ;;; (defmethod initialize-instance :after ((chain geom-chain) &rest initargs &key (error-p t) (hierarchicly-p t) (check-p t) (must-be-simple-p t) &allow-other-keys) (declare (ignore initargs)) (with-slots (segments point-list) chain (setf segments (order-chain-segments segments)) (setf point-list (apply #'append (mapcar #'point-list segments))) (when (and check-p (not (segment-list-ok-p segments nil must-be-simple-p))) (setf (error-flag chain) t) (when error-p (error "Bad ~A!" (type-of chain)))) (when hierarchicly-p (let ((p1 (first point-list)) (p2 (first (last point-list)))) (setf (p1 chain) p1 (p2 chain) p2) (push chain (part-of p1)) (push chain (part-of p2)) (push chain (p1-of p1)) (push chain (p2-of p2))) (dolist (segment segments) (push chain (part-of segment)))))) (defmethod initialize-instance :after ((poly geom-polygon) &rest initargs &key (hierarchicly-p t) (error-p t) (check-p t) (must-be-simple-p t) &allow-other-keys) (declare (ignore initargs)) (with-slots (segments point-list) poly (setf segments (order-poly-segments segments)) (setf point-list (apply #'append (mapcar #'point-list segments))) (when (and check-p (not (segment-list-ok-p segments t must-be-simple-p))) (setf (error-flag poly) t) (when error-p (error "Bad ~A!" (type-of poly)))) (when hierarchicly-p (dolist (segment segments) (push poly (part-of segment)))) (orientate-counterclockwise poly))) ;;; ;;; ;;; (defmethod delete-object progn ((obj geom-chain-or-polygon) &key) (dolist (segment (segments obj)) (setf (part-of segment) (delete obj (part-of segment)))) (when (typep obj 'geom-chain) (let ((p1 (p1 obj)) (p2 (p2 obj))) (setf (p1-of p1) (delete obj (p1-of p1))) (setf (p2-of p2) (delete obj (p2-of p2)))))) ;;; ;;; ;;; (defmethod initialize-instance :after ((line geom-line) &rest initargs &key (hierarchicly-p t) (check-p t) &allow-other-keys) (declare (ignore initargs)) (with-slots (p1 p2 point-list) line (when (and check-p (point-=-p p1 p2)) (error "Bad ~A!" (type-of line))) (setf point-list (list p1 p2)) (when hierarchicly-p (push line (part-of p1)) (push line (part-of p2)) (push line (p1-of p1)) (push line (p2-of p2))))) (defmethod delete-object progn ((obj geom-line) &key) (let ((p1 (p1 obj)) (p2 (p2 obj))) (setf (p1-of p1) (delete obj (p1-of p1))) (setf (p2-of p2) (delete obj (p2-of p2))) (setf (part-of p1) (delete obj (part-of p1))) (setf (part-of p2) (delete obj (part-of p2))))) ;;; ;;; ;;; (defmethod initialize-instance :after ((agg geom-aggregate) &rest initargs &key (hierarchicly-p t) (check-p t) &allow-other-keys) (declare (ignore initargs)) (with-slots (has-parts) agg (when (and check-p (not has-parts)) (error "Bad ~A!" (type-of agg))) (when hierarchicly-p (dolist (part has-parts) (push agg (part-of part)))))) (defmethod delete-object progn ((obj geom-aggregate) &key) (dolist (part (has-parts obj)) (setf (part-of part) (delete obj (part-of part))))) ;;; ;;; ;;; (defmethod initialize-instance :after ((bounding-box bounding-box) &rest initargs &key xmin ymin xmax ymax &allow-other-keys) (declare (ignore initargs)) (setf (pmin bounding-box) (make-point (min xmin xmax) (min ymin ymax) :affected-by-matrix-p nil)) (setf (pmax bounding-box) (make-point (max xmin xmax) (max ymin ymax) :affected-by-matrix-p nil)) (setf (radius bounding-box) (sqrt (+ (expt (/ (- xmax xmin) 2) 2) (expt (/ (- ymax ymin) 2) 2))))) ;;; ;;; ;;; (defmethod (setf centroid) :after (centroid (master geom-thing)) (push master (centroid-of centroid))) (defun centroid-of-pointlist (pointlist) (let ((n (length pointlist))) (values (/ (reduce #'+ (mapcar #'x pointlist)) n) (/ (reduce #'+ (mapcar #'y pointlist)) n)))) (defmethod calculate-centroid ((obj geom-line)) (when (centroid-p obj) (multiple-value-bind (x y) (centroid-of-pointlist (list (p1 obj) (p2 obj))) (setf (centroid obj) (make-point x y :class (class-of-internal-points obj) :affected-by-matrix-p (affected-by-matrix-p obj)))))) (defmethod calculate-centroid ((obj geom-chain-or-polygon)) (when (centroid-p obj) (multiple-value-bind (x y) (centroid-of-pointlist (point-list obj)) (setf (centroid obj) (make-point x y :class (class-of-internal-points obj) :affected-by-matrix-p (affected-by-matrix-p obj)))))) (defmethod calculate-centroid ((obj geom-aggregate)) (when (centroid-p obj) (multiple-value-bind (x y) (centroid-of-pointlist (mapcar #'centroid (has-parts obj))) (setf (centroid obj) (make-point x y :make (class-of-internal-points obj) :affected-by-matrix-p (affected-by-matrix-p obj)))))) ;;; ;;; ;;; (defmethod calculate-bounding-box :after ((obj bounding-box-mixin) &key &allow-other-keys) (when (bounding-box-p obj) (with-slots (radius pmin pmax) obj (setf radius (sqrt (+ (expt (/ (- (x pmax) (x pmin)) 2) 2) (expt (/ (- (y pmax) (y pmin)) 2) 2))))))) (defmethod calculate-bounding-box ((obj geom-line) &key reuse-internal-points-p) (when (bounding-box-p obj) (with-slots (pmin pmax p1 p2) obj (let ((xmax (max (x p1) (x p2))) (ymax (max (y p1) (y p2))) (xmin (min (x p1) (x p2))) (ymin (min (y p1) (y p2)))) (if (and reuse-internal-points-p pmin pmax) (setf (x pmax) xmax (y pmax) ymax (x pmin) xmin (y pmin) ymin) (setf pmax (make-point xmax ymax :class (class-of-internal-points obj) :affected-by-matrix-p nil) pmin (make-point xmin ymin :class (class-of-internal-points obj) :affected-by-matrix-p nil))))))) (defmethod calculate-bounding-box-for-complex-object ((obj bounding-box-mixin) parts &key reuse-internal-points-p) (when (bounding-box-p obj) (with-slots (pmin pmax) obj (let ((xmin nil) (ymin nil) (xmax nil) (ymax nil)) (dolist (part parts) (dolist (point (if (typep part 'bounding-box-mixin) (list (pmin part) (pmax part)) (list part))) (let ((x (x point)) (y (y point))) (when (or (not xmin) (< x xmin)) (setf xmin x)) (when (or (not xmax) (> x xmax)) (setf xmax x)) (when (or (not ymin) (< y ymin)) (setf ymin y)) (when (or (not ymax) (> y ymax)) (setf ymax y))))) (if (and reuse-internal-points-p pmin pmax) (setf (x pmin) xmin (y pmin) ymin (x pmax) xmax (y pmax) ymax) (setf pmin (make-point xmin ymin :affected-by-matrix-p nil) pmax (make-point xmax ymax :affected-by-matrix-p nil))))))) (defmethod calculate-bounding-box ((obj geom-chain-or-polygon) &key reuse-internal-points-p) (calculate-bounding-box-for-complex-object obj (segments obj) :reuse-internal-points-p reuse-internal-points-p)) (defmethod calculate-bounding-box ((obj geom-aggregate) &key reuse-internal-points-p) (calculate-bounding-box-for-complex-object obj (has-parts obj) :reuse-internal-points-p reuse-internal-points-p)) ;;; ;;; ;;; (defmethod recalculate-bounding-box ((obj bounding-box-mixin)) (calculate-bounding-box obj :reuse-internal-points-p t) (setf (last-trafo-id obj) (trafo-id *matrix*))) ;;; ;;; ;;; (defmethod invalidate-bounding-box ((obj bounding-box-mixin)) (setf (last-trafo-id obj) -2)) (defmethod invalidate-bounding-box ((obj geom-chain-or-polygon)) (dolist (segment (segments obj)) (invalidate-bounding-box segment)) (call-next-method)) (defmethod invalidate-bounding-box ((obj geom-aggregate)) (dolist (part (has-parts obj)) (invalidate-bounding-box part)) (call-next-method)) ;;; ;;; ;;; ;;; ;;; (defmethod calculate-intersection-point ((line1 geom-line) (line2 geom-line)) (when (member '0d (calculate-relation line1 line2 :lod 1)) (let* ((x1l1 (x (p1 line1))) (y1l1 (y (p1 line1))) (x2l1 (x (p2 line1))) (y2l1 (y (p2 line1))) (x1l2 (x (p1 line2))) (y1l2 (y (p1 line2))) (x2l2 (x (p2 line2))) (y2l2 (y (p2 line2))) (m1 (if (= x2l1 x1l1) 'infinit (/ (- y2l1 y1l1) (- x2l1 x1l1)))) (m2 (if (= x2l2 x1l2) 'infinit (/ (- y2l2 y1l2) (- x2l2 x1l2))))) (cond ((or (and (eq m1 'infinit) (eq m2 'infinit)) (and (not (or (eq m1 'infinit) (eq m2 'infinit))) ; (= ..) schuetzen (= m1 m2))) (let ((p (if (or (point-=-p (p1 line1) (p1 line2)) (point-=-p (p1 line1) (p2 line2))) (p1 line1) (p2 line1)))) (values (x p) (y p)))) ((eq m1 'infinit) (let* ((xs x2l1) (ys (+ y1l2 (* m2 (- xs x1l2))))) (values xs ys))) ((eq m2 'infinit) (let* ((xs x2l2) (ys (+ y1l1 (* m1 (- xs x1l1))))) (values xs ys))) (t (let* ((xs (/ (- (* m1 x1l1) (* m2 x1l2) (- y1l1 y1l2)) (- m1 m2))) (ys (+ y1l1 (* m1 (- xs x1l1))))) (values xs ys))))))) #| (defmethod calculate-intersection-line ((line1 geom-line) (line2 geom-line)) (let* ((x1l1 (x (p1 line1))) (y1l1 (y (p1 line1))) (x2l1 (x (p2 line1))) (y2l1 (y (p2 line1))) (x1l2 (x (p1 line2))) (y1l2 (y (p1 line2))) (x2l2 (x (p2 line2))) (y2l2 (y (p2 line2)))) (multiple-value-bind (rel l1p1-l2 l1p2-l2 l2p1-l1 l2p2-l1) (calculate-relation line1 line2 :detailed t) (case rel (equal (values x1l1 y1l1 x2l1 y2l1)) ((inside covered-by) (values x1l1 y1l1 x2l1 y2l1)) ((contains covers) (values x1l2 y1l2 x2l2 y2l2)) (overlaps (cond ((and l1p1-l2 l2p1-l1) (values x1l1 y1l1 x1l2 y1l2)) ((and l1p1-l2 l2p2-l1) (values x1l1 y1l1 x2l2 y2l2)) ((and l1p2-l2 l2p1-l1) (values x2l1 y2l1 x1l2 y1l2)) ((and l1p2-l2 l2p2-l1) (values x2l1 y2l1 x2l2 y2l2)))))))) |# ;;; ;;; ;;; (defun distance-between* (x1 y1 x2 y2 &key (sqrt t) (sx 1) (sy 1)) (let* ((dx (/ (- x2 x1) sx)) (dy (/ (- y2 y1) sy))) (if sqrt (sqrt (+ (* dx dx) (* dy dy))) (+ (* dx dx) (* dy dy))))) (defmethod distance-between-xy ((x number) (y number) (point geom-point) &key (sqrt t) (sx 1) (sy 1)) (distance-between* x y (x point) (y point) :sqrt sqrt :sx sx :sy sy)) (defmethod distance-between ((point1 geom-point) (point2 geom-point) &key (sqrt t) (sx 1) (sy 1)) (distance-between* (x point1) (y point1) (x point2) (y point2) :sqrt sqrt :sx sx :sy sy)) (defun distance-between-point-and-line (px py lx1 ly1 lx2 ly2 &key (sqrt t) (sx 1) (sy 1)) (flet ((betw-0-and-1 (number) (and (not (minusp number)) (<= number 1.0)))) (let* ((ax (/ (- lx2 lx1) sx)) (ay (/ (- ly2 ly1) sy)) (dx (/ (- lx1 px) sx)) (dy (/ (- ly1 py) sy)) (a2 (+ (* ax ax) (* ay ay))) (scalar (if (zerop a2) +big-int+ (/ (+ (* ax (- dx)) (* ay (- dy))) a2))) (x (+ dx (* scalar ax))) (y (+ dy (* scalar ay))) (res (if (betw-0-and-1 scalar) (+ (* x x) (* y y)) (min (distance-between* px py lx1 ly1 :sqrt nil :sx sx :sy sy) (distance-between* px py lx2 ly2 :sqrt nil :sx sx :sy sy))))) (if sqrt (sqrt res) res)))) (defmethod distance-between ((point geom-point) (line geom-line) &key (sqrt t) (sx 1) (sy 1)) (distance-between-point-and-line (x point) (y point) (x (p1 line)) (y (p1 line)) (x (p2 line)) (y (p2 line)) :sqrt sqrt :sx sx :sy sy)) (defmethod distance-between-xy ((x number) (y number) (line geom-line) &key (sqrt t) (sx 1) (sy 1)) (distance-between-point-and-line x y (x (p1 line)) (y (p1 line)) (x (p2 line)) (y (p2 line)) :sqrt sqrt :sx sx :sy sy)) (defmethod distance-between ((line geom-line) (point geom-point) &key (sqrt t) (sx 1) (sy 1)) (distance-between point line :sqrt sqrt :sx sx :sy sy)) (defmethod distance-between ((line1 geom-line) (line2 geom-line) &key (sqrt t) (sx 1) (sy 1)) (let* ((d1 (distance-between (p1 line1) line2 :sqrt sqrt :sx sx :sy sy)) (d2 (distance-between (p2 line1) line2 :sqrt sqrt :sx sx :sy sy)) (d3 (distance-between (p1 line2) line1 :sqrt sqrt :sx sx :sy sy)) (d4 (distance-between (p2 line2) line1 :sqrt sqrt :sx sx :sy sy))) (if (intersects-p line1 line2) 0 (min d1 d2 d3 d4)))) (defmethod distance-between ((line geom-line) (poly geom-chain-or-polygon) &key (sqrt t) (sx 1) (sy 1)) (loop as i in (segments poly) minimize (distance-between i line :sqrt sqrt :sx sx :sy sy))) (defmethod distance-between ((poly geom-chain-or-polygon) (line geom-line) &key (sqrt t) (sx 1) (sy 1)) (distance-between line poly :sqrt sqrt :sx sx :sy sy)) (defmethod distance-between ((poly1 geom-chain-or-polygon) (poly2 geom-chain-or-polygon) &key (sqrt t) (sx 1) (sy 1)) (loop as i in (segments poly1) minimize (distance-between i poly2 :sqrt sqrt :sx sx :sy sy))) (defmethod distance-between ((point geom-point) (poly geom-chain-or-polygon) &key (sqrt t) (sx 1) (sy 1)) (loop as i in (segments poly) minimize (distance-between point i :sqrt sqrt :sx sx :sy sy))) (defmethod distance-between-xy ((x number) (y number) (poly geom-chain-or-polygon) &key (sqrt t) (sx 1) (sy 1)) (loop as i in (segments poly) minimize (distance-between-xy x y i :sqrt sqrt :sx sx :sy sy))) (defmethod distance-between ((poly geom-chain-or-polygon) (point geom-point) &key (sqrt t) (sx 1) (sy 1)) (distance-between point poly :sqrt sqrt :sx sx :sy sy)) ;;; ;;; ;;; (defun angle-between* (x1 y1 x2 y2) (let* ((dx (- x2 x1)) (dy (- y2 y1)) (phi (phase (complex dx dy)))) (if (minusp phi) (+ +2pi+ phi) phi))) (defun distance-and-orientation* (x1 y1 x2 y2) (let ((dist (distance-between* x1 y1 x2 y2)) (angle (angle-between* x1 y1 x2 y2))) (values dist angle))) (defun normalize (angle) (mod angle +2pi+)) (defun angle-difference (a b) (min (normalize (- a b)) (normalize (- b a)))) ;;; ;;; ;;; (defmethod length-of-line ((line geom-line)) (distance-between (p1 line) (p2 line))) (defmethod global-orientation ((line geom-line)) (angle-between* (x (p1 line)) (y (p1 line)) (x (p2 line)) (y (p2 line)))) #| (defmethod angle-between ((line1 geom-line) (line2 geom-line)) "Draw line1 around nearest point w.r.t. line2 counterclockwise and measure angle!" (let* ((d11 (distance-between (p1 line1) (p1 line2))) (d21 (distance-between (p2 line1) (p1 line2))) (d12 (distance-between (p1 line1) (p2 line2))) (d22 (distance-between (p2 line1) (p2 line2))) (dmin (min d11 d21 d12 d22))) (multiple-value-bind (as ae bs be) (cond ((= dmin d11) (values (p1 line1) (p2 line1) (p1 line2) (p2 line2))) ((= dmin d12) (values (p1 line1) (p2 line1) (p2 line2) (p1 line2))) ((= dmin d21) (values (p2 line1) (p1 line1) (p1 line2) (p2 line2))) ((= dmin d22) (values (p2 line1) (p1 line1) (p2 line2) (p1 line2)))) (normalize (- (angle-between* (x as) (y as) (x ae) (y ae)) (angle-between* (x bs) (y bs) (x be) (y be))))))) |# ;;; ;;; ;;; (defmethod calculate-area ((obj geom-polygon)) (with-slots (point-list) obj (let ((f 0) (first (first point-list)) (last (first (last point-list)))) (mapc #'(lambda (pj pj+1 pj-1) (let ((xj (x pj)) (yj+1 (y pj+1)) (yj-1 (y pj-1))) (incf f (* xj (- yj+1 yj-1))))) point-list (append (rest point-list) (list first)) (cons last point-list)) (/ f 2)))) ;;; ;;; ;;; (defun det-0-vecs (x1 y1 x2 y2) (- (* x1 y2) (* x2 y1))) (defun det (x1s y1s x1e y1e x2s y2s x2e y2e) (let ((x1 (- x1e x1s)) (y1 (- y1e y1s)) (x2 (- x2e x2s)) (y2 (- y2e y2s))) (- (* x1 y2) (* x2 y1)))) ;;; ;;; ;;; (defmethod insert-new-border-points ((poly geom-polygon) points) (let ((points (mapcar #'(lambda (x) (if (typep x 'geom-point) x (if (and (typep x 'cons) (cdr x) (not (cddr x))) (p (first x) (second x)) (error "Bad point ~A in list!" x)))) points))) (unless (every #'(lambda (p) (lies-on-p p poly)) points) (error "Not on polygon border!")) (let ((points (remove-if #'(lambda (p) ;;; vorhandene entfernen (some #'(lambda (q) (point-=-p p q)) (point-list poly))) points)) (new-points nil)) (dolist (seg (segments poly)) (setf new-points (append new-points (sort (cons (p1 seg) (remove-if-not #'(lambda (p) (lies-on-p p seg)) points)) #'< :key #'(lambda (x) (distance-between (p1 seg) x)))))) (let ((new-points (mapcar #'(lambda (p) (list (x p) (y p))) (remove-duplicates new-points :test #'point-=-p)))) (poly-from-xy-list (append new-points (list (first new-points))) :affected-by-matrix-p nil))))) (defmethod insert-new-border-points ((chain geom-chain) points) (let ((points (mapcar #'(lambda (x) (if (typep x 'geom-point) x (if (and (typep x 'cons) (cdr x) (not (cddr x))) (p (first x) (second x)) (error "Bad point ~A in list!" x)))) points))) (unless (every #'(lambda (p) (lies-on-p p chain)) points) (error "Not on chain border!")) (let ((points (remove-if #'(lambda (p) ;;; vorhandene entfernen (some #'(lambda (q) (point-=-p p q)) (point-list chain))) points)) (new-points nil)) (dolist (seg (segments chain)) (setf new-points (append new-points (sort (cons (p1 seg) (remove-if-not #'(lambda (p) (lies-on-p p seg)) points)) #'< :key #'(lambda (x) (distance-between (p1 seg) x)))))) (let ((new-points (mapcar #'(lambda (p) (list (x p) (y p))) (remove-duplicates new-points :test #'point-=-p)))) (chain-from-xy-list (append new-points (list (list (x (p2 (first (last (segments chain))))) (y (p2 (first (last (segments chain)))))))) :affected-by-matrix-p nil))))) ;;; ;;; ;;; (defmethod orientation ((poly geom-polygon)) (let* ((points (remove-duplicates (point-list poly) :test #'point-=-p)) (rightmost-lowest-point (let ((current (first points))) (dolist (point points) (when (or (< (y point) (y current)) (and (= (y point) (y current)) (> (x point) (x current)))) (setf current point))) current)) (pos (position rightmost-lowest-point points)) (points (if (zerop pos) (list (first (last points)) (first points) (second points)) (if (= pos (1- (length points))) (append (subseq points (1- pos) (+ (1- pos) 2)) (list (first points))) (subseq points (1- pos) (+ (1- pos) 3)))))) (apply #'ccw points))) (defun decode-ccw (num) (ecase num (1 :counterclockwise) (-1 :clockwise))) (defmethod change-orientation ((poly geom-polygon)) (dolist (seg (segments poly)) (psetf (p1 seg) (p2 seg) (p2 seg) (p1 seg)) (push seg (p1-of (p1 seg))) (push seg (p2-of (p2 seg))) (setf (point-list seg) (list (p1 seg) (p2 seg))) (setf (p1-of (p2 seg)) (delete seg (p1-of (p2 seg)))) (setf (p2-of (p1 seg)) (delete seg (p2-of (p1 seg))))) (setf (segments poly) (nreverse (segments poly))) (setf (point-list poly) (apply #'append (mapcar #'point-list (segments poly)))) poly) (defmethod orientate-counterclockwise ((poly geom-polygon)) (if (= (orientation poly) 1) poly (change-orientation poly))) (defmethod orientate-clockwise ((poly geom-polygon)) (if (= (orientation poly) -1) poly (change-orientation poly))) ;;; ;;; ;;; (defmethod get-xy-list ((point geom-point)) (list (x point) (y point))) (defmethod get-xy-list ((line geom-line)) (mapcar #'get-xy-list (point-list line))) (defmethod get-xy-list ((obj geom-chain-or-polygon)) (mapcar #'get-xy-list (segments obj))) ;;; ;;; ;;; (defmethod get-float-xy-list ((point geom-point)) (list (float (x point)) '= (x point) (float (y point)) '= (y point))) (defmethod get-float-xy-list ((line geom-line)) (mapcar #'get-float-xy-list (point-list line))) (defmethod get-float-xy-list ((obj geom-chain-or-polygon)) (mapcar #'get-float-xy-list (segments obj))) ;;; ;;; ;;; (defmethod (setf affected-by-matrix-p) (val (obj geom-point)) (setf (slot-value obj 'affected-by-matrix-p) val)) (defmethod (setf affected-by-matrix-p) (val (obj geom-line)) (setf (slot-value obj 'affected-by-matrix-p) val (affected-by-matrix-p (p1 obj)) val (affected-by-matrix-p (p2 obj)) val)) (defmethod (setf affected-by-matrix-p) (val (obj geom-chain-or-polygon)) (setf (slot-value obj 'affected-by-matrix-p) val) (mapc #'(lambda (s) (setf (affected-by-matrix-p s) val)) (segments obj)))
46,778
Common Lisp
.lisp
1,327
26.618689
109
0.542669
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
2d19e47113b1df6ecfe3b749f7d93b8e1864537d43c3a43e37465011c7adc187
4,333
[ -1 ]
4,334
covering4.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/main/covering4.lisp
;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: TANGRAM -*- (in-package :tangram) (defun compactness (poly) (with-no-matrix-at-all (/ (loop as s in (segments poly) sum (length-of-line s)) (sqrt (tangram-geometry::calculate-area poly))))) (defun polygon-difference (x y) ;;; "x minus y" (if (not (member (calculate-rcc-relation x y) '(:tppi :ec))) (error "Bad polygons!") (let* ((points-of-y-on-x (remove-if-not #'(lambda (point-of-y) (lies-on-p point-of-y x)) (point-list y))) (points-of-x-on-y (remove-if-not #'(lambda (point-of-x) (lies-on-p point-of-x y)) (point-list x))) (x (insert-new-border-points x points-of-y-on-x)) (y (insert-new-border-points y points-of-x-on-y)) (good-y-segments (remove-if #'(lambda (y-seg) (some #'(lambda (x-seg) (line-=-p x-seg y-seg)) (segments x))) (segments y))) (good-x-segments (remove-if #'(lambda (y-seg) (some #'(lambda (x-seg) (line-=-p x-seg y-seg)) (segments y))) (segments x))) (segments (append good-x-segments good-y-segments))) (let ((ox (decode-ccw (orientation x))) (oy (decode-ccw (orientation y)))) (when (eq ox :clockwise) (orientate-counterclockwise x)) (when (eq oy :counterclockwise) (orientate-clockwise y)) (prog1 (mapcar #'(lambda (component) (poly-from-xy-list (mapcar #'get-xy-list (append (mapcar #'p1 component) (list (p2 (first (last component)))))) :normalize-p nil :affected-by-matrix-p nil)) (find-components segments)) (when (eq ox :clockwise) (orientate-clockwise x)) (when (eq oy :counterclockwise) (orientate-counterclockwise y))))))) (defun polygon-union (x y) ;;; "x vereinigt y" (if (not (or (eq (calculate-rcc-relation x y) :ec) (eq (calculate-rcc-relation x y) :dc) (eq (calculate-rcc-relation x y) :po))) (error "Bad polygons!") (let* ((points-of-y-on-x (remove-if-not #'(lambda (point-of-y) (lies-on-p point-of-y x)) (point-list y))) (points-of-x-on-y (remove-if-not #'(lambda (point-of-x) (lies-on-p point-of-x y)) (point-list x))) (new-intersection-points (let ((res nil)) (dolist (sa (segments x)) (dolist (sb (segments y)) (unless (joins-p sa sb) (multiple-value-bind (xc yc) (calculate-intersection-point sa sb) (when xc (push (list xc yc) res)))))) res)) (x (insert-new-border-points x (nconc points-of-y-on-x new-intersection-points))) (y (insert-new-border-points y (nconc points-of-x-on-y new-intersection-points))) (good-y-segments (remove-if #'(lambda (y-seg) (some #'(lambda (x-seg) (line-=-p x-seg y-seg)) (segments x))) (segments y))) (good-x-segments (remove-if #'(lambda (y-seg) (some #'(lambda (x-seg) (line-=-p x-seg y-seg)) (segments y))) (segments x))) (segments (append good-x-segments good-y-segments))) (let ((ox (decode-ccw (orientation x))) (oy (decode-ccw (orientation y)))) (when (eq ox :clockwise) (orientate-counterclockwise x)) (when (eq oy :clockwise) (orientate-counterclockwise y)) (prog1 (mapcar #'(lambda (component) (poly-from-xy-list (mapcar #'get-xy-list (append (mapcar #'p1 component) (list (p2 (first (last component)))))) :normalize-p nil :affected-by-matrix-p nil)) (let ((res (find-components segments))) (if res res (list (segments x) (segments y))))) (when (eq ox :clockwise) (orientate-clockwise x)) (when (eq oy :clockwise) (orientate-clockwise y))))))) (defun polygon-set-union (set-of-polygons) (let ((change t) (union set-of-polygons)) (loop while change do (setf change nil) (let ((pair nil)) (find-if #'(lambda (a) (find-if #'(lambda (b) (when (and (not (eq a b)) (some #'(lambda (a) (some #'(lambda (b) (1d-intersects-p a b)) (segments b))) (segments a)) (member (calculate-rcc-relation a b) '(:ec))) (setf pair (list a b)))) union)) union) (when pair (setf change t) (setf union (delete (first pair) union)) (setf union (delete (second pair) union)) (setf union (append union (polygon-union (first pair) (second pair))))))) union)) (defun find-components (segments) (let ((components nil)) (labels ((do-it (cur-component segments) (let* ((current-segment (first cur-component)) (succ-candidates (remove-if-not #'(lambda (cand) (point-=-p (p1 cand) (p2 current-segment))) segments))) (when (and (segment-list-ok-p cur-component t t) (some #'(lambda (x) (not (equal (part-of x) (part-of current-segment)))) cur-component)) (push (reverse cur-component) components) (when segments (do-it (list (first segments)) (rest segments)))) (dolist (succ-candidate succ-candidates) ; jeder Gabelung folgen! (do-it (cons succ-candidate cur-component) (remove succ-candidate segments)))))) (do-it (list (first segments)) (rest segments)) components))) (defun angle-between (sa sb) (let* ((x1 (x (p1 sa))) (y1 (y (p1 sa))) (x2 (x (p2 sa))) (y2 (y (p2 sa))) (phi-a (angle-between* x1 y1 x2 y2))) (let* ((x1 (x (p1 sb))) (y1 (y (p1 sb))) (x2 (x (p2 sb))) (y2 (y (p2 sb))) (phi-b (angle-between* x1 y1 x2 y2))) (mod (- phi-b phi-a) (* 2 pi))))) ;;; ;;; ;;; (defparameter *remove-congruent-configurations-p* t) (defparameter *debug-p* nil) (defvar *x* nil) ;;; ;;; ;;; (defun find-possible-alignments (a b &key how-many frame color score-p rem-tile-types) ;;; versuche "b" in "a" unterzubringen! (let ((res nil) (abma (affected-by-matrix-p a)) (abmb (affected-by-matrix-p b))) (orientate-counterclockwise a) (orientate-counterclockwise b) (block enumerate (dolist (sa (segments a)) (dolist (sb (segments b)) (let (phi xf yf xt yt) (setf phi (angle-between sb sa) xf (x (p1 sb)) yf (y (p1 sb)) xt (x (p1 sa)) yt (y (p1 sa))) ;;; Drehwinkel fuer "b" ;;; Drehpunkt: "p1" ;;; Die Transformation bezieht sich nur auf b! (setf (affected-by-matrix-p a) nil) (setf (affected-by-matrix-p b) t) (with-translation ( (- xf) (- yf) ) (with-rotation ( phi ) (with-translation ( xt yt ) (when (and frame (show-thinking-p frame)) (show-polygons (list b) :clear-p nil :inks (list +flipping-ink+) :filled-p nil)) (let* ((rel (calculate-rcc-relation a b))) (when *debug-p* (let ((aa (poly-from-xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments a))) (list (get-xy-list (p2 (first (last (segments a))))))) :affected-by-matrix-p nil)) (bb (poly-from-xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments b))) (list (get-xy-list (p2 (first (last (segments b))))))) :affected-by-matrix-p nil))) (setf *x* (list rel aa bb color)))) (case rel ((:tppi) (let* ((succ-conf (polygon-difference a b)) (aligned-poly (poly-from-xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments b))) (list (get-xy-list (p2 (first (last (segments b))))))) :affected-by-matrix-p nil)) (h (if score-p (alignment-result-heuristic-for-polygon aligned-poly succ-conf a rem-tile-types) 0))) (unless (eq h :bad) (push (list h aligned-poly succ-conf a rem-tile-types) res)) (when *debug-p* (let ((x (count-if #'(lambda (p) (inside-p p a)) (point-list b)))) (when (zerop x) (show-polygons (append succ-conf (list aligned-poly)) :clear-p t :inks (append (loop as x in succ-conf collect +blue+) (list +yellow+)) :filled-p t) (sleep 0.3))))) (when (and frame (show-thinking-p frame)) (show-polygons (list b) :clear-p nil :inks (list +flipping-ink+) :filled-p nil)) (when (and how-many (> (length res) how-many)) (return-from enumerate))) (:eq (let* ((succ-conf :match) (aligned-poly (poly-from-xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments b))) (list (get-xy-list (p2 (first (last (segments b))))))) :affected-by-matrix-p nil)) (h (if score-p (alignment-result-heuristic-for-polygon aligned-poly succ-conf a rem-tile-types) 0))) (when (and frame (show-thinking-p frame)) (show-polygons (list b) :clear-p nil :inks (list +flipping-ink+) :filled-p nil)) (return-from find-possible-alignments (prog1 (list (list h aligned-poly succ-conf a rem-tile-types)) (setf (affected-by-matrix-p a) abma) (setf (affected-by-matrix-p b) abmb))))) (otherwise (when (and frame (show-thinking-p frame)) (show-polygons (list b) :clear-p nil :inks (list +flipping-ink+) :filled-p nil)))))))) (setf (affected-by-matrix-p a) abma) (setf (affected-by-matrix-p b) abmb))))) (if *remove-congruent-configurations-p* (remove-duplicates res :key #'third :test #'(lambda (x y) (set-equal x y :test #'congruent-p))) res))) ;;; ;;; ;;; (defun history (n) (show-polygons (nth n *x*) :inks (list (first +gray-colors+) (third (nth n *x*))))) ;;; ;;; ;;; (defun tuple-> (a b) (when (and a b) (cond ((> (first a) (first b)) t) ((= (first a) (first b)) (tuple-> (rest a) (rest b))) (t nil)))) (defun find-covering (polygon-set tile-types &key (remove-used-tiles-p t) frame all-solutions-p allow-less-tiles-p show-thinking-fn) (let ((solutions nil)) (labels ((goal-p (polygons tile-types) (and (not polygons) (or allow-less-tiles-p (not tile-types)))) (do-it (polygons tile-types history) (cond ((goal-p polygons tile-types) (push (list polygons tile-types history) solutions) (when show-thinking-fn (funcall show-thinking-fn polygons tile-types history t)) (unless all-solutions-p (return-from do-it nil))) (t (when show-thinking-fn (funcall show-thinking-fn polygons tile-types history nil)) #+:ignore (sleep 1) (let* ((alignments nil) (perfect-alignments nil)) (dolist (polygon polygons) (dolist (tile-type tile-types) ; tile-type is the set of "mirrored" versions of that tile! defined by means of the "mirror values" for the tile (let ((rem-tile-types (if remove-used-tiles-p (remove tile-type tile-types) tile-types))) (dolist (tile tile-type) (dolist (succ-conf (find-possible-alignments polygon (shape tile) :frame frame :color (color tile) :score-p t :rem-tile-types rem-tile-types)) ;; succ-conf = (list h aligned-poly succ-conf orig-poly rem-tile-types) (if (eq (third succ-conf) :match) (push (list succ-conf tile ) perfect-alignments) (push (list succ-conf tile ) alignments))))))) (let ((sorted (append (sort perfect-alignments #'tuple-> :key #'caar) (subseq (sort alignments #'tuple-> :key #'caar) ;; best n only ? 0 ;; (min 4 (length alignments)) (length alignments) )))) (loop as ((h aligned-poly succ-conf orig-poly rem-tile-types) tile) in sorted do (let* ((rem-polygons (remove orig-poly polygons))) (do-it (if (eq succ-conf :match) rem-polygons (append succ-conf rem-polygons )) rem-tile-types (cons (list aligned-poly tile) history)))))))))) (do-it polygon-set tile-types nil) solutions))) ;;; ;;; ;;; (defun alignment-result-heuristic-for-polygon (aligned-polygon conf orig-polygon rem-tile-types) (cond ((symbolp conf) ; :match! (list (tangram-geometry::calculate-area aligned-polygon) 0)) ((some #'(lambda (poly) (every #'(lambda (tile-type) (let ((tile (first tile-type))) ; use first reflected variant (< (+ (tangram-geometry::calculate-area poly) 2) ;; account for inaccuracies... hack (tangram-geometry::calculate-area (shape tile))))) rem-tile-types)) conf) :bad ) (t ;; score list for lexicographic tuple->-p sorting (list (* (+ (reduce #'+ (mapcar #'(lambda (x) (compactness x)) conf))) (tangram-geometry::calculate-area aligned-polygon)) (- (reduce #'+ (mapcar #'length (mapcar #'segments conf)))) ;;(- (count-if #'(lambda (p) ;; (inside-p p orig-polygon)) ;; (point-list aligned-polygon))) ))))
20,604
Common Lisp
.lisp
415
25.308434
170
0.37877
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
2c67145b265dd73bc65002da7dac664424eaa29d5dd44a7dec3e0ea406934198
4,334
[ -1 ]
4,335
tests.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/main/tests.lisp
;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: TANGRAM -*- (in-package :tangram) (progn (setf a1 (poly-from-xy-list '((0 0) (80 0) (40 40) (0 0))) b1 (poly-from-xy-list '((0 0) (0 80) (40 40) (0 0))) c1 (poly-from-xy-list '((80 80) (80 40) (40 80) (80 80))) d1 (poly-from-xy-list '((80 0) (80 40) (60 20) (80 0))) e1 (poly-from-xy-list '((20 60) (60 60) (40 40) (20 60))) f1 (poly-from-xy-list '((60 20) (80 40) (60 60) (40 40) (60 20))) g1 (poly-from-xy-list '((0 80) (40 80) (60 60) (20 60) (0 80)))) (setf a2 (poly-from-xy-list '((0 0) (80 0) (40 40) (0 0))) b2 (poly-from-xy-list '((0 0) (0 80) (40 40) (0 0))) c2 (poly-from-xy-list '((80 80) (80 40) (40 80) (80 80))) d2 (poly-from-xy-list '((80 0) (80 40) (60 20) (80 0))) e2 (poly-from-xy-list '((20 60) (60 60) (40 40) (20 60))) f2 (poly-from-xy-list '((60 20) (80 40) (60 60) (40 40) (60 20))) g2 (poly-from-xy-list '((0 80) (40 80) (60 60) (20 60) (0 80)))) (setf x (with-translation (10 10) (let* ((poly c1) (xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments poly))) (list (get-xy-list (p2 (first (last (segments poly))))))))) (princ xy-list) (poly-from-xy-list xy-list)))) (setf y (with-translation (-10 -10) (let* ((poly x) (xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments poly))) (list (get-xy-list (p2 (first (last (segments poly))))))))) (princ xy-list) (poly-from-xy-list xy-list)))) (setf *x* nil) (let ((*debug-p* t)) (princ (congruent-p c1 y)) (terpri) (terpri) (princ `(:allignemnts ,(find-possible-alignments c1 x))) (pprint *x*))) (progn (setf x (poly-from-xy-list '((0 0) (10 0) (10 10) (0 10) (0 0)))) (setf y (poly-from-xy-list '((5 0) (10 5) (10 10) (5 10) (0 5) (5 0)))) (setf z (poly-from-xy-list '((5 0) (10 5) (5 10) (0 5) (5 0)))) (setf u (poly-from-xy-list '((0 5) (2 0) (3 3) (5 0) (6 0) (10 3) (5 5) (10 7) (10 10) (0 10) (0 5)))) (princ (mapcan #'(lambda (x) (format t "Component: ~A~%" (get-xy-list x))) (polygon-difference x y))) (terpri) (terpri) (princ (mapcan #'(lambda (x) (format t "Component: ~A~%" (get-xy-list x))) (polygon-difference x z))) (terpri) (terpri) (princ (mapcan #'(lambda (x) (format t "Component: ~A~%" (get-xy-list x))) (polygon-difference y z))) (terpri) (terpri) (princ (mapcan #'(lambda (x) (format t "Component: ~A~%" (get-xy-list x))) (polygon-difference x u)))) (progn (setf x (poly-from-xy-list '((0 0) (10 0) (10 10) (0 10) (0 0)))) (setf y (poly-from-xy-list '((5 5) (15 5) (15 15) (5 15) (5 5)))) (terpri) (terpri) (princ (remove-duplicates (polygon-union x y) :test #'congruent-p))) (progn (setf x (poly-from-xy-list '((0 0) (5 5) (10 0) (10 10) (0 10) (0 0)))) (setf y (poly-from-xy-list '((0 707/100) (707/100 707/100) (0 0) (0 707/100)))) (princ (mapcan #'(lambda (x) (format t "Component: ~A~%" (get-xy-list x))) (polygon-difference x y))) (terpri) (terpri)) (progn (setf a (poly-from-xy-list '((0 0) (30 0) (30 30) (0 30) (0 0)))) (setf b (poly-from-xy-list '((30 30) (50 30) (40 40) (30 30)))) (princ (find-possible-alignments a b))) (progn (setf x (poly-from-xy-list '((0 0) (10 0) (10 10) (0 0)))) (setf y (poly-from-xy-list '((12 0) (20 0) (20 20) (12 0)))) (terpri) (terpri) (princ (remove-duplicates (polygon-union x y) :test #'congruent-p))) (princ (length (find-covering (list (poly-from-xy-list '((0 0) (10 10) (0 10) (0 0)))) (list (list (make-tile 'a '((0 0) (5 5) (0 10) (0 0)) +black+))) :remove-used-tiles-p nil :allow-less-tiles-p t :all-solutions-p t))) (princ (length (find-covering (list (poly-from-xy-list '((822/5 411/5) (1233/5 411/5) (2877/10 1233/10) (411/2 1233/10) (822/5 411/5)))) (list (list (make-tile 'a '((822/5 411/5) (411/2 1233/10) (2877/10 1233/10) (1233/5 411/5) (822/5 411/5)) +black+)))))) (princ (prog2 (setf *x* nil) (find-covering (list (let ((poly (poly-from-xy-list '((0 80) (40 80) (60 60) (20 60) (0 80))))) (with-rotation (pi) (with-translation (0 0) (let ((xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments poly))) (list (get-xy-list (p2 (first (last (segments poly))))))))) (poly-from-xy-list xy-list)))))) (list ; a SET of set of tiles (list (make-tile 'a '((0 80) (40 80) (60 60) (20 60) (0 80)) (make-rgb-color 1 0.3 0.9))))) (pprint *x*))) (princ (find-covering (list (poly-from-xy-list '((0 80) (40 80) (60 60) (20 60) (0 80)))) (list ; a SET of set of tiles (list (make-tile 'a '((0 80) (40 80) (60 60) (20 60) (0 80)) (make-rgb-color 1 0.3 0.9)))))) (progn ;;c1 (poly-from-xy-list '((80 80) (80 40) (40 80) (80 80))) (setf x (poly-from-xy-list '((0 0) (10 0) (10 10) (0 10) (0 0)))) (setf y (poly-from-xy-list '((5 5) (15 5) (15 15) (5 15) (5 5)))) (setf x1 (let ((poly (poly-from-xy-list '((0 0) (10 0) (10 10) (0 10) (0 0))))) (with-rotation (pi) (with-translation (-10 -10) (let ((xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments poly))) (list (get-xy-list (p2 (first (last (segments poly))))))))) (print xy-list) (poly-from-xy-list xy-list)))))) (princ (congruent-p x x)) (princ (congruent-p x y)) (princ (congruent-p x x1)))
6,447
Common Lisp
.lisp
143
33.692308
104
0.466989
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
d47c1ddb9e845a8dc8b79293904876a7242768b8a0321ec41c09fb28d570ab11
4,335
[ -1 ]
4,336
covering3.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/main/covering3.lisp
;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: TANGRAM -*- (in-package :tangram) (defparameter *record-statistics* nil) (defvar *bad-counter* 0) (defvar *inc-counter* 0) (defvar *statistics* nil) (defun compactness (poly) (with-no-matrix-at-all (/ (loop as s in (segments poly) sum (length-of-line s)) (sqrt (tangram-geometry::calculate-area poly))))) (defun polygon-difference (x y) ;;; "x minus y" (if (not (member (calculate-rcc-relation x y) '(:tppi :ec))) (error "Bad polygons!") (let* ((points-of-y-on-x (remove-if-not #'(lambda (point-of-y) (lies-on-p point-of-y x)) (point-list y))) (points-of-x-on-y (remove-if-not #'(lambda (point-of-x) (lies-on-p point-of-x y)) (point-list x))) (x (insert-new-border-points x points-of-y-on-x)) (y (insert-new-border-points y points-of-x-on-y)) (good-y-segments (remove-if #'(lambda (y-seg) (some #'(lambda (x-seg) (line-=-p x-seg y-seg)) (segments x))) (segments y))) (good-x-segments (remove-if #'(lambda (y-seg) (some #'(lambda (x-seg) (line-=-p x-seg y-seg)) (segments y))) (segments x))) (segments (append good-x-segments good-y-segments))) (let ((ox (decode-ccw (orientation x))) (oy (decode-ccw (orientation y)))) (when (eq ox :clockwise) (orientate-counterclockwise x)) (when (eq oy :counterclockwise) (orientate-clockwise y)) (prog1 (mapcar #'(lambda (component) (poly-from-xy-list (mapcar #'get-xy-list (append (mapcar #'p1 component) (list (p2 (first (last component)))))) :normalize-p nil :affected-by-matrix-p nil)) (find-components segments)) (when (eq ox :clockwise) (orientate-clockwise x)) (when (eq oy :counterclockwise) (orientate-counterclockwise y))))))) (defun polygon-union (x y) ;;; "x vereinigt y" (if (not (or (eq (calculate-rcc-relation x y) :ec) (eq (calculate-rcc-relation x y) :dc) (eq (calculate-rcc-relation x y) :po))) (error "Bad polygons!") (let* ((points-of-y-on-x (remove-if-not #'(lambda (point-of-y) (lies-on-p point-of-y x)) (point-list y))) (points-of-x-on-y (remove-if-not #'(lambda (point-of-x) (lies-on-p point-of-x y)) (point-list x))) (new-intersection-points (let ((res nil)) (dolist (sa (segments x)) (dolist (sb (segments y)) (unless (joins-p sa sb) (multiple-value-bind (xc yc) (calculate-intersection-point sa sb) (when xc (push (list xc yc) res)))))) res)) (x (insert-new-border-points x (nconc points-of-y-on-x new-intersection-points))) (y (insert-new-border-points y (nconc points-of-x-on-y new-intersection-points))) (good-y-segments (remove-if #'(lambda (y-seg) (some #'(lambda (x-seg) (line-=-p x-seg y-seg)) (segments x))) (segments y))) (good-x-segments (remove-if #'(lambda (y-seg) (some #'(lambda (x-seg) (line-=-p x-seg y-seg)) (segments y))) (segments x))) (segments (append good-x-segments good-y-segments))) (let ((ox (decode-ccw (orientation x))) (oy (decode-ccw (orientation y)))) (when (eq ox :clockwise) (orientate-counterclockwise x)) (when (eq oy :clockwise) (orientate-counterclockwise y)) (prog1 (mapcar #'(lambda (component) (poly-from-xy-list (mapcar #'get-xy-list (append (mapcar #'p1 component) (list (p2 (first (last component)))))) :normalize-p nil :affected-by-matrix-p nil)) (let ((res (find-components segments))) (if res res (list (segments x) (segments y))))) (when (eq ox :clockwise) (orientate-clockwise x)) (when (eq oy :clockwise) (orientate-clockwise y))))))) (defun polygon-set-union (set-of-polygons) (let ((change t) (union set-of-polygons)) (loop while change do (setf change nil) (let ((pair nil)) (find-if #'(lambda (a) (find-if #'(lambda (b) (when (and (not (eq a b)) (some #'(lambda (a) (some #'(lambda (b) (1d-intersects-p a b)) (segments b))) (segments a)) (member (calculate-rcc-relation a b) '(:ec))) (setf pair (list a b)))) union)) union) (when pair (setf change t) (setf union (delete (first pair) union)) (setf union (delete (second pair) union)) (setf union (append union (polygon-union (first pair) (second pair))))))) union)) (defun find-components (segments) (let ((components nil)) (labels ((do-it (cur-component segments) (let* ((current-segment (first cur-component)) (succ-candidates (remove-if-not #'(lambda (cand) (point-=-p (p1 cand) (p2 current-segment))) segments))) (when (and (segment-list-ok-p cur-component t t) (some #'(lambda (x) (not (equal (part-of x) (part-of current-segment)))) cur-component)) (push (reverse cur-component) components) (when segments (do-it (list (first segments)) (rest segments)))) (dolist (succ-candidate succ-candidates) ; jeder Gabelung folgen! (do-it (cons succ-candidate cur-component) (remove succ-candidate segments)))))) (do-it (list (first segments)) (rest segments)) components))) (defun angle-between (sa sb) (let* ((x1 (x (p1 sa))) (y1 (y (p1 sa))) (x2 (x (p2 sa))) (y2 (y (p2 sa))) (phi-a (angle-between* x1 y1 x2 y2))) (let* ((x1 (x (p1 sb))) (y1 (y (p1 sb))) (x2 (x (p2 sb))) (y2 (y (p2 sb))) (phi-b (angle-between* x1 y1 x2 y2))) (mod (- phi-b phi-a) (* 2 pi))))) ;;; ;;; ;;; (defparameter *remove-congruent-configurations-p* t) (defparameter *debug-p* nil) (defvar *x* nil) ;;; ;;; ;;; (defun find-possible-alignments (a b &key how-many frame color score-p rem-tile-types) ;;; versuche "b" in "a" unterzubringen! (let ((res nil) (abma (affected-by-matrix-p a)) (abmb (affected-by-matrix-p b))) (orientate-counterclockwise a) (orientate-counterclockwise b) (block enumerate (dolist (sa (segments a)) (dolist (sb (segments b)) (let (phi xf yf xt yt) (setf phi (angle-between sb sa) xf (x (p1 sb)) yf (y (p1 sb)) xt (x (p1 sa)) yt (y (p1 sa))) ;;; Drehwinkel fuer "b" ;;; Drehpunkt: "p1" ;;; Die Transformation bezieht sich nur auf b! (setf (affected-by-matrix-p a) nil) (setf (affected-by-matrix-p b) t) (with-translation ( (- xf) (- yf) ) (with-rotation ( phi ) (with-translation ( xt yt ) (when (and frame (show-thinking-p frame)) (show-polygons (list b) :clear-p nil :inks (list +flipping-ink+) :filled-p nil)) (let* ((rel (calculate-rcc-relation a b))) (when *debug-p* (let ((aa (poly-from-xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments a))) (list (get-xy-list (p2 (first (last (segments a))))))) :affected-by-matrix-p nil)) (bb (poly-from-xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments b))) (list (get-xy-list (p2 (first (last (segments b))))))) :affected-by-matrix-p nil))) (setf *x* (list rel aa bb color)))) (case rel ((:tppi) (let* ((succ-conf (polygon-difference a b)) (aligned-poly (poly-from-xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments b))) (list (get-xy-list (p2 (first (last (segments b))))))) :affected-by-matrix-p nil)) (h (if score-p (alignment-result-heuristic-for-polygon aligned-poly succ-conf a rem-tile-types) 0))) (when (and (eq h :bad) *record-statistics*) (incf *bad-counter*)) (unless (eq h :bad) (push (list h aligned-poly succ-conf a rem-tile-types) res)) (when *debug-p* (let ((x (count-if #'(lambda (p) (inside-p p a)) (point-list b)))) (when (zerop x) (show-polygons (append succ-conf (list aligned-poly)) :clear-p t :inks (append (loop as x in succ-conf collect +blue+) (list +yellow+)) :filled-p t) (sleep 3))))) (when (and frame (show-thinking-p frame)) (show-polygons (list b) :clear-p nil :inks (list +flipping-ink+) :filled-p nil)) (when (and how-many (> (length res) how-many)) (return-from enumerate))) (:eq (let* ((succ-conf :match) (aligned-poly (poly-from-xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments b))) (list (get-xy-list (p2 (first (last (segments b))))))) :affected-by-matrix-p nil)) (h (if score-p (alignment-result-heuristic-for-polygon aligned-poly succ-conf a rem-tile-types) 0))) (when (and frame (show-thinking-p frame)) (show-polygons (list b) :clear-p nil :inks (list +flipping-ink+) :filled-p nil)) (return-from find-possible-alignments (prog1 (list (list h aligned-poly succ-conf a rem-tile-types)) (setf (affected-by-matrix-p a) abma) (setf (affected-by-matrix-p b) abmb))))) (otherwise (when (and frame (show-thinking-p frame)) (show-polygons (list b) :clear-p nil :inks (list +flipping-ink+) :filled-p nil)))))))) (setf (affected-by-matrix-p a) abma) (setf (affected-by-matrix-p b) abmb))))) (if *remove-congruent-configurations-p* (remove-duplicates res :key #'third :test #'(lambda (x y) (set-equal x y :test #'congruent-p))) res))) ;;; ;;; ;;; (defun history (n) (show-polygons (nth n *x*) :inks (list (first +gray-colors+) (third (nth n *x*))))) ;;; ;;; ;;; (defun tuple-> (a b) (when (and a b) (cond ((> (first a) (first b)) t) ((= (first a) (first b)) (tuple-> (rest a) (rest b))) (t nil)))) (defun reset-statistics () (setf *bad-counter* 0) (setf *inc-counter* 0) (setf *statistics* nil)) (defun find-covering (polygon-set tile-types &key (remove-used-tiles-p t) frame all-solutions-p allow-less-tiles-p show-thinking-fn) (let ((solutions nil)) (labels ((goal-p (polygons tile-types) (and (not polygons) (or allow-less-tiles-p (not tile-types)))) (do-it (polygons tile-types history) (when *record-statistics* (incf *inc-counter*)) (cond ((goal-p polygons tile-types) (push (list polygons tile-types history) solutions) (when show-thinking-fn (funcall show-thinking-fn polygons tile-types history t)) (unless all-solutions-p (return-from find-covering solutions))) (t (when show-thinking-fn (funcall show-thinking-fn polygons tile-types history nil)) #+:ignore (sleep 1) (let* ((alignments nil) (perfect-alignments nil)) (dolist (polygon polygons) (dolist (tile-type tile-types) ;; tile-type is the set of reflected variants of that tile (let ((rem-tile-types (if remove-used-tiles-p (remove tile-type tile-types) tile-types))) (dolist (tile tile-type) (dolist (succ-conf (find-possible-alignments polygon (shape tile) :frame frame :color (color tile) :score-p t :rem-tile-types rem-tile-types)) ;; succ-conf = (list h aligned-poly succ-conf orig-poly rem-tile-types) (if (eq (third succ-conf) :match) (push (list succ-conf tile ) perfect-alignments) (push (list succ-conf tile ) alignments))))))) (let ((sorted (append (sort perfect-alignments #'tuple-> :key #'caar) (subseq (sort alignments #'tuple-> :key #'caar) ;; best n only ? 0 (length alignments) )))) (when *record-statistics* (push (list *inc-counter* (length tile-types) (length sorted)) *statistics*)) (loop as ((h aligned-poly succ-conf orig-poly rem-tile-types) tile) in sorted do (let* ((rem-polygons (remove orig-poly polygons))) (do-it (if (eq succ-conf :match) rem-polygons (append succ-conf rem-polygons )) rem-tile-types (cons (list aligned-poly tile) history)))))))))) (do-it polygon-set tile-types nil) solutions))) ;;; ;;; ;;; (defun alignment-result-heuristic-for-polygon (aligned-polygon conf orig-polygon rem-tile-types) (cond ((symbolp conf) ; :match! (list (tangram-geometry::calculate-area aligned-polygon) 0)) ((some #'(lambda (poly) (every #'(lambda (tile-type) (let ((tile (first tile-type))) ; use first reflected variant (< (+ (tangram-geometry::calculate-area poly) 2) ;; account for inaccuracies... hack (tangram-geometry::calculate-area (shape tile))))) rem-tile-types)) conf) :bad ) (t ;; score list for lexicographic tuple->-p sorting (list (tangram-geometry::calculate-area aligned-polygon) (- (count-if #'(lambda (p) (inside-p p orig-polygon)) (point-list aligned-polygon))) (apply #'min (mapcar #'(lambda (x) (- (compactness x))) conf)) (- (reduce #'+ (mapcar #'length (mapcar #'segments conf))))))))
21,104
Common Lisp
.lisp
430
25.130233
117
0.382661
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
d56d56c3e78d3c96587410606e793b25269617bd388db992ef0ffe707737964d
4,336
[ -1 ]
4,337
tests.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/persistence/tests.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: PERSISTENCE-MANAGER; Base: 10 -*- (in-package persistence-manager) ;;; ;;; ;;; (defpersistentclass test () ((a :accessor a :initarg :a) (b :accessor b :initarg :b))) (defpersistentclass test2 (test) ((c :accessor c :initarg :c))) (defun run-test () (setf table (let ((table (make-hash-table :test #'equal :size 100 :rehash-size 100))) (loop as i from 1 to 100 do (setf (gethash (list i i i) table) (loop as j from 1 to (+ i 10) collect (list (* j j ) (- (* j j )))))) table)) (setf x (make-instance 'test :a table)) (setf y (make-instance 'test :a x :b (make-array '(10)))) (setf z (make-instance 'test2 :c (list x y (make-array '(3) :initial-contents (list x y x))))) (setf orig (vector x y z (list x table (vector x z y) x z))) (make-object-persistent orig "test") (setf copy (load-persistent-object "test"))) (defpersistentstruct stest (a) (b)) (defpersistentstruct (stest2 (:include stest)) (c)) (defun run-stest () (setf table (let ((table (make-hash-table :test #'equal :size 100 :rehash-size 100))) (loop as i from 1 to 100 do (setf (gethash (list i i i) table) (loop as j from 1 to (+ i 10) collect (* j j )))) table)) (setf x (make-stest :a table)) (setf y (make-stest :a x :b (make-array '(10)))) (setf z (make-stest2 :c (list x y (make-array '(3) :initial-contents (list x y x))))) (setf orig (vector x y z (list x table (vector x z y) x z))) (make-object-persistent orig "test") (setf copy (load-persistent-object "test"))) (defun test () (with-open-file (stream "pertest" :element-type 'unsigned-byte :direction :output :if-exists :supersede :if-does-not-exist :create) (write-coded-string stream "das ist ein test!") (write-coded-integer stream 123) (write-coded-symbol stream 'clim::test) (write-coded-number stream 123.345) (write-coded-number stream 4/3) (write-coded-list stream (list 1 2 3 4)) (make-instance 'test :a table) ) (with-open-file (stream "pertest" :element-type 'unsigned-byte :direction :input) (list (read-coded-string stream) (read-coded-integer stream) (read-coded-symbol stream) (read-coded-number stream) (read-coded-number stream) (read-coded-list stream)))) (defun test () (make-object-persistent (list 'symbol 123 'clim::test "abcdef" 123.3 4/3 (list 'a 1 2 'b "xyz")) "pertest") (load-persistent-object "pertest"))
3,287
Common Lisp
.lisp
83
26.855422
98
0.492776
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
4b6fc92ae705e1502946c6e3e5b2e753001f80ff8720e1d0a094f9562d076b7e
4,337
[ -1 ]
4,338
persistence2.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/persistence/persistence2.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: PERSISTENCE-MANAGER; Base: 10 -*- (in-package tangram-persistence-manager) (defun print-persistence-manager-info (&optional (stream t)) (format stream ";;; The store/restore facility is based on software developed~%~ ;;; by Michael Wessel.~2%")) (cl:defstruct (big-vector (:constructor make-big-vector-internal)) n-elements n-subarrays (arrays nil)) (defconstant +max-n-of-array-elements+ (- array-total-size-limit 1)) (defun make-big-vector (dimension &key (initial-element nil)) (multiple-value-bind (n-subarrays-minus-1 size-of-rest-array) (floor dimension +max-n-of-array-elements+) (let ((big-vector (make-big-vector-internal))) (setf (big-vector-n-subarrays big-vector) (+ n-subarrays-minus-1 1)) (setf (big-vector-n-elements big-vector) dimension) (setf (big-vector-arrays big-vector) (coerce (append (loop repeat n-subarrays-minus-1 collect (make-array +max-n-of-array-elements+ :initial-element initial-element)) (list (make-array size-of-rest-array))) 'vector)) big-vector))) (declaim (inline bvref)) (defun bvref (big-array index) (multiple-value-bind (subarray-index index-of-rest-array) (floor index +max-n-of-array-elements+) (svref (svref (big-vector-arrays big-array) subarray-index) index-of-rest-array))) (declaim (inline (setf bvref))) (defun (setf bvref) (new-value big-array index) (multiple-value-bind (subarray-index index-of-rest-array) (floor index +max-n-of-array-elements+) (setf (svref (svref (big-vector-arrays big-array) subarray-index) index-of-rest-array) new-value))) ;;; ;;; ;;; (defconstant +persistence-version+ 3) (defconstant +n-bytes-for-written-objects+ 16) (defconstant +maximum-written-objects+ (- (expt 10 +n-bytes-for-written-objects+) 1)) ;;(defconstant +vector-size+ 1000000) (defconstant +hash-table-size+ 10000) (defconstant +rehash-size+ 40000) (defvar *read-objects* nil) ;; (make-array +vector-size+ :initial-element nil) (defvar *written-objects* (make-hash-table :test #'eql :size +hash-table-size+ :rehash-size +rehash-size+)) ;;; ;;; ;;; (defvar *io-id-counter* 0) (defvar *aux-counter* 0) (defvar *ref-counter* 0) (declaim (inline get-io-id-for create-io-id store retrieve write-coded-string1 write-coded-string read-coded-string write-coded-symbol read-coded-symbol write-coded-integer read-coded-integer write-coded-number read-coded-numer write-coded-marker read-coded-marker write-coded-list read-coded-list read-byte* unread-byte*)) ;;; ;;; ;;; (defun write-coded-string (stream string) (write-coded-integer stream (length string)) (loop as char across string do (write-byte (char-code char) stream))) (defun write-coded-string-1 (stream string) (loop as char across string do (write-byte (char-code char) stream))) (defun read-coded-string (stream) (let* ((n (read-coded-integer stream)) (string (make-string n :initial-element #\space))) (loop as i from 1 to n do (setf (aref string (1- i)) (code-char (read-byte stream)))) string)) (defun write-coded-symbol (stream symbol) (let* ((package (symbol-package symbol)) (name (symbol-name symbol)) (length (if (null package) (+ 2 (length name)) (+ (length (package-name package)) 2 (length name))))) (write-coded-integer stream length) (if (null package) (write-coded-string-1 stream "#:") (progn (write-coded-string-1 stream (package-name package)) (write-coded-string-1 stream "::"))) (write-coded-string-1 stream (symbol-name symbol)))) (defun read-coded-symbol (stream) (read-from-string (read-coded-string stream))) (defun write-coded-integer (stream num) (unless (integerp num) (error "You have given ~A to write-coded-integer!" num)) (let ((orig-num num) (num (abs num))) (loop (multiple-value-bind (div mod) (floor num 254) (write-byte mod stream) (setf num div) (when (= 0 div) (write-byte (if (minusp orig-num) 254 255) stream) (return-from write-coded-integer)))))) (defun read-coded-integer (stream) (let ((num 0) (index 1)) (loop (let ((byte (read-byte* stream))) (cond ((eq byte 'eof) (return-from read-coded-integer 'eof)) ((= byte 255) (return-from read-coded-integer num)) ((= byte 254) (return-from read-coded-integer (- num))) (t (incf num (* index byte)) (setf index (* index 254)))))))) (defun write-coded-number (stream num) (write-coded-string stream (write-to-string num))) (defun read-coded-number (stream) (read-from-string (read-coded-string stream))) (defun write-coded-marker (stream marker) (write-byte marker stream)) (defun read-coded-marker (stream) (read-byte* stream)) (defun write-coded-list (stream list) (write-coded-string stream (format nil "~S" list))) (defun read-coded-list (stream) (read-from-string (read-coded-string stream))) ;;; ;;; ;;; (defvar *last-byte-read* nil) (defvar *unread-occured-p* nil) (defun read-byte* (stream) (if (and *unread-occured-p* *last-byte-read*) (progn (setf *unread-occured-p* nil) *last-byte-read*) (let ((byte (read-byte stream nil 'eof))) (if (eq byte 'eof) (setf *last-byte-read* nil) (setf *last-byte-read* byte)) byte))) (defun unread-byte* () (setf *unread-occured-p* t)) ;;; ;;; ;;; (defun get-io-id-for (object) (or (gethash object *written-objects*) (error "Can't find object ~A!" object))) (defun create-io-id () (incf *io-id-counter*)) (defun store (io-id obj) (setf *io-id-counter* (max io-id *io-id-counter*)) (setf (bvref *read-objects* io-id) obj) obj) (defun retrieve (io-id) (or (bvref *read-objects* io-id) (error "Object ~A not found! Dangling pointer!" io-id))) (defun reset () (setf *io-id-counter* 0 *aux-counter* 0 *ref-counter* 0 *unread-occured-p* nil) (clrhash *written-objects*)) (defun read-reset (n-of-objects-to-read) (setf *io-id-counter* 0 *aux-counter* 0 *ref-counter* 0 *unread-occured-p* nil) (setf *read-objects* (make-big-vector (+ n-of-objects-to-read 3) :initial-element nil))) ;;; ;;; ;;; (cl:defclass persistent-object () ()) (defmethod write-object-constructor ((obj persistent-object) stream) (declare (ignore stream)) nil) (defmethod write-object-initializer ((obj persistent-object) stream) (declare (ignore stream)) nil) (defmethod fill-persistent-object ((obj persistent-object) stream) (declare (ignore stream)) nil) ;;; ;;; verhindere, da"s initialize-instance fuer Subklassen aufgerufen wird! ;;; (defmethod initialize-instance :around ((obj persistent-object) &rest initargs &key (dont-initialize nil)) (if (not dont-initialize) (progn (call-next-method)) ; normale Initialisierung (apply #'shared-initialize obj t initargs))) (defmethod initialize-loaded-persistent-object ((obj persistent-object)) nil) ;;; ;;; ;;; (cl:defstruct persistent-structure) (defmethod write-object-constructor ((obj persistent-structure) stream) (declare (ignore stream)) nil) (defmethod write-object-initializer ((obj persistent-structure) stream) (declare (ignore stream)) nil) (defmethod fill-persistent-object ((obj persistent-structure) stream) (declare (ignore stream)) nil) (defmethod initialize-loaded-persistent-object ((obj persistent-structure)) nil) ;;; ;;; ;;; (defconstant +string-marker+ 10) (defconstant +array-marker+ 20) (defconstant +hashtable-marker+ 30) (defconstant +cons-marker+ 40) (defconstant +nil-marker+ 50) (defconstant +integer-marker+ 60) (defconstant +number-marker+ 70) (defconstant +symbol-marker+ 80) (defconstant +object-marker+ 90) (defconstant +structure-marker+ 100) (defconstant +unbound-marker+ 110) (defconstant +section-marker+ 120) (defconstant +user-responsibility-marker+ 130) (defvar *secret-hashtable-size-key* (gensym "*#?@secret-")) ;;; ;;; ;;; (defmacro with-only-once-constructed-object ((object marker stream) &body body) `(unless (gethash ,object *written-objects*) (let ((io-id (create-io-id))) (setf (gethash ,object *written-objects*) io-id) (write-coded-marker ,stream ,marker) (write-coded-integer ,stream io-id) ,@body))) (defmethod write-constructor :after ((object t) stream) (declare (ignore stream)) (incf *ref-counter*)) ;;; ;;; ;;; (defmethod user-write-constructor (stream (object t)) (error "Please create a method \"USER-WRITE-CONSTRUCTOR (STREAM (OBJECT ~S))\" and use subsequent calls to \"(USER-WRITE-COMPONENT-CONSTRUCTOR STREAM COMPONENT)\" to construct the component objects of the object!" (type-of object))) (defmethod user-write-component-constructor (stream (object t)) (write-constructor object stream)) ;;; ;;; ;;; (defmethod write-constructor ((object t) stream) (with-only-once-constructed-object (object +user-responsibility-marker+ stream) (write-coded-symbol stream (type-of object)) (user-write-constructor stream object)) (values)) (defmethod write-constructor ((object null) stream) (declare (ignore stream)) (values)) (defmethod write-constructor ((object number) stream) (declare (ignore stream)) (values)) (defmethod write-constructor ((object cons) stream) (with-only-once-constructed-object (object +cons-marker+ stream) (write-constructor (car object) stream) (write-constructor (cdr object) stream)) (values)) (defmethod write-constructor ((object string) stream) (with-only-once-constructed-object (object +string-marker+ stream) (write-coded-string stream object)) (values)) (defmethod write-constructor ((object symbol) stream) (with-only-once-constructed-object (object +symbol-marker+ stream) (write-coded-symbol stream object)) (values)) (defmethod write-constructor ((object array) stream) (with-only-once-constructed-object (object +array-marker+ stream) (write-coded-list stream (array-dimensions object)) (dotimes (i (array-total-size object)) (write-constructor (row-major-aref object i) stream))) (values)) (defmethod write-constructor ((object hash-table) stream) (with-only-once-constructed-object (object +hashtable-marker+ stream) (write-coded-integer stream (hash-table-count object)) (write-coded-integer stream (hash-table-size object)) (write-coded-integer stream (hash-table-rehash-size object)) (write-coded-number stream (hash-table-rehash-threshold object)) (write-coded-symbol stream (hash-table-test object)) (maphash #'(lambda (key value) (write-constructor key stream) (write-constructor value stream)) object)) (values)) (defmethod write-constructor ((object persistent-object) stream) (write-constructor (type-of object) stream) (with-only-once-constructed-object (object +object-marker+ stream) (write-referencer (type-of object) stream) (write-object-constructor object stream)) (values)) (defmethod write-constructor ((object persistent-structure) stream) (write-constructor (type-of object) stream) (with-only-once-constructed-object (object +structure-marker+ stream) (write-referencer (type-of object) stream) (write-object-constructor object stream)) (values)) ;;; ;;; ;;; (defmacro with-complex-object-header ((stream object) &body body) `(progn (write-coded-integer ,stream (get-io-id-for ,object)) ,@body)) (defun write-referencer (object stream) (typecase object (null (write-coded-marker stream +nil-marker+)) ((or cons array hash-table string symbol persistent-object) (write-coded-marker stream +object-marker+) (write-coded-integer stream (get-io-id-for object))) (persistent-structure (write-coded-marker stream +structure-marker+) (write-coded-integer stream (get-io-id-for object))) (integer (write-coded-marker stream +integer-marker+) (write-coded-integer stream object)) (number (write-coded-marker stream +number-marker+) (write-coded-number stream object)) (otherwise (write-coded-marker stream +user-responsibility-marker+) (write-coded-integer stream (get-io-id-for object))))) ;;; ;;; ;;; (defmethod user-write-initializer (stream (object t)) (error "Please create a method \"USER-WRITE-INITIALIZER (STREAM (OBJECT ~S))\" and use subsequent calls to \"(USER-WRITE-COMPONENT-INITIALIZER STREAM COMPONENT)\" to initialize the component objects of the object!" (type-of object))) (defmethod user-write-component-initializer (stream (object t)) (write-referencer object stream)) ;;; ;;; ;;; (defmethod write-initializer ((object t) stream) (with-complex-object-header (stream object) (user-write-initializer stream object)) (values)) (defmethod write-initializer ((object string) stream) (values)) (defmethod write-initializer ((object symbol) stream) (values)) (defmethod write-initializer ((object cons) stream) (with-complex-object-header (stream object) (write-referencer (car object) stream) (write-referencer (cdr object) stream)) (values)) (defmethod write-initializer ((object array) stream) (with-complex-object-header (stream object) (dotimes (i (array-total-size object)) (write-referencer (row-major-aref object i) stream))) (values)) (defmethod write-initializer ((object hash-table) stream) (with-complex-object-header (stream object) (maphash #'(lambda (key value) (write-referencer key stream) (write-referencer value stream)) object)) (values)) (defmethod write-initializer ((object persistent-object) stream) (with-complex-object-header (stream object) (write-object-initializer object stream)) (values)) (defmethod write-initializer ((object persistent-structure) stream) (with-complex-object-header (stream object) (write-object-initializer object stream)) (values)) ;;; ;;; ;;; (defmethod fill-object ((object symbol) stream) (declare (ignore stream)) object) (defmethod fill-object ((object string) stream) (declare (ignore stream)) object) (defmethod fill-object ((object cons) stream) (declare (ignore stream)) (setf (car object) (read-value stream)) (setf (cdr object) (read-value stream)) object) (defmethod fill-object ((object array) stream) (dotimes (i (array-total-size object)) (setf (row-major-aref object i) (read-value stream))) object) (defmethod fill-object ((object hash-table) stream) (dotimes (i (gethash *secret-hashtable-size-key* object)) (let ((key (read-value stream)) (value (read-value stream))) (setf (gethash key object) value))) (remhash *secret-hashtable-size-key* object) object) (defmethod fill-object ((object persistent-object) stream) (fill-persistent-object object stream) object) (defmethod fill-object ((object persistent-structure) stream) (fill-persistent-object object stream) object) (defmethod fill-object ((object t) stream) (user-fill-object stream object)) ;;; ;;; ;;; (defmethod user-fill-object (stream (object t)) (error "Please create a method \"USER-FILL-OBJECT (STREAM (OBJECT ~S))\" and use subsequent calls to \"(USER-READ-COMPONENT-OBJECT STREAM)\" to read-in and get the component objects of the object; assign these to the appropriate places within the ~S and return the object!" (type-of object) (type-of object))) (defmethod user-read-component-object (stream) (read-value stream)) ;;; ;;; ;;; (defun read-value (stream) (let ((marker (read-coded-marker stream))) (cond ((or (= marker +object-marker+) (= marker +structure-marker+) (= marker +array-marker+) (= marker +hashtable-marker+) (= marker +user-responsibility-marker+)) (values (retrieve (read-coded-integer stream)))) ((= marker +nil-marker+) (values nil)) ((= marker +integer-marker+) (values (read-coded-integer stream))) ((= marker +number-marker+) (values (read-coded-number stream))) ((= marker +unbound-marker+) (values nil)) (t (error "Bad marker ~A in read-value!" marker))))) (defun probe-bound-p (stream) (let ((marker (read-coded-marker stream))) (prog1 (not (= marker +unbound-marker+)) (unread-byte*)))) (defmethod user-create-empty-object ((type t)) (error "Please create a method \"USER-CREATE-EMPTY-OBJECT (TYPE (EQL '~S))\" that creates an EMPTY container object of type ~S!" type type)) (defun construct-object (stream) (loop (let ((marker (read-coded-marker stream))) (if (or (= marker +section-marker+) (eq marker 'eof)) (return) (let ((id (read-coded-integer stream))) (store id (cond ((= marker +string-marker+) (read-coded-string stream)) ((= marker +symbol-marker+) (read-coded-symbol stream)) ((= marker +cons-marker+) (cons (incf *aux-counter*) nil)) ((= marker +array-marker+) (make-array (read-coded-list stream))) ((= marker +hashtable-marker+) (let* ((no-of-entries (read-coded-integer stream)) (size (read-coded-integer stream)) (rehash-size (read-coded-integer stream)) (rehash-threshold (read-coded-number stream)) (test (read-coded-symbol stream)) (table (make-hash-table :size size :rehash-size rehash-size :rehash-threshold rehash-threshold :test test))) (setf (gethash *secret-hashtable-size-key* table) no-of-entries) table)) ((= marker +object-marker+) (make-instance (read-value stream) :allow-other-keys t :dont-initialize t)) ((= marker +structure-marker+) (funcall (structure-initializer (read-value stream)))) ((= marker +user-responsibility-marker+) (let ((type (read-coded-symbol stream))) (user-create-empty-object type))) (t (error "Unknown marker: ~A." marker))))))))) (defun initialize-object (stream) (loop (let ((io-id (read-coded-integer stream))) (if (eq io-id 'eof) (return) (fill-object (retrieve io-id) stream))))) ;;; ;;; ;;; (defmacro defpersistentclass (&rest rest) `(progn ,@(let* ((name (first rest)) (superclasses (append (second rest) '(persistent-object))) (body (third rest)) (slotnames (mapcar #'first body))) (list `(cl:defclass ,name ,superclasses ,(loop for slotspec in body collect (remove :not-persistent slotspec))) `(defmethod write-object-constructor ((obj ,name) stream) #+:allegro (declare (ignore-if-unused stream)) #+:lispworks (declare (ignore stream)) #+:mcl (declare (ccl:ignore-if-unused stream)) (with-slots ,slotnames obj ,@(mapcan #'(lambda (slot) (let ((name (first slot))) (unless (member :not-persistent slot) `((when (slot-boundp obj ',name) (write-constructor ,name stream)))))) (reverse body))) (call-next-method)) `(defmethod write-object-initializer ((obj ,name) stream) #+:allegro (declare (ignore-if-unused stream)) #+:lispworks (declare (ignore stream)) #+:mcl (declare (ccl:ignore-if-unused stream)) (progn ;;with-slots ,slotnames obj ,@(mapcan #'(lambda (slot) (let ((name (first slot))) (unless (member :not-persistent slot) `((if (slot-boundp obj ',name) (write-referencer (slot-value obj ',name) stream) (write-coded-marker stream +unbound-marker+)))))) (reverse body))) (call-next-method)) `(defmethod fill-persistent-object ((obj ,name) stream) #+:allegro (declare (ignore-if-unused stream)) #+:lispworks (declare (ignore stream)) #+:mcl (declare (ccl:ignore-if-unused stream)) (let (val unbound) #+:allegro (declare (ignore-if-unused val unbound)) #+:lispworks (declare (ignore val unbound)) #+:mcl (declare (ccl:ignore-if-unused val unbound)) (with-slots ,slotnames obj ,@(mapcan #'(lambda (slot) (let ((name (first slot))) (unless (member :not-persistent slot) `((if (probe-bound-p stream) (setf ,name (read-value stream)) (read-value stream)))))) (reverse body))) (call-next-method))) (list 'quote name))))) (defmacro defclass (&rest forms) `(defpersistentclass .,forms)) ;;; ;;; ;;; (cl:defstruct structure-info name options slot-specifications slotnames initializer) (defvar *structures* (make-hash-table)) (defun find-structure (name &key (error-p t)) (let ((result (gethash name *structures*))) (if (null result) (if error-p (error "Cannot find structure with name ~A." name) nil) result))) (defun (setf find-structure) (new-value name) (if (null new-value) (remhash name *structures*) (setf (gethash name *structures*) new-value))) (defmacro with-structure-slots (structure-name slotnames obj &body forms) `(symbol-macrolet ,(mapcar (lambda (slotname) (list slotname (structure-slot-accessor structure-name slotname obj))) slotnames) .,forms)) (defun structure-slot-accessor (structure-name slotname obj) (let ((conc-name (or (second (find ':conc-name (structure-info-options (find-structure structure-name)) :key #'first)) (concatenate 'string (symbol-name structure-name) "-")))) (if (symbolp conc-name) (setf conc-name (symbol-name conc-name))) (list (intern (concatenate 'string conc-name (symbol-name slotname)) (symbol-package structure-name)) obj))) (defun set-structure-initializer (structure-entry) (let* ((user-defined-constructor (find ':constructor (structure-info-options structure-entry) :key #'first)) (constructor (if user-defined-constructor (let ((arguments (required-arguments (third user-defined-constructor)))) (if arguments #'(lambda () (apply (second user-defined-constructor) (loop repeat (length arguments) collect nil))) (second user-defined-constructor))) (intern (concatenate 'string "MAKE-" (symbol-name (structure-info-name structure-entry))) (symbol-package (structure-info-name structure-entry)))))) (setf (structure-info-initializer structure-entry) constructor))) (defun required-arguments (arguments) (if (null arguments) nil (if (member (first arguments) '(&rest &key &optional &allow-other-keys)) nil (cons (first arguments) (required-arguments (rest arguments)))))) (declaim (inline structure-initializer)) (defun structure-initializer (structure-name) (structure-info-initializer (find-structure structure-name))) (defun all-structure-slots (structure-entry) (let ((included-structure-name (structure-info-included-structure structure-entry))) (if (null included-structure-name) (structure-info-slotnames structure-entry) (append (structure-info-slotnames structure-entry) (all-structure-slots (find-structure included-structure-name)))))) (defun structure-info-included-structure (structure-entry) (second (find ':include (structure-info-options structure-entry) :key #'first))) (defun real-structure-p (options) (not (find ':type options :key #'first))) (defmacro defpersistentstruct (name-or-name-and-specifications &rest doc-and-slots) (let* ((name (if (consp name-or-name-and-specifications) (first name-or-name-and-specifications) name-or-name-and-specifications)) (options (if (consp name-or-name-and-specifications) (rest name-or-name-and-specifications) nil)) (include (second (find ':include options :key #'first))) (documentation (if (stringp (first doc-and-slots)) (list (first doc-and-slots)))) (slots (if documentation (rest doc-and-slots) doc-and-slots)) (slot-specifications (mapcar (lambda (slot-spec) (cond ((symbolp slot-spec) (list slot-spec nil)) ((consp slot-spec) slot-spec) (t (error "Illegal slot specification: ~A." slot-spec)))) slots)) (slotnames (mapcar #'first slot-specifications)) all-slotnames (structure-entry-var (gensym)) (structure-entry (find-structure name :error-p nil))) (if structure-entry (setf (structure-info-options structure-entry) options (structure-info-slot-specifications structure-entry) slots (structure-info-slotnames structure-entry) slotnames) (setf structure-entry (make-structure-info :name name :options options :slot-specifications slot-specifications :slotnames slotnames))) (set-structure-initializer structure-entry) (setf (find-structure name) structure-entry) (setf all-slotnames (all-structure-slots structure-entry)) (if (real-structure-p options) `(progn (let ((,structure-entry-var (find-structure ',name :error-p nil))) (if ,structure-entry-var (setf (structure-info-options ,structure-entry-var) ',options (structure-info-slot-specifications ,structure-entry-var) ',slots (structure-info-slotnames ,structure-entry-var) ',slotnames) (setf ,structure-entry-var (make-structure-info :name ',name :options ',options :slot-specifications ',slot-specifications :slotnames ',slotnames))) (set-structure-initializer ,structure-entry-var) (setf (find-structure ',name) ,structure-entry-var)) (cl:defstruct (,name .,(if (null include) (cons (list :include 'persistent-structure) options) options)) ,@documentation .,slot-specifications) (defmethod write-object-constructor ((obj ,name) stream) #+:allegro (declare (ignore-if-unused stream)) #+:lispworks (declare (ignore stream)) #+:mcl (declare (ccl:ignore-if-unused stream)) (with-structure-slots ,name ,all-slotnames obj ,@(mapcan #'(lambda (slotname) `((write-constructor ,slotname stream))) all-slotnames))) (defmethod write-object-initializer ((obj ,name) stream) #+:allegro (declare (ignore-if-unused stream)) #+:lispworks (declare (ignore stream)) #+:mcl (declare (ccl:ignore-if-unused stream)) (with-structure-slots ,name ,all-slotnames obj ,@(mapcan #'(lambda (slotname) `((write-referencer ,slotname stream))) all-slotnames))) (defmethod fill-persistent-object ((obj ,name) stream) #+:allegro (declare (ignore-if-unused stream)) #+:lispworks (declare (ignore stream)) #+:mcl (declare (ccl:ignore-if-unused stream)) (with-structure-slots ,name ,all-slotnames obj ,@(mapcan #'(lambda (slotname) `((setf ,slotname (read-value stream)))) all-slotnames))) ',name) `(cl:defstruct (,name .,options) ,@documentation .,slot-specifications)))) (defmacro defstruct (&rest forms) `(defpersistentstruct .,forms)) ;;; ;;; ;;; (defconstant +file-type-marker+ 66647963) (defun write-section-separator (stream) (write-coded-marker stream +section-marker+)) (defun generate-temp-filename (filename) (let* ((pathname (pathname filename)) (name (pathname-name pathname)) new-name) (loop for i from 1 to 100 do (when (not (probe-file (setf new-name (merge-pathnames (concatenate 'string name "_" (format nil "~D" i)) pathname)))) (return-from generate-temp-filename new-name))) (error "Cannot generate name for temp file."))) (defun make-object-persistent (obj fn &optional (package *package*)) (let ((filename (generate-temp-filename fn))) (handler-case (progn (with-open-file (stream filename :element-type 'unsigned-byte :direction :output :if-exists :supersede :if-does-not-exist :create) (let ((*package* package)) (reset) (write-coded-integer stream +file-type-marker+) (write-coded-string stream (make-string +n-bytes-for-written-objects+ :initial-element #\space)) (write-coded-string stream (package-name package)) (write-coded-integer stream +persistence-version+) (write-constructor (list obj) stream) (write-section-separator stream) (maphash #'(lambda (key value) (declare (ignore value)) (write-initializer key stream)) *written-objects*))) (when (> *io-id-counter* +maximum-written-objects+) (error "Maximum number of objects per file (~D) exceeded." +maximum-written-objects+)) (with-open-file (stream filename :element-type 'unsigned-byte :direction :output :if-exists :overwrite :if-does-not-exist :create) (write-coded-integer stream +file-type-marker+) (write-coded-string stream (format nil (concatenate 'string "~" (format nil "~D" +n-bytes-for-written-objects+) ",d") *io-id-counter*))) (when (probe-file fn) (delete-file fn )) (rename-file filename fn) (format nil "~A objects and ~A references have been written to ~A." *io-id-counter* *ref-counter* fn)) (error (c) (format *error-output* "~A" c) (when (probe-file filename) (delete-file filename)) nil)))) (defun load-persistent-object (fn &key (initialization-protocol t)) (with-open-file (stream fn :direction :input :element-type 'unsigned-byte) (let ((file-type-marker (read-coded-integer stream))) (unless (= file-type-marker +file-type-marker+) (error "File ~S is not a Racer dump file." fn)) (let* ((n-of-objects-to-read (read-from-string (read-coded-string stream))) (package-name (read-coded-string stream)) (package (find-package package-name)) (*package* (or package (error "Cannot restore object: Package ~S not found." package-name))) (version (read-coded-integer stream))) (unless (= version +persistence-version+) (error "Dump file format of ~A not compatible with current version of Racer." fn)) (read-reset n-of-objects-to-read) (construct-object stream) (initialize-object stream) (when initialization-protocol (dotimes (i (+ 2 *io-id-counter*)) (let ((obj (bvref *read-objects* i))) (when (or (typep obj 'persistent-object) (typep obj 'persistent-structure)) (initialize-loaded-persistent-object obj))))) (let ((result (first (retrieve 1)))) (setf *read-objects* nil) (values result (format nil "Loaded ~A objects from ~A." (+ 2 *io-id-counter*) fn) #|(loop as i from 1 to *io-id-counter* when (typep (retrieve i) 'persistent-object) collect (retrieve i))|#)))))) ;;; ;;; How to enable the framework to store and restore CLIM's RGB-COLOR objects! ;;; (defmethod user-write-constructor (stream (object clim-utils:rgb-color)) ;; write appropriate component constructors for the object ;; (the frame work doesn't know the structure of the object!) (multiple-value-bind (r g b) (clim-utils::color-rgb object) (user-write-component-constructor stream r) ;; not strictly necessary if the component objects are (user-write-component-constructor stream g) ;; atomic values (e.g., symbols or numbers), but (user-write-component-constructor stream b) ;; doesn't harm the frame work either (values))) (defmethod user-write-initializer (stream (object clim-utils:rgb-color)) (multiple-value-bind (r g b) (clim-utils::color-rgb object) (user-write-component-initializer stream r) ;; ensure to write-out the component objects (user-write-component-initializer stream g) ;; (numbers in this case) (user-write-component-initializer stream b))) (defmethod user-create-empty-object ((type (eql 'clim-utils::rgb-color))) ;; create an "empty container" object of appropriate type, return it ;; in this case, ensure that CLIM really creates an RGB-COLOR object ;; (and not just a GRAY-COLOR object!) (clim::make-rgb-color 0.1 0.2 0.3)) (defmethod user-fill-object (stream (object clim-utils::rgb-color)) ;; read in the component values and assign them to appropriate places within object ;; don't forget to return the object! (with-slots (clim-utils::red clim-utils::green clim-utils::blue) object (setf clim-utils::red (user-read-component-object stream) clim-utils::green (user-read-component-object stream) clim-utils::blue (user-read-component-object stream))) object) ;;; ;;; Same Thing for Gray Colors ;;; ;;; ;;; aus irgendeinem Grund gibt der "make-gray-color"-Konstruktor ;;; u.U. ein bereits konstruiertes (falsches!) Farb-Objekt zurück! ;;; Funktioniert also nicht richtig... ;;; (defmethod user-write-constructor (stream (object clim-utils:gray-color)) (with-slots (clim-utils::luminosity) object (user-write-component-constructor stream clim-utils::luminosity) (values))) (defmethod user-write-initializer (stream (object clim-utils:gray-color)) (with-slots (clim-utils::luminosity) object (user-write-component-initializer stream clim-utils::luminosity))) (defmethod user-create-empty-object ((type (eql 'clim-utils::gray-color))) (clim::make-gray-color 0.3)) (defmethod user-fill-object (stream (object clim-utils::gray-color)) (setf (slot-value object 'clim-utils::luminosity) (user-read-component-object stream)) object)
36,510
Common Lisp
.lisp
896
32.738839
112
0.627651
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
da4acaf13cd8e2a02901fd44ff2f6f66e73b7ff2b5468d5d1e50a2b4c5b76d86
4,338
[ -1 ]
4,339
aux8.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/tools/aux8.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: CL-USER; Base: 10 -*- (in-package cl-user) (defconstant +pi/2+ (/ pi 2)) (defconstant +2pi+ (* 2 pi)) ;;; ;;; ;;; (defun yes (&rest args) (declare (ignore args)) t) (defun no (&rest args) (declare (ignore args)) nil) ;;; ;;; ;;; (defparameter *round-p* t) ;; when t -> Koordinaten werden auf "Round precision"-Stellen Genauigkeit reduziert (defparameter *rounding-precision* 10) (defmacro my-round (num) `(if *round-p* (/ (floor (+ (* ,num *rounding-precision*) 1/2)) *rounding-precision*) ,num)) ;;; ;;; ;;; (defun forcecdr (stream &key num (fn #'identity)) (let ((res nil) (count 0)) (loop while (and stream (if (numberp num) (< count num) t)) do (incf count) (push (funcall fn (first stream)) res) (setf stream (funcall (second stream)))) (reverse res))) #+(or allegro mcl) (defun get-lambda-args (fn) (nreverse (mapcar #'(lambda (arg) (if (consp arg) (first arg) arg)) (set-difference #+:allegro (excl:arglist fn) #+:mcl (arglist fn) '(&rest &optional &key))))) (defun set-disjoint (a b) (and (not (some #'(lambda (i) (member i b)) a)) (not (some #'(lambda (i) (member i a)) b)))) (defun set-equal (a b &rest args) (and (apply #'subsetp a b args) (apply #'subsetp b a args))) (defun make-cyclic (x) (when x (setf (cdr (last x)) x))) ;;; ;;; ;;; #| (defconstant +epsilon+ 1e-6) (defmacro zerop-eps (a) `(=-eps 0 ,a)) (defmacro =-eps (a b &optional (epsilon +epsilon+)) `(<= (abs (- ,a ,b)) ,epsilon)) (defmacro <=-eps (a b &optional (epsilon +epsilon+)) `(<= ,a (+ ,b ,epsilon))) (defmacro >=-eps (a b &optional (epsilon +epsilon+)) `(>= ,a (- ,b ,epsilon))) |# ;;; ;;; ;;; ;(defun => (a b) ; (or (not a) b)) (defmacro => (a b) `(or (not ,a) ,b)) (defmacro <=> (a b) `(and (=> ,a ,b) (=> ,b ,a))) (defmacro xor (&rest args) `(or ,@(mapcar #'(lambda (arg) `(and ,arg ,@(mapcar #'(lambda (arg) `(not ,arg)) (remove arg args :count 1)))) args))) (defun ensure-list (arg) (if (listp arg) arg (list arg))) ;;; ;;; ;;; (defmacro rotate-to (list n) `(rotate-by ,list (position ,n ,list))) (defmacro rotate-by (list n) `(progn (when (and ,n ,list) (let ((n (mod ,n (length ,list)))) (unless (zerop n) (setf ,list (nconc (subseq ,list n) (subseq ,list 0 n)))))) ,list)) ;;; ;;; ;;; (defun tree-reverse (liste) (labels ((do-it (liste akku) (cond ((null liste) akku) (t (let ((first (first liste))) (do-it (rest liste) (cons (if (listp first) (do-it first nil) first) akku))))))) (do-it liste nil))) (defun tree-remove (item tree) (cond ((not (consp tree)) (if (eq item tree) nil tree)) (t (let ((car (tree-remove item (car tree))) (cdr (tree-remove item (cdr tree)))) (if car (cons car cdr) cdr))))) (defun tree-collect-if (fn tree) (let ((items nil)) (labels ((do-it (tree) (if (and tree (not (consp tree))) (when (funcall fn tree) (push tree items)) (when tree (do-it (car tree)) (do-it (cdr tree)))))) (do-it tree) items))) (defun tree-find (tree x &rest args) (or (apply #'member x tree args) (some #'(lambda (sub) (and (consp sub) (apply #'tree-find sub x args))) tree))) (defun tree-find-if (fn tree &rest args) (some #'(lambda (sub) (cond ((consp sub) (apply #'tree-find-if fn sub args)) (t (apply fn sub args)))) tree)) (defun tflatten (tree) (if (consp tree) (append (tflatten (car tree)) (tflatten (cdr tree))) (when tree (list tree)))) ;;; ;;; ;;; (defun one-of (sequence) (elt sequence (random (length sequence)))) ;;; ;;; ;;; (defun subseq-member (seqa sequence) (let ((n (length seqa))) (some #'(lambda (item) (loop as seq on item when (equal (subseq seq 0 (min n (length seq))) seqa) return t)) sequence))) (defmacro enqueue (elem queue) `(setf ,queue (nconc ,queue (list ,elem)))) (defmacro dequeue (queue) `(prog1 (first (last ,queue)) (setf ,queue (butlast ,queue)))) (defun reorder (sequence) (let ((res nil) (sequence (copy-list sequence)) (length (length sequence))) (loop (when (null sequence) (return res)) (let ((elem (elt sequence (random length)))) (push elem res) (setf sequence (delete elem sequence :count 1) length (1- length)))))) ;;; ;;; ;;; (defun splice-in (sym list) (append (mapcan #'(lambda (x) (list x sym)) (butlast list)) (last list))) (defun build-elem-pairs-in-list (list) (let ((res nil) (pre nil) (succ (copy-list list))) (loop (unless (cdr succ) (return res)) (push (append pre (cons (list (first succ) (second succ)) (cddr succ))) res) (setf pre (append pre (list (first succ)))) (setf succ (cdr succ))))) (defun stringsubst-char-with-string (orgstring char string) (let ((pos (position char orgstring))) (if pos (concatenate 'string (subseq orgstring 0 pos) string (stringsubst-char-with-string (subseq orgstring (1+ pos)) char string)) orgstring))) (defparameter *replacements* `(("--" "-" t) (" " " " t))) (defun blank-line-p (line) (or (eq line 'newline) (and (typep line 'string) (not (position-if-not #'(lambda (i) (char= i #\space)) line))))) (defun string-substitute (string &optional (rules *replacements*) &key add-spaces) (labels ((do-it (string akku) (cond ((blank-line-p string) akku) (t (let ((min-pos nil) (min-from-to)) (dolist (from-to rules) (let* ((from (first from-to)) (pos (search from string))) (when pos (if (or (not min-pos) (< pos min-pos)) (setf min-from-to from-to min-pos pos))))) (let ((from (first min-from-to)) (to (second min-from-to)) (replaced-as-new-input-p (third min-from-to))) (if min-pos (if replaced-as-new-input-p (do-it (concatenate 'string to (subseq string (+ min-pos (length from)))) (append akku (list (subseq string 0 min-pos)))) (do-it (subseq string (+ min-pos (length from))) (append akku (list (subseq string 0 min-pos)) (list to)))) (append akku (list string))))))))) (let ((res (do-it (if add-spaces (concatenate 'string " " string " ") string) nil))) (if res (reduce #'(lambda (x y) (concatenate 'string x y)) res) "")))) (defun transform-xy-list (xylist) (loop for x in xylist by #'cddr for y in (cdr xylist) by #'cddr collect (list x y))) (defmacro pushend (obj list) `(setf ,list (nconc ,list (list ,obj)))) (defmacro mynconc (lista listb) `(setf ,lista (nconc ,lista ,listb))) (defmacro my-format (stream indent-level string &rest args) `(progn (dotimes (i (* 7 ,indent-level)) (princ " " ,stream)) (format ,stream ,string ,@args))) (defmacro my-read (stream) #+:allegro `(read ,stream) #+(or mcl lispworks) `(read-from-string (read-line ,stream))) #+(or allegro lispworks) (defun circle-subseq (list from to) (let* ((copy (copy-list list))) (setf (rest (last copy)) copy) (subseq copy from to))) #+:mcl (defun circle-subseq (list from to) (let* ((copy (copy-list list))) (setf (rest (last copy)) copy) (let ((start copy)) (loop repeat from do (setf start (cdr start))) (loop repeat (- to from) collect (car start) do (setf start (cdr start)))))) #+:allegro (defun recode-german-characters (string) (nsubstitute (character 228) (character 204) string) ; dos aeh -> unix aeh (nsubstitute (character 246) (character 224) string) ; dos oeh -> unix oeh (nsubstitute (character 252) (character 201) string) ; dos ueh -> unix ueh (nsubstitute (character 196) (character 216) string) ; dos AEH -> unix AEH (nsubstitute (character 214) (character 231) string) ; dos OEH -> unix OEH (nsubstitute (character 220) (character 232) string) ; dos UEH -> unix UEH (nsubstitute (character 223) #\· string) ; dos sz -> unix sz (nsubstitute (character 228) (character 132) string) ; siemens aeh -> unix aeh ; dxf (nsubstitute (character 246) (character 148) string) ; siemens oeh -> unix oeh ; dxf (nsubstitute (character 252) (character 129) string) ; siemens ueh -> unix ueh ; dxf (nsubstitute (character 214) (character 153) string) ; siemens OEH -> unix OEH ; andere Code unbekannt! ; dxf (nsubstitute (character 228) (character #xbf) string) ; siemens aeh -> unix aeh ; sqd (nsubstitute (character 246) (character #xd0) string) ; siemens oeh -> unix oeh ; sqd (nsubstitute (character 252) (character #xdd) string) ; siemens ueh -> unix ueh ; sqd (nsubstitute (character 214) (character #xf0) string) ; siemens OEH -> unix OEH ; andere Codes sind unbekannt! ; dxf (nsubstitute (character 223) (character #xc5) string) ; dos sz -> unix sz ; dxf string) #+:lispworks (defun recode-german-characters (string) (dolist (subs '((#\Ö #\U+0095) (#\Ö #\U+0099) (#\ß #\U+0089) (#\ß #\á) (#\ä #\ø) (#\ä #\U+0084) (#\ü #\ð) (#\ü #\U+0081) (#\ö #\Soft-Hyphen) (#\ö #\U+0094))) (nsubstitute (first subs) (second subs) string)) string) #+:mcl (defun recode-german-characters (string) string) ;;; ;;; ;;; (defun compute-all-subsets (set &optional (akku '(nil))) (let ((newakku akku)) (mapl #'(lambda (lset) (let ((item (first lset))) (unless (some #'(lambda (set) (member item set)) newakku) (dolist (expand akku) (let ((new (cons item expand))) (push new newakku))) (setf newakku (compute-all-subsets (rest lset) newakku))))) set) newakku)) (defun prod-pow-n (xs n) (if (= n 1) (mapcar #'list xs) (prodnx (loop as i from 1 to n collect xs)))) (defun prod (xs ys) (reduce #'nconc (mapcar #'(lambda (x) (mapcar #'(lambda (y) (list x y)) ys)) xs))) (defun prodn (&rest args) (reduce #'prod args)) (defun prodnx (arguments) (reduce #'prod arguments)) (defun newprod (list-of-args) (if (not (cdr list-of-args)) list-of-args (let ((list (first list-of-args)) (res (newprod (rest list-of-args)))) (if (not (cddr list-of-args)) (apply #'append (mapcar #'(lambda (elem1) (mapcar #'(lambda (elem2) (list elem1 elem2)) (first list-of-args))) (second list-of-args))) (apply #'append (mapcar #'(lambda (list2) (mapcar #'(lambda (elem1) (cons elem1 list2)) list)) res)))))) (defun power (xs n) (mapcar #'tflatten (prod-pow-n xs n))) #| (defun perm (list) (if (cdr list) (remove-duplicates (mapcan #'(lambda (a) (let ((rest (remove a list :count 1))) (mapcar #'(lambda (rest) (cons a rest)) (perm rest)))) list) :test #'equal) (list list))) |# (defun permutations (list &optional (n (length list)) (i 0)) (perm list n i)) (defun perm (list &optional (n (length list)) (i 0)) ;;; choose "k" out of "n" (if (= i n) '(nil) (remove-duplicates (mapcan #'(lambda (a) (let ((rest (remove a list :count 1))) (mapcar #'(lambda (rest) (cons a rest)) (perm rest n (1+ i))))) list) :test #'equal))) ;;; ;;; ;;; (defun fac (n) (if (zerop n) 1 (* n (fac (1- n))))) (defun n-over-k (n k) (/ (fac n) (* (fac (- n k)) (fac k)))) (defun k-out-of-n (k n) (/ (fac n) (fac (- n k)))) ;;; ;;; ;;; (defun vector-orientation (fromx fromy tox toy) (let ((dx (let ((d (- tox fromx))) (if (< (abs d) 0.0001) 0 d))) (dy (let ((d (- toy fromy))) (if (< (abs d) 0.0001) 0 d)))) (if (and (zerop dx) (zerop dy)) (error "~A ~A. Degenerate point vector - no orientation!" dx dy) (if (zerop dy) (if (plusp dx) 0 pi) (if (zerop dx) (if (plusp dy) (/ pi 2) (* 3/2 pi)) (if (plusp dx) (if (plusp dy) (atan (/ dy dx)) (- (* 2 pi) (atan (/ (abs dy) dx)))) (if (plusp dy) ;;; (minusp dx) (- pi (atan (/ dy (abs dx)))) (+ pi (atan (/ (abs dy) (abs dx))))))))))) (defun intervall-intersects-p (a b c d) (not (or (< b c) (< d a)))) (defun lies-in-circle-intervall-p (x a b) (if (= a b) t (if (<= a b) (<= a x b) (or (>= b x) (>= x a))))) (defun circle-intervall-intersects-p (a b c d) (or (lies-in-circle-intervall-p b c d) (lies-in-circle-intervall-p d a b))) (defun circle-intervall-length (a b &optional (modulo +2pi+)) (if (<= a b) (- b a) (+ (- modulo a) b))) ;;; ;;; ;;; (defun rad-to-deg (phi) (* 180 (/ phi pi))) (defun deg-to-rad (phi) (* pi (/ phi 180))) ;;; ;;; ;;; (defparameter *use-store* t) (defvar *all-tables* nil) (defun reset-memo () (mapc #'clrhash *all-tables*)) (defmacro defun-memo (function-name lambda-list (params-to-memoize &rest hash-args) &body body) (let ((hash (apply #'make-hash-table (append '(:test equal) hash-args)))) (push hash *all-tables*) `(defun ,function-name ,lambda-list (if *use-store* (multiple-value-bind (ret found-p) (gethash (list ,@params-to-memoize) ,hash) (if found-p (apply #'values ret) (apply #'values (setf (gethash (list ,@params-to-memoize) ,hash) (multiple-value-list (progn ,@body)))))) (progn ,@body))))) (defmacro defmethod-memo (method-name lambda-list (params-to-memoize &rest hash-args) &body body) (let ((hash (apply #'make-hash-table (append '(:test equal) hash-args)))) (push hash *all-tables*) `(defmethod ,method-name ,lambda-list (if *use-store* (multiple-value-bind (ret found-p) (gethash (list ,@params-to-memoize) ,hash) (if found-p (apply #'values ret) (apply #'values (setf (gethash (list ,@params-to-memoize) ,hash) (multiple-value-list (progn ,@body)))))) (progn ,@body))))) ;;; ;;; ;;; (defun concept-name (x &optional package) (let ((x (format nil "~A" x))) (intern (nstring-upcase (string-substitute (string-substitute x '((" " " " t) (" " "-" t) ("." "-" t) (";" "-" t) ("," "-" t) ("/" "-" t) ("\\" "-" t) ("!" "" t) ("," "-" t) ("(" "-" t) (")" "" t) ("--" "-" t))) '(("--" "-" t)))) (or package *package*)))) #+:lispworks (defun run (fn) (mp:process-run-function "Process" '(:size 1400000) ;;; set Stack Size! fn)) #+:lispworks (defun kill (&optional name) (let ((process (mp:find-process-from-name (or name "Process")))) (when process (mp:process-kill process)))) ;;; ;;; ;;; (defmacro with-standard-output-to-file ((file) &rest body) `(with-open-file (stream ,file :direction :output :if-exists :supersede) (let ((*standard-output* stream)) ,@body))) ;;; ;;; AVL-Trees laut Wirth ;;; (declaim (inline balance-r balance-l)) (defun find-in-avl-tree (item tree &key (key #'identity) (compare-fn #'<) (match-fn #'=) (apply-key-to-item-argument-p t)) (macrolet ((item (x) `(first ,x)) (bal (x) `(second ,x)) (left (x) `(third ,x)) (right (x) `(fourth ,x))) (let ((x (if apply-key-to-item-argument-p (funcall key item) item))) (labels ((search (p) (when p (if (funcall match-fn (funcall key (item p)) x) (item p) (if (funcall compare-fn x (funcall key (item p))) (search (left p)) (search (right p))))))) (search tree))))) (defun insert-into-avl-tree* (item tree &key (key #'identity) (compare-fn #'<) (match-fn #'=)) (macrolet ((item (x) `(first ,x)) (bal (x) `(second ,x)) (left (x) `(third ,x)) (right (x) `(fourth ,x))) (let ((x (funcall key item))) (labels ((search (p) (if (not p) (values (list item 0 nil nil) t) (if (funcall match-fn (funcall key (item p)) x) (error "Already present!") (if (funcall compare-fn x (funcall key (item p))) (multiple-value-bind (subtree h) (search (left p)) (setf (left p) subtree) (when h (case (bal p) (1 (setf (bal p) 0 h nil)) (0 (setf (bal p) -1)) (-1 ;; rebalance (let ((p1 (left p))) (if (= (bal p1) -1) (setf (left p) (right p1) (right p1) p (bal p) 0 p p1) (let ((p2 (right p1))) (setf (right p1) (left p2) (left p2) p1 (left p) (right p2) (right p2) p) (if (= (bal p2) -1) (setf (bal p) 1) (setf (bal p) 0)) (if (= (bal p2) 1) (setf (bal p1) -1) (setf (bal p1) 0)) (setf p p2)))) (setf (bal p) 0 h nil)))) (values p h)) ;; (> x (item p)) (multiple-value-bind (subtree h) (search (right p)) (setf (right p) subtree) (when h (case (bal p) (-1 (setf (bal p) 0 h nil)) (0 (setf (bal p) 1)) (1 ;; rebalance (let ((p1 (right p))) (if (= (bal p1) 1) (setf (right p) (left p1) (left p1) p (bal p) 0 p p1) (let ((p2 (left p1))) (setf (left p1) (right p2) (right p2) p1 (right p) (left p2) (left p2) p) (if (= (bal p2) 1) (setf (bal p) -1) (setf (bal p) 0)) (if (= (bal p2) -1) (setf (bal p1) 1) (setf (bal p1) 0)) (setf p p2)))) (setf (bal p) 0 h nil)))) (values p h))))))) (search tree))))) (defun delete-from-avl-tree* (item tree &key (key #'identity) (compare-fn #'<) (match-fn #'=)) (macrolet ((item (x) `(first ,x)) (bal (x) `(second ,x)) (left (x) `(third ,x)) (right (x) `(fourth ,x))) (let ((x (funcall key item))) (labels ((get-subtree-and-rightmost-item (r) (if (right r) (multiple-value-bind (subtree item h) (get-subtree-and-rightmost-item (right r)) (setf (right r) subtree) (when h (multiple-value-bind (nr nh) (balance-r r h) (setf r nr h nh))) (values r item h)) (progn (values (left r) (item r) t)))) (delete-it (p h) (when p (if (funcall match-fn x (funcall key (item p))) (cond ((not (right p)) (setf p (left p) h t)) ((not (left p)) (setf p (right p) h t)) (t (multiple-value-bind (subtree item nh) (get-subtree-and-rightmost-item (left p)) (setf (item p) item) (setf (left p) subtree) (setf h nh) (when h (multiple-value-bind (np nh) (balance-l p h) (setf p np h nh)))))) (if (funcall compare-fn x (funcall key (item p))) (multiple-value-bind (subtree nh) (delete-it (left p) h) (setf (left p) subtree) (setf h nh) (when h (multiple-value-bind (np nh) (balance-l p h) (setf p np h nh)))) (multiple-value-bind (subtree nh) (delete-it (right p) h) (setf (right p) subtree) (setf h nh) (when h (multiple-value-bind (np nh) (balance-r p h) (setf p np h nh)))))) (values p h)))) (delete-it tree nil))))) (defun balance-l (p h) (macrolet ((item (x) `(first ,x)) (bal (x) `(second ,x)) (left (x) `(third ,x)) (right (x) `(fourth ,x))) (case (bal p) (-1 (setf (bal p) 0)) (0 (setf (bal p) 1 h nil)) (1 (let* ((p1 (right p)) (b1 (bal p1))) (if (>= b1 0) (progn (setf (right p) (left p1) (left p1) p) (if (= 0 b1) (setf (bal p) 1 (bal p1) -1 h nil) (setf (bal p) 0 (bal p1) 0)) (setf p p1)) (let* ((p2 (left p1)) (b2 (bal p2))) (setf (left p1) (right p2) (right p2) p1 (right p) (left p2) (left p2) p) (if (= 1 b2) (setf (bal p) -1) (setf (bal p) 0)) (if (= -1 b2) (setf (bal p1) 1) (setf (bal p1) 0)) (setf p p2 (bal p2) 0)))))) (values p h))) (defun balance-r (p h) (macrolet ((item (x) `(first ,x)) (bal (x) `(second ,x)) (left (x) `(third ,x)) (right (x) `(fourth ,x))) (case (bal p) (1 (setf (bal p) 0)) (0 (setf (bal p) -1 h nil)) (-1 (let* ((p1 (left p)) (b1 (bal p1))) (if (<= b1 0) (progn (setf (left p) (right p1) (right p1) p) (if (= 0 b1) (setf (bal p) -1 (bal p1) 1 h nil) (setf (bal p) 0 (bal p1) 0)) (setf p p1)) (let* ((p2 (right p1)) (b2 (bal p2))) (setf (right p1) (left p2) (left p2) p1 (left p) (right p2) (right p2) p) (if (= -1 b2) (setf (bal p) 1) (setf (bal p) 0)) (if (= 1 b2) (setf (bal p1) -1) (setf (bal p1) 0)) (setf p p2 (bal p2) 0)))))) (values p h))) (defun get-items-from-avl-tree (tree) (macrolet ((item (x) `(first ,x)) (bal (x) `(second ,x)) (left (x) `(third ,x)) (right (x) `(fourth ,x))) (when tree (cons (item tree) (append (get-items-from-avl-tree (left tree)) (get-items-from-avl-tree (right tree))))))) (defmacro loop-over-avl-tree ((var tree) &rest body) (let ((fn-sym (gensym)) (node-sym (gensym))) `(progn (labels ((,fn-sym (,node-sym) (when ,node-sym (let ((,var (first ,node-sym))) ,@body) (,fn-sym (third ,node-sym)) (,fn-sym (fourth ,node-sym))))) (,fn-sym ,tree))))) (defmacro insert-into-avl-tree (item tree &rest args) `(setf ,tree (insert-into-avl-tree* ,item ,tree ,@args))) (defmacro delete-from-avl-tree (item tree &rest args) `(setf ,tree (delete-from-avl-tree* ,item ,tree ,@args))) (defun print-avl-tree (tree stream) (macrolet ((item (x) `(first ,x)) (bal (x) `(second ,x)) (left (x) `(third ,x)) (right (x) `(fourth ,x))) (labels ((do-it (tree &optional (level 0) next) (let ((node (item tree)) (children (remove nil (list (left tree) (right tree))))) (format stream ";;;") (if (= level 0) (format stream " ~A~%" node) (progn (dolist (item (butlast next)) (if item (format stream " |") (format stream " "))) (let ((last (first (last next)))) (if last (format stream " |---~A~%" node) (format stream " \\___~A~%" node))))) (let ((last (first (last children)))) (dolist (child children) (do-it child (1+ level) (append next (list (not (eq child last)))))))))) (do-it tree)))) #| (defun test-avl-trees (n) (loop (let* ((keys (reorder (loop as i from 1 to n collect i))) (tree nil)) (princ "*") (dolist (key keys) (setf tree (insert-into-avl-tree key tree))) (dolist (key (reorder keys)) (unless tree (error "!")) (setf tree (delete-from-avl-tree key tree))) (when tree (error "!"))))) |#
31,205
Common Lisp
.lisp
883
21.272933
126
0.408038
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
c6578c0181a7fb6032febde60d007cc06ed1f385731c1af1d3752c1ef425a33c
4,339
[ -1 ]
4,340
gui3.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/gui/gui3.lisp
;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: TANGRAM -*- (in-package :tangram) (define-gesture-name :align :pointer-button (:middle :shift)) (define-gesture-name :move :pointer-button (:left)) (define-gesture-name :rotate :pointer-button (:left :shift)) (define-gesture-name :mirror :pointer-button (:right :shift)) (define-gesture-name :delete :pointer-button (:middle)) (defvar *tangram-frame*) (defvar *tangram-sets*) (defvar *process* nil) (defvar *search-process* nil) (defmacro with-tangram-frame ((frame) &body body) `(let ((,frame *tangram-frame*)) ,@body)) ;;; ;;; ;;; (defpersistentclass tangram-tile () ((shape :accessor shape :initarg :shape) (color :accessor color :initarg :color) (name :accessor name :initarg :name) (x-off :accessor x-off :initform 100) (y-off :accessor y-off :initform 100) (orientation :accessor orientation :initform 0) (congruent-tiles :accessor congruent-tiles :initform nil) (mirror-value :accessor mirror-value :initform '(1 1)) (mirror-values :accessor mirror-values :initform '((1 1)) :initarg :mirror-values) (on-board-p :accessor on-board-p :initform nil) (ref-point :accessor ref-point :initarg :ref-point))) (defun make-tile (name xy-shape color &key (mirror-values '((1 1)))) (let* ((shape (poly-from-xy-list xy-shape :affected-by-matrix-p t)) (ref (first (last (point-list shape))))) (orientate-counterclockwise shape) (make-instance 'tangram-tile :mirror-values mirror-values :name name :shape shape :color color :ref-point ref))) (defmethod set-reference-point ((tile tangram-tile) (point geom-point)) (setf (ref-point tile) point)) (defmethod put-on-board ((tile tangram-tile)) (with-tangram-frame (frame) (home tile) (unless (current-tile frame) (setf (current-tile frame) tile) (align-grid-to-tile tile frame)) (setf (on-board-p tile) t))) (defmethod remove-from-board ((tile tangram-tile)) (with-tangram-frame (frame) (setf (on-board-p tile) nil) (when (eq (current-tile frame) tile) (setf (current-tile frame) nil) (loop as tile in (tiles (current-set frame)) when (on-board-p tile) do (align-grid-to-tile tile frame))))) (defpersistentclass tangram-set () ((tiles :accessor tiles :initarg :tiles))) (defmethod congruent-p ((a tangram-tile) (b tangram-tile)) (eq (first (first (find-possible-alignments (shape a) (shape b)) )) :match)) (defun make-tangram-set (&rest tiles) (dolist (a tiles) (dolist (b tiles) (unless (eq a b) (when (congruent-p a b) (pushnew b (congruent-tiles a)) (pushnew a (congruent-tiles b)))))) (make-instance 'tangram-set :tiles tiles)) (defmethod get-max-width-and-height ((set tangram-set)) (get-max-width-and-height (tiles set))) (defmethod get-max-width-and-height ((set list)) (values (loop as tile in set maximize (bb-width (shape tile))) (loop as tile in set maximize (bb-height (shape tile))))) (defmethod get-min-width-and-height ((set tangram-set)) (values (loop as tile in (tiles set) minimize (bb-width (shape tile))) (loop as tile in (tiles set) minimize (bb-height (shape tile))))) (defpersistentclass tangram-problem () ((polygons :accessor polygons :initarg :polygons) (tiles :accessor tiles :initarg :tiles) (aggregate :accessor aggregate :initarg :aggregate) (known-solutions :accessor known-solutions :initform nil))) (defmethod register-solution ((problem tangram-problem) solution) (with-tangram-frame (frame) (push solution (known-solutions problem)) (setf (current-solution frame) solution))) (defun make-problem (polygons tiles) (let* ((polygons (mapcar #'(lambda (x) (if (typep x 'geom-polygon) x (poly-from-xy-list polygons))) (ensure-list polygons))) (agg (make-aggregate polygons))) (make-instance 'tangram-problem :polygons polygons :tiles tiles :aggregate agg))) ;;; ;;; ;;; (define-application-frame tangram-frame () ((current-set :initform nil :accessor current-set) (current-tile :initform nil :accessor current-tile) (current-problem :initform nil :accessor current-problem) (current-solution :initform nil :accessor current-solution) (show-problem-p :initform nil :accessor show-problem-p) (show-thinking-p :initform t :accessor show-thinking-p) (game-type :initform 'all :accessor game-type) (all-solutions-p :initform t :accessor all-solutions-p) (display-view :initform 'construction :accessor display-view) (grid-xmin :accessor grid-xmin :initform 0) (grid-xmax :accessor grid-xmax :initform 0) (grid-ymin :accessor grid-ymin :initform 0) (grid-ymax :accessor grid-ymax :initform 0) (all-sets :initform *tangram-sets* :accessor all-sets) (problems :initform nil :accessor problems)) (:panes (new-button (make-pane 'push-button :label "New" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (dolist (tile (tiles (current-set frame))) (home tile)) (setf (current-tile frame) nil) (setf (display-view frame) 'construction) (refresh-all))))) (save-button (make-pane 'push-button :label "Save" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (with-slots (current-set current-tile current-problem current-solution show-problem-p show-thinking-p game-type all-solutions-p display-view grid-xmin grid-xmax grid-ymin grid-ymax all-sets problems) frame (let ((file (file-selector "Save" "tangram:" "tan" :save t))) (when file (make-object-persistent (list current-set current-tile current-problem current-solution show-problem-p show-thinking-p game-type all-solutions-p display-view grid-xmin grid-xmax grid-ymin grid-ymax all-sets problems) (format nil "~A" file))) (refresh-all))))))) (load-button (make-pane 'push-button :label "Load" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (with-slots (current-set current-tile current-problem current-solution show-problem-p show-thinking-p game-type all-solutions-p display-view grid-xmin grid-xmax grid-ymin grid-ymax all-sets problems) frame (let ((file (file-selector "Load" "tangram:" "tan" :save nil))) (when file (let ((obj (load-persistent-object file))) (setf current-set (pop obj) current-tile (pop obj) current-problem (pop obj) current-solution (pop obj) show-problem-p (pop obj) show-thinking-p (pop obj) game-type (pop obj) all-solutions-p (pop obj) display-view (pop obj) grid-xmin (pop obj) grid-xmax (pop obj) grid-ymin (pop obj) grid-ymax (pop obj) all-sets (pop obj) problems (pop obj)) (refresh-all))))))))) (left-button (make-pane 'push-button :label "<" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (multiple-value-bind (dx) (get-grid-cell-dimension frame) (dolist (tile (tiles (current-set frame))) (when (on-board-p tile) (decf (x-off tile) dx))) (when (current-tile frame) (align-grid-to-tile (current-tile frame) frame)) (setf (display-view frame) 'construction) (refresh-display)))))) (right-button (make-pane 'push-button :label ">" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (multiple-value-bind (dx) (get-grid-cell-dimension frame) (dolist (tile (tiles (current-set frame))) (when (on-board-p tile) (incf (x-off tile) dx))) (when (current-tile frame) (align-grid-to-tile (current-tile frame) frame)) (setf (display-view frame) 'construction) (refresh-display)))))) (up-button (make-pane 'push-button :label "/\\" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (multiple-value-bind (dx dy) (get-grid-cell-dimension frame) (declare (ignore dx)) (dolist (tile (tiles (current-set frame))) (when (on-board-p tile) (decf (y-off tile) dy))) (when (current-tile frame) (align-grid-to-tile (current-tile frame) frame)) (setf (display-view frame) 'construction) (refresh-display)))))) (down-button (make-pane 'push-button :label "\\/" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (multiple-value-bind (dx dy) (get-grid-cell-dimension frame) (declare (ignore dx)) (dolist (tile (tiles (current-set frame))) (when (on-board-p tile) (incf (y-off tile) dy))) (when (current-tile frame) (align-grid-to-tile (current-tile frame) frame)) (setf (display-view frame) 'construction) (refresh-display)))))) (refresh-button (make-pane 'push-button :label "Refresh" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (setf (display-view frame) 'construction) (refresh-all))))) (stop-button (make-pane 'push-button :label "Stop" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (when *search-process* #+:lispworks (kill "Tangram Solver") #+:allegro (mp:process-kill *search-process*)) (setf (display-view frame) 'construction) (refresh-display) (Beep))))) (quit-button (make-pane 'push-button :label "Quit" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (when *process* #+:allegro (mp:process-kill *process*) #+:lispwork (kill "Tangram") (frame-exit frame)))))) (problem-button (make-pane 'push-button :label "Problem" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (create-problem (current-set frame)) (refresh-problems))))) (solve-button (make-pane 'push-button :label "Solve!" :activate-callback #'(lambda (&rest args) (declare (ignore args)) (with-tangram-frame (frame) (setf *search-process* (mp:process-run-function "Tangram Solver" #+:lispworks '(:size 250000) ;;; set Stack Size! #'(lambda () (setf *application-frame* frame) (solve-problem frame)))))))) (display :application ;:end-of-line-action :allow ;:end-of-page-action :allow :display-function #'draw-display :initial-cursor-visibility nil :incremental-redisplay t :scroll-bars nil) (tiles :application :display-function #'draw-tiles :initial-cursor-visibility nil :incremental-redisplay nil :scroll-bars nil) (tile-sets :application :label "Available Tile Sets" :display-function #'show-tile-sets :initial-cursor-visibility nil :incremental-redisplay t :end-of-line-action :allow :scroll-bars :vertical) (problems :application :label "Available Problems" :display-function #'show-problems :initial-cursor-visibility nil :end-of-line-action :allow :end-of-page-action :allow :incremental-redisplay t :scroll-bars :vertical) (solutions :application :label "Known Solutions" :display-function #'show-solutions :incremental-redisplay t :end-of-line-action :allow :end-of-page-action :allow :scroll-bars :vertical) (options :accept-values :scroll-bars nil :min-height :compute :height :compute :max-height :compute :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (formatting-table (stream :x-spacing '(2 :character)) (formatting-column (stream) (formatting-cell (stream :align-x :center) (let ((view (accept 'completion :query-identifier 'display :prompt nil :prompt-mode :raw :stream stream :default (display-view frame) :view `(option-pane-view :items (Construction Problem Solution))))) (setf (display-view frame) view))) (formatting-cell (stream :align-x :center) (let ((type (accept 'completion :query-identifier 'type :prompt nil :prompt-mode :raw :stream stream :default (game-type frame) :view `(option-pane-view :items (all less copies))))) (setf (game-type frame) type))) (formatting-cell (stream :align-x :center) (let ((bool (accept 'boolean :prompt " Show Thinking" :stream stream :default (show-thinking-p frame) :query-identifier 'show-thinking))) (setf (show-thinking-p frame) bool))) (formatting-cell (stream :align-x :center) (let ((bool (accept 'boolean :prompt " All Solutions" :stream stream :default (all-solutions-p frame) :query-identifier 'all-solutions))) (setf (all-solutions-p frame) bool))))))))) (:layouts (:default (vertically () (1/10 (horizontally () (1/8 quit-button) (1/8 load-button) (1/8 save-button) (1/8 stop-button) (1/8 refresh-button) (1/8 new-button) (1/8 problem-button) (1/8 solve-button))) (6/10 (horizontally () (3/4 #-:mswindows (vertically () (1/20 up-button) (18/20 (horizontally () (1/20 left-button) (18/20 (outlining () display)) (1/20 right-button))) (1/20 down-button)) #+:mswindows (outlining () display)) (1/4 (outlining () (vertically () (1/4 options) (3/4 tiles)))))) (3/10 (horizontally () (1/3 (outlining () tile-sets)) (1/3 (outlining () problems)) (1/3 (outlining () solutions)))))))) (defun refresh-display () (with-tangram-frame (frame) (window-clear (get-frame-pane frame 'display)) (redisplay-frame-pane frame (get-frame-pane frame 'display) :force-p t))) (defun refresh-tiles () (with-tangram-frame (frame) (redisplay-frame-pane frame (get-frame-pane frame 'tiles) :force-p t))) (defun refresh-solutions () (with-tangram-frame (frame) (redisplay-frame-pane frame (get-frame-pane frame 'solutions) :force-p t))) (defun refresh-problems () (with-tangram-frame (frame) (redisplay-frame-pane frame (get-frame-pane frame 'problems) :force-p t))) (defun refresh-all () (refresh-display) (refresh-solutions) (refresh-tiles)) ;;; ;;; ;;; (defmethod get-window-dimension ((frame tangram-frame)) (let ((stream (get-frame-pane frame 'display))) (bounding-rectangle-size (bounding-rectangle (window-viewport stream))))) (defconstant +grid-resolution+ 20) (defmethod get-grid-cell-dimension ((frame tangram-frame)) (let ((stream (get-frame-pane frame 'display))) (multiple-value-bind (window-width window-height) (bounding-rectangle-size (bounding-rectangle (window-viewport stream))) (let* ((dx (/ window-width +grid-resolution+)) (dy (/ window-height +grid-resolution+)) (s (min dx dy))) (values s s))))) (defmethod get-scaling-factors-for-tile ((tile tangram-tile) (frame tangram-frame)) (multiple-value-bind (min-tile-width min-tile-height) (get-min-width-and-height (current-set frame)) (multiple-value-bind (dx dy) (get-window-dimension frame) (let ((dx (/ dx 10)) (dy (/ dy 10))) (let* ((tile-width (bb-width (shape tile))) (tile-height (bb-height (shape tile))) (s (min (/ (* dx (/ tile-width min-tile-width)) tile-width) (/ (* dy (/ tile-height min-tile-height)) tile-height)))) (values s s)))))) ;;; ;;; ;;; (defmethod home ((tile tangram-tile)) (with-tangram-frame (frame) (multiple-value-bind (widht height) (get-window-dimension frame) (setf (on-board-p tile) nil (x-off tile) (x (centroid (shape tile))) (y-off tile) (y (centroid (shape tile))) (orientation tile) 0 (mirror-value tile) (first (mirror-values tile))) (set-reference-point tile (first (point-list (shape tile))))))) (defmethod align-grid-to-tile ((tile tangram-tile) (frame tangram-frame)) (with-tangram-frame (frame) (setf (current-tile frame) tile) (with-slots (grid-xmin grid-ymin grid-xmax grid-ymax) frame (multiple-value-bind (sx sy) (get-scaling-factors-for-tile tile frame) (let* ((xc (x (ref-point tile))) (yc (y (ref-point tile))) (phi (* (/ +2pi+ 8) (mod (orientation tile) 8))) (mx (first (mirror-value tile))) (my (second (mirror-value tile)))) ;;; ;;; Achtung! "meine" Transformationsoperationen ;;; sind genau entgegengesetzt zu den CLIM-Transformationen ;;; geschachtelt! ;;; (with-translation ((- xc) (- yc)) (with-rotation (phi) (with-scaling ((* mx sx) (* my sy)) (with-translation ((x-off tile) (y-off tile)) (setf grid-xmin (x (pmin (shape tile))) grid-ymin (y (pmin (shape tile))) grid-xmax (x (pmax (shape tile))) grid-ymax (y (pmax (shape tile))))))))))))) ;;; ;;; ;;; (defclass handle () ()) #| (define-presentation-method highlight-presentation ((type tangram-tile) record stream state) (with-tangram-frame (frame) (let ((tile (presentation-object record))) (when (on-board-p tile) (multiple-value-bind (sx sy) (get-scaling-factors-for-tile tile frame) (let* ((xc (x (ref-point tile))) (yc (y (ref-point tile))) (phi (* (/ +2pi+ 8) (mod (orientation tile) 8))) (mx (first (mirror-value tile))) (my (second (mirror-value tile)))) (clim:with-translation (stream (x-off tile) (y-off tile)) (clim:with-scaling (stream (* mx sx) (* sy my)) (clim:with-rotation (stream phi) (clim:with-translation (stream (- xc) (- yc)) (draw tile stream :highlight-p t))))))))))) |# (defmethod draw-display ((frame tangram-frame) stream) (with-correct-clipping (stream) (case (display-view frame) (problem (show-current-problem frame)) (solution (show-solution frame)) (construction (multiple-value-bind (window-width window-height) (bounding-rectangle-size (bounding-rectangle (window-viewport stream))) (let ((tiles (tiles (current-set frame)))) (dolist (tile tiles) (multiple-value-bind (sx sy) (get-scaling-factors-for-tile tile frame) (let* ((xc (x (ref-point tile))) (yc (y (ref-point tile))) (phi (* (/ +2pi+ 8) (mod (orientation tile) 8))) (mx (first (mirror-value tile))) (my (second (mirror-value tile)))) (when (on-board-p tile) (updating-output (stream :unique-id tile :cache-value (list (ref-point tile) (x-off tile) (y-off tile) phi mx my) :cache-test #'equal) (clim:with-translation (stream (x-off tile) (y-off tile)) (clim:with-scaling (stream (* mx sx) (* sy my)) (clim:with-rotation (stream phi) (clim:with-translation (stream (- xc) (- yc)) (with-output-as-presentation (stream tile (type-of tile) :allow-sensitive-inferiors t :single-box t) (draw tile stream) (dolist (point (point-list (shape tile))) (with-output-as-presentation (stream (list point tile) 'handle :single-box t) (draw-circle* stream (x point) (y point) (/ 8 sx) :filled t :ink +blue+))) (draw-circle* stream (x (ref-point tile)) (y (ref-point tile)) (/ 8 sx) :filled t :ink +red+)))))) (when (eq tile (current-tile frame)) (with-output-recording-options (stream :record nil) (with-slots (grid-xmin grid-ymin grid-xmax grid-ymax) frame (draw-line* stream 0 grid-ymin window-width grid-ymin :ink +yellow+) (draw-line* stream 0 grid-ymax window-width grid-ymax :ink +yellow+) (draw-line* stream grid-xmin 0 grid-xmin window-height :ink +yellow+) (draw-line* stream grid-xmax 0 grid-xmax window-height :ink +yellow+))))))))))))))) (defmethod draw-tiles ((frame tangram-frame) stream) (case (display-view frame) (construction (draw-given-tiles (tiles (current-set frame)))) (problem (when (current-problem frame) (draw-given-tiles (mapcar #'first (tiles (current-problem frame)))))) (solution (when (current-problem frame) (draw-given-tiles (mapcar #'first (tiles (current-problem frame)))))))) (defclass tangram-tile-not-on-board () ()) (defun draw-given-tiles (tiles &key (clear-p t)) (when tiles ;(dolist (tile tiles) ; (geometry::recalculate-bounding-box (shape tile))) (with-tangram-frame (frame) (let ((stream (get-frame-pane frame 'tiles))) (when clear-p (window-clear stream)) (multiple-value-bind (tile-width tile-height) (get-max-width-and-height tiles) (multiple-value-bind (window-width window-height) (bounding-rectangle-size (bounding-rectangle (window-viewport stream))) (let* ((y-inc (/ window-height (1+ (length tiles)))) (y 0) (xs (/ (- window-width 30) tile-width)) (ys (/ window-height (* (1+ (length tiles)) tile-height))) (s (min xs ys))) (dolist (tile tiles) (when (or (eq (display-view frame) 'problem) (and (not (eq (display-view frame) 'problem)) (not (on-board-p tile)))) (let* ((xc (x (centroid (shape tile)))) (yc (y (centroid (shape tile))))) (incf y y-inc) (clim:with-translation (stream (/ window-width 2) y) (clim:with-scaling (stream s s) (clim:with-translation (stream (- xc) (- yc)) (with-output-as-presentation (stream tile 'tangram-tile-not-on-board :single-box t) (draw tile stream))))))))))))))) (defmethod draw ((tile tangram-tile) stream &key highlight-p) (draw-polygon* stream (apply #'append (mapcar #'get-xy-list (point-list (shape tile)))) :ink (if highlight-p +flipping-ink+ (color tile))) (draw-polygon* stream (apply #'append (mapcar #'get-xy-list (point-list (shape tile)))) :ink (if highlight-p +flipping-ink+ +black+) :filled nil)) (defclass solution nil nil) (defmethod show-solutions ((frame tangram-frame) stream) (when (current-problem frame) (let ((problem (current-problem frame))) (multiple-value-bind (window-width window-height) (bounding-rectangle-size (bounding-rectangle (window-viewport stream))) (let ((y 0)) (dolist (solution (known-solutions (current-problem frame))) (updating-output (stream :unique-id solution) (with-output-as-presentation (stream solution 'solution :single-box t) (let ((width (bb-width (aggregate problem))) (height (bb-height (aggregate problem)))) (let* ((xs (/ window-width width)) (ys (/ (/ window-height 3) height)) (s (min xs ys)) (xc (x (centroid (aggregate problem)))) (yc (y (centroid (aggregate problem))))) (clim:with-translation (stream (/ window-width 2) (+ y (/ (/ window-height 2) 2))) (clim:with-scaling (stream s s) (clim:with-translation (stream (- xc) (- yc)) (dolist (entry solution) (let* ((polygon (first entry)) (tile (second entry)) (list (apply #'append (mapcar #'get-xy-list (mapcar #'p1 (segments polygon)))))) (draw-polygon* stream list :filled t :ink (color tile)) (draw-polygon* stream list :filled nil :ink +black+)))))) (incf y (+ 15 (* s height))))))))))))) (defmethod show-solution ((frame tangram-frame) &key (clear-p t)) (when (current-solution frame) (let ((stream (get-frame-pane frame 'display))) (when clear-p (window-clear stream)) (dolist (entry (current-solution frame)) (let ((polygon (first entry)) (tile (second entry))) (draw-polygon* stream (apply #'append (mapcar #'get-xy-list (mapcar #'p1 (segments polygon)))) :filled t :ink (color tile)) (draw-polygon* stream (apply #'append (mapcar #'get-xy-list (mapcar #'p1 (segments polygon)))) :filled nil :ink +black+)))))) (defmethod show-tile-sets ((frame tangram-frame) stream) (multiple-value-bind (window-width window-height) (bounding-rectangle-size (bounding-rectangle (window-viewport stream))) (let ((y 0)) (updating-output (stream :cache-value (all-sets frame) :cache-test #'equal) (dolist (set (all-sets frame)) (with-output-as-presentation (stream set (type-of set) :single-box t) (let ((tiles (tiles set))) (multiple-value-bind (tile-width tile-height) (get-max-width-and-height set) (let* ((x-inc (/ window-width (1+ (length tiles)))) (x 0) (xs (/ window-width (* (1+ (length tiles)) tile-height))) (ys (/ (/ window-height 3) tile-width))) (incf y (+ 10 (/ window-height 3))) (dolist (tile tiles) (let ((xc (x (centroid (shape tile)))) (yc (y (centroid (shape tile))))) (incf x x-inc) (clim:with-translation (stream x y) (clim:with-scaling (stream xs ys) (clim:with-translation (stream (- xc) (- yc)) (draw tile stream))))))))))))))) (defmethod show-problems ((frame tangram-frame) stream) (multiple-value-bind (window-width window-height) (bounding-rectangle-size (bounding-rectangle (window-viewport stream))) (let ((y 0)) (dolist (problem (problems frame)) (updating-output (stream :unique-id problem) (with-output-as-presentation (stream problem (type-of problem) :single-box t) (let ((polygons (polygons problem)) (width (bb-width (aggregate problem))) (height (bb-height (aggregate problem)))) (let* ((xs (/ window-width width)) (ys (/ (/ window-height 3) height)) (s (min xs ys)) (xc (x (centroid (aggregate problem)))) (yc (y (centroid (aggregate problem))))) (clim:with-translation (stream (/ window-width 2) (+ y (/ (/ window-height 2) 2))) (clim:with-scaling (stream s s) (clim:with-translation (stream (- xc) (- yc)) (dolist (polygon polygons) (draw-polygon* stream (apply #'append (mapcar #'get-xy-list (mapcar #'p1 (segments polygon)))) :filled t :ink (if (eq problem (current-problem frame)) +yellow+ (make-rgb-color 0.6 0.6 0.6)))) (loop as polygon in polygons as ink in (make-cyclic (list +red+ +green+ +blue+ +black+ +yellow+)) do (dolist (s (segments polygon)) (draw-line* stream (x (p1 s)) (y (p1 s)) (x (p2 s)) (y (p2 s)) :line-thickness 3 :ink ink)))))) (incf y (+ 15 (* s height))))))))))) ;;; ;;; ;;; (define-tangram-frame-command (com-select-set) ((set 'tangram-set)) (with-tangram-frame (frame) (setf (current-set frame) set) (setf (display-view frame) 'construction)) (refresh-all)) (define-tangram-frame-command (com-select-solution) ((solution 'solution)) (with-tangram-frame (frame) (setf (display-view frame) 'solution) (setf (current-solution frame) solution)) (refresh-all)) (define-tangram-frame-command (com-delete-solution) ((solution 'tangram-problem)) (with-tangram-frame (frame) (setf (known-solutions (current-problem frame)) (delete solution (known-solutions (current-problem frame)))) (when (eq (current-solution frame) solution) (setf (current-solution frame) (first (known-solutions (current-problem frame)))))) (refresh-all)) (define-tangram-frame-command (com-select-problem) ((problem 'tangram-problem)) (with-tangram-frame (frame) (setf (display-view frame) 'problem) (setf (current-problem frame) problem)) (refresh-all)) (define-tangram-frame-command (com-delete-problem) ((problem 'tangram-problem)) (with-tangram-frame (frame) (setf (problems frame) (delete problem (problems frame))) (when (eq problem (current-problem frame)) (setf (current-problem frame) (first (problems frame))))) (refresh-all)) (define-tangram-frame-command (com-put-tile-on-board) ((object 'tangram-tile-not-on-board)) (put-on-board object) (refresh-display)) (define-tangram-frame-command (com-align-grid-to-tile) ((tile 'tangram-tile) (frame 'tangram-frame)) (align-grid-to-tile tile frame) (refresh-display)) (define-tangram-frame-command (com-remove-tile-from-board) ((object 'tangram-tile)) (remove-from-board object) (refresh-display)) (define-tangram-frame-command (com-move-tile) ((tile 'tangram-tile) (frame 'tangram-frame)) (let ((stream (get-frame-pane frame 'display)) (first-click t) (ox) (oy)) (with-correct-clipping (stream) (cond ((eq tile (current-tile frame)) (tracking-pointer (stream) (:pointer-motion (x y) (when first-click (setf ox (x-off tile) oy (y-off tile)) (setf first-click nil)) (setf (x-off tile) x (y-off tile) y) (align-grid-to-tile tile frame) (refresh-display) ) (:pointer-button-press (event) (when (= (pointer-event-button event) +pointer-right-button+) (setf (x-off tile) ox (y-off tile) oy) (align-grid-to-tile tile frame)) (refresh-display) (return)))) (t (let* ((coords (get-grid-points frame tile)) (point nil) (last-point nil) (min-dist nil)) (with-output-recording-options (stream :record nil) (format stream " ")) (tracking-pointer (stream) (:pointer-motion (x y) (when first-click (setf ox x oy y) (setf first-click nil)) (setf min-dist nil) (loop as coord in coords do (let* ((xt (first coord)) (yt (second coord)) (dist (distance-between* xt yt x y))) (when (or (not min-dist) (< dist min-dist)) (setf min-dist dist point coord)))) (unless (equal last-point point) (setf (x-off tile) (first point) (y-off tile) (second point)) (setf last-point point) (refresh-display) (with-output-recording-options (stream :record nil) (dolist (coord coords) (draw-circle* stream (first coord) (second coord) 2 :filled nil :ink +red+))))) (:pointer-button-press (event) (when (= (pointer-event-button event) +pointer-right-button+) (setf (x-off tile) ox (y-off tile) oy) (align-grid-to-tile (current-tile frame) frame)) (refresh-display) (return))))))))) (defmethod get-grid-points ((frame tangram-frame) (tile tangram-tile)) (multiple-value-bind (sx sy) (get-scaling-factors-for-tile tile frame) (let* ((xc (x (ref-point tile))) (yc (y (ref-point tile))) (phi (* (/ +2pi+ 8) (mod (orientation tile) 8))) (mx (first (mirror-value tile))) (my (second (mirror-value tile)))) ;;; ;;; Achtung! "meine" Transformationsoperationen ;;; sind genau entgegengesetzt zu den CLIM-Transformationen ;;; geschachtelt! ;;; (with-translation ((- xc) (- yc)) (with-rotation (phi) (with-scaling ((* mx sx) (* my sy)) (with-translation ((x-off tile) (y-off tile)) (get-coords1 frame tile)))))))) (defun get-coords1 (frame tile) (let* ((tile-xmin (x (pmin (shape tile)))) (tile-ymin (y (pmin (shape tile)))) (tile-xmax (x (pmax (shape tile)))) (tile-ymax (y (pmax (shape tile)))) (tile-width (- tile-xmax tile-xmin)) (tile-height (- tile-ymax tile-ymin)) (coords nil)) (with-slots (grid-xmin grid-ymin grid-xmax grid-ymax) frame (multiple-value-bind (window-width window-height) (get-window-dimension frame) (let ((x-coords (list 0 (- grid-xmin (/ tile-width 2)) (- grid-xmin tile-width) (- grid-xmin (* 2 tile-width)) grid-xmin (+ grid-xmin (/ tile-width 2)) (+ grid-xmin tile-width) (+ grid-xmin (* 2 tile-width)) (- grid-xmax (/ tile-width 2)) (- grid-xmax tile-width) (- grid-xmax (* 2 tile-width)) grid-xmax (+ grid-xmax (/ tile-width 2)) (+ grid-xmax tile-width) (+ grid-xmax (* 2 tile-width)) window-width)) (y-coords (list 0 (- grid-ymin (/ tile-height 2)) (- grid-ymin tile-height) (- grid-ymin (* 2 tile-height)) grid-ymin (+ grid-ymin (/ tile-height 2)) (+ grid-ymin tile-height) (+ grid-ymin (* 2 tile-height)) (- grid-ymax (/ tile-height 2)) (- grid-ymax tile-height) (- grid-ymax (* 2 tile-height)) grid-ymax (+ grid-ymax (/ tile-height 2)) (+ grid-ymax tile-height) (+ grid-ymax (* 2 tile-height)) window-height))) (dolist (x x-coords) (dolist (y y-coords) (push (list x y) coords)))))) coords)) (define-tangram-frame-command (com-make-reference-point) ((point-and-tile 'handle)) (let* ((point (first point-and-tile)) (tile (second point-and-tile))) (set-reference-point tile point)) (refresh-display)) (define-tangram-frame-command (com-rotate-tile) ((tile 'tangram-tile)) (incf (orientation tile)) (with-tangram-frame (frame) (when (eq (current-tile frame) tile) (align-grid-to-tile tile frame))) (refresh-display)) (define-tangram-frame-command (com-mirror-tile) ((tile 'tangram-tile)) (setf (mirror-value tile) (let ((next (member (mirror-value tile) (mirror-values tile) :test #'equal))) (if (cdr next) (first (cdr next)) (first (mirror-values tile))))) (with-tangram-frame (frame) (when (eq (current-tile frame) tile) (align-grid-to-tile tile frame))) (refresh-display)) ;;; ;;; ;;; (define-presentation-to-command-translator select-set (tangram-set com-select-set tangram-frame :gesture :select) (object) (list object)) (define-presentation-to-command-translator select-problem (tangram-problem com-select-problem tangram-frame :gesture :select) (object) (list object)) (define-presentation-to-command-translator delete-problem (tangram-problem com-delete-problem tangram-frame :gesture :delete) (object) (list object)) (define-presentation-to-command-translator select-solution (solution com-select-solution tangram-frame :gesture :select) (object) (list object)) (define-presentation-to-command-translator delete-solution (solution com-delete-solution tangram-frame :gesture :delete) (object) (list object)) (define-presentation-to-command-translator put-tile-on-board (tangram-tile-not-on-board com-put-tile-on-board tangram-frame :gesture :select :tester ((frame) (eq (display-view frame) 'construction))) (object) (list object)) (define-presentation-to-command-translator move-tile (tangram-tile com-move-tile tangram-frame :gesture :move) (object frame) (list object frame)) (define-presentation-to-command-translator align-grid-to-tile (tangram-tile com-align-grid-to-tile tangram-frame :gesture :align) (object frame) (list object frame)) (define-presentation-to-command-translator make-reference-point (handle com-make-reference-point tangram-frame :gesture :select) (object) (list object)) (define-presentation-to-command-translator rotate-tile (tangram-tile com-rotate-tile tangram-frame :gesture :rotate) (object) (list object)) (define-presentation-to-command-translator mirror-tile (tangram-tile com-mirror-tile tangram-frame :gesture :mirror) (object) (list object)) (define-presentation-to-command-translator remove-tile-from-board (tangram-tile com-remove-tile-from-board tangram-frame :gesture :describe) (object) (list object)) ;;; ;;; ;;; (defmethod solve-problem ((frame tangram-frame)) (let ((stream (get-frame-pane frame 'display))) (when (current-problem frame) (window-clear stream) (setf (display-view frame) 'problem) (refresh-display) (find-covering (polygons (current-problem frame)) (reverse (tiles (current-problem frame))) :frame frame :all-solutions-p (all-solutions-p frame) :remove-used-tiles-p (member (game-type frame) '(less all)) :allow-less-tiles-p (member (game-type frame) '(copies less)) :show-thinking-fn #'(lambda (polygons tiles history solution-p) (when (or (show-thinking-p frame) solution-p) (setf (display-view frame) 'problem) (unless solution-p (show-polygons polygons :clear-p t)) (when history (dolist (entry history) (let* ((poly (first entry)) (tile (second entry)) (list (apply #'append (mapcar #'get-xy-list (mapcar #'p1 (segments poly)))))) (draw-polygon* stream list :filled t :ink (color tile)) (draw-polygon* stream list :filled nil :ink +black+)))) #+:ignore (draw-given-tiles tiles :clear-p t) ;;; draw only one from each set of congruent tiles (first) (draw-given-tiles (mapcar #'(lambda (x) (first (ensure-list x))) tiles) :clear-p t) (when solution-p (setf (display-view frame) 'solution) (register-solution (current-problem frame) history) (redisplay-frame-pane frame (get-frame-pane frame 'solutions)))))) (setf (display-view frame) 'construction) (refresh-all)))) ;;; ;;; ;;; (defmethod create-problem ((set tangram-set)) (let ((polygons nil) (problem-tiles nil)) (with-tangram-frame (frame) (dolist (tile (tiles set)) (multiple-value-bind (sx sy) (get-scaling-factors-for-tile tile frame) (let* ((xc (x (ref-point tile))) (yc (y (ref-point tile))) (phi (* (/ +2pi+ 8) (mod (orientation tile) 8))) (mx (first (mirror-value tile))) (my (second (mirror-value tile)))) ;;; ;;; Achtung! "meine" Transformationsoperationen ;;; sind genau entgegengesetzt zu den CLIM-Transformationen ;;; geschachtelt! ;;; (with-translation ((- xc) (- yc)) (with-rotation (phi) (with-scaling ((* mx sx) (* my sy)) (with-translation ((x-off tile) (y-off tile)) (let ((xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments (shape tile)))) (list (get-xy-list (p2 (first (last (segments (shape tile)))))))))) (when (on-board-p tile) (push (poly-from-xy-list xy-list :affected-by-matrix-p nil) polygons))))))) (let ((ms-tiles nil)) (dolist (m (mirror-values tile)) (let ((mx (first m)) (my (second m))) (with-scaling ((* sx mx) (* sy my)) (with-translation ((x-off tile) (y-off tile)) (let ((xy-list (append (mapcar #'get-xy-list (mapcar #'p1 (segments (shape tile)))) (list (get-xy-list (p2 (first (last (segments (shape tile)))))))))) (push (make-tile (name tile) xy-list (color tile)) ms-tiles)))))) (push (remove-duplicates ms-tiles :test #'congruent-p) problem-tiles))))) (setf *x* polygons) (when (some #'(lambda (a) (some #'(lambda (b) (and (not (eq a b)) (not (member (calculate-rcc-relation a b) '(:dc :ec))))) polygons)) polygons) (beep) (return-from create-problem nil)) (when polygons (let ((union (polygon-set-union polygons))) (dolist (tile-set problem-tiles) (let* ((tile (first tile-set)) (orig-tile (find tile (tiles set) :test #'(lambda (x y) (eq (name x) (name y)))))) (unless orig-tile (error "!")) (setf (congruent-tiles tile) (remove-if-not #'(lambda (x) (find x (congruent-tiles orig-tile) :test #'(lambda (x y) (eq (name x) (name y))))) (mapcar #'first problem-tiles))))) (push (make-problem union problem-tiles) (problems frame)) (setf (current-problem frame) (first (problems frame)))))))) (defmethod show-current-problem ((frame tangram-frame)) (when (current-problem frame) (show-polygons (polygons (current-problem frame))))) (defparameter +gray-colors+ (make-cyclic (list (make-gray-color 0.3) (make-gray-color 0.4) (make-gray-color 0.5) (make-gray-color 0.6) (make-gray-color 0.7) (make-gray-color 0.8) (make-gray-color 0.9)))) (defun show-polygons (polygons &key (filled-p t) (clear-p t) (inks +gray-colors+)) (with-tangram-frame (frame) (let ((stream (get-frame-pane frame 'display))) (when clear-p (window-clear stream)) (loop as p in polygons as ink in inks do (draw-polygon* stream (apply #'append (mapcar #'get-xy-list (mapcar #'p1 (segments p)))) :filled filled-p :ink ink))))) ;;; ;;; ;;; (defun tangram () (setf cl-user::*use-store* nil) (setf *tangram-sets* (list (make-tangram-set ;;; ACHTUNG! NAMEN MUESSEN UNIQUE SEIN (make-tile 'a '((0 0) (80 0) (40 40) (0 0)) +red+) (make-tile 'b '((0 0) (0 80) (40 40) (0 0)) +green+) (make-tile 'c '((80 80) (80 40) (40 80) (80 80)) +yellow+) (make-tile 'd '((80 0) (80 40) (60 20) (80 0)) +blue+) (make-tile 'e '((20 60) (60 60) (40 40) (20 60)) +black+) (make-tile 'f '((60 20) (80 40) (60 60) (40 40) (60 20)) +cyan+) (make-tile 'g '((0 80) (40 80) (60 60) (20 60) (0 80)) +magenta+ :mirror-values '((1 1) (-1 1) (1 -1) (-1 -1)))) #+:ignore (make-tangram-set (make-tile 'a '((0 0) (80 0) (40 40) (0 0)) +red+) (make-tile 'b '((0 0) (0 80) (40 40) (0 0)) +green+) (make-tile 'c '((80 80) (80 40) (40 80) (80 80)) +yellow+) (make-tile 'd '((80 0) (80 40) (60 20) (80 0)) +blue+) (make-tile 'e '((20 60) (60 60) (40 40) (20 60)) +black+) (make-tile 'f '((60 20) (80 40) (60 60) (40 40) (60 20)) +cyan+) (make-tile 'g '((0 80) (40 80) (60 60) (20 60) (0 80)) (make-rgb-color 1 0.3 0.9) :mirror-values '((1 1) (-1 1) (1 -1) (-1 -1))) (make-tile 'a1 '((0 0) (80 0) (40 40) (0 0)) +red+) (make-tile 'b1 '((0 0) (0 80) (40 40) (0 0)) +green+) (make-tile 'c1 '((80 0) (80 40) (60 20) (80 0)) +blue+) (make-tile 'd1 '((80 80) (80 40) (40 80) (80 80)) +yellow+) (make-tile 'e1 '((20 60) (60 60) (40 40) (20 60)) +black+) (make-tile 'f1 '((60 20) (80 40) (60 60) (40 40) (60 20)) +cyan+) (make-tile 'g1 '((0 80) (40 80) (60 60) (20 60) (0 80)) (make-rgb-color 1 0.3 0.9) :mirror-values '((1 1) (-1 1) (1 -1) (-1 -1)))) )) (setf *tangram-frame* #-:mswindows (make-application-frame 'tangram-frame :left 40 :top 40 :width 900 :height 950) #+:mswindows (make-application-frame 'tangram-frame :left 40 :top 40 :width 800 :height 750)) (setf (current-set *tangram-frame*) (first (all-sets *tangram-frame*))) (setf *process* #+mcl (ccl:process-run-function "Tangram" #'(lambda () (run-frame-top-level *tangram-frame*))) (mp:process-run-function "Tangram" #+lispworks '(:size 250000) ;;; set Stack Size! #'(lambda () (run-frame-top-level *tangram-frame*)))))
61,195
Common Lisp
.lisp
1,268
28.764196
117
0.448751
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
85757eb7cef57bdf06fc6c7b394b671a05e3257453d86c6077c9009afe4b567a
4,340
[ -1 ]
4,341
gui-aux.lisp
lambdamikel_Common-Lisp-Tangram-Solver/src/gui/gui-aux.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: TANGRAM; Base: 10 -*- (in-package tangram) #+:mcl (defun file-selector (title directory pattern &key save) (declare (ignore title)) (loop (let ((pathname (ccl:catch-cancel (if (not save) (ccl:choose-file-dialog :directory directory) (ccl:choose-new-file-dialog :directory directory))))) (cond ((eq pathname :cancel) (return nil)) ((string-equal (pathname-type pathname) pattern) (return pathname)) (t (ccl:message-dialog (format nil "Required File Extension: ~A" pattern))))))) #+:allegro (defun file-selector (title directory pattern &key (save nil)) (with-application-frame (frame) (loop (let ((file (select-file frame :pattern (concatenate 'string "*." pattern) :title title :directory (namestring (truename directory))))) (if file (when (and file (not (string= "" file))) (cond ((char= (elt file (1- (length file))) #\/) (notify-user frame "You must select a file, not a directory!" :style :error)) ((not (string= (subseq file (- (length file) (length pattern))) pattern)) (notify-user frame (format nil "Required File Extension: ~A" pattern) :style :error)) (save (when (cl-user:=> (probe-file file) (notify-user frame (format nil "Overwrite ~A?" file) :style :warning)) (return file))) ((and (not save) (probe-file file)) (return file)) (t (notify-user frame (format nil "File ~A does not exist" file) :style :error)))) (return nil)))))) #+:lispworks (defun file-selector (title directory pattern &key (save nil)) (with-application-frame (frame) (loop (let ((file (select-file frame :pattern (concatenate 'string "*." pattern) :title title :directory (directory-namestring (translate-logical-pathname directory))))) (if file (let ((file (namestring file))) (when (and file (not (string= "" file))) (cond ((char= (elt file (1- (length file))) #\/) (notify-user frame "You must select a file, not a directory!" :style :error)) ((not (string= (subseq file (- (length file) (length pattern))) pattern)) (notify-user frame (format nil "Required File Extension: ~A" pattern) :style :error)) (save (when (cl-user:=> (probe-file file) (notify-user frame (format nil "Overwrite ~A?" file) :style :warning)) (return file))) ((and (not save) (probe-file file)) (return file)) (t (notify-user frame (format nil "File ~A does not exist" file) :style :error))))) (return nil)))))) #+:mcl (defmacro mcl-pane (&body body) `(outlining () ,@body)) (defun inverse-highlighter (type record stream state) (declare (ignore state type)) (multiple-value-bind (xoff yoff) (convert-from-relative-to-absolute-coordinates stream (output-record-parent record)) (with-bounding-rectangle* (left top right bottom) record (draw-rectangle* stream (+ left xoff) (+ top yoff) (+ right xoff) (+ bottom yoff) :ink +flipping-ink+)))) (defmacro with-centering ((stream) &body body) (let ((x (gensym))) `(multiple-value-bind (,x) (window-inside-size ,stream) (formatting-table (stream) (formatting-row (stream) (formatting-cell (stream :align-x :center :align-y :center :min-width ,x) ,@body))) (terpri stream)))) (defmacro with-border ((stream &key (offset 0)) &body body) (let ((or (gensym))) `(let ((,or (with-output-to-output-record (,stream) ,@body))) (draw-rectangle* ,stream (- (bounding-rectangle-min-x ,or) ,offset) (- (bounding-rectangle-min-y ,or) ,offset) (+ (bounding-rectangle-max-x ,or) ,offset) (+ (bounding-rectangle-max-y ,or) ,offset) :line-dashes '(1 1) :filled nil) ,@body))) (defmacro draw-marker* (stream x y radius &rest args) `(let ((x ,x) (y ,y) (r ,radius)) (clim:draw-rectangle* ,stream (- x r) (- y r) (+ x r) (+ y r) :line-thickness 1 :filled nil ,@args) (clim:draw-line* stream (- x r) (- y r) (+ x r) (+ y r) :line-thickness 1 ,@args) (clim:draw-line* stream (- x r) (+ y r) (+ x r) (- y r) :line-thickness 1 ,@args))) (defun get-size-of-graphic (stream fn) (let ((or (with-output-to-output-record (stream) (funcall fn)))) (values (bounding-rectangle-width or) (bounding-rectangle-height or)))) #+:lispworks (defmacro with-correct-clipping ((stream) &body body) `(multiple-value-bind (window-width window-height) (bounding-rectangle-size (bounding-rectangle (window-viewport ,stream))) (with-drawing-options (,stream :clipping-region (make-bounding-rectangle 0 0 window-width window-height)) ,@body))) #-:lispworks (defmacro with-correct-clipping ((stream) &body body) body)
6,484
Common Lisp
.lisp
170
24.452941
93
0.475199
lambdamikel/Common-Lisp-Tangram-Solver
30
6
0
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
e0324befd4e15411130f6a717e31e4347eec09b0c1d104225459baa2398d28c8
4,341
[ -1 ]
4,375
demo.lisp
jnjcc_cl-qrencode/demo.lisp
(cl-qrencode:encode-png "01234567" :fpath "numer.png" :version 1 :level :level-m) (cl-qrencode:encode-png "HELLO WORLD" :fpath "alnum.png" :version 1 :level :level-q) (let ((text (cl-qrencode:read-file-content #p"README.md"))) (cl-qrencode:encode-png (subseq text 0 200) :fpath "byte.png" :margin 12)) ;;; normally, we choose not to encode :kanji ;;; in case you are interested, here's how we did it (it sucks...) ; (cl-qrencode:encode-png-bytes :fpath "kanji.png" '(#x93 #x5f #x26 #xe4 #xaa))
547
Common Lisp
.lisp
9
53.888889
79
0.639252
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
a4a104367664301ce73c403f6ee564034472327d7df2629622fd533327f260d1
4,375
[ -1 ]
4,376
packages.lisp
jnjcc_cl-qrencode/packages.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-user) (defpackage #:cl-qrencode (:nicknames :qrcode) (:use #:cl) (:import-from #:zpng #:png #:data-array #:write-png) (:export #:encode-symbol #:encode-symbol-bytes ; this should have been deprecated ;; QR code representation ;; this should be enough to write another backend for QR symbol #:qr-symbol #:matrix #:modules #:dark-module-p ;; png backend ;; strictly speaking, this should not be part of this package #:encode-png #:encode-png-bytes ; this should have been deprecated #:encode-png-stream ; #:encode-png-bytes-stream #:read-file-content #:sdebug #:undebug))
893
Common Lisp
.lisp
27
23.407407
74
0.547454
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
16aad38972155b300abdf80da8753ed5e73a84b88087d709d522a39119668b3e
4,376
[ -1 ]
4,377
utils.lisp
jnjcc_cl-qrencode/test/utils.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; test utils (in-package #:cl-qrencode-test) (defun function-pattern-symbol (version) "qr symbol only consisted of function patterns" (let* ((modules (cl-qrencode::matrix-modules version)) (matrix (cl-qrencode::make-modules-matrix modules))) (cl-qrencode::function-patterns matrix version) (make-instance 'cl-qrencode::qr-symbol :matrix matrix :modules modules))) (defun string->input (text &key (version 1) (level :level-m) (mode :numeric)) (let ((bytes (cl-qrencode::ascii->bytes text))) (cl-qrencode::bytes->input bytes version level mode))) (defun raw-symbol (text &key (version 1) (level :level-m) (mode nil)) "raw symbol, without masking" (let ((input (string->input text :version version :level level :mode mode))) (make-instance 'cl-qrencode::qr-symbol :matrix (cl-qrencode::matrix input) :modules (cl-qrencode::matrix-modules (cl-qrencode::version input))))) (defun function-pattern-png (version) "dump function patterns into png" (let ((fp (function-pattern-symbol version))) (cl-qrencode::symbol->png fp "funtion-pattern.png" 9 8))) (defun raw-symbol-png (text &key (version 1) (level :level-m) (mode nil)) "dump raw symbol into png" (let ((raw (raw-symbol text :version version :level level :mode mode))) (cl-qrencode::symbol->png raw "raw-symbol.png" 9 8)))
1,469
Common Lisp
.lisp
28
47.071429
78
0.677577
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
7b7474b54302fcb0a0d96c755229bb4db33c08c24e327b4459d465c8289bf7c6
4,377
[ -1 ]
4,378
tests.lisp
jnjcc_cl-qrencode/test/tests.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-qrencode-test) (defun run-all-tests () (let ((result (run-tests :all :cl-qrencode-test))) (test-names result) result))
220
Common Lisp
.lisp
7
28.714286
66
0.668246
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
708e87f24ba3d2ee4a74121acdf048d721bda00a9aeb582888c8affb4900e807
4,378
[ -1 ]
4,379
spec-test.lisp
jnjcc_cl-qrencode/test/spec-test.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-qrencode-test) (define-test validate-align-centers (loop for v from 1 to 40 do (let ((centers (cl-qrencode::align-centers v))) (assert-eql (aref cl-qrencode::*align-coord-table* v 0) (length centers))))) (define-test validate-align-version7 (let ((expected '((6 22) (22 6) (22 22) (22 38) (38 22) (38 38))) (centers (cl-qrencode::align-centers 7))) (labels ((cmp (a b) (cond ((= (car a) (car b)) (< (cadr a) (cadr b))) (t (< (car a) (car b)))))) (setf centers (sort centers #'cmp)) (assert-equal expected centers))))
722
Common Lisp
.lisp
17
34.647059
67
0.55761
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
c20f6d312fbbdfbbd2d3cd982965b47a3deef538a4e4a13ee2b81b5bcf6f8909
4,379
[ -1 ]
4,380
pre-spec.lisp
jnjcc_cl-qrencode/test/pre-spec.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; pre-computed results, we chose not to use them in application, though (in-package #:cl-qrencode-test) ;;; Pre-Computed Generator Polynomial for RS error correction codewords ;;; varies between # of error correction codewords ;;; for validation purpose only (defvar *generator-poly* #(() () ; 0/1 error correction codewords (0 25 1) ; x^2 + a^25*x + a () () ; 3/4 error correction codewords (0 113 164 166 119 10) ; x^5 (0 166 0 134 5 176 15) ; x^6: you serious about this?! (0 87 229 146 149 238 102 21) ; x^7 (0 175 238 208 249 215 252 196 28) ; x^8 () ; 9 error correction codewords (0 251 67 46 61 118 70 64 94 32 45) ; x^10 () () ; 11/12 (0 74 152 176 100 86 100 106 104 130 218 206 140 78) ; x^13 (0 199 249 155 48 190 124 218 137 216 87 207 59 22 91) ; x^14 (0 8 183 61 91 202 37 51 58 58 237 140 124 5 99 105) ; x^15 (0 120 104 107 109 102 161 76 3 91 191 147 169 182 194 225 120) ; x^16 (0 43 139 206 78 43 239 123 206 214 147 24 99 150 39 243 163 136) ; x^17 (0 215 234 158 94 184 97 118 170 79 187 152 148 252 179 5 98 96 153) ; x^18 () ; 19 (0 17 60 79 50 61 163 26 187 202 180 221 225 83 239 156 164 212 212 188 190) ; x^20 () ; 21 (0 210 171 247 242 93 230 14 109 221 53 200 74 8 172 98 80 219 134 160 105 165 231) ; x^22 () ; 23 (0 229 121 135 48 211 117 251 126 159 180 169 152 192 226 228 218 111 0 117 232 87 96 227 21) ; x^24 () ; 25 (0 173 125 158 2 103 182 118 17 145 201 111 28 165 53 161 21 245 142 13 102 48 227 153 145 218 70) ; x^26 () ; 27 (0 168 223 200 104 224 234 108 180 110 190 195 147 205 27 232 201 21 43 245 87 42 195 212 119 242 37 9 123) ; x^28 () ; 29 (0 41 173 145 152 216 31 179 182 50 48 110 86 239 96 222 125 42 173 226 193 224 130 156 37 251 216 238 40 192 180) ; x^30 () ; 31 (0 10 6 106 190 249 167 4 67 209 138 138 32 242 123 89 27 120 185 80 156 38 69 171 60 28 222 80 52 254 185 220 241) ; x^32 () ; 33 (0 111 77 146 94 26 21 108 19 105 94 113 193 86 140 163 125 58 158 229 239 218 103 56 70 114 61 183 129 167 13 98 62 129 51) ; x^34 () ; 35 (0 200 183 98 16 172 31 246 234 60 152 115 0 167 152 113 248 238 107 18 63 218 37 87 210 105 177 120 74 121 196 117 251 113 233 30 120) ; x^36 () () () ; 37, 38, 39 (0 59 116 79 161 252 98 128 205 128 161 247 57 163 56 235 106 53 26 187 174 226 104 170 7 175 35 181 114 88 41 47 163 125 134 72 20 232 53 35 15) ; x^40 () ; 41 (0 250 103 221 230 25 18 137 231 0 3 58 242 221 191 110 84 230 8 188 106 96 147 15 131 139 34 101 223 39 101 213 199 237 254 201 123 171 162 194 117 50 96) ; x^42 () ; 43 (0 190 7 61 121 71 246 69 55 168 188 89 243 191 25 72 123 9 145 14 247 1 238 44 78 143 62 224 126 118 114 68 163 52 194 217 147 204 169 37 130 113 102 73 181) ; x^44 () ; 45 (0 112 94 88 112 253 224 202 115 187 99 89 5 54 113 129 44 58 16 135 216 169 211 36 1 4 96 60 241 73 104 234 8 249 245 119 174 52 25 157 224 43 202 223 19 82 15) ; x^46 () ; 47 (0 228 25 196 130 211 146 60 24 251 90 39 102 240 61 178 63 46 123 115 18 221 111 135 160 182 205 107 206 95 150 120 184 91 21 247 156 140 238 191 11 94 227 84 50 163 39 34 108) ; x^48 () ; 49 (0 232 125 157 161 164 9 118 46 209 99 203 193 35 3 209 111 195 242 203 225 46 13 32 160 126 209 130 160 242 215 242 75 77 42 189 32 113 65 124 69 228 114 235 175 124 170 215 232 133 205) ; x^50 () ; 51 (0 116 50 86 186 50 220 251 89 192 46 86 127 124 19 184 233 151 215 22 14 59 145 37 242 203 134 254 89 190 94 59 65 124 113 100 233 235 121 22 76 86 97 39 242 200 220 101 33 239 254 116 51) ; x^52 () ; 53 (0 183 26 201 87 210 221 113 21 46 65 45 50 238 184 249 225 102 58 209 218 109 165 26 95 184 192 52 245 35 254 238 175 172 79 123 25 122 43 120 108 215 80 128 201 235 8 153 59 101 31 198 76 31 156) ; x^54 () ; 55 (0 106 120 107 157 164 216 112 116 2 91 248 163 36 201 202 229 6 144 254 155 135 208 170 209 12 139 127 142 182 249 177 174 190 28 10 85 239 184 101 124 152 206 96 23 163 61 27 196 247 151 154 202 207 20 61 10) ; x^56 () ; 57 (0 82 116 26 247 66 27 62 107 252 182 200 185 235 55 251 242 210 144 154 237 176 141 192 248 152 249 206 85 253 142 65 165 125 23 24 30 122 240 214 6 129 218 29 145 127 134 206 245 117 29 41 63 159 142 233 125 148 123) ; x^58 () ; 59 (0 107 140 26 12 9 141 243 197 226 197 219 45 211 101 219 120 28 181 127 6 100 247 2 205 198 57 115 219 101 109 160 82 37 38 238 49 160 209 121 86 11 124 30 181 84 25 194 87 65 102 190 220 70 27 209 16 89 7 33 240) ; x^60 () ; 61 (0 65 202 113 98 71 223 248 118 214 94 0 122 37 23 2 228 58 121 7 105 135 78 243 118 70 76 223 89 72 50 70 111 194 17 212 126 181 35 221 117 235 11 229 149 147 123 213 40 115 6 200 100 26 246 182 218 127 215 36 186 110 106) ; x^62 () ; 63 (0 45 51 175 9 7 158 159 49 68 119 92 123 177 204 187 254 200 78 141 149 119 26 127 53 160 93 199 212 29 24 145 156 208 150 218 209 4 216 91 47 184 146 47 140 195 195 125 242 238 63 99 108 140 230 242 31 204 11 178 243 217 156 213 231) ; x^64 () ; 65 (0 5 118 222 180 136 136 162 51 46 117 13 215 81 17 139 247 197 171 95 173 65 137 178 68 111 95 101 41 72 214 169 197 95 7 44 154 77 111 236 40 121 143 63 87 80 253 240 126 217 77 34 232 106 50 168 82 76 146 67 106 171 25 132 93 45 105) ; x^66 () ; 67 (0 247 159 223 33 224 93 77 70 90 160 32 254 43 150 84 101 190 205 133 52 60 202 165 220 203 151 93 84 15 84 253 173 160 89 227 52 199 97 95 231 52 177 41 125 137 241 166 225 118 2 54 32 82 215 175 198 43 238 235 27 101 184 127 3 5 8 163 238))) ; x^68 ;;; Pre-Computed Format information ecc hex for each level & mask pattern ;;; for validation purpose only (defvar *format-info-hex* #(#x5412 #x5125 #x5E7C #x5B4B #x45F9 #x40CE #x4F97 #x4AA0 ; 00000 - 00111, 0-7 #x77C4 #x72F3 #x7DAA #x789D #x662F #x6318 #x6C41 #x6976 #x1689 #x13BE #x1CE7 #x19D0 #x0762 #x0255 #x0D0C #x083B #x355F #x3068 #x3F31 #x3A06 #x24B4 #x2183 #x2EDA #x2BED)) ;;; Pre-Computed Version information ecc hex for each version ;;; for validation purpose only (defvar *version-info-hex* #(#x07C94 #x085BC #x09A99 #x0A4D3 #x0BBF6 #x0C762 ; 7 ~ 12 #x0D847 #x0E60D #x0F928 #x10B78 #x1145D #x12A17 ; 13 ~ 18 #x13532 #x149A6 #x15683 #x168C9 #x177EC #x18EC4 ; 19 ~ 24 #x191E1 #x1AFAB #x1B08E #x1CC1A #x1D33F #x1ED75 ; 25 ~ 30 #x1F250 #x209D5 #x216F0 #x228BA #x2379F #x24B0B ; 31 ~ 36 #x2542E #x26A64 #x27541 #x28C69)) ; 37 ~ 40
6,744
Common Lisp
.lisp
128
47.828125
87
0.642771
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
82386a5dfbe45fe828dc3b0a8e0463d65778d92cf1171b7f79d6ecb6e4773925
4,380
[ -1 ]
4,381
encode-test.lisp
jnjcc_cl-qrencode/test/encode-test.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; "01234567" version 1, level-m, :numeric (in-package #:cl-qrencode-test) (defvar text "01234567") (defvar input (string->input text :mode :numeric)) (defvar data-encoding '(0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0 1 0 1 1 0 0 1 1 0 0 0 0 1 1 0 0 0 0 0 0 0 1 1 1 0 1 1 0 0 0 0 0 1 0 0 0 1 1 1 1 0 1 1 0 0 0 0 0 1 0 0 0 1 1 1 1 0 1 1 0 0 0 0 0 1 0 0 0 1 1 1 1 0 1 1 0 0 0 0 0 1 0 0 0 1 1 1 1 0 1 1 0 0 0 0 0 1 0 0 0 1)) (defvar ec-coding '(1 0 1 0 0 1 0 1 0 0 1 0 0 1 0 0 1 1 0 1 0 1 0 0 1 1 0 0 0 0 0 1 1 1 1 0 1 1 0 1 0 0 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 1 0 0 0 1 0 1 0 1 0 1)) (define-test validate-data-encoding0-7 (assert-equal data-encoding (cl-qrencode::bstream input))) (define-test validate-ec-coding0-7 (assert-equal ec-coding (reduce #'append (mapcar #'(lambda (dec) (cl-qrencode::decimal->bstream dec 8)) (car (cl-qrencode::ecc-blocks input)))))) #| (define-test validate-symbol0-7 (cl-qrencode::symbol->png (cl-qrencode::input->symbol input) "figure-i1.png" 9 8) (format t "compare figure-i1.png with Figure I.1 yourself...")) |# (define-test validate-mask0-7 (multiple-value-bind (masked mask-ref) (cl-qrencode::data-masking input) (declare (ignore masked)) (assert-equal '(0 1 0) mask-ref))) (defun hex-string-to-bytes (string) (with-input-from-string (stream string) (loop with *read-base* = 16 for x = (read stream NIL) while x collect x))) (define-test validate-encoding (let ((expected (hex-string-to-bytes "40 86 86 57 27 06 46 57 27 00 ec 11 ec 11 ec 11")) (generated (cl-qrencode::bytes->input (cl-qrencode::ascii->bytes "herpderp") 1 :level-m NIL))) (assert-equal expected (cl-qrencode::bstream->codewords (slot-value generated 'cl-qrencode::bstream)))))
2,128
Common Lisp
.lisp
45
39.6
92
0.57253
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
3eff0caf8f9efd8749d43b83eff59b8d5c1ec5e00b4dcbb6dbf239bf00e0f977
4,381
[ -1 ]
4,382
ecc-test.lisp
jnjcc_cl-qrencode/test/ecc-test.lisp
;;;; Copyright (c) 2011-2014 jncc, Yste.org. All rights reserved. ;;;; (in-package #:cl-qrencode-test) (define-test validate-gen-poly (loop for ec from 2 to 68 do (let ((expect (aref *generator-poly* ec))) (when expect (let* ((rs (make-instance 'cl-qrencode::rs-ecc :ec ec :k nil)) (gpoly (cl-qrencode::gen-poly-gflog rs))) (assert-equal expect gpoly)))))) (defun encode-alnum (text) (let ((input (string->input text :version 1 :level :level-m :mode :alnum))) input)) (define-test validate-hello-world-ecc "blocks input" (let ((input (encode-alnum "HELLO WORLD"))) (assert-equal '(32 91 11 120 209 114 220 77 67 64 236 17 236 17 236 17) (car (cl-qrencode::blocks input))) (assert-equal '(196 35 39 119 235 215 231 226 93 23) (car (cl-qrencode::ecc-blocks input))))) (define-test validate-version-ecc (loop for v from 7 to 40 do (let ((vib (cl-qrencode::version-ecc v))) (assert-eql (aref *version-info-hex* (- v 7)) (cl-qrencode::bstream->decimal vib 18))))) (define-test validate-format-ecc (let ((idx 0)) ;; 00 01 10 11 (dolist (l '(:level-m :level-l :level-h :level-q)) ;; 000 ~ 111 (dotimes (m cl-qrencode::*mask-pattern-num*) (let ((seq (append (cl-qrencode::level-indicator l) (cl-qrencode::mask-pattern-ref m))) (fib (cl-qrencode::format-ecc l m))) (assert-eql idx (cl-qrencode::bstream->decimal seq 5)) (assert-eql (aref *format-info-hex* idx) (cl-qrencode::bstream->decimal fib 15)) (incf idx))))))
1,690
Common Lisp
.lisp
38
36.052632
77
0.584447
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
2d60c94c17bb861a6eab07c655443a6ddd6ce30a25b7a74bce5c986b7368fb24
4,382
[ -1 ]
4,383
packages.lisp
jnjcc_cl-qrencode/test/packages.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-user) (defpackage #:cl-qrencode-test (:nicknames :qrcode-test) (:use #:cl #:lisp-unit #:cl-qrencode) (:import-from #:cl-qrencode #:ec-coding) (:export #:run-all-tests #:function-pattern-symbol #:function-pattern-png #:raw-symbol #:raw-symbol-png))
407
Common Lisp
.lisp
13
24.923077
66
0.594388
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
7dca4723e16eeb25f917f2dbff3c03c6e62d8e438b7905b33069dc3c97f0045e
4,383
[ -1 ]
4,384
util.lisp
jnjcc_cl-qrencode/utils/util.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org, all rights reserved. ;;;; (in-package #:cl-qrencode) ;;; Adapted from P. Norvig's PAIP (defvar *dbg-ids* nil) (defun sdebug (&rest ids) (setf *dbg-ids* (union ids *dbg-ids*))) (defun undebug (&rest ids) (setf *dbg-ids* (if (null ids) nil (set-difference *dbg-ids* ids)))) (defun dbg (id format-string &rest args) (when (member id *dbg-ids*) (fresh-line *debug-io*) (apply #'format *debug-io* format-string args))) (defun read-file-content (fpath) (with-open-file (fp fpath) (let ((content (make-string (file-length fp)))) (read-sequence content fp) content)))
684
Common Lisp
.lisp
20
29.3
66
0.620846
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
1fe9b611d9c384f6e98559cc7804ecde6cad5d6f3db23958c3c5b7e1c3290e89
4,384
[ -1 ]
4,385
png.lisp
jnjcc_cl-qrencode/image/png.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; png backend for QR code symbol (in-package #:cl-qrencode) (defun set-color (pngarray x y color) (setf (aref pngarray x y 0) color) (setf (aref pngarray x y 1) color) (setf (aref pngarray x y 2) color)) (defun symbol->png (symbol pixsize margin) "return the qr symbol written into a zpng:png object with PIXSIZE pixels for each module, and MARGIN pixels on all four sides" (with-slots (matrix modules) symbol (let* ((size (+ (* modules pixsize) (* margin 2))) (qrpng (make-instance 'zpng:png :width size :height size)) (qrarray (zpng:data-array qrpng))) (dotimes (x size) (dotimes (y size) (if (and (<= margin x (- size margin 1)) (<= margin y (- size margin 1))) (let ((i (floor (- x margin) pixsize)) (j (floor (- y margin) pixsize))) (if (dark-module-p matrix i j) (set-color qrarray x y 0) (set-color qrarray x y 255))) ;; quiet zone (set-color qrarray x y 255)))) qrpng))) (defun encode-png (text &key (fpath "qrcode.png") (version 1) (level :level-m) (mode nil) (pixsize 9) (margin 8)) (let ((symbol (encode-symbol text :version version :level level :mode mode))) (zpng:write-png (symbol->png symbol pixsize margin) fpath))) (defun encode-png-stream (text stream &key (version 1) (level :level-m) (mode nil) (pixsize 9) (margin 8)) (let ((symbol (encode-symbol text :version version :level level :mode mode))) (zpng:write-png-stream (symbol->png symbol pixsize margin) stream))) (defun encode-png-bytes (bytes &key (fpath "kanji.png") (version 1) (level :level-m) (mode nil) (pixsize 9) (margin 8)) (let ((symbol (encode-symbol-bytes bytes :version version :level level :mode mode))) (zpng:write-png (symbol->png symbol pixsize margin) fpath))) (defun encode-png-bytes-stream (bytes stream &key (version 1) (level :level-m) (mode nil) (pixsize 9) (margin 8)) (let ((symbol (encode-symbol-bytes bytes :version version :level level :mode mode))) (zpng:write-png-stream (symbol->png symbol pixsize margin) stream)))
2,404
Common Lisp
.lisp
45
43.333333
79
0.59286
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
189a9c1e0ff0878b4393c520b943d146bbc0f28618dc9898a6a5d7c1c43c9d01
4,385
[ -1 ]
4,386
encode.lisp
jnjcc_cl-qrencode/qrencode/encode.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; final QR code symbol (in-package #:cl-qrencode) (defclass qr-symbol () ((matrix :initform nil :initarg :matrix :reader matrix :documentation "qr code symbol as matrix") (modules :initform nil :initarg :modules :reader modules :documentation "qr code symbol modules"))) (defmethod print-object ((symbol qr-symbol) stream) (fresh-line stream) (with-slots (matrix modules) symbol (format stream "qr symbol ~A x ~A:~%" modules modules) (dotimes (i modules) (dotimes (j modules) (if (dark-module-p matrix i j) (format stream "1 ") (format stream "0 "))) (format stream "~%")))) ;;; FIXME: other encodings??? (defun ascii->bytes (text) (map 'list #'char-code text)) (defun bytes->input (bytes version level mode) (setf version (min (max version 1) 40)) (let ((input (make-instance 'qr-input :bytes bytes :version version :ec-level level :mode mode))) (data-encoding input) (ec-coding input) (structure-message input) (module-placement input) input)) (defun input->symbol (input) "encode qr symbol from a qr-input" (multiple-value-bind (matrix mask-ref) (data-masking input) (declare (ignore mask-ref)) (let ((modules (matrix-modules (version input)))) (make-instance 'qr-symbol :matrix matrix :modules modules)))) (defun encode-symbol-bytes (bytes &key (version 1) (level :level-m) (mode nil)) "encode final qr symbol from BYTES list" (let ((input (bytes->input bytes version level mode))) (dbg :dbg-input "version: ~A; segments: ~A~%" (version input) (segments input)) (input->symbol input))) ;;;----------------------------------------------------------------------------- ;;; One Ring to Rule Them All, One Ring to Find Them, ;;; One Ring to Bring Them All and In the Darkness Blind Them: ;;; This function wraps all we need. ;;;----------------------------------------------------------------------------- ;; (sdebug :dbg-input) (defun encode-symbol (text &key (version 1) (level :level-m) (mode nil)) "encode final qr symbol, unless you know what you are doing, leave MODE NIL" (let ((bytes (ascii->bytes text))) (encode-symbol-bytes bytes :version version :level level :mode mode)))
2,362
Common Lisp
.lisp
54
39.037037
80
0.619296
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
0d690fa60e9f0a0875094577cb1d24d77adfb3e51ae943a6c6dbba01e9eb430d
4,386
[ -1 ]
4,387
modes.lisp
jnjcc_cl-qrencode/qrencode/modes.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-qrencode) (deftype qr-mode () '(member :unknown :numeric :alnum :byte :kanji ;; Extended Channel Interpretation, Structured Append, FNC1 :eci :structured :fnc1)) (defun mode-indicator (mode) (declare (type qr-mode mode)) (case mode (:numeric '(0 0 0 1)) ; "0001" (:alnum '(0 0 1 0)) ; "0010" (:byte '(0 1 0 0)) ; "0100" (:kanji '(1 0 0 0)) ; "1000" (:eci '(0 1 1 1)) ; "0111" (:structured '(0 0 1 1)) ; "0011" (:fnc1 '(0 1 0 1)))) ; FIXME: "0101" & "1001" (defun terminator (bstream version level) "End of message" (let* ((nbits (length bstream)) (diff (- (* (data-words-capacity version level) 8) nbits))) (cond ((< diff 0) (error "you serious about this?!")) ((<= diff 4) (make-list diff :initial-element 0)) (t (make-list 4 :initial-element 0))))) (defun byte-value (mode byte) "BYTE value under MODE" (declare (type qr-mode mode)) (case mode (:numeric (and (<= #x30 byte #x39) (- byte #x30))) (:alnum (cond ((<= #x30 byte #x39) (- byte #x30)) ; 0-9 ((<= #x41 byte #x5A) (+ (- byte #x41) 10)) ; A-Z ((= byte #x20) 36) ; SP ((= byte #x24) 37) ; $ ((= byte #x25) 38) ; % ((= byte #x2A) 39) ; * ((= byte #x2B) 40) ; + ((= byte #x2D) 41) ; - ((= byte #x2E) 42) ; . ((= byte #x2F) 43) ; / ((= byte #x3A) 44) ; : (t nil))) ((:byte :kanji) byte))) (defun kanji-word-p (word) "(kanji-p, kanji-range: {0, 1})" (cond ((<= #x8140 word #x9ffc) (values t 0)) ((<= #xe040 word #xebbf) (values t 1)) (t (values nil nil)))) (defun starts-kanji-p (bytes) "(BYTES starts with kanji-p, kanji word value, kanji-range: {0, 1})" (declare (type list bytes)) (let* ((first (car bytes)) (second (cadr bytes)) (word (and second (+ (ash first 8) second)))) (if (and first second) (multiple-value-bind (kanji-p range) (kanji-word-p word) (values kanji-p word range)) (values nil nil nil)))) (defun xor-subset-of (bytes) "exclusive subset of first unit of BYTES. as for unit, one byte for :numeric, :alnum; two bytes for :kanji" (declare (type list bytes)) (let* ((first (car bytes))) (cond ((null first) :unknown) ((byte-value :numeric first) :numeric) ((byte-value :alnum first) :alnum) ;; excluding reserved values 80-9F & E0-FF ((and (not (<= #x80 first #x9F)) (not (<= #xE0 first #xFF))) :byte) ((starts-kanji-p bytes) :kanji))))
2,693
Common Lisp
.lisp
81
27.518519
70
0.541859
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
397098a599c30c1387ed5eb76a4b21b230ad07544757d8c375afd07ec47383ac
4,387
[ -1 ]
4,388
qrspec.lisp
jnjcc_cl-qrencode/qrencode/qrspec.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-qrencode) ;;; Table 1 - Codeword capacity of all versions of QR Code 2005 ;;; excluding Micro QR Code, varies between version (defvar *codeword-capacity-table* #2A((-1 -1 -1 -1 -1 -1) ; 0, no such version (21 202 31 208 26 0) (25 235 31 359 44 7) (29 243 31 567 70 7) (33 251 31 807 100 7) (37 259 31 1079 134 7) (41 267 31 1383 172 7) (45 390 67 1568 196 0) (49 398 67 1936 242 0) (53 406 67 2336 292 0) (57 414 67 2768 346 0) ; Version 10 (61 422 67 3232 404 0) (65 430 67 3728 466 0) (69 438 67 4256 532 0) (73 611 67 4651 581 3) (77 619 67 5243 655 3) (81 627 67 5867 733 3) (85 635 67 6523 815 3) (89 643 67 7211 901 3) (93 651 67 7931 991 3) (97 659 67 8683 1085 3) ; Version 20 (101 882 67 9252 1156 4) (105 890 67 10068 1258 4) (109 898 67 10916 1364 4) (113 906 67 11796 1474 4) (117 914 67 12708 1588 4) (121 922 67 13652 1706 4) (125 930 67 14628 1828 4) (129 1203 67 15371 1921 3) (133 1211 67 16411 2051 3) (137 1219 67 17483 2185 3) ; Version 30 (141 1227 67 18587 2323 3) (145 1235 67 19723 2465 3) (149 1243 67 20891 2611 3) (153 1251 67 22091 2761 3) (157 1574 67 23008 2876 0) (161 1582 67 24272 3034 0) (165 1590 67 25568 3196 0) (169 1598 67 26896 3362 0) (173 1606 67 28256 3532 0) (177 1614 67 29648 3706 0)) ; Version 40 "Number of modules (as version increases, 4 modules added) A | Function pattern modules B | Format and Version information modules C | Data modules (A^2-B-C) | Data capacity codewords (bytes, including ecc codewords) | Remainder bits.") (defun codeword-capacity (version) "codeword: data word + ecc word" (aref *codeword-capacity-table* version 4)) (defun matrix-modules (version) (aref *codeword-capacity-table* version 0)) (defun remainder-bits (version) (aref *codeword-capacity-table* version 5)) (defun mode->index (mode) (case mode (:numeric 0) (:alnum 1) (:byte 2) (:kanji 3))) (deftype ecc-level () '(member :level-l :level-m :level-q :level-h)) (defun level->index (level) (case level (:level-l 0) (:level-m 1) (:level-q 2) (:level-h 3))) ;;; (Part I of) Table 9 - Number of Error Correction Codewords (bytes) ;;; varies between version and level (defvar *ecc-codewords-table* ;; (:level-l :level-m :level-q :level-h) #2A((-1 -1 -1 -1) ;; 0, no such version (7 10 13 17) (10 16 22 28) (15 26 36 44) (20 36 52 64) (26 48 72 88) (36 64 96 112) (40 72 108 130) (48 88 132 156) (60 110 160 192) (72 130 192 224) (80 150 224 264) (96 176 260 308) (104 198 288 352) (120 216 320 384) (132 240 360 432) (144 280 408 480) (168 308 448 532) (180 338 504 588) (196 364 546 650) (224 416 600 700) (224 442 644 750) (252 476 690 816) (270 504 750 900) (300 560 810 960) (312 588 870 1050) (336 644 952 1110) (360 700 1020 1200) (390 728 1050 1260) (420 784 1140 1350) (450 812 1200 1440) (480 868 1290 1530) (510 924 1350 1620) (540 980 1440 1710) (570 1036 1530 1800) (570 1064 1590 1890) (600 1120 1680 1980) (630 1204 1770 2100) (660 1260 1860 2220) (720 1316 1950 2310) (750 1372 2040 2430))) ;; version 1 ~ 40 (defun ecc-words-capacity (version level) (aref *ecc-codewords-table* version (level->index level))) (defun data-words-capacity (version level) (- (codeword-capacity version) (ecc-words-capacity version level))) ;;; (Part II of) Table 9 - Error Correction blocks ;;; varies between version and level (defvar *ecc-blocks* ;; (version, level) => ;; (# of ec codewords for each blk, # of blk 1, # of data words for blk 1, ;; # of blk 2, # of data words for blk 2) ;; :level-l :level-m :level-q :level-h #3A(((0 0 0 0 0) (0 0 0 0 0) (0 0 0 0 0) (0 0 0 0 0)) ; no such version ((7 1 19 0 0) (10 1 16 0 0) (13 1 13 0 0) (17 1 9 0 0)) ; Version 1 ((10 1 34 0 0) (16 1 28 0 0) (22 1 22 0 0) (28 1 16 0 0)) ((15 1 55 0 0) (26 1 44 0 0) (18 2 17 0 0) (22 2 13 0 0)) ((20 1 80 0 0) (18 2 32 0 0) (26 2 24 0 0) (16 4 9 0 0)) ((26 1 108 0 0) (24 2 43 0 0) (18 2 15 2 16) (22 2 11 2 12)) ; Version 5 ((18 2 68 0 0) (16 4 27 0 0) (24 4 19 0 0) (28 4 15 0 0)) ((20 2 78 0 0) (18 4 31 0 0) (18 2 14 4 15) (26 4 13 1 14)) ((24 2 97 0 0) (22 2 38 2 39) (22 4 18 2 19) (26 4 14 2 15)) ((30 2 116 0 0) (22 3 36 2 37) (20 4 16 4 17) (24 4 12 4 13)) ((18 2 68 2 69) (26 4 43 1 44) (24 6 19 2 20) (28 6 15 2 16)) ; Version 10 ((20 4 81 0 0) (30 1 50 4 51) (28 4 22 4 23) (24 3 12 8 13)) ((24 2 92 2 93) (22 6 36 2 37) (26 4 20 6 21) (28 7 14 4 15)) ((26 4 107 0 0) (22 8 37 1 38) (24 8 20 4 21) (22 12 11 4 12)) ((30 3 115 1 116) (24 4 40 5 41) (20 11 16 5 17) (24 11 12 5 13)) ((22 5 87 1 88) (24 5 41 5 42) (30 5 24 7 25) (24 11 12 7 13)) ; Version 15 ((24 5 98 1 99) (28 7 45 3 46) (24 15 19 2 20) (30 3 15 13 16)) ((28 1 107 5 108) (28 10 46 1 47) (28 1 22 15 23) (28 2 14 17 15)) ((30 5 120 1 121) (26 9 43 4 44) (28 17 22 1 23) (28 2 14 19 15)) ((28 3 113 4 114) (26 3 44 11 45) (26 17 21 4 22) (26 9 13 16 14)) ((28 3 107 5 108) (26 3 41 13 42) (30 15 24 5 25) (28 15 15 10 16)) ; Version 20 ((28 4 116 4 117) (26 17 42 0 0) (28 17 22 6 23) (30 19 16 6 17)) ((28 2 111 7 112) (28 17 46 0 0) (30 7 24 16 25) (24 34 13 0 0)) ((30 4 121 5 122) (28 4 47 14 48) (30 11 24 14 25) (30 16 15 14 16)) ((30 6 117 4 118) (28 6 45 14 46) (30 11 24 16 25) (30 30 16 2 17)) ((26 8 106 4 107) (28 8 47 13 48) (30 7 24 22 25) (30 22 15 13 16)) ; Version 25 ((28 10 114 2 115) (28 19 46 4 47) (28 28 22 6 23) (30 33 16 4 17)) ((30 8 122 4 123) (28 22 45 3 46) (30 8 23 26 24) (30 12 15 28 16)) ((30 3 117 10 118) (28 3 45 23 46) (30 4 24 31 25) (30 11 15 31 16)) ((30 7 116 7 117) (28 21 45 7 46) (30 1 23 37 24) (30 19 15 26 16)) ((30 5 115 10 116) (28 19 47 10 48) (30 15 24 25 25) (30 23 15 25 16)) ; Version 30 ((30 13 115 3 116) (28 2 46 29 47) (30 42 24 1 25) (30 23 15 28 16)) ((30 17 115 0 0) (28 10 46 23 47) (30 10 24 35 25) (30 19 15 35 16)) ((30 17 115 1 116) (28 14 46 21 47) (30 29 24 19 25) (30 11 15 46 16)) ((30 13 115 6 116) (28 14 46 23 47) (30 44 24 7 25) (30 59 16 1 17)) ((30 12 121 7 122) (28 12 47 26 48) (30 39 24 14 25) (30 22 15 41 16)) ; Version 35 ((30 6 121 14 122) (28 6 47 34 48) (30 46 24 10 25) (30 2 15 64 16)) ((30 17 122 4 123) (28 29 46 14 47) (30 49 24 10 25) (30 24 15 46 16)) ((30 4 122 18 123) (28 13 46 32 47) (30 48 24 14 25) (30 42 15 32 16)) ((30 20 117 4 118) (28 40 47 7 48) (30 43 24 22 25) (30 10 15 67 16)) ((30 19 118 6 119) (28 18 47 31 48) (30 34 24 34 25) (30 20 15 61 16)) ; Version 40 )) (defun ecc-block-nums (version level) "# of ec codewords for each blk, # of blk 1, # of data words for blk 1, ..." (let ((lidx (level->index level))) (values (aref *ecc-blocks* version lidx 0) (aref *ecc-blocks* version lidx 1) (aref *ecc-blocks* version lidx 2) (aref *ecc-blocks* version lidx 3) (aref *ecc-blocks* version lidx 4)))) (defun minimum-version (init-version nbytes level) "minimum version that can hold NBYTES data words, or INIT-VERSION if bigger" (do ((v init-version (1+ v))) ((> v 40) nil) (when (>= (data-words-capacity v level) nbytes) (return-from minimum-version v)))) (defun version-range (version) (cond ((<= 1 version 9) 0) ((<= 10 version 26) 1) ((<= 27 version 40) 2))) ;;; Table 3 - Number of bits in character count indicator for QR Code 2005 (defvar *char-count-indicator* ;; :numeric :alnum :byte :kanji #2A((10 9 8 8) ; version-range 0 (12 11 16 10) ; version-range 1 (14 13 16 12))) ; version-range 2 (defun char-count-bits (version mode) (let ((i (version-range version)) (j (mode->index mode))) (aref *char-count-indicator* i j))) ;;; Table E.1 - Row/column coordinates of center modules of alignment patterns ;;; varies between versions (defvar *align-coord-table* #2A((0 ()) ; 0, no such version (0 ()) (1 (6 18)) (1 (6 22)) (1 (6 26)) (1 (6 30)) (1 (6 34)) (6 (6 22 38)) (6 (6 24 42)) (6 (6 26 46)) (6 (6 28 50)) (6 (6 30 54)) (6 (6 32 58)) (6 (6 34 62)) (13 (6 26 46 66)) (13 (6 26 48 70)) (13 (6 26 50 74)) (13 (6 30 54 78)) (13 (6 30 56 82)) (13 (6 30 58 86)) (13 (6 34 62 90)) (22 (6 28 50 72 94)) (22 (6 26 50 74 98)) (22 (6 30 54 78 102)) (22 (6 28 54 80 106)) (22 (6 32 58 84 110)) (22 (6 30 58 86 114)) (22 (6 34 62 90 118)) (33 (6 26 50 74 98 122)) (33 (6 30 54 78 102 126)) (33 (6 26 52 78 104 130)) (33 (6 30 56 82 108 134)) (33 (6 34 60 86 112 138)) (33 (6 30 58 86 114 142)) (33 (6 34 62 90 118 146)) (46 (6 30 54 78 102 126 150)) (46 (6 24 50 76 102 128 154)) (46 (6 28 54 80 106 132 158)) (46 (6 32 58 84 110 136 162)) (46 (6 26 54 82 110 138 166)) (46 (6 30 58 86 114 142 170))) "# of Alignment Patterns, row/column coordinates of center modules.") (defun valid-center-p (x y modules) "The alignment center module is not in Finder Patterns." (not (or (and (<= 0 x 8) (<= 0 y 8)) ; upleft finder pattern (and (<= 0 x 8) (<= (- modules 8) y (- modules 1))) ; upright finder pattern (and (<= (- modules 8) x (- modules 1)) (<= 0 y 8))))) (defun align-centers (version) "list of all valid alignment pattern center modules under VERSION" (let* ((modules (matrix-modules version)) (coords (aref *align-coord-table* version 1)) (len (length coords)) (centers nil)) (dotimes (i len) (loop for j from i to (- len 1) do (let ((x (nth i coords)) (y (nth j coords))) (when (valid-center-p x y modules) (push (list x y) centers)) (unless (= x y) (when (valid-center-p y x modules) (push (list y x) centers)))))) centers)) (defvar *mask-pattern-num* 8) (defun mask-condition (indicator) (lambda (i j) (case indicator ;; (i + j) mod 2 == 0 (0 (= (mod (+ i j) 2) 0)) ;; i mod 2 == 0 (1 (= (mod i 2) 0)) ;; j mod 3 == 0 (2 (= (mod j 3) 0)) ;; (i + j) mod 3 == 0 (3 (= (mod (+ i j) 3) 0)) ;; ((i/2) + (j/3)) mod 2 == 0 (4 (= (mod (+ (floor i 2) (floor j 3)) 2) 0)) ;; (i*j) mod 2 + (i*j) mod 3 == 0 (5 (= (+ (mod (* i j) 2) (mod (* i j) 3)) 0)) ;; ((i*j) mod 2 + (i*j) mod 3)) mod 2 == 0 (6 (= (mod (+ (mod (* i j) 2) (mod (* i j) 3)) 2) 0)) ;; ((i+j) mod 2 + (i*j) mod 3)) mod 2 == 0 (7 (= (mod (+ (mod (+ i j) 2) (mod (* i j) 3)) 2) 0))))) (defvar *ecc-level-indicator* #((0 1) (0 0) (1 1) (1 0)) ":level-l :level-m :level-q :level-h") (defun level-indicator (level) (aref *ecc-level-indicator* (level->index level))) (defvar *mask-pattern-reference* #((0 0 0) (0 0 1) (0 1 0) (0 1 1) (1 0 0) (1 0 1) (1 1 0) (1 1 1))) (defun mask-pattern-ref (ind) (aref *mask-pattern-reference* ind))
11,977
Common Lisp
.lisp
223
47.973094
95
0.531085
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
fe1f81e100bd7a3674d23e6cb15a3320b465f0587ddb8a03c9764ba590015b0a
4,388
[ -1 ]
4,389
bstream.lisp
jnjcc_cl-qrencode/qrencode/bstream.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; bit stream (a list of 0-1 values) utilities (in-package #:cl-qrencode) (defun decimal->bstream (dec nbits) "using NBITS bits to encode decimal DEC" (let ((bstream nil)) (dotimes (i nbits) (if (logbitp i dec) (push 1 bstream) (push 0 bstream))) bstream)) (defun bstream->decimal (bstream nbits) (declare (type list bstream)) (let ((nbits (min nbits (length bstream))) (dec 0)) (dotimes (i nbits) (setf dec (+ (* dec 2) (nth i bstream)))) dec)) ;;; :numeric mode (defun group->decimal (values ndigits) "digit groups of length NDIGITS (1, 2 or 3) to decimal" (declare (type list values)) (case ndigits (1 (nth 0 values)) (2 (+ (* (nth 0 values) 10) (nth 1 values))) (3 (+ (* (nth 0 values) 100) (* (nth 1 values) 10) (nth 2 values))))) (defun final-digit-bits (n) "the final one or two digits are converted to 4 or 7 bits respectively" (case n (0 0) (1 4) (2 7))) (defun numeric->bstream (bytes) (declare (type list bytes)) (labels ((num-value (byte) (byte-value :numeric byte))) (let ((values (mapcar #'num-value bytes)) (bstream nil)) (do ((v values (nthcdr 3 v))) ((null v) bstream) (case (length v) (1 ; only 1 digits left (setf bstream (append bstream (decimal->bstream (group->decimal v 1) (final-digit-bits 1))))) (2 ; only 2 digits left (setf bstream (append bstream (decimal->bstream (group->decimal v 2) (final-digit-bits 2))))) (otherwise ; at least 3 digits left (setf bstream (append bstream (decimal->bstream (group->decimal v 3) 10))))))))) ;;; :alnum mode (defun pair->decimal (values num) "alnum pairs of length NUM (1 or 2) to decimal" (declare (type list values)) (case num (1 (nth 0 values)) (2 (+ (* (nth 0 values) 45) (nth 1 values))))) (defun alnum->bstream (bytes) (declare (type list bytes)) (labels ((alnum-value (byte) (byte-value :alnum byte))) (let ((values (mapcar #'alnum-value bytes)) (bstream nil)) (do ((v values (nthcdr 2 v))) ((null v) bstream) (case (length v) (1 ; only 1 alnum left (setf bstream (append bstream (decimal->bstream (pair->decimal v 1) 6)))) (otherwise ; at least 2 alnum left (setf bstream (append bstream (decimal->bstream (pair->decimal v 2) 11))))))))) ;;; :byte mode (defun byte->bstream (bytes) (declare (type list bytes)) (labels ((join (prev cur) (append prev (decimal->bstream (byte-value :byte cur) 8)))) (reduce #'join bytes :initial-value nil))) ;;; :kanji mode (defun kanji->decimal (word range) (let ((subtractor (ecase range (0 #x8140) (1 #xc140)))) (decf word subtractor) (setf word (+ (* (ash word -8) #xc0) (boole boole-and word #xff))))) (defun kanji->bstream (bytes) (declare (type list bytes)) (labels ((kanji-value (byte) (byte-value :kanji byte))) (let ((values (mapcar #'kanji-value bytes)) (delta 1) (bstream nil)) (do ((v values (nthcdr delta v))) ((null v) bstream) (case (length v) (1 ; only 1 byte left (setf bstream (append bstream (decimal->bstream (car v) 13))) (setf delta 1)) (otherwise ; at least 2 bytes left (multiple-value-bind (kanji-p word range) (starts-kanji-p v) (if kanji-p (progn (setf bstream (append bstream (decimal->bstream (kanji->decimal word range) 13))) (setf delta 2)) (progn (setf bstream (append bstream (decimal->bstream (car v) 13))) (setf delta 1)))))))))) ;;; :eci mode (defun eci->bstream (bytes) "TODO" (declare (ignore bytes)) (error "eci->bstream: TODO...")) (defun bstream-trans-func (mode) (case mode (:numeric #'numeric->bstream) (:alnum #'alnum->bstream) (:byte #'byte->bstream) (:kanji #'kanji->bstream))) (defun kanji-bytes-length (bytes) (declare (type list bytes)) (let ((step 1) (len 0)) (do ((b bytes (nthcdr step b))) ((null b) len) (if (starts-kanji-p b) (setf step 2) (setf step 1)) (incf len)))) (defun bytes-length (bytes mode) "number of data characters under MODE" (declare (type list bytes) (type qr-mode mode)) (case mode ((:numeric :alnum :byte) (length bytes)) (:kanji (kanji-bytes-length bytes)))) (defun segment-bstream-length (segment version) "bit stream length of SEGMENT (:mode b0 b1 ...) under VERSION" (declare (type list segment)) (let* ((mode (car segment)) (bytes (cdr segment)) (m 4) (c (char-count-bits version mode)) (d (bytes-length bytes mode)) (r 0)) ;; M = number of bits in mode indicator ;; C = number of bits in character count indicator ;; D = number of input data characters (case mode (:numeric (setf r (final-digit-bits (mod d 3))) ;; B = M + C + 10 * (D / 3) + R (+ m c (* 10 (floor d 3)) r)) (:alnum (setf r (mod d 2)) ;; B = M + C + 11 * (D / 2) + 6 * (D % 2) (+ m c (* 11 (floor d 2)) (* 6 r))) (:byte ;; B = M + C + 8 * D (+ m c (* 8 d))) (:kanji ;; B = M + C + 13 * D (+ m c (* 13 d)))))) (defun segment->bstream (segment version) "SEGMENT (:mode b0 b1 ...) to bit stream under VERSION" (declare (type list segment)) (let* ((mode (car segment)) (bytes (cdr segment)) (len (bytes-length bytes mode)) (n (char-count-bits version mode)) (bstream nil)) (append bstream (mode-indicator mode) (decimal->bstream len n) ; character count indicator (funcall (bstream-trans-func mode) bytes))))
6,431
Common Lisp
.lisp
182
26.626374
78
0.532468
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
d1ce8c02d5dfadfc91c2d5c33d9142578398306e736f752e8d5631f0e2f40990
4,389
[ -1 ]
4,390
matrix.lisp
jnjcc_cl-qrencode/qrencode/matrix.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Codeword placement in matrix (in-package #:cl-qrencode) (deftype module-color () ":RAW, nothing has been done to this module; :RESERVE, format info reserve module :FLIGHT/:FDARK, function pattern light/dark module; :LIGHT/:DARK, data modules" '(member :raw :flight :fdark :reserve :light :dark)) (defun same-color-p (color1 color2) "during QR symbol evaluation, :fdark & :dark are considered to be same" (case color1 ((:flight :light) (or (eq color2 :flight) (eq color2 :light))) ((:fdark :dark) (or (eq color2 :fdark) (eq color2 :fdark))) (otherwise (eq color1 color2)))) (defun raw-module-p (matrix i j) "nothing has been done to MATRIX[I, J]" (eq (aref matrix i j) :raw)) (defun make-modules-matrix (modules &optional (init :raw)) "make a raw matrix with MODULES * MODULES elements" (make-array `(,modules ,modules) :initial-element init)) (defun make-matrix (version &optional (init :raw)) "make a raw matrix according to VERSION" (let ((n (matrix-modules version))) (make-modules-matrix n init))) (defun paint-square (matrix x y n &optional (color :fdark)) "Paint a square of size N*N starting from upleft (X, Y) in MATRIX to COLOR" (let ((maxx (+ x n -1)) (maxy (+ y n -1))) (loop for i from x to maxx do (loop for j from y to maxy do (setf (aref matrix i j) color)))) matrix) ;;; Function Patterns (defun function-patterns (matrix version) (let ((modules (matrix-modules version))) (finder-patterns matrix modules) (separator matrix modules) (timing-patterns matrix modules) (alignment-patterns matrix version)) matrix) ;; a) Finder Patterns: fixed position in matrix (defun one-finder-pattern (matrix x y) "Paint one finder pattern starting from upleft (X, Y)" (paint-square matrix x y 7 :fdark) (paint-square matrix (+ x 1) (+ y 1) 5 :flight) (paint-square matrix (+ x 2) (+ y 2) 3 :fdark)) (defun finder-patterns (matrix modules) ;; top-left finder pattern (one-finder-pattern matrix 0 0) ;; top-right finder pattern (one-finder-pattern matrix (- modules 7) 0) ;; bottom-left finder pattern (one-finder-pattern matrix 0 (- modules 7))) ;; b) Separator: fixed position in matrix (defun separator (matrix modules) (dotimes (j 8) ;; top-left horizontal separator (setf (aref matrix 7 j) :flight) ;; top-right horizontal separator (setf (aref matrix 7 (- modules j 1)) :flight) ;; bottom-left horizontal separator (setf (aref matrix (- modules 8) j) :flight)) (dotimes (i 8) ;; top-left vertical separator (setf (aref matrix i 7) :flight) ;; bottom-left vertical separator (setf (aref matrix (- modules i 1) 7) :flight) ;; top-right vertical separator (setf (aref matrix i (- modules 8)) :flight)) matrix) ;; c) Timing patterns (defun timing-patterns (matrix modules) (let ((color :fdark)) (loop for idx from 8 to (- modules 9) do (if (evenp idx) (setf color :fdark) (setf color :flight)) ;; Horizontal (setf (aref matrix 6 idx) color) ;; Vertical (setf (aref matrix idx 6) color))) matrix) ;; d) Alignment Patterns: varies between versions ;; may overlap timing patterns, modules coincide with that of timing patterns (defun one-align-pattern (matrix x y) "Paint one alignment pattern centered at (X, Y)" (paint-square matrix (- x 2) (- y 2) 5 :fdark) (paint-square matrix (- x 1) (- y 1) 3 :flight) (paint-square matrix x y 1 :fdark)) (defun alignment-patterns (matrix version) (dolist (center (align-centers version) matrix) (one-align-pattern matrix (first center) (second center)))) ;;; Encoding Region (defun symbol-character (bstream matrix version) (let ((modules (matrix-modules version))) (reserve-information matrix version) (bstream-placement bstream matrix modules)) matrix) ;; reserve format information & version information (defun reserve-information (matrix version) (let ((modules (matrix-modules version))) ;; format information... ;; top-left & top-right horizontal (dotimes (j 8) (when (raw-module-p matrix 8 j) (setf (aref matrix 8 j) :reserve)) (setf (aref matrix 8 (- modules j 1)) :reserve)) (setf (aref matrix 8 8) :reserve) ;; top-left & bottom-left vertical (dotimes (i 8) (when (raw-module-p matrix i 8) (setf (aref matrix i 8) :reserve)) (setf (aref matrix (- modules i 1) 8) :reserve)) ;; dark module... (setf (aref matrix (- modules 8) 8) :fdark) ;; version information for version 7-40 (when (>= version 7) (version-information matrix modules version)))) (defun paint-fcolor-bit (matrix i j bit) "Paint function pattern color for MATRIX[I, J] according to BIT of {0, 1}" (setf (aref matrix i j) (case bit (0 :flight) (1 :fdark)))) (defun version-information (matrix modules version) "version information placement on two blocks of modules: bottom-left 3*6 block: [modules-11, modules-9] * [0, 5] top-right 6*3 block: [0, 5] * [modules-11, modules-9]" (assert (>= version 7)) (let ((vib (version-ecc version)) (i (- modules 9)) (start (- modules 9)) (bound (- modules 11)) (j 5)) (dolist (bit vib matrix) (paint-fcolor-bit matrix i j bit) (paint-fcolor-bit matrix j i bit) (if (>= (- i 1) bound) (decf i) (progn (decf j) (setf i start)))))) ;; Symbol character placement (defun paint-color-bit (matrix i j bit) "Paint data color for MATRIX[I, J] according to BIT of {0, 1}" (setf (aref matrix i j) (case bit (0 :light) (1 :dark)))) (defun bstream-placement (bstream matrix modules) "2X4 module block for a regular symbol character. Regard the interleaved codeword sequence as a single bit stream, which is placed in the two module wide columns, alternately in the right and left modules, moving upwards or downwards according to DIRECTION, skipping function patterns, changing DIRECTION at the top or bottom of the symbol. The only exception is that no block should ever overlap the vertical timing pattern." (let ((i (- modules 1)) (j (- modules 1)) ;; -1: upwards, +1: downwards (direction -1) (len (length bstream))) (do ((idx 0)) ((>= idx len) matrix) (when (raw-module-p matrix i j) (paint-color-bit matrix i j (nth idx bstream)) (incf idx)) (when (and (>= (- j 1) 0) (raw-module-p matrix i (- j 1))) ;; try left module (paint-color-bit matrix i (- j 1) (nth idx bstream)) (incf idx)) (if (< -1 (+ i direction) modules) (incf i direction) (progn ;; reverse direction (setf direction (- direction)) (if (= j 8) ;; vertical timing pattern reached, the next block starts ;; to the left of it (decf j 3) (decf j 2))))))) ;;; format information, during and after masking (defun format-information (matrix modules level mask-ind) ;; format information bistream (let ((fib (format-ecc level mask-ind)) (darks 0) (idx 0) (idx2 0)) (setf darks (count-if #'(lambda (elem) (= elem 1)) fib)) ;; horizontal 14 ~ 8 (loop for j from 0 to 7 do (when (eq (aref matrix 8 j) :reserve) (paint-fcolor-bit matrix 8 j (nth idx fib)) (incf idx))) ;; vertical 14 ~ 8 (loop for i from (- modules 1) downto (- modules 7) do (paint-fcolor-bit matrix i 8 (nth idx2 fib)) (incf idx2)) ;; horizontal 7 - 0 (loop for j from (- modules 8) to (- modules 1) do (paint-fcolor-bit matrix 8 j (nth idx fib)) (incf idx)) ;; vertical 7 - 0 (loop for i from 8 downto 0 do (when (eq (aref matrix i 8) :reserve) (paint-fcolor-bit matrix i 8 (nth idx2 fib)) (incf idx2))) (values matrix darks)))
8,131
Common Lisp
.lisp
204
34.166667
83
0.636835
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
01d1178e60a6f87356c87bb057e5a32b1dac5e334048e0cd1ad51512de0446e5
4,390
[ -1 ]
4,391
input.lisp
jnjcc_cl-qrencode/qrencode/input.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-qrencode) (defclass qr-input () ((bytes :initform nil :initarg :bytes :reader bytes :type list :documentation "list of bytes to be encoded") (version :initform 1 :initarg :version :reader version :documentation "version of qr symbol, adapted according to BYTES") (ec-level ; cannot be NIL :initform :level-m :initarg :ec-level :reader level :type ecc-level) (mode :initform nil :initarg :mode :reader mode :type (or null qr-mode) :documentation "if supplied, we force all BYTES to be under MODE, therefore, unless you know exactly what you are doing, leave this NIL") (cur-byte :initform 0 :accessor cur-byte :documentation "index of BYTES during data analysis") (segments :initform nil :accessor segments :type list :documentation "list of list, of the form ((:mode1 byte ...) (:mode2 byte ...) ...)") (bstream :initform nil :reader bstream :type list :documentation "list of 0-1 values after encoding SEGMENTS") (blocks :initform nil :reader blocks :type list :documentation "list of list, of the form ((codeword ...) (codeword ...) ...) after converting BSTREAM to codewords") (ecc-blocks ; error correction blocks :initform nil :reader ecc-blocks :type list :documentation "list of list, ec codewords corresponding to BLOCKS") (msg-codewords :initform nil :reader message :type list :documentation "list of codewords from BLOCKS & ECC-BLOCKS, interleaving if neccessary") (matrix :initform nil :accessor matrix :documentation "raw QR code symbol (without masking) as matrix"))) (defmethod initialize-instance :after ((input qr-input) &rest args) (declare (ignore args)) (validate-and-analysis input)) ;;; 0) Data analysis (defgeneric validate-and-analysis (input) (:documentation "adapt VERSION according to BYTES, and fill SEGMENTS slot")) ;;; 1) Data encoding (defgeneric data-encoding (input) (:documentation "encode SEGMENTS into BSTREAM slot")) ;;; 2) Error correction coding (defgeneric ec-coding (input) (:documentation "split BSTREAM into BLOCKS, do rs-ecc, and fill ECC-BLOCKS")) ;;; 3) Structure final message (defgeneric structure-message (input) (:documentation "interleaving BLOCKS and ECC-BLOCKS into MSG-CODEWORDS")) ;;; 4) Codeword placement in matrix, a.k.a, raw QR code symbol (defgeneric module-placement (input) (:documentation "write MSG-CODEWORDS into the raw (without masking) MATRIX")) ;;; 5) Data masking & Format information (defgeneric data-masking (input) (:documentation "mask MATRIX with best pattern, generate the final symbol")) (defgeneric data-analysis (input) (:documentation "BYTES -> SEGMETS, switch bewteen modes as necessary to achieve the most efficient conversion of data")) (defgeneric redo-data-analysis (input) (:documentation "VERSION changed, reset CUR-BYTE and redo data analysis")) (defgeneric analyse-byte-mode (input &optional seg)) (defgeneric analyse-alnum-mode (input &optional seg)) (defgeneric analyse-numeric-mode (input &optional seg)) (defgeneric analyse-kanji-mode (input &optional seg)) (defgeneric append-cur-byte (input &optional seg) (:documentation "append CUR-BYTE of BYTES into SEGMENTS")) (defun mode-analyse-func (mode) "put CUR-BYTE into MODE, and then look at following BYTES for new segment" (case mode (:byte #'analyse-byte-mode) (:alnum #'analyse-alnum-mode) (:numeric #'analyse-numeric-mode) (:kanji #'analyse-kanji-mode))) (defmethod data-analysis ((input qr-input)) (with-slots (mode cur-byte segments) input (when mode ; MODE supplied (let ((seg (append (list mode) (bytes input)))) (setf cur-byte (length (bytes input))) (setf segments (append segments (list seg)))) (return-from data-analysis))) (with-slots (bytes version segments) input (let ((init-mode (select-init-mode bytes version))) (funcall (mode-analyse-func init-mode) input)))) (defmethod redo-data-analysis ((input qr-input)) (with-slots (cur-byte segments) input (setf cur-byte 0) (setf segments nil) (data-analysis input))) (defun select-init-mode (bytes version) "optimization of bitstream length: select initial mode" (declare (type list bytes)) (let ((init-xor (xor-subset-of bytes))) (case init-xor (:byte :byte) (:kanji (case (xor-subset-of (nthcdr 2 bytes)) ((:numeric :alnum) :kanji) (:byte (let ((nunits (ecase (version-range version) ((0 1) 5) (2 6)))) (if (every-unit-matches (nthcdr 3 bytes) 2 nunits :kanji) :byte :kanji))) (otherwise :kanji))) (:alnum (let ((nunits (ecase (version-range version) (0 6) (1 7) (2 8)))) ;; number of units (characters) match :alnum, followed by a :byte unit (multiple-value-bind (n last-mode) (nunits-matches (cdr bytes) :alnum) (if (and (< n nunits) (eq last-mode :byte)) :byte :alnum)))) (:numeric (let ((nbunits (ecase (version-range version) ((0 1) 4) (2 5))) (naunits (ecase (version-range version) (0 7) (1 8) (2 9)))) (multiple-value-bind (n last-mode) (nunits-matches (cdr bytes) :numeric) (if (and (< n nbunits) (eq last-mode :byte)) :byte (if (and (< n naunits) (eq last-mode :alnum)) :alnum :numeric)))))))) ;;; UNIT: character under a certain mode, ;;; a byte under :numeric :alnum & :byte, or a byte-pair under :kanji (defun every-unit-matches (bytes usize nunits mode) "if every unit of USZIE bytes (at most NUNITS unit) within BYTES matches MODE" (declare (type list bytes) (type qr-mode mode)) (when (>= (length bytes) (* usize nunits)) (dotimes (i nunits) (let ((b (nthcdr (* usize i) bytes))) (unless (eq (xor-subset-of b) mode) (return-from every-unit-matches nil)))) (return-from every-unit-matches t))) (defun nunits-matches (bytes mode) "(number of units that matches MODE, and mode for the first unmatched unit)" (declare (type list bytes) (type qr-mode mode)) (let ((usize (ecase mode ((:byte :alnum :numeric) 1) ;; as for :kanji, 2 bytes forms a single unit (:kanji 2))) (nunits 0)) (do ((b bytes (nthcdr usize b))) ((or (null b) (not (eq (xor-subset-of b) mode))) (values nunits (xor-subset-of b))) (incf nunits)))) (defmethod analyse-byte-mode ((input qr-input) &optional (seg '(:byte))) (declare (type list seg)) (setf seg (append-cur-byte input seg)) (unless seg (return-from analyse-byte-mode)) (with-slots (bytes cur-byte version segments) input (let* ((range (version-range version)) (nkunits (ecase range ; number of :kanji units before more :byte (0 9) (1 12) (2 13))) (nanuits (ecase range ; number of :alnum units before more :byte (0 11) (1 15) (2 16))) (nmunits1 (ecase range ; number of :numeric units before more :byte (0 6) (1 8) (2 9))) (nmunits2 (ecase range ; number of :numeric units before more :alnum (0 6) (1 7) (2 8))) (switch-mode nil)) (multiple-value-bind (nmatches last-mode) (nunits-matches (nthcdr cur-byte bytes) :kanji) (and (>= nmatches nkunits) (eq last-mode :byte) (setf switch-mode :kanji))) (unless switch-mode (multiple-value-bind (nmatches last-mode) (nunits-matches (nthcdr cur-byte bytes) :alnum) (and (>= nmatches nanuits) (eq last-mode :byte) (setf switch-mode :alnum)))) (unless switch-mode (multiple-value-bind (nmatches last-mode) (nunits-matches (nthcdr cur-byte bytes) :numeric) (case last-mode (:byte (and (>= nmatches nmunits1) (setf switch-mode :numeric))) (:alnum (and (>= nmatches nmunits2) (setf switch-mode :numeric)))))) (if switch-mode (progn ;; current segment finished, add a new SWITCH-MODE segment (setf segments (append segments (list seg))) (setf seg (list switch-mode))) (setf switch-mode :byte)) (funcall (mode-analyse-func switch-mode) input seg)))) (defmethod analyse-alnum-mode ((input qr-input) &optional (seg '(:alnum))) (declare (type list seg)) (setf seg (append-cur-byte input seg)) (unless seg (return-from analyse-alnum-mode)) (with-slots (bytes cur-byte version segments) input (let ((nmunits (ecase (version-range version) (0 13) (1 15) (2 17))) (switch-mode nil)) (when (>= (nunits-matches (nthcdr cur-byte bytes) :kanji) 1) (setf switch-mode :kanji)) (unless switch-mode (when (>= (nunits-matches (nthcdr cur-byte bytes) :byte) 1) (setf switch-mode :byte))) (unless switch-mode (multiple-value-bind (nmatches last-mode) (nunits-matches (nthcdr cur-byte bytes) :numeric) (and (>= nmatches nmunits) (eq last-mode :alnum) (setf switch-mode :numeric)))) (if switch-mode (progn (setf segments (append segments (list seg))) (setf seg (list switch-mode))) (setf switch-mode :alnum)) (funcall (mode-analyse-func switch-mode) input seg)))) (defmethod analyse-numeric-mode ((input qr-input) &optional (seg '(:numeric))) (declare (type list seg)) (setf seg (append-cur-byte input seg)) (unless seg (return-from analyse-numeric-mode)) (with-slots (bytes cur-byte version segments) input (let ((switch-mode nil)) (when (>= (nunits-matches (nthcdr cur-byte bytes) :kanji) 1) (setf switch-mode :kanji)) (unless switch-mode (when (>= (nunits-matches (nthcdr cur-byte bytes) :byte) 1) (setf switch-mode :byte))) (unless switch-mode (when (>= (nunits-matches (nthcdr cur-byte bytes) :alnum) 1) (setf switch-mode :alnum))) (if switch-mode (progn (setf segments (append segments (list seg))) (setf seg (list switch-mode))) (setf switch-mode :numeric)) (funcall (mode-analyse-func switch-mode) input seg)))) (defmethod append-cur-byte ((input qr-input) &optional seg) "if CUR-BYTE is the last byte, return nil" (declare (type list seg)) (with-slots (bytes cur-byte segments) input (setf seg (append seg (list (nth cur-byte bytes)))) (incf cur-byte) (when (>= cur-byte (length bytes)) (setf segments (append segments (list seg))) (setf seg nil)) (return-from append-cur-byte seg))) (defmethod analyse-kanji-mode ((input qr-input) &optional (seg '(:kanji))) (declare (type list seg)) (with-slots (bytes cur-byte segments) input (setf seg (append seg (nthcdr cur-byte bytes))) (setf cur-byte (length bytes)) (setf segments (append segments (list seg))))) (defmethod validate-and-analysis ((input qr-input)) (with-slots ((level ec-level) segments) input (unless (<= 1 (version input) 40) (error "version ~A out of bounds" (version input))) (do ((prev -1)) ((<= (version input) prev)) (setf prev (version input)) (redo-data-analysis input) (labels ((seg-bstream-len (seg) (segment-bstream-length seg (version input)))) (let* ((blen (reduce #'+ (mapcar #'seg-bstream-len segments) :initial-value 0)) (min-v (minimum-version prev (ceiling blen 8) level))) (if min-v (setf (slot-value input 'version) min-v) (error "no version to hold ~A bytes" (ceiling blen 8)))))))) (defmethod data-encoding ((input qr-input)) (with-slots (version (level ec-level) segments) input (labels ((seg->bstream (seg) (segment->bstream seg version))) (let* ((bs (reduce #'append (mapcar #'seg->bstream segments) :initial-value nil)) (tt (terminator bs version level)) ;; connect bit streams in all segment, with terminator appended (bstream (append bs tt))) ;; add padding bits (setf bstream (append bstream (padding-bits bstream))) ;; add pad codewords, finishes data encoding (setf (slot-value input 'bstream) (append bstream (pad-codewords bstream version level))))))) (defmethod ec-coding ((input qr-input)) (with-slots (version (level ec-level) bstream) input (let ((codewords (bstream->codewords bstream)) (blocks nil) (ecc-blocks nil) ;; RS error correction obj for blk1 & blk2 (rs1 nil) (rs2 nil)) (multiple-value-bind (ecc-num blk1 data1 blk2 data2) (ecc-block-nums version level) (when (> blk1 0) (setf rs1 (make-instance 'rs-ecc :k data1 :ec ecc-num))) (when (> blk2 0) (setf rs2 (make-instance 'rs-ecc :k data2 :ec ecc-num))) (dotimes (i blk1) (setf blocks (append blocks (list (subseq codewords 0 data1)))) (setf codewords (nthcdr data1 codewords))) (dotimes (i blk2) (setf blocks (append blocks (list (subseq codewords 0 data2)))) (setf codewords (nthcdr data2 codewords))) (dotimes (i blk1) (setf ecc-blocks (append ecc-blocks (list (ecc-poly rs1 (nth i blocks)))))) (dotimes (i blk2) (setf ecc-blocks (append ecc-blocks (list (ecc-poly rs2 (nth (+ i blk1) blocks)))))) (setf (slot-value input 'blocks) blocks) (setf (slot-value input 'ecc-blocks) ecc-blocks))))) (defmethod structure-message ((input qr-input)) (with-slots (version (level ec-level) blocks ecc-blocks) input (let ((final nil)) (multiple-value-bind (ecc-num blk1 data1 blk2 data2) (ecc-block-nums version level) (declare (ignore ecc-num)) (setf (slot-value input 'msg-codewords) (append final ;; interleave data blocks, data blocks may differ in length (take-data-in-turn blocks blk1 data1 blk2 data2) ;; we know error correction blocks are of the same length (take-in-turn ecc-blocks))))))) (defmethod module-placement ((input qr-input)) (setf (matrix input) (make-matrix (version input))) (with-slots (version msg-codewords matrix) input ;; Function pattern placement (function-patterns matrix version) ;; Symbol character placement (let ((rbits (remainder-bits version)) (bstream nil)) (labels ((dec->byte (codeword) (decimal->bstream codeword 8))) (setf bstream (append (reduce #'append (mapcar #'dec->byte msg-codewords)) ;; data capacity of _symbol_ does not divide by 8 (make-list rbits :initial-element 0)))) (symbol-character bstream matrix version)))) (defmethod data-masking ((input qr-input)) "(masked matrix, mask pattern reference)" (with-slots (version (level ec-level) matrix) input (let ((modules (matrix-modules version))) (multiple-value-bind (masked indicator) (choose-masking matrix modules level) (values masked (mask-pattern-ref indicator))))))
15,779
Common Lisp
.lisp
350
36.957143
83
0.621301
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
3455cd885fe3fb836d6259e6c1c21c85651a6ca2e4970c6e3ece997dd607fdbe
4,391
[ -1 ]
4,392
codeword.lisp
jnjcc_cl-qrencode/qrencode/codeword.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; bit stream to codeword conversion (in-package #:cl-qrencode) (defun padding-bits (bstream) "add padding bits so that BSTREAM ends at a codeword boundary" (multiple-value-bind (quot rem) (ceiling (length bstream) 8) (declare (ignore quot)) (make-list (- rem) :initial-element 0))) (defun pad-codewords (bstream version level) "add pad codewords (after adding padding-bits) to fill data codeword capacity" (let ((pad-words '((1 1 1 0 1 1 0 0) (0 0 0 1 0 0 0 1))) (pad-len (- (data-words-capacity version level) (/ (length bstream) 8))) (ret nil)) (dotimes (i pad-len) (setf ret (append ret (nth (mod i 2) pad-words)))) ret)) (defun bstream->codewords (bstream) "convert bstream into codewords, as coefficients of the terms of a polynomial" (do ((b bstream (nthcdr 8 b)) (codewords nil)) ((null b) codewords) (setf codewords (append codewords (list (bstream->decimal b 8)))))) (defun take-in-turn (blks) "taking codewords from each block (bound by minimum length) in turn" (reduce #'append (apply #'mapcar #'list blks))) (defun take-data-in-turn (blocks blk1 data1 blk2 data2) "taking data words from each block (might have different length) in turn" (let ((data-final nil) (left-blks nil)) (setf data-final (take-in-turn blocks)) (cond ((or (= blk1 0) (= blk2 0)) ;; only one kind of block exists (setf left-blks nil)) ((> data1 data2) ;; block 1 has more elements left (setf left-blks (mapcar #'(lambda (blk) (nthcdr data2 blk)) (subseq blocks 0 blk1)))) ((> data2 data1) ;; block 2 has more elements left (setf left-blks (mapcar #'(lambda (blk) (nthcdr data1 blk)) (subseq blocks blk1 (+ blk1 blk2)))))) (if left-blks (append data-final (take-in-turn left-blks)) data-final)))
2,104
Common Lisp
.lisp
50
34.08
80
0.600586
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
8b9b75d14489ac59fd03945346b3d6c856c71889ab505362ac3b25a4f70b5bc5
4,392
[ -1 ]
4,393
mask.lisp
jnjcc_cl-qrencode/qrencode/mask.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Data masking (in-package #:cl-qrencode) ;;; only encoding region modules (excluding format information) are masked (defun encoding-module-p (matrix i j) "modules belong to encoding region, excluding format & version information" (or (eq (aref matrix i j) :light) (eq (aref matrix i j) :dark))) (defun non-mask-module-p (matrix i j) (not (encoding-module-p matrix i j))) (defun reverse-module-color (matrix i j) (case (aref matrix i j) (:dark :light) (:light :dark))) ;;; all modules are evaluated: ;;; there should be only :dark :light :fdark :flight modules left by now (defun dark-module-p (matrix i j) (or (eq (aref matrix i j) :fdark) (eq (aref matrix i j) :dark))) (defun copy-and-mask (matrix modules level mask-ind) "make a new matrix and mask using MASK-IND for later evaluation" (let ((ret (make-modules-matrix modules)) (mask-p (mask-condition mask-ind)) (darks 0)) (dotimes (i modules) (dotimes (j modules) (cond ((non-mask-module-p matrix i j) (setf (aref ret i j) (aref matrix i j))) ((funcall mask-p i j) ; need mask (setf (aref ret i j) (reverse-module-color matrix i j))) (t (setf (aref ret i j) (aref matrix i j)))) (when (dark-module-p ret i j) (incf darks)))) (multiple-value-bind (dummy fi-darks) (format-information ret modules level mask-ind) (declare (ignore dummy)) ;; add format information dark modules (values ret (+ darks fi-darks))))) (defun mask-matrix (matrix modules level mask-ind) "do not evaluate, just go ahead and mask MATRIX using MASK-IND mask pattern" (let ((mask-p (mask-condition mask-ind))) (dotimes (i modules) (dotimes (j modules) (and (encoding-module-p matrix i j) (funcall mask-p i j) (setf (aref matrix i j) (reverse-module-color matrix i j))))) ;; paint format information (format-information matrix modules level mask-ind) matrix)) (defun choose-masking (matrix modules level) "mask and evaluate using each mask pattern, choose the best mask result" (let ((n4 10) (best-matrix nil) (mask-indicator nil) (min-penalty nil) (square (* modules modules)) (cur-penalty 0)) (dotimes (i *mask-pattern-num*) (multiple-value-bind (cur-matrix darks) (copy-and-mask matrix modules level i) ;; feature 4: proportion of dark modules in entire symbol (let ((bratio (/ (+ (* darks 200) square) square 2))) (setf cur-penalty (* (/ (abs (- bratio 50)) 5) n4))) (incf cur-penalty (evaluate-feature-123 cur-matrix modules)) (when (or (null min-penalty) (< cur-penalty min-penalty)) (setf min-penalty cur-penalty mask-indicator i best-matrix cur-matrix)))) (values best-matrix mask-indicator))) ;;; feature 1 & 2 & 3 (defun evaluate-feature-123 (matrix modules) (let ((penalty 0)) (incf penalty (evaluate-feature-2 matrix modules)) (dotimes (col modules) (let ((rlength (calc-run-length matrix modules col))) (incf penalty (evaluate-feature-1 rlength)) (incf penalty (evaluate-feature-3 rlength)))) (dotimes (row modules) (let ((rlength (calc-run-length matrix modules row :col))) (incf penalty (evaluate-feature-1 rlength)) (incf penalty (evaluate-feature-3 rlength)))) penalty)) (defun calc-run-length (matrix modules num &optional (direction :row)) "list of number of adjacent modules in same color" (let ((rlength nil) (ridx 0)) (labels ((get-elem (idx) (case direction (:row (aref matrix num idx)) (:col (aref matrix idx num)))) (add-to-list (list elem) (append list (list elem)))) ;; we make sure (NTH 1 rlength) is for dark module (when (same-color-p (get-elem 0) :dark) (setf rlength (add-to-list rlength -1) ridx 1)) (setf rlength (add-to-list rlength 1)) (loop for i from 1 to (- modules 1) do (if (same-color-p (get-elem i) (get-elem (- i 1))) (incf (nth ridx rlength)) (progn (incf ridx) (setf rlength (add-to-list rlength 1))))) rlength))) (defun evaluate-feature-1 (rlength) "(5 + i) adjacent modules in row/column in same color. (N1 + i) points, N1 = 3" (let ((n1 3) (penalty 0)) (dolist (sz rlength penalty) (when (> sz 5) (incf penalty (+ n1 sz -5)))))) (defun evaluate-feature-3 (rlength) "1:1:3:1:1 ration (dark:light:dark:light:dark) pattern in row/column, preceded or followed by light area 4 modules wide. N3 points, N3 = 40" (let ((n3 40) (len (length rlength)) (penalty 0)) (do ((i 3 (+ i 2))) ((>= i (- len 2)) penalty) (when (and (= (mod i 2) 1) ; for dark module (= (mod (nth i rlength) 3) 0) (let ((fact (floor (nth i rlength) 3))) ;; 1:1:3:1:1 (when (= fact (nth (- i 2) rlength) (nth (- i 1) rlength) (nth (+ i 1) rlength) (nth (+ i 2) rlength)) (cond ((<= (- i 3) 0) (incf penalty n3)) ((>= (+ i 4) len) (incf penalty n3)) ((>= (nth (- i 3) rlength) (* 4 fact)) (incf penalty n3)) ((>= (nth (+ i 3) rlength) (* 4 fact)) (incf penalty n3)))))))))) (defun evaluate-feature-2 (matrix modules) "block m * n of modules in same color. N2 * (m-1) * (n-1) points, N2=3" (let ((n2 3) (penalty 0) (bcount 0)) (dotimes (i (- modules 1) penalty) (dotimes (j (- modules 1)) (when (dark-module-p matrix i j) (incf bcount)) (when (dark-module-p matrix (+ i 1) j) (incf bcount)) (when (dark-module-p matrix i (+ j 1)) (incf bcount)) (when (dark-module-p matrix (+ i 1) (+ j 1)) (incf bcount)) (when (or (= bcount 0) (= bcount 4)) (incf penalty n2))))))
6,252
Common Lisp
.lisp
153
32.830065
81
0.57746
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
803b75904e93a5e60badd6771df7f6e2e1e9b8694a58f01b6b386ed7cacd4f77
4,393
[ -1 ]
4,394
galois.lisp
jnjcc_cl-qrencode/rs-ecc/galois.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Galois Field with primitive element 2, as used by Reed-Solomon code (in-package #:cl-qrencode) (defclass galois () ((power :initform nil :initarg :power :reader gf-power :documentation "Galois Field GF(2^POWER)") (prime-poly :initform nil :initarg :ppoly :reader prime-poly :documentation "prime polynomial") (order :initform nil :reader gf-order) (exp-table :initform nil) (log-table :initform nil))) (defmethod initialize-instance :after ((gf galois) &rest args) (declare (ignore args)) (setf (slot-value gf 'order) (ash 1 (slot-value gf 'power))) (let* ((order (gf-order gf)) (ppoly (prime-poly gf)) ;; 2^0 = 1 && (log 0) = -1 (exptab (make-array order :initial-element 1)) (logtab (make-array order :initial-element -1))) (do ((i 1 (1+ i))) ((>= i order)) (setf (aref exptab i) (* (aref exptab (- i 1)) 2)) (when (>= (aref exptab i) order) (setf (aref exptab i) (boole boole-and (- order 1) (boole boole-xor (aref exptab i) ppoly)))) (setf (aref logtab (aref exptab i)) i)) (setf (aref logtab 1) 0) (setf (slot-value gf 'exp-table) exptab) (setf (slot-value gf 'log-table) logtab))) ;;; value accessor (defgeneric gf-exp (gf pow) (:documentation "2^POW under Galois Field GF")) (defgeneric gf-log (gf value) (:documentation "VALUE should be within range [0, 2^POW - 1]")) (defmethod gf-exp ((gf galois) pow) (let* ((sz (- (gf-order gf) 1)) (idx (mod pow sz))) (aref (slot-value gf 'exp-table) idx))) (defmethod gf-log ((gf galois) value) (let* ((sz (gf-order gf)) (idx (mod value sz))) (aref (slot-value gf 'log-table) idx))) ;;; Galois Field arithmetic (defgeneric gf-add (gf a b)) (defgeneric gf-subtract (gf a b)) (defgeneric gf-multiply (gf a b)) (defgeneric gf-divide (gf a b)) (defmethod gf-add ((gf galois) a b) (boole boole-xor a b)) (defmethod gf-subtract ((gf galois) a b) (boole boole-xor a b)) (defmethod gf-multiply ((gf galois) a b) (let ((sum (+ (gf-log gf a) (gf-log gf b)))) (gf-exp gf sum))) (defmethod gf-divide ((gf galois) a b) (when (= b 0) (error "divide by zero")) (if (= a 0) 0 (let ((sub (- (gf-log gf a) (gf-log gf b)))) (gf-exp gf sub)))) ;;; open-paren at beg of line confuses `slime-compile-defun` which uses ;;; elisp function `beginning-of-defun`, which in turn involves ;;; backward-searching open-paren at beg of line ;;; there seems to be no easy way to fix this problem ;; with an extra leading '\', docstring is kind of ulgy now, though (defmacro with-gf-accessors (accessors gf &body body) "shortcuts for gf-exp & gf-log, usage: \(with-gf-accessors ((gfexp gf-exp)) *gf-instance* ...)" `(labels ,(mapcar (lambda (acc-entry) (let ((acc-name (car acc-entry)) (method-name (cadr acc-entry))) `(,acc-name (a) (,method-name ,gf a)))) accessors) ,@body)) (defmacro with-gf-arithmetics (ariths gf &body body) "shortcuts for gf-add, gf-subtract, gf-multiply & gf-divide, usage: \(with-gf-arithmetics ((gf+ gf-add)) *gf-instance* ...)" `(labels ,(mapcar (lambda (arith-entry) (let ((arith-name (car arith-entry)) (method-name (cadr arith-entry))) `(,arith-name (a b) (,method-name ,gf a b)))) ariths) ,@body)) (defmacro with-gf-shortcuts (accessors ariths gf &body body) "combined with-gf-accessors & with-gf-arithmetics, usage: \(with-gf-shortcuts ((gflog gf-log)) ((gf* gf-multiply)) *gf-instance* ...)" `(labels ,(append (mapcar (lambda (acc-entry) (let ((acc-name (car acc-entry)) (method-name (cadr acc-entry))) `(,acc-name (a) (,method-name ,gf a)))) accessors) (mapcar (lambda (arith-entry) (let ((arith-name (car arith-entry)) (method-name (cadr arith-entry))) `(,arith-name (a b) (,method-name ,gf a b)))) ariths)) ,@body))
4,483
Common Lisp
.lisp
105
33.714286
76
0.559221
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
9e30c1559e2bad89a3dd368e6c47e41cc6034adbaa005491605bbcbcb0c9d603
4,394
[ -1 ]
4,395
bch-ecc.lisp
jnjcc_cl-qrencode/rs-ecc/bch-ecc.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Bose-Chaudhuri-Hocquenghem (BCH) error correction code (in-package #:cl-qrencode) ;;; Polynomial (using list) arithmetics ;;; by polynomial list (3 2 1), we mean 3*x^2 + 2*x + 1 (defun poly-ash (poly s) "shift left POLY by S" (declare (type list poly)) (append poly (make-list s :initial-element 0))) (defun poly-multiply (poly b &optional (op #'*)) "multiply B on every element of POLY using OP" (labels ((mult (elem) (funcall op elem b))) (mapcar #'mult poly))) (defun poly-substract (lhs rhs &optional (op #'-)) (labels ((sub (elem1 elem2) (funcall op elem1 elem2))) (mapcar #'sub lhs rhs))) (defun poly-mod (msg gen rem &optional (sub #'poly-substract) (mul #'poly-multiply)) "MSG % GEN, with REM remainders" (labels ((cdrnzero (msg rem) (do ((head msg (cdr head))) ((or (null head) (<= (length head) rem) (/= (car head) 0)) head) head))) (do ((m (poly-ash msg rem) (cdrnzero m rem))) ((<= (length m) rem) m) (let* ((glen (length gen)) (sft (- (length m) glen)) ;; LEAD coffiecient of message polynomial (lead (car m))) (setf m (funcall sub m (poly-ash (funcall mul gen lead) sft))))))) (defclass bch-ecc () ((k :initform nil :initarg :k :documentation "# of data codewords") (ec :initform nil :initarg :ec :documentation "# of error correction codewords"))) (defun bch* (poly b) (poly-multiply poly b)) (defun bch- (lhs rhs) (labels ((xor (a b) (boole boole-xor a b))) (poly-substract lhs rhs #'xor))) (defun bch-xor (lhs rhs) (labels ((xor (a b) (boole boole-xor a b))) (mapcar #'xor lhs rhs))) (defun bch% (msg gen rem) (poly-mod msg gen rem #'bch- #'bch*)) (defgeneric bch-ecc (bch msgpoly genpoly) (:documentation "do bch error correction under BCH(K+EC, K)")) (defmethod bch-ecc ((bch bch-ecc) msg gen) (with-slots (k ec) bch (unless (= (length msg) k) (error "wrong msg length, expect: ~A; got: ~A~%" k (length msg))) (bch% msg gen ec))) ;;; As used by format information ecc & version information ecc respectively ;;; BCH(15, 5) & BCH(18, 6) (let ((fi-ecc (make-instance 'bch-ecc :k 5 :ec 10)) ;; format information generator polynomial ;; x^10 + x^8 + x^5 + x^4 + x^2 + x + 1 (fi-gpoly '(1 0 1 0 0 1 1 0 1 1 1)) (fi-xor '(1 0 1 0 1 0 0 0 0 0 1 0 0 1 0))) (defun format-ecc (level mask-ind) (let ((seq (append (level-indicator level) (mask-pattern-ref mask-ind)))) (bch-xor (append seq (bch-ecc fi-ecc seq fi-gpoly)) fi-xor)))) (let ((vi-ecc (make-instance 'bch-ecc :k 6 :ec 12)) ;; version information generator polynomial ;; x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1 (vi-gpoly '(1 1 1 1 1 0 0 1 0 0 1 0 1))) (defun version-ecc (version) (let ((seq (decimal->bstream version 6))) (append seq (bch-ecc vi-ecc seq vi-gpoly)))))
3,071
Common Lisp
.lisp
75
35.28
84
0.5917
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
d26e7cf4a567f27eb559c3e62c59ce0be26bb3514a1a1321d6d9e8760bc79936
4,395
[ -1 ]
4,396
rs-ecc.lisp
jnjcc_cl-qrencode/rs-ecc/rs-ecc.lisp
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Reed-Solomon error correction code as used by QR code (in-package #:cl-qrencode) (defclass rs-ecc () ((k :initform nil :initarg :k :documentation "# of data codewords") (ec :initform nil :initarg :ec :documentation "# of error correction codewords") (gpoly :initform nil :reader gpoly :documentation "with EC, we calculate generator poly immediately"))) ;;; Reed-Solomon code uses GF(2^8) with prime polynomial 285, ;;; or 1,0001,1101, or (x^8 + x^4 + x^3 + x^2 + 1) (let ((gf256 (make-instance 'galois :power 8 :ppoly 285))) ;; Polynomial arithmetics under GF(2^8), as used by Reed-Solomon ecc (defun rs* (poly b) "multiply B on every element of POLY under GF(2^8)" (with-gf-arithmetics ((gf* gf-multiply)) gf256 (poly-multiply poly b #'gf*))) (defun rs- (lhs rhs) (with-gf-arithmetics ((gf- gf-subtract)) gf256 (poly-substract lhs rhs #'gf-))) (defun rs% (msg gen rem) (poly-mod msg gen rem #'rs- #'rs*)) (defmethod initialize-instance :after ((rs rs-ecc) &rest args) (declare (ignore args)) (setf (slot-value rs 'gpoly) (gen-poly rs))) (defgeneric gen-poly (rs)) (defmethod gen-poly ((rs rs-ecc)) "Generator Polynomial: (x-a^0) * (x-a^1) * ... * (x-a^(ec-1))" (with-slots (ec) rs (let* ((size (+ ec 1)) (poly (make-list size :initial-element nil))) (with-gf-shortcuts ((gfexp gf-exp)) ((gf+ gf-add) (gf* gf-multiply)) gf256 (setf (nth 0 poly) 1 (nth 1 poly) 1) (do ((i 2 (1+ i))) ((> i ec) poly) (setf (nth i poly) 1) (do ((j (- i 1) (1- j))) ((<= j 0)) (if (not (= (nth j poly) 0)) (setf (nth j poly) (gf+ (nth (- j 1) poly) (gf* (nth j poly) (gfexp (- i 1))))) (setf (nth j poly) (nth (- j 1) poly)))) (setf (nth 0 poly) (gf* (nth 0 poly) (gfexp (- i 1)))))) (reverse poly)))) (defgeneric gen-poly-gflog (rs)) (defgeneric ecc-poly (rs msg)) (defmethod gen-poly-gflog ((rs rs-ecc)) (with-gf-accessors ((gflog gf-log)) gf256 ;; GPOLY already calculated when making new instance (mapcar #'gflog (gpoly rs)))) (defmethod ecc-poly ((rs rs-ecc) msg-poly) "Error Correction codewords Polynomial for MSG-POLY" (with-slots (k ec gpoly) rs (unless (= (length msg-poly) k) (error "wrong msg-poly length, expect: ~A~%" k)) (rs% msg-poly gpoly ec))))
2,609
Common Lisp
.lisp
60
36
82
0.569067
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
7f14f93cebb3536df97c6a33da0f4068856a799d97697ec152e6557053271819
4,396
[ -1 ]
4,397
cl-qrencode.asd
jnjcc_cl-qrencode/cl-qrencode.asd
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; (asdf:defsystem #:cl-qrencode :description "QR code 2005 encoder in Common Lisp" :version "0.1.1" :author "jnjcc at live.com" :licence "GPL" :serial t :depends-on (#:zpng) :in-order-to ((asdf:test-op (asdf:load-op #:cl-qrencode-test))) :perform (asdf:test-op :after (op c) (funcall (find-symbol (symbol-name '#:run-all-tests) '#:cl-qrencode-test))) :components ((:file "packages") (:module "utils" :components ((:file "util"))) (:module "rs-ecc" :components ((:file "galois") (:file "bch-ecc") (:file "rs-ecc"))) (:module "qrencode" :components ((:file "modes") (:file "qrspec") (:file "input") (:file "bstream") (:file "codeword") (:file "matrix") (:file "mask") (:file "encode"))) (:module "image" :components ((:file "png")))))
1,324
Common Lisp
.asd
30
25.766667
88
0.403712
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
4fbc2afb61be7b52fec2f6f65200c5c0b850cf33e70a1282b93d988698520bfd
4,397
[ -1 ]
4,398
cl-qrencode-test.asd
jnjcc_cl-qrencode/cl-qrencode-test.asd
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; (asdf:defsystem #:cl-qrencode-test :description "QR code encoder test suites" :version "0.1.1" :author "jnjcc at live.com" :licence "GPL" :depends-on (#:cl-qrencode #:lisp-unit) :components ((:module "test" :serial t :components ((:file "packages") (:file "utils") (:file "pre-spec") (:file "ecc-test") (:file "spec-test") (:file "encode-test") (:file "tests")))))
720
Common Lisp
.asd
17
24.705882
66
0.413105
jnjcc/cl-qrencode
32
7
2
GPL-2.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
446336509eb17b1f05475bced4fbdcd1cf29709411277670e416224fba82f333
4,398
[ -1 ]
4,438
package.lisp
vindarel_cl-readline/package.lisp
;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*- ;;; ;;; Package definition for cl-readline, bindings to GNU Readline library. ;;; ;;; Copyright © 2015–2018 Mark Karpov ;;; ;;; cl-readline is free software: you can redistribute it and/or modify it ;;; under the terms of the GNU General Public License as published by the ;;; Free Software Foundation, either version 3 of the License, or (at your ;;; option) any later version. ;;; ;;; cl-readline is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General ;;; Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License along ;;; with this program. If not, see <http://www.gnu.org/licenses/>. (defpackage :cl-readline (:nicknames :rl) (:use #:common-lisp #:alexandria #:cffi) (:export ;; Readline Variables #:*line-buffer* #:*point* #:+end+ #:*mark* #:*done* #:+dispatching+ #:+prompt+ #:*display-prompt* #:+library-version+ #:+readline-version+ #:+gnu-readline-p+ #:*terminal-name* #:*readline-name* #:*prefer-env-winsize* #:+executing-keymap+ #:+binding-keymap+ #:+executing-macro+ #:+executing-key+ #:+executing-keyseq+ #:+key-sequence-length+ #:+readline-state+ #:+explicit-arg+ #:+numeric-arg+ #:+editing-mode+ #:*catch-signals* #:*catch-sigwinch* #:*change-environment* #:*basic-word-break-characters* #:*basic-quote-characters* #:*completer-word-break-characters* #:*completion-query-items* #:*completion-append-character* #:*ignore-completion-duplicates* #:*sort-completion-matches* #:+completion-type+ #:*inhibit-completion* ;; Basic Functionality #:readline #:add-defun ;; Hooks and Custom Functions #:register-hook #:register-function ;; Work with Keymaps #:make-keymap #:copy-keymap #:free-keymap #:get-keymap #:set-keymap #:get-keymap-by-name #:get-keymap-name #:with-new-keymap ;; Binding keys #:bind-key #:unbind-key #:unbind-command #:bind-keyseq #:parse-and-bind #:read-init-file ;; Associating Function Names and Bindings #:function-dumper #:list-funmap-names #:funmap-names #:add-funmap-entry ;; Allowing Undoing #:undo-group #:add-undo #:free-undo-list #:do-undo #:modifying ;; Redisplay #:redisplay #:forced-update-display #:on-new-line #:reset-line-state #:crlf #:show-char #:with-message #:set-prompt ;; Modifying Text #:insert-text #:delete-text #:kill-text ;; Character Input #:read-key #:stuff-char #:execute-next #:clear-pending-input #:set-keyboard-input-timeout ;; Moving the cursor #:forward-byte #:backward-byte #:backward-char #:forward-char #:forward-word #:backward-word #:beginning-of-line #:end-of-line #:refresh-line #:clear-screen #:clear-display ;; Terminal Management #:prep-terminal #:deprep-terminal #:tty-set-default-bindings #:tty-unset-default-bindings #:reset-terminal ;; Utility Functions #:replace-line #:extend-line-buffer #:initialize #:ding ;; Miscellaneous Functions #:macro-dumper #:variable-bind #:variable-value #:variable-dumper #:*blink-matching-paren* #:set-paren-blink-timeout #:clear-history #:read-history #:write-history ;; Signal Handling #:cleanup-after-signal #:free-line-state #:reset-after-signal #:echo-signal-char #:resize-terminal #:set-screen-size #:get-screen-size #:reset-screen-size #:set-signals #:clear-signals))
3,770
Common Lisp
.lisp
157
20.216561
76
0.666482
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
e205436eea076414d6975b2de114326aa113f066234fe8e16e949cc094fc80ec
4,438
[ -1 ]
4,439
cl-readline.lisp
vindarel_cl-readline/cl-readline.lisp
;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*- ;;; ;;; cl-readline, bindings to GNU Readline library. ;;; ;;; Copyright © 2015–2018 Mark Karpov ;;; ;;; cl-readline is free software: you can redistribute it and/or modify it ;;; under the terms of the GNU General Public License as published by the ;;; Free Software Foundation, either version 3 of the License, or (at your ;;; option) any later version. ;;; ;;; cl-readline is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General ;;; Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License along ;;; with this program. If not, see <http://www.gnu.org/licenses/>. (in-package #:cl-readline) (define-foreign-library readline ;; On OSX we first search readline, installed by brew install readline ;; because native system version of readline is a symlink to libedit. ;; Some people on the internet advice to "fix" it by running: ;; brew link --force readline ;; but it is a bad idea, because this command may break some system utilities, ;; depending on libedit's internals. (:darwin (:or "/usr/local/opt/readline/lib/libreadline.dylib" "/opt/homebrew/opt/readline/lib/libreadline.dylib" "/opt/local/lib/libreadline.dylib" "libreadline.dylib")) (:openbsd (:default "libereadline")) (:unix (:or "libreadline.so.6.3" "libreadline.so.6" "libreadline.so.7" "libreadline.so.8" "libreadline.so")) (t (:default "libreadline"))) (use-foreign-library readline) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Readline Variables ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Descriptions here are from the official documentation for GNU Readline. ;; The documentation can be found at ;; http://cnswww.cns.cwru.edu/php/chet/readline/readline.html (defcvar ("rl_line_buffer" *line-buffer*) :string "This is the line gathered so far. You are welcome to modify the contents of the line, but remember about undoing. The function `extend-line-buffer' is available to increase the memory allocated to `*line-buffer*'.") ;; rl_point is the place in the string where the cursor is. Sometimes ;; this is the same as rl_end. (defcvar ("rl_point" *point*) :int "The offset of the current cursor position in `*line-buffer*' (the point).") (defcvar ("rl_end" +end+ :read-only t) :int "The number of characters present in `*line-buffer*'. When `*point*' is at the end of the line, `*point*' and `+end+' are equal.") (defcvar ("rl_mark" *mark*) :int "The mark (saved position) in the current line. If set, the mark and point define a region.") (defcvar ("rl_done" *done*) :boolean "Setting this to a non-NIL value causes Readline to return the current line immediately.") (defcvar ("rl_num_chars_to_read" *num-chars-to-read*) :int "Setting this to a positive value before calling READLINE causes Readline to return after accepting that many characters, rather than reading up to a character bound to accept-line.") (defcvar ("rl_pending_input" *pending-input*) :int ;; not used "Setting this to a value makes it the next keystroke read. This is a way to stuff a single character into the input stream.") (defcvar ("rl_dispatching" +dispatching+ :read-only t) :boolean "Set to a non-NIL value if a function is being called from a key binding; NIL otherwise. Application functions can test this to discover whether they were called directly or by Readline's dispatching mechanism.") (defcvar ("rl_erase_empty_line" *erase-empty-line*) :boolean "Setting this to a non-NIL value causes Readline to completely erase the current line, including any prompt, any time a newline is typed as the only character on an otherwise-empty line. The cursor is moved to the beginning of the newly-blank line.") (defcvar ("rl_prompt" +prompt+ :read-only t) :string "The prompt Readline uses. This is set from the argument to `readline', and should not be assigned to directly. The `set-prompt' function may be used to modify the prompt string after calling `readline'.") (defcvar ("rl_display_prompt" *display-prompt*) :string "The string displayed as the prompt. This is usually identical to `+prompt+', but may be changed temporarily by functions that use the prompt string as a message area, such as incremental search.") (defcvar ("rl_already_prompted" *already-prompted*) :boolean "If an application wishes to display the prompt itself, rather than have Readline do it the first time READLINE is called, it should set this variable to a non-NIL value after displaying the prompt. The prompt must also be passed as the argument to READLINE so the redisplay functions can update the display properly. The calling application is responsible for managing the value; Readline never sets it.") (defcvar ("rl_library_version" +library-version+ :read-only t) :string "The version number of this revision of the library.") (defcvar ("rl_readline_version" +readline-version+ :read-only t) version "Major and minor version numbers of Readline library.") (defcvar ("rl_gnu_readline_p" +gnu-readline-p+ :read-only t) :boolean "Always evaluated to T, denoting that this is GNU readline rather than some emulation.") (defcvar ("rl_terminal_name" *terminal-name*) :string "The terminal type, used for initialization. If not set by the application, Readline sets this to the value of the TERM environment variable the first time it is called.") (defcvar ("rl_readline_name" *readline-name*) :string "This symbol-macro should be set to a unique name by each application using Readline. The value allows conditional parsing of the inputrc file.") (defcvar ("rl_instream" *instream*) :pointer ;; not used "The stdio stream from which Readline reads input. If NULL, Readline defaults to stdin.") (defcvar ("rl_outstream" *outstream*) :pointer "The stdio stream to which Readline performs output. If NULL, Readline defaults to stdout.") (defcvar ("rl_prefer_env_winsize" *prefer-env-winsize*) :boolean "If non-NIL, Readline gives values found in the LINES and COLUMNS environment variables greater precedence than values fetched from the kernel when computing the screen dimensions.") (defcvar ("rl_last_func" *last-func*) :pointer ;; not used "The address of the last command function Readline executed. May be used to test whether or not a function is being executed twice in succession, for example.") (defcvar ("rl_startup_hook" *startup-hook*) :pointer "If non-zero, this is the address of a function to call just before readline prints the first prompt.") (defcvar ("rl_pre_input_hook" *pre-input-hook*) :pointer "If non-zero, this is the address of a function to call after the first prompt has been printed and just before readline starts reading input characters.") (defcvar ("rl_event_hook" *event-hook*) :pointer "If non-zero, this is the address of a function to call periodically when Readline is waiting for terminal input. By default, this will be called at most ten times a second if there is no keyboard input.") (defcvar ("rl_getc_function" *getc-function*) :pointer "If non-zero, Readline will call indirectly through this pointer to get a character from the input stream. By default, it is set to `rl_getc', the default Readline character input function (see section 2.4.8 Character Input). In general, an application that sets `rl_getc_function' should consider setting `rl_input_available_hook' as well.") (defcvar ("rl_signal_event_hook" *signal-event-hook*) :pointer "If non-zero, this is the address of a function to call if a read system call is interrupted when Readline is reading terminal input.") (defcvar ("rl_input_available_hook" *input-available-hook*) :pointer "If non-zero, Readline will use this function's return value when it needs to determine whether or not there is available input on the current input source.") (defcvar ("rl_redisplay_function" *redisplay-function*) :pointer "If non-zero, Readline will call indirectly through this pointer to update the display with the current contents of the editing buffer. By default, it is set to `rl_redisplay', the default Readline redisplay function (see section 2.4.6 Redisplay).") (defcvar ("rl_prep_term_function" *prep-term-function*) :pointer "If non-zero, Readline will call indirectly through this pointer to initialize the terminal. The function takes a single argument, an int flag that says whether or not to use eight-bit characters. By default, this is set to `rl_prep_terminal' (see section 2.4.9 Terminal Management).") (defcvar ("rl_deprep_term_function" *deprep-term-function*) :pointer "If non-zero, Readline will call indirectly through this pointer to reset the terminal. This function should undo the effects of `rl_prep_term_function.' By default, this is set to `rl_deprep_terminal' (see section 2.4.9 Terminal Management).") (defcvar ("rl_executing_keymap" +executing-keymap+ :read-only t) :pointer "This symbol macro is evaluated to the keymap in which the currently executing Readline function was found.") (defcvar ("rl_binding_keymap" +binding-keymap+ :read-only t) :pointer "This symbol macro is evaluated to the keymap in which the last key binding occurred.") (defcvar ("rl_executing_macro" +executing-macro+ :read-only t) :string "This symbol macro is evaluated to the text of any currently-executing macro.") (defcvar ("rl_executing_key" +executing-key+ :read-only t) int-char "The key that caused the dispatch to the currently-executing Readline function.") (defcvar ("rl_executing_keyseq" +executing-keyseq+ :read-only t) :string "The full key sequence that caused the dispatch to the currently-executing Readline function.") (defcvar ("rl_key_sequence_length" +key-sequence-length+ :read-only t) :int "The number of characters in `+executing-keyseq+'.") (defcvar ("rl_readline_state" +readline-state+ :read-only t) state "This symbol macro is evaluated to a list containing keywords that denote state of Readline. For list of possible values see `+states+'.") (defcvar ("rl_explicit_arg" +explicit-arg+ :read-only t) :boolean "Evaluated to T if an explicit numeric argument was specified by the user. Only valid in a bindable command function.") (defcvar ("rl_numeric_arg" +numeric-arg+ :read-only t) :int "Evaluated to the value of any numeric argument explicitly specified by the user before executing the current Readline function. Only valid in a bindable command function.") (defcvar ("rl_editing_mode" +editing-mode+ :read-only t) editing-mode "Evaluated to keyword denoting actual editing mode: :EMACS or :VI.") (defcvar ("rl_catch_signals" *catch-signals*) :boolean "If this variable is non-NIL, Readline will install signal handlers for SIGINT, SIGQUIT, SIGTERM, SIGHUP, SIGALRM, SIGTSTP, SIGTTIN, and SIGTTOU. The default value of `*catch-signals*' is T.") (defcvar ("rl_catch_sigwinch" *catch-sigwinch*) :boolean "If this variable is set to a non-NIL value, Readline will install a signal handler for SIGWINCH. The default value of `*catch-sigwinch*' is T.") (defcvar ("rl_change_environment" *change-environment*) :boolean "If this variable is set to a non-NIL value, and Readline is handling SIGWINCH, Readline will modify the LINES and COLUMNS environment variables upon receipt of a SIGWINCH. The default value of `*change-environment*' is T.") (defcvar ("rl_attempted_completion_function" *attempted-completion-function*) :pointer "A pointer to an alternative function to create matches. The function is called with TEXT, START, and END. START and END are indices in `*line-buffer*' defining the boundaries of text, which is a character string. If this function exists and returns NULL, or if this variable is set to NULL, then `complete' will call the value of `*completion-entry-function*' to generate matches, otherwise the array of strings returned will be used. If this function sets the `*attempted-completion-over*' variable to a non-NIL value, Readline will not perform its default completion even if this function returns no matches.") (defcvar ("rl_completion_display_matches_hook" *completion-display-matches-hook*) :pointer "If non-zero, then this is the address of a function to call when completing a word would normally display the list of possible matches. This function is called au lieu de Readline displaying the list. It takes three arguments: (char **matches, int num_matches, int max_length) where matches is the array of matching strings, `num_matches' is the number of strings in that array, and `max_length' is the length of the longest string in that array.") (defcvar ("rl_basic_word_break_characters" *basic-word-break-characters*) :string "The basic list of characters that signal a break between words for the completer routine. The default value of this variable is the characters which break words for completion in Bash.") (defcvar ("rl_basic_quote_characters" *basic-quote-characters*) :string "A list of quote characters which can cause a word break.") (defcvar ("rl_completer_word_break_characters" *completer-word-break-characters*) :string "The list of characters that signal a break between words for `complete-internal'. The default list is the value of `*basic-word-break-characters*.'") (defcvar ("rl_completion_query_items" *completion-query-items*) :int "Up to this many items will be displayed in response to a `possible-completions' call. After that, Readline asks the user if she is sure she wants to see them all. The default value is 100. A negative value indicates that Readline should never ask the user.") (defcvar ("rl_completion_append_character" *completion-append-character*) int-char "When a single completion alternative matches at the end of the command line, this character is appended to the inserted completion text. The default is a space character. Setting this to the null character prevents anything being appended automatically. This can be changed in application-specific completion functions to provide the 'most sensible word separator character' according to an application-specific command line syntax specification.") (defcvar ("rl_ignore_completion_duplicates" *ignore-completion-duplicates*) :boolean "If non-NIL, then duplicates in the matches are removed. The default is T.") (defcvar ("rl_attempted_completion_over" *attempted-completion-over*) :boolean "If an application-specific completion function assigned to `*attempted-completion-function*' sets this variable to a non-NIL value, Readline will not perform its default filename completion even if the application's completion function returns no matches. It should be set only by an application's completion function.") (defcvar ("rl_sort_completion_matches" *sort-completion-matches*) :boolean "If an application sets this variable to NIL, Readline will not sort the list of completions (which implies that it cannot remove any duplicate completions). The default value is T, which means that Readline will sort the completions and, depending on the value of `*ignore-completion-duplicates*', will attempt to remove duplicate matches.") (defcvar ("rl_completion_type" +completion-type+ :read-only t) completion-type "Set to a keyword describing the type of completion Readline is currently attempting. Possible values are: :STANDARD-COMPLETION tells Readline to do standard completion; :DISPLAY-AND-PERFORM means to display all possible completions if there is more than one, as well as performing partial completion; :INSERT-ALL means insert all possible completions; :LIST-ALL means list the possible completions; :NOT-LIST-CMN-PREFIX is similar to :DISPLAY-AND-PERFORM but possible completions are not listed if the possible completions share a common prefix.") (defcvar ("rl_inhibit_completion" *inhibit-completion*) :boolean "If this variable is non-NIL, completion is inhibited. The completion character will be inserted as any other bound to self-insert.") (defcvar ("history_base" +history-base+ :read-only t) :int "The logical offset of the first entry in the history list.") (defcvar ("history_length" +history-length+ :read-only t) :int "The number of entries currently stored in the history list.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Basic Functionality ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun recent-history-line-satisfies-p (predicate) "Check if the most recent history line satisfies given predicate PREDICATE. Return T if there is no history saved." (if (zerop +history-length+) t (funcall predicate (foreign-string-to-lisp (with-foreign-slots ((line) (foreign-funcall "history_get" :int (1- (+ +history-base+ +history-length+)) :pointer) (:struct history-entry)) line))))) (defun readline (&key prompt already-prompted num-chars erase-empty-line add-history novelty-check) "Get a line from user with editing. PROMPT, if supplied, is printed before reading of input. Non-NIL value of ALREADY-PROMPTED will tell Readline that the application has printed prompt already. However, PROMPT must be supplied in this case too, so redisplay functions can update the display properly. If NUM-CHARS argument is a positive number, Readline will return after accepting that many characters. If ERASE-EMPTY-LINE is not NIL, `readline' will completely erase the current line, including any prompt, any time a newline is typed as the only character on an otherwise-empty line. The cursor is moved to the beginning of the newly-blank line. Supplying ADD-HISTORY tells Readline that user's input should be added to history. However, blank lines don't get into history anyway. NOVELTY-CHECK, if given, must be a predicate that takes two strings: the actual line and the most recent history line. Only when the predicate evaluates to non-NIL value new line will be added to the history. Return value on success is the actual string and NIL on failure." (setf *already-prompted* already-prompted *num-chars-to-read* (or num-chars 0) *erase-empty-line* erase-empty-line) (let* ((prompt (if prompt (string prompt) "")) (ptr (foreign-funcall "readline" :string prompt :pointer))) (unless (null-pointer-p ptr)) (unwind-protect (let ((str (foreign-string-to-lisp ptr))) (when (and add-history (not (emptyp str)) (or (not novelty-check) (recent-history-line-satisfies-p (curry novelty-check str)))) (foreign-funcall "add_history" :string str :void)) str) (foreign-funcall "free" :pointer ptr :void)))) (defun ensure-initialization () "Make sure that Readline is initialized. If it's not initialized yet, initialize it." (unless (find :initialized +readline-state+) (initialize))) (defmacro with-possible-redirection (filename append &body body) "If FILENAME is not NIL, try to create C file named FILENAME, temporarily reassign `*outstream*' to pointer to this file, perform BODY, then close the file and assign `*outstream*' the old value. If APPEND is not NIL, output will be appended to the file. Returns NIL on success and T on failure." (with-gensyms (temp-outstream file-pointer body-fnc) `(flet ((,body-fnc () ,@body)) (if ,filename (let ((,temp-outstream *outstream*) (,file-pointer (foreign-funcall "fopen" :string ,filename :string (if ,append "a" "w") :pointer))) (if (null-pointer-p ,file-pointer) t (unwind-protect (progn (setf *outstream* ,file-pointer) (,body-fnc)) (foreign-funcall "fclose" :pointer ,file-pointer :boolean) (setf *outstream* ,temp-outstream)))) (,body-fnc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Hooks and Custom Functions ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun register-hook (hook function) "Register a hook. HOOK should be a keyword, one of the following: :STARTUP hook is called just before READLINE prints the prompt. :PRE-INPUT hook is called after prompt has been printed and just before READLINE starts reading input characters. :EVENT hook is called periodically when waiting for terminal input. By default, this will be called at most ten times a second if there is no keyboard input. :SIGNAL hook is called when a read system call is interrupted when READLINE is reading terminal input. :INPUTP hook is called when Readline need to determine whether or not there is available input on the current input source. If FUNCTION returns NIL, it means that there is no available input. :LSMATCHES hook is called to display list of completions. FUNCTION must be able to take three arguments: list of completions, length of the list, and length of the longest completion in the list. It's up to the function how to display these completions. Other values of HOOK will be ignored. FUNCTION must be a function that takes no arguments and returns NIL on success and T on failure. If FUNCTION is NIL, hook will be removed (or default function will be used)." (let ((cb (if (and (eql hook :lsmatches) function) (produce-callback (lambda (matches num max-length) (funcall function (to-list-of-strings matches) num max-length)) :void (:pointer :int :int)) (produce-callback function :boolean)))) (case hook (:startup (setf *startup-hook* cb)) (:pre-input (setf *pre-input-hook* cb)) (:event (setf *event-hook* cb)) (:signal (setf *signal-event-hook* cb)) (:inputp (setf *input-available-hook* cb)) (:lsmatches (setf *completion-display-matches-hook* cb)))) nil) (defun register-function (func function) "Register a function. FUNC should be a keyword, one of the following: :GETC function is used to get a character from the input stream, thus FUNCTION should take pointer to C stream and return a character if this function is desired to be registered. In general, an application that registers :GETC function should consider registering :INPUTP hook as well (see REGISTER-HOOK). :REDISPLAY function is used to update the display with the current contents of the editing buffer, thus FUNCTION should take no arguments and return NIL on success and non-NIL of failure. By default, it is set to REDISPLAY, the default Readline redisplay function. :PREP-TERM function is used to initialize the terminal, so FUNCTION must be able to take one argument, a flag that says whether or not to use eight-bit characters. By default, PREP-TERMINAL is used. :DEPREP-TERM function is used to reset the terminal. This function should undo the effects of :PREP-TERM function. :COMPLETE function is used to generate list of possible completions for given partially entered word. The function must be able to take three arguments: partially entered word, start index of the word in *LINE-BUFFER* and end index of the word in the buffer. The function must return a list where first element is the actual completion (or part of completion if two or more completions share common prefix) and the rest arguments are possible completions. Other values of FUNC will be ignored. FUNCTION must be a function, if FUNCTION is NIL, result is unpredictable." (case func (:getc (setf *getc-function* (produce-callback* function int-char '(:pointer)))) (:redisplay (setf *redisplay-function* (produce-callback* function :void))) (:prep-term (setf *prep-term-function* (produce-callback* function :void '(:boolean)))) (:deprep-term (setf *deprep-term-function* (produce-callback* function :void))) (:complete (setf *attempted-completion-function* (produce-callback* (lambda (text start end) (prog1 (to-array-of-strings (funcall function text start end)) (setf *attempted-completion-over* t))) :pointer '(:string :int :int))))) nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Work with Keymaps ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun make-keymap (&optional bare) "Return a new keymap with self-inserting printing characters, the lowercase Meta characters bound to run their equivalents, and the Meta digits bound to produce numeric arguments. If BARE is supplied and it's not NIL, empty keymap will be returned." (if bare (foreign-funcall "rl_make_bare_keymap" :pointer) (foreign-funcall "rl_make_keymap" :pointer))) (defcfun ("rl_copy_keymap" copy-keymap) :pointer "Return a new keymap which is a copy of KEYMAP." (keymap :pointer)) (defcfun ("rl_free_keymap" free-keymap) :void "Free all storage associated with KEYMAP." (keymap :pointer)) (defcfun ("rl_get_keymap" get-keymap) :pointer "Return currently active keymap.") (defcfun ("rl_set_keymap" set-keymap) :void "Make KEYMAP the currently active keymap." (keymap :pointer)) (defcfun ("rl_get_keymap_by_name" get-keymap-by-name) :pointer "Return the keymap matching NAME. NAME is one which would be supplied in a set keymap inputrc line." (name :string)) (defcfun ("rl_get_keymap_name" get-keymap-name) :string "Return the name matching KEYMAP. Name is one which would be supplied in a set keymap inputrc line." (keymap :pointer)) (defmacro with-new-keymap (form &body body) "Create new keymap evaluating FORM, bind symbol `keymap' to the result, then free it when control flow leaves BODY. `make-keymap' and `copy-keymap' can be used to produce new keymap." `(let ((keymap ,form)) (unwind-protect (progn ,@body) (free-keymap keymap)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Binding Keys ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun add-defun (name function &optional key) "Add NAME to the list of named functions. Make FUNCTION be the function that gets called. If KEY is not NIL and it's a character, then bind it to function using `bind-key'. FUNCTION must be able to take two arguments: integer representing its argument and character representing key that has invoked it." (ensure-initialization) (foreign-funcall "rl_add_defun" :string name :pointer (produce-callback function :boolean (:int int-char)) :int (if key (char-code key) -1))) (defun bind-key (key function &key keymap if-unbound) "Bind KEY to FUNCTION in the currently active keymap. If KEYMAP argument supplied, binding takes place in specified keymap. If IF-UNBOUND is supplied and it's not NIL, KEY will be bound to FUNCTION only if it's not already bound." (ensure-initialization) (let ((cb (produce-callback* function :boolean '(:int int-char)))) (cond ((and keymap if-unbound) (foreign-funcall "rl_bind_key_if_unbound_in_map" int-char key :pointer cb :pointer keymap :boolean)) (keymap (foreign-funcall "rl_bind_key_in_map" int-char key :pointer cb :pointer keymap :boolean)) (if-unbound (foreign-funcall "rl_bind_key_if_unbound" int-char key :pointer cb :boolean)) (t (foreign-funcall "rl_bind_key" int-char key :pointer cb :boolean))))) (defun unbind-key (key &optional keymap) "Unbind KEY in KEYMAP. If KEYMAP is not supplied or it's NIL, KEY will be unbound in currently active keymap. The function returns NIL on success and T on failure." (ensure-initialization) (if keymap (foreign-funcall "rl_unbind_key_in_map" int-char key :pointer keymap :boolean) (foreign-funcall "rl_unbind_key" int-char key :boolean))) (defun unbind-command (command keymap) "Unbind all keys that are bound to COMMAND in KEYMAP." (ensure-initialization) (foreign-funcall "rl_unbind_command_in_map" :string command :pointer keymap :boolean)) (defun bind-keyseq (keyseq function &key keymap if-unbound) "Bind the key sequence represented by the string KEYSEQ to the function FUNCTION, beginning in the current keymap. This makes new keymaps as necessary. If KEYMAP is supplied and it's not NIL, initial bindings are performed in KEYMAP. If IF-UNBOUND is supplied and it's not NIL, KEYSEQ will be bound to FUNCTION only if it's not already bound. The return value is T if KEYSEQ is invalid and NIL otherwise." (ensure-initialization) (let ((cb (produce-callback* function :boolean '(:int int-char)))) (cond ((and keymap if-unbound) (foreign-funcall "rl_bind_keyseq_if_unbound_in_map" :string keyseq :pointer cb :pointer keymap :boolean)) (keymap (foreign-funcall "rl_bind_keyseq_in_map" :string keyseq :pointer cb :pointer keymap :boolean)) (if-unbound (foreign-funcall "rl_bind_keyseq_if_unbound" :string keyseq :pointer cb :boolean)) (t (foreign-funcall "rl_bind_keyseq" :string keyseq :pointer cb :boolean))))) (defun parse-and-bind (line) "Parse LINE as if it had been read from the inputrc file and perform any key bindings and variable assignments found." (ensure-initialization) (foreign-funcall "rl_parse_and_bind" :string line :boolean)) (defun read-init-file (filename) "Read keybindings and variable assignments from FILENAME." (ensure-initialization) (foreign-funcall "rl_read_init_file" :string filename :boolean)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Associating Function Names and Bindings ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun function-dumper (readable &optional filename append) "Print the Readline function names and the key sequences currently bound to them to stdout. If READABLE is non-NIL, the list is formatted in such a way that it can be made part of an inputrc file and re-read. If FILENAME is supplied and it's a string or path, output will be redirected to the file. APPEND allows to append text to the file instead of overwriting it." (ensure-initialization) (with-possible-redirection filename append (foreign-funcall "rl_function_dumper" :boolean readable :void))) (defun list-funmap-names (&optional filename append) "Print the names of all bindable Readline functions to stdout. If FILENAME is supplied and it's a string or path, output will be redirected to the file. APPEND allows append text to the file instead of overwriting it." (ensure-initialization) (with-possible-redirection filename append (foreign-funcall "rl_list_funmap_names" :void))) (defun funmap-names () "Return a list of known function names. The list is sorted." (ensure-initialization) (let ((ptr (foreign-funcall "rl_funmap_names" :pointer))) (unless (null-pointer-p ptr) (unwind-protect (to-list-of-strings ptr) (foreign-funcall "free" :pointer ptr :void))))) (defun add-funmap-entry (name function) "Add NAME to the list of bindable Readline command names, and make FUNCTION the function to be called when name is invoked." (foreign-funcall "rl_add_funmap_entry" :string name :pointer (produce-callback function :boolean (:int int-char)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Allowing Undoing ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro undo-group (&body body) "All insertion and deletion inside this macro will be grouped together into one undo operation." `(unwind-protect (progn (foreign-funcall "rl_begin_undo_group" :boolean) ,@body) (foreign-funcall "rl_end_undo_group" :boolean))) (defcfun ("rl_add_undo" add-undo) :void "Remember how to undo an event (according to WHAT). The affected text runs from START to END, and encompasses TEXT. Possible values of WHAT include: :UNDO-DELETE, :UNDO-INSERT, :UNDO-BEGIN, and :UNDO-END." (what undo-code) (start :int) (end :int) (text :string)) (defcfun ("rl_free_undo_list" free-undo-list) :void "Free the existing undo list.") (defcfun ("rl_do_undo" do-undo) :boolean "Undo the first thing on the undo list. Returns NIL if there was nothing to undo, T if something was undone.") (defcfun ("rl_modifying" modifying) :boolean "Tell Readline to save the text between START and END as a single undo unit. It is assumed that you will subsequently modify that text." (start :int) (end :int)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Redisplay ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defcfun ("rl_redisplay" redisplay) :void "Change what's displayed on the screen to reflect the current contents of `*line-buffer*'.") (defcfun ("rl_forced_update_display" forced-update-display) :boolean "Force the line to be updated and redisplayed, whether or not Readline thinks the screen display is correct.") (defun on-new-line (&optional with-prompt) "Tell the update functions that we have moved onto a new (empty) line, usually after outputting a newline. When WITH-PROMPT is not NIL, Readline will think that prompt is already displayed. This could be used by applications that want to output the prompt string themselves, but still need Readline to know the prompt string length for redisplay. This should be used together with :ALREADY-PROMPTED keyword argument of `readline'." (if with-prompt (foreign-funcall "rl_on_new_line_with_prompt" :boolean) (foreign-funcall "rl_on_new_line" :boolean))) (defcfun ("rl_reset_line_state" reset-line-state) :boolean "Reset the display state to a clean state and redisplay the current line starting on a new line.") (defcfun ("rl_crlf" crlf) :boolean "Move the cursor to the start of the next screen line.") (defcfun ("rl_show_char" show-char) :boolean "Display character CHAR on outstream. If Readline has not been set to display meta characters directly, this will convert meta characters to a meta-prefixed key sequence. This is intended for use by applications which wish to do their own redisplay." (char int-char)) (defmacro with-message (message save-prompt &body body) "Show message MESSAGE in the echo area while executing BODY. If SAVE-PROMPT is not NIL, save prompt before showing the message and restore it before clearing the message." `(unwind-protect (progn (when ,save-prompt (foreign-funcall "rl_save_prompt" :void)) (foreign-funcall "rl_message" :string ,message :boolean) ,@body) (when ,save-prompt (foreign-funcall "rl_restore_prompt" :void)) (foreign-funcall "rl_clear_message" :boolean))) (defcfun ("rl_set_prompt" set-prompt) :boolean "Make Readline use PROMPT for subsequent redisplay. This calls `expand-prompt' to expand the prompt and sets `+prompt+' to the result." (prompt :string)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Modifying Text ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defcfun ("rl_insert_text" insert-text) :int "Insert TEXT into the line at the current cursor position. Return the number of characters inserted." (text :string)) (defcfun ("rl_delete_text" delete-text) :int "Delete the text between START and END in the current line. Return the number of characters deleted." (start :int) (end :int)) (defcfun ("rl_kill_text" kill-text) :boolean "Copy the text between START and END in the current line to the kill ring, appending or prepending to the last kill if the last command was a kill command. The text is deleted. If START is less than END, the text is appended, otherwise prepended. If the last command was not a kill, a new kill ring slot is used." (start :int) (end :int)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Character Input ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defcfun ("rl_read_key" read-key) int-char "Return the next character available from Readline's current input stream.") (defcfun ("rl_stuff_char" stuff-char) :boolean "Insert CHAR into the Readline input stream. It will be «read» before Readline attempts to read characters from the terminal with `read-key'. Up to 512 characters may be pushed back. `stuff-char' returns T if the character was successfully inserted; NIL otherwise." (char int-char)) (defcfun ("rl_execute_next" execute-next) :boolean "Make CHAR be the next command to be executed when `read-key' is called." (char int-char)) (defcfun ("rl_clear_pending_input" clear-pending-input) :boolean "Negate the effect of any previous call to `execute-next'. This works only if the pending input has not already been read with `read-key'.") (defcfun ("rl_set_keyboard_input_timeout" set-keyboard-input-timeout) :int "While waiting for keyboard input in `read-key', Readline will wait for U microseconds for input before calling any function assigned to `event-hook'. U must be greater than or equal to zero (a zero-length timeout is equivalent to a poll). The default waiting period is one-tenth of a second. Return the old timeout value." (u :int)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Moving the cursor ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Wrappers around readline bindable *commands* ;; (and not external C functions). ;; Any command that is called interactively receives two arguments. ;; The first is a count: the numeric arg passed to this command. ;; The second is the key which invoked this command. ;; ;; @vindarel, 2023/10: ;; The Lisp wrappers do not use the second key argument: what is it used for? ;; It is probably not necessary when used programmatically, ;; but anyways it creates an issue. When binding a key to one of these commands: ;; (rl:bind-keyseq "\\C-o" #'rl:forward-word) ;; the "key" parameter given to our function is not an int, ;; but (probably) the representation of a (SIGNED-BYTE 32), ;; which creates a fatal error. We ignore the key argument (defun forward-byte (&optional (count 1) key) "Move forward COUNT bytes (1 by default)." (declare (ignore key)) (foreign-funcall "rl_forward_byte" :int count :int 0 :int)) (defun backward-byte (&optional (count 1) key) "Move backward COUNT bytes (1 by default)." (declare (ignore key)) (foreign-funcall "rl_backward_byte" :int count :int 0 :int)) (defun backward-char (&optional (count 1) key) "Move backward COUNT characters (1 by default). KEY is ignored." (declare (ignore key)) (foreign-funcall "rl_backward_char" :int count :int 0 :int)) (defun forward-char (&optional (count 1) key) "Move forward COUNT characters (1 by default)." (declare (ignore key)) (foreign-funcall "rl_forward_char" :int count :int 1 :int)) (defun beginning-of-line (&optional (count 1) key) "Move to the beginning of the line. " (declare (ignore key)) (foreign-funcall "rl_beg_of_line" :int count :int 0 :int)) (defun end-of-line (&optional (count 1) key) "Move to the end of the line. " (declare (ignore key)) (foreign-funcall "rl_end_of_line" :int count :int 0 :int)) (defun forward-word (&optional (count 1) key) "Move forward COUNT word(s). We do what Emacs does. Handles multibyte chars." (declare (ignore key)) (foreign-funcall "rl_forward_word" :int count :int 0 :int)) (defun backward-word (&optional (count 1) key) "Move backward COUNT word(s). We do what Emacs does. Handles multibyte chars." (declare (ignore key)) (foreign-funcall "rl_backward_word" :int count :int 0 :int)) (defun refresh-line (&optional (count 1) key) "Clear the current line. Numeric argument to C-l does this." (declare (ignore key)) (foreign-funcall "rl_refresh_line" :int count :int 0 :int)) (defun clear-screen (&optional (count 1) key) "C-l typed to a line without quoting clears the screen, and then reprints the prompt and the current input line. Given a numeric arg, redraw only the current line." (declare (ignore key)) (foreign-funcall "rl_clear_screen" :int count :int 0 :int)) (defun clear-display (&optional (count 1) key) "Clear the screen and update the display." (declare (ignore key)) (foreign-funcall "rl_clear_display" :int count :int 0 :int)) ;; and more: insert, quoted insert, delete or show completions, insert comment… ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Terminal Management ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defcfun ("rl_prep_terminal" prep-terminal) :void "Modify the terminal settings for Readline's use, so `readline' can read a single character at a time from the keyboard. The EIGHT-BIT-INPUT argument should be non-NIL if Readline should read eight-bit input." (eight-bit-input :boolean)) (defcfun ("rl_deprep_terminal" deprep-terminal) :void "Undo the effects of `prep-terminal', leaving the terminal in the state in which it was before the most recent call to `prep-terminal'.") (defun tty-set-default-bindings (keymap) "Read the operating system's terminal editing characters (as would be displayed by stty) to their Readline equivalents. The bindings are performed in KEYMAP." (ensure-initialization) (foreign-funcall "rl_tty_set_default_bindings" :pointer keymap :void)) (defcfun ("rl_tty_unset_default_bindings" tty-unset-default-bindings) :void "Reset the bindings manipulated by `tty-set-default-bindings' so that the terminal editing characters are bound to `insert'. The bindings are performed in KEYMAP." (keymap :pointer)) (defcfun ("rl_reset_terminal" reset-terminal) :boolean "Reinitialize Readline's idea of the terminal settings using TERMINAL as the terminal type (e.g., vt100)." (terminal :string)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Utility Functions ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defcfun ("rl_replace_line" replace-line) :void "Replace the contents of `*line-buffer*' with TEXT. The point and mark are preserved, if possible. If CLEAR-UNDO is non-NIL, the undo list associated with the current line is cleared." (text :string) (clear-undo :boolean)) (defcfun ("rl_extend_line_buffer" extend-line-buffer) :void "Ensure that line buffer has enough space to hold LEN characters, possibly reallocating it if necessary." (len :int)) (defcfun ("rl_initialize" initialize) :boolean "Initialize or re-initialize Readline's internal state. It's not strictly necessary to call this; `readline' calls it before reading any input.") (defcfun ("rl_ding" ding) :boolean "Ring the terminal bell, obeying the setting of bell-style.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Miscellaneous Functions ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun macro-dumper (readable &optional filename append) "Print the key sequences bound to macros and their values, using the current keymap to stdout. If READABLE is non-NIL, the list is formatted in such a way that it can be made part of an inputrc file and re-read. If FILENAME is supplied and it's a string or path, output will be redirected to the file. APPEND allows to append text to the file instead of overwriting it." (ensure-initialization) (with-possible-redirection filename append (foreign-funcall "rl_macro_dumper" :boolean readable :void))) (defun variable-bind (variable value) "Make the Readline variable VARIABLE have VALUE. This behaves as if the readline command 'set variable value' had been executed in an inputrc file." (ensure-initialization) (foreign-funcall "rl_variable_bind" :string variable :string value :boolean)) (defun variable-value (variable) "Return a string representing the value of the Readline variable VARIABLE. For Boolean variables, this string is either 'on' or 'off'." (ensure-initialization) (foreign-funcall "rl_variable_value" :string variable :string)) (defun variable-dumper (readable &optional filename append) "Print the readline variable names and their current values to stdout. If readable is not NIL, the list is formatted in such a way that it can be made part of an inputrc file and re-read. If FILENAME is supplied and it's a string or path, output will be redirected to the file. APPEND allows to append text to the file instead of overwriting it." (ensure-initialization) (with-possible-redirection filename append (foreign-funcall "rl_variable_dumper" :boolean readable :void))) (defcvar ("rl_blink_matching_paren" *blink-matching-paren*) :boolean "If this variable is non-NIL, matching parenthesis (if its key is bound to rl_insert_close) will blink whenever the closing parenthesis is inserted.") (defcfun ("rl_set_paren_blink_timeout" set-paren-blink-timeout) :int "Set the time interval (in microseconds) that Readline waits when showing a balancing character when 'blink-matching-paren' has been enabled. The function returns previous value of the parameter." (micros :int)) (defcfun ("rl_clear_history" clear-history) :void "Clear the history list by deleting all of the entries.") (defcfun ("read_history" read-history) :int "Add the contents of filename to the history list, a line at a time." (filename :string)) (defcfun ("write_history" write-history) :int "Write the current history to filename, overwriting filename if necessary." (filename :string)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; Signal Handling ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defcfun ("rl_cleanup_after_signal" cleanup-after-signal) :void "This function will reset the state of the terminal to what it was before `readline' was called, and remove the Readline signal handlers for all signals, depending on the values of `*catch-signals*' and `*catch-sigwinch*'.") (defcfun ("rl_free_line_state" free-line-state) :void "This will free any partial state associated with the current input line (undo information, any partial history entry, any partially-entered keyboard macro, and any partially-entered numeric argument). This should be called before `cleanup-after-signal.' The Readline signal handler for SIGINT calls this to abort the current input line.") (defcfun ("rl_reset_after_signal" reset-after-signal) :void "This will reinitialize the terminal and reinstall any Readline signal handlers, depending on the values of `*catch-signals*' and `*catch-sigwinch*'.") (defcfun ("rl_echo_signal_char" echo-signal-char) :void "If an application wishes to install its own signal handlers, but still have readline display characters that generate signals, calling this function with SIG set to :SIGINT, :SIGQUIT, or :SIGTSTP will display the character generating that signal." (sig unix-signal)) (defun resize-terminal () "Update Readline's internal screen size by reading values from the kernel." (ensure-initialization) (foreign-funcall "rl_resize_terminal" :void)) (defcfun ("rl_set_screen_size" set-screen-size) :void "Set Readline's idea of the terminal size to ROWS rows and COLS columns. If either rows or columns is less than or equal to 0, Readline's idea of that terminal dimension is unchanged." (rows :int) (cols :int)) (defun get-screen-size () "Return Readline's idea of the terminal's size. The function returns multiple values: number of rows and columns." (ensure-initialization) (with-foreign-objects ((rows :int) (cols :int)) (foreign-funcall "rl_get_screen_size" :pointer rows :pointer cols :void) (values (mem-ref rows :int) (mem-ref cols :int)))) (defcfun ("rl_reset_screen_size" reset-screen-size) :void "Cause Readline to reobtain the screen size and recalculate its dimensions.") (defcfun ("rl_set_signals" set-signals) :boolean "Install Readline's signal handler for SIGINT, SIGQUIT, SIGTERM, SIGHUP, SIGALRM, SIGTSTP, SIGTTIN, SIGTTOU, and SIGWINCH, depending on the values of `*catch-signals*' and `*catch-sigwinch*'.") (defcfun ("rl_clear_signals" clear-signals) :boolean "Remove all of the Readline signal handlers installed by `set-signals'.")
55,630
Common Lisp
.lisp
1,072
45.676306
114
0.626567
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
bd92cd0038915d435e9f6d98831ecf6c37e1ea3448c6cd0cf5fffae6d1951044
4,439
[ -1 ]
4,440
utils.lisp
vindarel_cl-readline/utils.lisp
;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*- ;;; ;;; Utilities for cl-readline, bindings to GNU Readline library. ;;; ;;; Copyright © 2015–2018 Mark Karpov ;;; ;;; cl-readline is free software: you can redistribute it and/or modify it ;;; under the terms of the GNU General Public License as published by the ;;; Free Software Foundation, either version 3 of the License, or (at your ;;; option) any later version. ;;; ;;; cl-readline is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General ;;; Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License along ;;; with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :cl-readline) (defvar +states+ '(:initializing ; 0x0000001 initializing :initialized ; 0x0000002 initialization done :termprepped ; 0x0000004 terminal is prepped :readcmd ; 0x0000008 reading a command key :metanext ; 0x0000010 reading input after ESC :dispatching ; 0x0000020 dispatching to a command :moreinput ; 0x0000040 reading more input in a command function :isearch ; 0x0000080 doing incremental search :nsearch ; 0x0000100 doing non-incremental search :search ; 0x0000200 doing a history search :numericarg ; 0x0000400 reading numeric argument :macroinput ; 0x0000800 getting input from a macro :macrodef ; 0x0001000 defining keyboard macro :overwrite ; 0x0002000 overwrite mode :completing ; 0x0004000 doing completion :sighandler ; 0x0008000 in readline sighandler :undoing ; 0x0010000 doing an undo :inputpending ; 0x0020000 rl_execute_next called :ttycsaved ; 0x0040000 tty special chars saved :callback ; 0x0080000 using the callback interface :vimotion ; 0x0100000 reading vi motion arg :multikey ; 0x0200000 reading multiple-key command :vicmdonce ; 0x0400000 entered vi command mode at least once :redisplaying ; 0x0800000 updating terminal display :done) ; 0x1000000 done; accepted line "Possible state values for `+readline-state+'.") (defvar +c-buffer-size+ 256 "How many bytes to allocate per Lisp string when converting list of Lisp strings into array of C strings.") (defun decode-version (version) "Transform VERSION into two values representing major and minor numbers of Readline library version." (values (ldb (byte 8 8) version) (ldb (byte 8 0) version))) (defun decode-state (state) "Transform Readline state STATE into list of keywords. See `+states+' for list of components that can appear in result list." (mapcan (lambda (index keyword) (when (logbitp index state) (list keyword))) (iota (length +states+)) +states+)) (defmacro produce-callback (function return-type &optional func-arg-list) "Return pointer to callback that calls FUNCTION. RETURN-TYPE specifies return type of the function and FUNC-ARG-LIST is list of argument types (it can be ommited if FUNCTION doesn't take any arguments)." (let ((gensymed-list (mapcar (lambda (x) (list (gensym) x)) func-arg-list))) (with-gensyms (temp) `(if ,function (progn (defcallback ,temp ,return-type ,gensymed-list (funcall ,function ,@(mapcar #'car gensymed-list))) (get-callback ',temp)) (null-pointer))))) (defun produce-callback* (function return-type &optional func-arg-list) "Variant of PRODUCE-CALLBACK that should hopefully be more portable. This avoids using a GENSYM as the name of a callback, and is also funcallable." (let ((gensymed-list (mapcar (lambda (x) (list (gensym) x)) func-arg-list))) (with-gensyms (temp) (if function (progn (eval `(defcallback ,temp ,return-type ,gensymed-list (funcall ,function ,@(mapcar #'car gensymed-list)))) (get-callback temp)) (null-pointer))))) (defun to-list-of-strings (pointer) "Convert a null-terminated array of pointers to chars that POINTER points to into list of Lisp strings." (unless (null-pointer-p pointer) (let (result) (do ((i 0 (1+ i))) ((null-pointer-p (mem-aref pointer :pointer i)) (reverse result)) (push (foreign-string-to-lisp (mem-aref pointer :pointer i)) result))))) (defun to-array-of-strings (list) "Convert a list of Lisp strings LIST into null-terminated array of C strings. Memory for every string and the array itself should be freed with `free' (C function). If LIST is NIL, null pointer will be returned." (if list (let* ((len (length list)) (ptr (foreign-funcall "malloc" :unsigned-int (* (1+ len) (foreign-type-size :pointer)) :pointer))) (setf (mem-aref ptr :pointer len) (null-pointer)) (do ((i 0 (1+ i)) (lst list (cdr lst))) ((null lst) ptr) (let* ((string (car lst)) (buffer (foreign-funcall "malloc" :unsigned-int (* +c-buffer-size+ (foreign-type-size :char)) :pointer))) (setf (mem-aref ptr :pointer i) (lisp-string-to-foreign string buffer +c-buffer-size+))))) (null-pointer)))
5,767
Common Lisp
.lisp
122
38.827869
79
0.635008
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
d4108ed4a27d6477aefa98babae124ed20b4f57e289bd84a6e50069db16a5eda
4,440
[ -1 ]
4,441
ctypes.lisp
vindarel_cl-readline/ctypes.lisp
;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*- ;;; ;;; Definitions of some C types for cl-readline, bindings to GNU Readline. ;;; ;;; Copyright © 2015–2018 Mark Karpov ;;; ;;; cl-readline is free software: you can redistribute it and/or modify it ;;; under the terms of the GNU General Public License as published by the ;;; Free Software Foundation, either version 3 of the License, or (at your ;;; option) any later version. ;;; ;;; cl-readine is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General ;;; Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License along ;;; with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :cl-readline) (defctype int-char (:wrapper :int :from-c code-char :to-c char-code) "Wrapper for conversion between C int and Lisp character.") (defctype version (:wrapper :int :from-c decode-version) "Wrapper for conversion between raw C int representing version of Readline library and Lisp values.") (defctype state (:wrapper :int :from-c decode-state) "Wrapper for conversion between raw C int representing state of Readline and list of keywords.") (defcenum editing-mode "Enumeration of all possible editing modes in Readline." :vi :emacs) (defcstruct history-entry "C structure that represents a history entry in Readline." (line :pointer) (time :pointer) (data :pointer)) (defcenum undo-code "This enumeration contains codes for various types of undo operations." :undo-delete :undo-insert :undo-begin :undo-end) (defcenum unix-signal "Enumeration of some Unix signals for use with some Readline functions, see section «Signal Handling»." (:sighup 1) (:sigint 2) (:sigquit 3) (:sigalrm 14) (:sigterm 15) (:sigtstp 20) (:sigttin 26) (:sigttou 27)) (defcenum completion-type "Types of completion performed by Readline. See description of `+completion-type+' for more information." (:standard-completion 9) (:display-and-perform 33) (:insert-all 42) (:list-all 63) (:not-list-cmn-prefix 64))
2,300
Common Lisp
.lisp
68
30.735294
76
0.71596
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
f526a887ea511fac5ad4793779378ddd8643ff1b5356651ea8b1ef71289b6a00
4,441
[ -1 ]
4,442
highlight-lisp.js
vindarel_cl-readline/doc/js/highlight-lisp.js
/** * Common Lisp syntax highlighter * * @version 0.1.1 * @author Andrew "Danger" Lyon * @copyright Lyon Bros. Enterprises, LLC * @licence MIT */ var highlight_lisp = function() { // all of the following functions were pulled straight from my syntax/lisp.vim // file in my vim directory. var funcs = '\\* find-method pprint-indent find-package pprint-linear find-restart ' + 'pprint-logical-block \\+ find-symbol pprint-newline finish-output ' + 'pprint-pop first pprint-tab - fixnum pprint-tabular / flet prin1 // float ' + 'prin1-to-string /// float-digits princ /= float-precision princ-to-string 1\\+ ' + 'float-radix print 1- float-sign print-not-readable < floating-point-inexact ' + 'print-not-readable-object <= floating-point-invalid-operation print-object = ' + 'floating-point-overflow print-unreadable-object > floating-point-underflow ' + 'probe-file >= floatp proclaim abort floor prog abs fmakunbound prog\\* access ' + 'force-output prog1 acons format prog2 acos formatter progn acosh fourth ' + 'program-error add-method fresh-line progv adjoin fround provide adjust-array ' + 'ftruncate psetf adjustable-array-p ftype psetq allocate-instance funcall push ' + 'alpha-char-p function pushnew alphanumericp function-keywords putprop and ' + 'function-lambda-expression quote append functionp random apply gbitp ' + 'random-state applyhook gcd random-state-p apropos generic-function rassoc ' + 'apropos-list gensym rassoc-if aref gentemp rassoc-if-not arithmetic-error get ' + 'ratio arithmetic-error-operands get-decoded-time rational ' + 'arithmetic-error-operation get-dispatch-macro-character rationalize array ' + 'get-internal-real-time rationalp array-dimension get-internal-run-time read ' + 'array-dimension-limit get-macro-character read-byte array-dimensions ' + 'get-output-stream-string read-char array-displacement get-properties ' + 'read-char-no-hang array-element-type get-setf-expansion read-delimited-list ' + 'array-has-fill-pointer-p get-setf-method read-eval-print array-in-bounds-p ' + 'get-universal-time read-from-string array-rank getf read-line array-rank-limit ' + 'gethash read-preserving-whitespace array-row-major-index go read-sequence ' + 'array-total-size graphic-char-p reader-error array-total-size-limit handler-bind ' + 'readtable arrayp handler-case readtable-case ash hash-table readtablep asin ' + 'hash-table-count real asinh hash-table-p realp assert hash-table-rehash-size ' + 'realpart assoc hash-table-rehash-threshold reduce assoc-if hash-table-size ' + 'reinitialize-instance assoc-if-not hash-table-test rem atan host-namestring ' + 'remf atanh identity remhash atom if remove base-char if-exists ' + 'remove-duplicates base-string ignorable remove-if bignum ignore remove-if-not ' + 'bit ignore-errors remove-method bit-and imagpart remprop bit-andc1 import ' + 'rename-file bit-andc2 in-package rename-package bit-eqv in-package replace ' + 'bit-ior incf require bit-nand initialize-instance rest bit-nor inline restart ' + 'bit-not input-stream-p restart-bind bit-orc1 inspect restart-case bit-orc2 ' + 'int-char restart-name bit-vector integer return bit-vector-p ' + 'integer-decode-float return-from bit-xor integer-length revappend block ' + 'integerp reverse boole interactive-stream-p room boole-1 intern rotatef ' + 'boole-2 round boole-and intersection ' + 'row-major-aref boole-andc1 invalid-method-error rplaca boole-andc2 ' + 'invoke-debugger rplacd boole-c1 invoke-restart safety boole-c2 ' + 'invoke-restart-interactively satisfies boole-clr isqrt sbit boole-eqv keyword ' + 'scale-float boole-ior keywordp schar boole-nand labels search boole-nor ' + 'second boole-orc1 lambda-list-keywords sequence boole-orc2 ' + 'lambda-parameters-limit serious-condition boole-set last set boole-xor lcm ' + 'set-char-bit boolean ldb set-difference both-case-p ldb-test ' + 'set-dispatch-macro-character boundp ldiff set-exclusive-or break ' + 'least-negative-double-float set-macro-character broadcast-stream ' + 'least-negative-long-float set-pprint-dispatch broadcast-stream-streams ' + 'least-negative-normalized-double-float set-syntax-from-char built-in-class ' + 'least-negative-normalized-long-float setf butlast ' + 'least-negative-normalized-short-float setq byte ' + 'least-negative-normalized-single-float seventh byte-position ' + 'least-negative-short-float shadow byte-size least-negative-single-float ' + 'shadowing-import call-arguments-limit least-positive-double-float ' + 'shared-initialize call-method least-positive-long-float shiftf ' + 'call-next-method least-positive-normalized-double-float short-float capitalize ' + 'least-positive-normalized-long-float short-float-epsilon car ' + 'least-positive-normalized-short-float short-float-negative-epsilon case ' + 'least-positive-normalized-single-float short-site-name catch ' + 'least-positive-short-float signal ccase least-positive-single-float ' + 'signed-byte cdr length signum ceiling simple-condition cell-error ' + 'simple-array cell-error-name lisp simple-base-string cerror ' + 'lisp-implementation-type simple-bit-vector change-class ' + 'lisp-implementation-version simple-bit-vector-p char list ' + 'simple-condition-format-arguments char-bit list\\* ' + 'simple-condition-format-control char-bits list-all-packages simple-error ' + 'char-bits-limit list-length simple-string char-code listen simple-string-p ' + 'char-code-limit listp simple-type-error char-control-bit load simple-vector ' + 'char-downcase load-logical-pathname-translations simple-vector-p char-equal ' + 'load-time-value simple-warning char-font locally sin char-font-limit log ' + 'single-flaot-epsilon char-greaterp logand single-float char-hyper-bit logandc1 ' + 'single-float-epsilon char-int logandc2 single-float-negative-epsilon ' + 'char-lessp logbitp sinh char-meta-bit logcount sixth char-name logeqv sleep ' + 'char-not-equal logical-pathname slot-boundp char-not-greaterp ' + 'logical-pathname-translations slot-exists-p char-not-lessp logior ' + 'slot-makunbound char-super-bit lognand slot-missing char-upcase lognor ' + 'slot-unbound char/= lognot slot-value char< logorc1 software-type char<= ' + 'logorc2 software-version char= logtest some char> logxor sort char>= ' + 'long-float space character long-float-epsilon special characterp ' + 'long-float-negative-epsilon special-form-p check-type long-site-name ' + 'special-operator-p cis loop speed class loop-finish sqrt class-name ' + 'lower-case-p stable-sort class-of machine-instance standard clear-input ' + 'machine-type standard-char clear-output machine-version standard-char-p close ' + 'macro-function standard-class clrhash macroexpand standard-generic-function ' + 'code-char macroexpand-1 standard-method coerce macroexpand-l standard-object ' + 'commonp macrolet step compilation-speed make-array storage-condition compile ' + 'make-array store-value compile-file make-broadcast-stream stream ' + 'compile-file-pathname make-char stream-element-type compiled-function ' + 'make-concatenated-stream stream-error compiled-function-p make-condition ' + 'stream-error-stream compiler-let make-dispatch-macro-character ' + 'stream-external-format compiler-macro make-echo-stream streamp ' + 'compiler-macro-function make-hash-table streamup complement make-instance ' + 'string complex make-instances-obsolete string-capitalize complexp make-list ' + 'string-char compute-applicable-methods make-load-form string-char-p ' + 'compute-restarts make-load-form-saving-slots string-downcase concatenate ' + 'make-method string-equal concatenated-stream make-package string-greaterp ' + 'concatenated-stream-streams make-pathname string-left-trim cond ' + 'make-random-state string-lessp condition make-sequence string-not-equal ' + 'conjugate make-string string-not-greaterp cons make-string-input-stream ' + 'string-not-lessp consp make-string-output-stream string-right-strim constantly ' + 'make-symbol string-right-trim constantp make-synonym-stream string-stream ' + 'continue make-two-way-stream string-trim control-error makunbound ' + 'string-upcase copy-alist map string/= copy-list map-into string< ' + 'copy-pprint-dispatch mapc string<= copy-readtable mapcan string= copy-seq ' + 'mapcar string> copy-structure mapcon string>= copy-symbol maphash stringp ' + 'copy-tree mapl structure cos maplist structure-class cosh mask-field ' + 'structure-object count max style-warning count-if member sublim count-if-not ' + 'member-if sublis ctypecase member-if-not subseq debug merge subsetp decf ' + 'merge-pathname subst declaim merge-pathnames subst-if declaration method ' + 'subst-if-not declare method-combination substitute decode-float ' + 'method-combination-error substitute-if decode-universal-time method-qualifiers ' + 'substitute-if-not defclass min subtypep defconstant minusp svref defgeneric ' + 'mismatch sxhash define-compiler-macro mod symbol define-condition ' + 'most-negative-double-float symbol-function define-method-combination ' + 'most-negative-fixnum symbol-macrolet define-modify-macro ' + 'most-negative-long-float symbol-name define-setf-expander ' + 'most-negative-short-float symbol-package define-setf-method ' + 'most-negative-single-float symbol-plist define-symbol-macro ' + 'most-positive-double-float symbol-value defmacro most-positive-fixnum symbolp ' + 'defmethod most-positive-long-float synonym-stream defpackage ' + 'most-positive-short-float synonym-stream-symbol defparameter ' + 'most-positive-single-float sys defsetf muffle-warning system defstruct ' + 'multiple-value-bind deftype multiple-value-call tagbody defun ' + 'multiple-value-list tailp defvar multiple-value-prog1 tan delete ' + 'multiple-value-seteq tanh delete-duplicates multiple-value-setq tenth ' + 'delete-file multiple-values-limit terpri delete-if name-char the delete-if-not ' + 'namestring third delete-package nbutlast throw denominator nconc time ' + 'deposit-field next-method-p trace describe translate-logical-pathname ' + 'describe-object nintersection translate-pathname destructuring-bind ninth ' + 'tree-equal digit-char no-applicable-method truename digit-char-p ' + 'no-next-method truncase directory not truncate directory-namestring notany ' + 'two-way-stream disassemble notevery two-way-stream-input-stream ' + 'division-by-zero notinline two-way-stream-output-stream do nreconc type do\\* ' + 'nreverse type-error do-all-symbols nset-difference type-error-datum ' + 'do-exeternal-symbols nset-exclusive-or type-error-expected-type ' + 'do-external-symbols nstring type-of do-symbols nstring-capitalize typecase ' + 'documentation nstring-downcase typep dolist nstring-upcase unbound-slot ' + 'dotimes nsublis unbound-slot-instance double-float nsubst unbound-variable ' + 'double-float-epsilon nsubst-if undefined-function ' + 'double-float-negative-epsilon nsubst-if-not unexport dpb nsubstitute unintern ' + 'dribble nsubstitute-if union dynamic-extent nsubstitute-if-not unless ecase ' + 'nth unread echo-stream nth-value unread-char echo-stream-input-stream nthcdr ' + 'unsigned-byte echo-stream-output-stream null untrace ed number unuse-package ' + 'eighth numberp unwind-protect elt numerator ' + 'update-instance-for-different-class encode-universal-time nunion ' + 'update-instance-for-redefined-class end-of-file oddp ' + 'upgraded-array-element-type endp open upgraded-complex-part-type ' + 'enough-namestring open-stream-p upper-case-p ensure-directories-exist optimize ' + 'use-package ensure-generic-function or use-value eq otherwise user eql ' + 'output-stream-p user-homedir-pathname equal package values equalp ' + 'package-error values-list error package-error-package vector etypecase ' + 'package-name vector-pop eval package-nicknames vector-push eval-when ' + 'package-shadowing-symbols vector-push-extend evalhook package-use-list vectorp ' + 'evenp package-used-by-list warn every packagep warning exp pairlis when export ' + 'parse-error wild-pathname-p expt parse-integer with-accessors extended-char ' + 'parse-namestring with-compilation-unit fboundp pathname ' + 'with-condition-restarts fceiling pathname-device with-hash-table-iterator ' + 'fdefinition pathname-directory with-input-from-string ffloor pathname-host ' + 'with-open-file fifth pathname-match-p with-open-stream file-author ' + 'pathname-name with-output-to-string file-error pathname-type ' + 'with-package-iterator file-error-pathname pathname-version with-simple-restart ' + 'file-length pathnamep with-slots file-namestring peek-char ' + 'with-standard-io-syntax file-position phase write file-stream write-byte ' + 'file-string-length plusp write-char file-write-date pop write-line fill ' + 'position write-sequence fill-pointer position-if write-string find ' + 'position-if-not write-to-string find-all-symbols pprint y-or-n-p find-class ' + 'pprint-dispatch yes-or-no-p find-if pprint-exit-if-list-exhausted zerop ' + 'find-if-not pprint-fill'; // common lisp global variables. also from lisp.vim var standard_vars = '\\*applyhook\\* \\*load-pathname\\* \\*print-pprint-dispatch\\* \\*break-on-signals\\* ' + '\\*load-print\\* \\*print-pprint-dispatch\\* \\*break-on-signals\\* \\*load-truename\\* ' + '\\*print-pretty\\* \\*break-on-warnings\\* \\*load-verbose\\* \\*print-radix\\* ' + '\\*compile-file-pathname\\* \\*macroexpand-hook\\* \\*print-readably\\* ' + '\\*compile-file-pathname\\* \\*modules\\* \\*print-right-margin\\* \\*compile-file-truename\\* ' + '\\*package\\* \\*print-right-margin\\* \\*compile-file-truename\\* \\*print-array\\* ' + '\\*query-io\\* \\*compile-print\\* \\*print-base\\* \\*random-state\\* \\*compile-verbose\\* ' + '\\*print-case\\* \\*read-base\\* \\*compile-verbose\\* \\*print-circle\\* ' + '\\*read-default-float-format\\* \\*debug-io\\* \\*print-escape\\* \\*read-eval\\* ' + '\\*debugger-hook\\* \\*print-gensym\\* \\*read-suppress\\* \\*default-pathname-defaults\\* ' + '\\*print-length\\* \\*readtable\\* \\*error-output\\* \\*print-level\\* \\*standard-input\\* ' + '\\*evalhook\\* \\*print-lines\\* \\*standard-output\\* \\*features\\* \\*print-miser-width\\* ' + '\\*terminal-io\\* \\*gensym-counter\\* \\*print-miser-width\\* \\*trace-output\\* ' + 'pi internal-time-units-per-second'; // common lisp known keywords var keywords = ':abort :from-end :overwrite :adjustable :gensym :predicate :append :host ' + ':preserve-whitespace :array :if-does-not-exist :pretty :base :if-exists :print ' + ':case :include :print-function :circle :index :probe :conc-name :inherited ' + ':radix :constructor :initial-contents :read-only :copier :initial-element ' + ':rehash-size :count :initial-offset :rehash-threshold :create :initial-value ' + ':rename :default :input :rename-and-delete :defaults :internal :size :device ' + ':io :start :direction :junk-allowed :start1 :directory :key :start2 ' + ':displaced-index-offset :length :stream :displaced-to :level :supersede ' + ':element-type :name :test :end :named :test-not :end1 :new-version :type :end2 ' + ':nicknames :use :error :output :verbose :escape :output-file :version ' + ':external :documentation :shadowing-import-from :modern :export ' + ':case-sensitive :case-inverted :shadow :import-from :intern :fill-pointer ' + ':upcase :downcase :preserve :invert :load-toplevel :compile-toplevel :execute ' + ':while :until :for :do :if :then :else :when :unless :in :across :finally ' + ':collect :nconc :maximize :minimize :sum :and :with :initially :append :into ' + ':count :end :repeat :always :never :thereis :from :to :upto :downto :below ' + ':above :by :on :being :each :the :hash-key :hash-keys :hash-value :hash-values ' + ':using :of-type :upfrom :downfrom :arguments :return-type :library :full ' + ':malloc-free :none :alloca :in :out :in-out :stdc-stdcall :stdc :c :language ' + ':built-in :typedef :external :fini :init-once :init-always'; var lambda = '&allow-other-keys &aux &body &environment &key &optional &rest &whole'; var special = 'let let\\* lambda'; /** * Given a list of items in a string: 'item1 item2 item2 ...' * * return a regex *string*: '(item1|item2|item2|...)' */ var list_to_regex = function(list) { var items = list.replace(/(^ | $)/gm, '').split(/ /g); return '('+items.join('|')+')'; }; var is_in_list = function(item, list) { var items = list.replace(/(^ | $)/gm, '').split(/ /g); for(var i = 0, n = items.length; i < n; i++) { if(items[i] == item) return true; } return false; }; /** * Collections of search and replaces to make. */ var replace = [ // --------------------------------------------------------------------- // strings (should !!ALWAYS!! be first, lest our <span> tags be destroyed...) // --------------------------------------------------------------------- {regex: /"([\s\S]*?)"/gm, replace: '<span class="string">"$1"</span>'}, // --------------------------------------------------------------------- // comments // --------------------------------------------------------------------- {regex: /(;.*)(\n|$)/gm, replace: '<span class="comment">$1</span>$2'}, // --------------------------------------------------------------------- // "special" (let/lambda) // --------------------------------------------------------------------- { regex: new RegExp('.'+list_to_regex(special)+'(?=[\\s()])', 'g'), replace: function(fullmatch, fnname) { if(fullmatch[0] == '(') { return '(<span class="function special known">' + fnname + '</span>'; } else { return fullmatch; } } }, // --------------------------------------------------------------------- // function matches // --------------------------------------------------------------------- // known functions { regex: new RegExp('.'+list_to_regex(funcs)+'(?=[\\s()])', 'g'), replace: function(fullmatch, fnname) { if(fullmatch[0] == '(') { return '(<span class="function known">' + fnname + '</span>'; } else { return fullmatch; } } }, // symbol functions (#'my-fn) { regex: /([\s()])(#'(\w[\w_-]*))(?=[\s()])/g, replace: function(fullmatch, delim1, symfun, sym) { var known = false; if(is_in_list(sym, funcs)) { known = true; } return delim1 +'<span class="function symbol'+ (known ? ' known' : '') +'">'+ symfun +'</span>'; } }, // --------------------------------------------------------------------- // lambda keywords // --------------------------------------------------------------------- {regex: new RegExp('([\\s()])'+list_to_regex(lambda)+'(?=[\\s()])', 'g'), replace: '$1<span class="lambda-list">$2</span>'}, // --------------------------------------------------------------------- // symbols/keywords/variables // --------------------------------------------------------------------- // generic symbols {regex: /([\s()])('\w[\w_-]*)(?=[\s()])/g, replace: '$1<span class="symbol">$2</span>'}, // known keywords { regex: new RegExp('([\\s()])'+list_to_regex(keywords)+'([\\s()])', 'g'), replace: function(fullmatch, whitespace, keyword, whitespace2) { return whitespace + '<span class="keyword known">'+ keyword +'</span>'+ whitespace2; } }, // generic keywords { regex: /([\s()])(:\w[\w_-]*)/g, replace: function(fullmatch, delim, keyword) { if(fullmatch[0].match(/[\s()]/gm)) { return delim + '<span class="keyword">'+ keyword +'</span>'; } return fullmatch; } }, // known variables { regex: new RegExp('([\\s()])'+list_to_regex(standard_vars)+'([\\s()])', 'g'), replace: function(fullmatch, whitespace, varname, whitespace2) { return whitespace + '<span class="variable known">'+ varname +'</span>'+ whitespace2; } }, // globals/constants {regex: /([\s()])(\*\w[\w_-]*\*)(?=[\s()])/g, replace: '$1<span class="variable global">$2</span>'}, {regex: /([\s()])(\+\w[\w_-]*\+)(?=[\s()])/g, replace: '$1<span class="variable constant">$2</span>'}, // --------------------------------------------------------------------- // numbers // --------------------------------------------------------------------- // binary {regex: /([\s()])(#b[01]+)(?=[\s()])/ig, replace: '$1<span class="number binary">$2</span>'}, // hex {regex: /([\s()])(#x[\da-f]+)(?=[\s()])/ig, replace: '$1<span class="number hex">$2</span>'}, // float {regex: /([\s()])([+-]?(?:\d+\.\d+|\d+\.|\.\d+))(?=[\s()])/g, replace: '$1<span class="number float">$2</span>'}, // ratio {regex: /([\s()])([+-]?\d+(?:\/\d+)?)(?=[\s()])/g, replace: '$1<span class="number ratio">$2</span>'}, // integers {regex: /([\s()])([+-]?\d+)(?=[\s()])/g, replace: '$1<span class="number integer">$2</span>'}, // --------------------------------------------------------------------- // misc parsers // --------------------------------------------------------------------- // t/nil {regex: /([\s()])(nil|t)(?=[\s()])/g, replace: '$1<span class="nil">$2</span>'}, // generic "maybe a function" forms. best second to last {regex: /\((\w[\w_:-]*)(?=[\s()])/g, replace: '(<span class="function">$1</span>'}, // ()'s (should most probably be last, unless there's a good reason) {regex: /([()])/g, replace: '<span class="list">$1</span>'} ]; /** * Main highlight function. */ this.highlight_element = function(code_el) { code_el.className += ' hl-highlighted'; var html = code_el.innerHTML; // can't have &...;'s running wild like a pack of animals... html = html.replace(/&amp;/g, '&'); html = html.replace(/&lt;/g, '<'); html = html.replace(/&gt;/g, '>'); // pad the HTML string (makes regexs much simpler) html = "\n" + html + "\n"; for(var i = 0, n = replace.length; i < n; i++) { var rep = replace[i]; html = html.replace(rep.regex, rep.replace); } // unpad HTML string html = html.replace(/(^\n|\n$)/g, ''); html = html.replace(/<(?!\/?span)/g, '&lt;'); // Re-encode stray &s to conform with XHTML //html = html.replace(/&/g, '&amp;'); code_el.innerHTML = html; }, /** * Automatically highlight all <code class="lisp"> blocks * * Takes an options arg, which can be used to specify the classname of the * <code> tags you wish to highlight. */ this.highlight_auto = function(options) { options || (options = {}); var classname = options.className ? options.className : 'lisp'; var codes = document.getElementsByTagName('code'); for(var i = 0, n = codes.length; i < n; i++) { var code = codes[i]; if(code.className.match(classname)) { this.highlight_element(code); } } }, /** * If called, enables paren matching (hovering over a paren will add the * "active" class to both the highlighted and the matching paren) */ this.paren_match = function(options) { options || (options = {}); if(!('querySelector' in document)) { console.error('HighlightLisp.paren_match: browser does not support querySelector/matches'); return; } var matches = function(element, selector) { if(!element) return; var domatch; var tests = ['matches', 'msMatchesSelector', 'mozMatchesSelector', 'webkitMatchesSelector']; for(var i = 0; i < tests.length; i++) { if(!(tests[i] in element)) continue; domatch = element[tests[i]]; break; } return domatch.call(element, selector); }; var is_paren = function(el) { return matches(el, 'code > .list, code span:not(.comment):not(.string) .list'); }; var find_match = function(paren) { // grab all non-commented/stringed parens var children = paren.parentElement.querySelectorAll('code > span.list, code span:not(.comment):not(.string) .list'); // turn them into a real array children = Array.prototype.slice.call(children); var is_opening = function(el) { return el.innerHTML == '('; }; // tracks when to start counting parens var count = false; // tests if this is an opening or closing paren var opening = is_opening(paren); // if this is a closing paren, reverse the children so we can search // backwards just by going forwards if(!opening) children.reverse(); for(var i = 0; i < children.length; i++) { var child = children[i]; var open = is_opening(child); // mark the first occurance of the paren, and start counting // from there if(child === paren) { count = 1; continue; } if(count === false) continue; if(opening == open) count++; else count--; if(count === 0) return child; } }; var toggle_class = function(element, classname) { if (element.classList) { element.classList.toggle(classname); } else { //for IE9 var classes = element.className.split(" "); var i = classes.indexOf(classname); if (i >= 0) { classes.splice(i, 1); } else { classes.push(classname); element.className = classes.join(" "); } } } var codes = document.getElementsByClassName('hl-highlighted'); for(var i = 0; i < codes.length; i++) { var code = codes[i]; var listener = function(add, e) { var hovered = e.target; if(!is_paren(hovered)) return; var match = find_match(hovered); toggle_class(hovered, 'active'); toggle_class(match, 'active'); }; code.addEventListener('mouseover', listener.bind(this, true)); code.addEventListener('mouseout', listener.bind(this, false)); } } }; var HighlightLisp = new highlight_lisp();
26,071
Common Lisp
.lisp
499
48.314629
126
0.657621
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
388261334d997e9aa07a8986cade816d9559d94b4a378d65c042c9582c14d6bc
4,442
[ -1 ]
4,443
cl-readline.asd
vindarel_cl-readline/cl-readline.asd
;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*- ;;; ;;; ASDF file for cl-readline, bindings to GNU Readline library. ;;; ;;; Copyright © 2015–2018 Mark Karpov ;;; ;;; cl-readline is free software: you can redistribute it and/or modify it ;;; under the terms of the GNU General Public License as published by the ;;; Free Software Foundation, either version 3 of the License, or (at your ;;; option) any later version. ;;; ;;; cl-readline is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General ;;; Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License along ;;; with this program. If not, see <http://www.gnu.org/licenses/>. (asdf:defsystem :cl-readline :version "0.1.1" :description "Common Lisp bindings to GNU Readline library" :author "Mark Karpov" :license "GNU GPL, version 3" :serial t :components ((:file "package") (:file "utils") (:file "ctypes") (:file "cl-readline")) :depends-on (:alexandria :cffi))
1,219
Common Lisp
.asd
30
36.766667
76
0.667511
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
166f83fccb4b56f89447de32543bedf42c2337cfeb700bbc45619e5e48ac4a1f
4,443
[ -1 ]
4,450
.travis.yml
vindarel_cl-readline/.travis.yml
language: lisp sudo: required env: matrix: - LISP=abcl - LISP=sbcl # - LISP=sbcl32 - LISP=ccl # - LISP=ccl32 - LISP=clisp # - LISP=clisp32 install: - if [ -x ./install.sh ] && head -2 ./install.sh | grep '^# cl-travis' > /dev/null; then ./install.sh; else curl https://raw.githubusercontent.com/luismbo/cl-travis/master/install.sh | sh; fi before_script: - echo "(defsystem :dummy-cl-travis-system)" > ~/lisp/dummy-cl-travis-system.asd script: - cl -e '(ql:quickload :alexandria) (ql:quickload :cffi) (asdf:load-system :cl-readline)' [ $? -eq 1 ] notifications: email: false
668
Common Lisp
.l
27
20.296296
86
0.621069
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
f4ab972202b8f5a27997b142ed1acb2d689052b1760235673c68f1c0aca3dc06
4,450
[ -1 ]
4,451
Makefile
vindarel_cl-readline/doc/Makefile
.PHONY: html clean # # Edit cl-readline.texi # run make html # or make html-local to have syntax highlighting locally # then update and commit index.html in the gh-pages branch (the one at the project root, not doc/index.html) # html: # --css-include manual.css # makeinfo --html --split=chapter cl-readline.texi makeinfo --html --no-split cl-readline.texi -o index.html sed -i "s@<head>@<head> <script type=\"text/javascript\" src=\"https://vindarel.github.io/cl-readline/doc/js/highlight-lisp.js\"></script> <link rel=\"stylesheet\" href=\"https://vindarel.github.io/cl-readline/doc/js/github.css\">@g" index.html sed -i "s@</pre>@</code></pre>@g" index.html sed -i "s@<pre class=\"lisp\">@<pre><code class=\"lisp\">@g" index.html sed -i "s@</body>@</body> <script> HighlightLisp.highlight_auto(); HighlightLisp.paren_match(); </script>@g" index.html # and update the gh-pages branch. html-local: html sed -i "s@https://vindarel.github.io/cl-readline/doc@@g" index.html clean: rm -f cl-readline/*
1,021
Common Lisp
.l
20
49
245
0.708124
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
6e6f383de7c442fcd6fcb2df102f0031350a5e7099a2a12f2be1375b006331ca
4,451
[ -1 ]
4,452
cl-readline.texi
vindarel_cl-readline/doc/cl-readline.texi
\input texinfo @c -*-texinfo-*- @comment %**start of header (This is for running Texinfo on a region.) @setfilename cl-readline.info @settitle cl-readline Library @set EDITION 0.1.1 @set VERSION 0.1.1 @set UPDATED 18 June 2015 @set UPDATED-MONTH June 2015 @set LASTCHANGE Sat Jun 18 21:03:13 EST 2015 @c How to edit this file: @c - best in Emacs @c - when adding or removing a section, update the menu on that file. See the Emacs Texinfo menu or call M-x texinfo-all-menus-update. @c - try the rendering with M-x makeinfo-buffer (C-c RET C-b) @c - run make html (which calls makeinfo --html) @comment %**end of header (This is for running Texinfo on a region.) @synindex vr fn @copying This manual describes the cl-readline Library (version @value{VERSION}, @value{UPDATED}), bindings to GNU Readline Library. This documentation is derived from original GNU Readline documentation by Brian Fox and Chet Ramey. Copyright @copyright{} 2015 Mark Karpov, Brian Fox, Chet Ramey @quotation Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. @end quotation @end copying @dircategory Libraries @direntry * cl-readline: (cl-readline). cl-readline library API. @end direntry @titlepage @title cl-readline Library @subtitle Edition @value{EDITION}, for @code{cl-readline Library} Version @value{VERSION}. @subtitle @value{UPDATED-MONTH} @author Mark Karpov, Brian Fox, Chet Ramey @page @vskip 0pt plus 1filll @insertcopying @end titlepage @contents @ifnottex @node Top @top cl-readline Library This document describes cl-readline library, bindings to GNU Readline library. This program is distributed under GNU General Public License, version 3. All symbols described in this document live in @code{cl-readline} package, it has the following nicknames: @code{rl}. @menu * Basic Functionality:: Most basic functions and symbol macros. * Hooks and Custom Functions:: How to change behavior of cl-readline. * Work with Keymaps:: Modify existing keymaps and create new ones. * Binding Keys:: How to change keymaps. * Associating Function Names and Bindings:: Translate function names to key sequences. * Allowing Undoing:: How to make your functions undoable. * Redisplay:: Functions to control line display. * Adding and modifying Text:: * Character Input:: Functions to read keyboard input. * Moving the cursor:: * Terminal Management:: Functions to manage terminal settings. * Utility Functions:: Generally useful functions. * Miscellaneous Functions:: Functions that don't fall into any category. * Signal Handling:: How Readline behaves when it receives signals. * Example:: A complete example of cl-readline use. * GNU Free Documentation License:: License for copying this manual. * Concept Index:: Index of concepts described in this manual. * Function and Variable Index:: Index of externally visible functions and variables. @end menu @end ifnottex @node Basic Functionality @chapter Basic Functionality This section describes most basic functions and symbol-macros that represent underlying C variables. For every symbol macro we give data type it evaluates to. If name of a symbol macro is enclosed in plus signs (for example, @var{+prompt+}), it means that you should not (and, in fact, cannot) modify its value. Other symbol macros are setfable and you can set their values with @code{setf} macro. @defvr {Symbol Macro} *line-buffer* String. This is the line gathered so far. You are welcome to modify the contents of the line, but remember about undoing (@pxref{Allowing Undoing}). The function @code{extend-line-buffer} is available to increase the memory allocated to @var{*line-buffer*}. @end defvr @defvr {Symbol Macro} *point* Integer. The offset of the current cursor position in @var{*line-buffer*} (the point). @end defvr @defvr {Symbol Macro} +end+ Integer. The number of characters present in @var{*line-buffer*}. When @var{*point*} is at the end of the line, @var{*point*} and @var{+end+} are equal. @end defvr @defvr {Symbol Macro} *mark* Integer. The mark (saved position) in the current line. If set, the mark and point define a region. @end defvr @defvr {Symbol Macro} *done* Boolean. Setting this to a non-@code{nil} value causes Readline to return the current line immediately. @end defvr @defvr {Symbol Macro} +prompt+ String. The prompt Readline uses. This is set from the argument to @code{readline}, and should not be assigned to directly. The @code{set-prompt} function may be used to modify the prompt string after calling @code{readline}. @end defvr @defvr {Symbol Macro} *display-prompt* String. The string displayed as the prompt. This is usually identical to @var{+prompt+}, but may be changed temporarily by functions that use the prompt string as a message area, such as incremental search. @end defvr @defvr {Symbol Macro} +library-version+ String. The version number of this revision of the library. @end defvr @defvr {Symbol Macro} +readline-version+ Two integer values. Major and minor version numbers of Readline library. @end defvr @defvr {Symbol Macro} +gnu-readline-p+ Boolean. Always evaluated to @code{t}, denoting that this is GNU readline rather than some emulation. @end defvr @defvr {Symbol Macro} *readline-name* String. This symbol-macro should be set to a unique name by each application using Readline. The value allows conditional parsing of the inputrc file. @end defvr @cindex readline state @defvr {Symbol Macro} +readline-state+ List of keywords. This symbol macro is evaluated to a list containing keywords that denote state of Readline. The following flags are used: @itemize @item @code{:initializing} -- initializing; @item @code{:initialized} -- initialization done; @item @code{:termprepped} -- terminal is prepped; @item @code{:readcmd} -- reading a command key; @item @code{:metanext} -- reading input after ESC; @item @code{:dispatching} -- dispatching to a command; @item @code{:moreinput} -- reading more input in a command function; @item @code{:isearch} -- doing incremental search; @item @code{:nsearch} -- doing non-incremental search; @item @code{:search} -- doing a history search; @item @code{:numericarg} -- reading numeric argument; @item @code{:macroinput} -- getting input from a macro; @item @code{:macrodef} -- defining keyboard macro; @item @code{:overwrite} -- overwrite mode; @item @code{:completing} -- doing completion; @item @code{:sighandler} -- in readline sighandler; @item @code{:undoing} -- doing a undo; @item @code{:inputpending} -- @code{execute-next} called; @item @code{:ttycsaved} -- tty special chars saved; @item @code{:callback} -- using the callback interface; @item @code{:vimotion} -- reading vi motion argument; @item @code{:multikey} -- reading multiple-key command; @item @code{:vicmdonce} -- entered vi command at least once; @item @code{:redisplaying} -- undating terminal display; @item @code{:done} -- done; accepted line. @end itemize @end defvr @defvr {Symbol macro} +editing-mode+ Keyword. Evaluated to keyword denoting actual editing mode: @code{:emacs} or @code{:vi}. @end defvr @cindex readline, function @defun readline @code{&key} prompt already-prompted num-chars erase-empty-line add-history novelty-check Get a line from user with editing. @var{prompt}, if supplied, is printed before reading of input. Non-@code{nil} value of @var{already-prompted} will tell Readline that the application has printed prompt already. However, @var{prompt} must be supplied in this case too, so redisplay functions can update the display properly. If @var{num-chars} argument is a positive number, Readline will return after accepting that many characters. If @var{erase-empty-line} is not @code{nil}, @code{readline} will completely erase the current line, including any prompt, any time a newline is typed as the only character on an otherwise-empty line. The cursor is moved to the beginning of the newly-blank line. Supplying @var{add-history} tells Readline that user's input should be added to history. However, blank lines don't get into history anyway. @var{novelty-check}, if given, must be a predicate that takes two strings: the actual line and the most recent history line. Only when the predicate evaluates to non-@code{nil} value new line will be added to the history. Return value on success is the actual string and @code{nil} on failure. @end defun @node Hooks and Custom Functions @chapter Hooks and Custom Functions cl-readline provides ways to register custom functions, so you can rewrite some parts of Readline library in Lisp. @defvr {Symbol macro} *basic-word-break-characters* String. The basic list of characters that signal a break between words for the completer routine. The default value of this variable is the characters which break words for completion in Bash. @end defvr @defvr {Symbol macro} *basic-quote-characters* String. A list of quote characters which can cause a word break. @end defvr @defvr {Symbol macro} *completer-word-break-characters* String. The list of characters that signal a break between words for @code{complete-internal}. The default list is the value of @var{*basic-word-break-characters*}. @end defvr @defvr {Symbol macro} *completion-query-items* Up to this many items will be displayed in response to a @code{possible-completions} call. After that, Readline asks the user if she is sure she wants to see them all. The default value is @code{100}. A negative value indicates that Readline should never ask the user. @end defvr @defvr {Symbol macro} *completion-append-character* Character. When a single completion alternative matches at the end of the command line, this character is appended to the inserted completion text. The default is a space character. Setting this to the null character prevents anything being appended automatically. This can be changed in application-specific completion functions to provide the 'most sensible word separator character' according to an application-specific command line syntax specification. @end defvr @defvr {Symbol macro} *ignore-completion-duplicates* Boolean. If non-@code{nil}, then duplicates in the matches are removed. The default is @code{t}. @end defvr @defvr {Symbol macro} *sort-completion-matches* Boolean. If an application sets this variable to @code{nil}, Readline will not sort the list of completions (which implies that it cannot remove any duplicate completions). The default value is @code{t}, which means that Readline will sort the completions and, depending on the value of @var{*ignore-completion-duplicates*}, will attempt to remove duplicate matches. @end defvr @cindex completion types @defvr {Symbol macro} +completion-type+ Keyword. Set to a keyword describing the type of completion Readline is currently attempting. Possible values are: @itemize @item @code{:standard-completion} tells Readline to do standard completion; @item @code{:display-and-perform} means to display all possible completions if there is more than one, as well as performing partial completion; @item @code{:insert-all} means insert all possible completions; @item @code{:list-all} means list the possible completions; @item @code{:not-list-cmn-prefix} is similar to @code{:display-and-perform} but possible completions are not listed if the possible completions share a common prefix. @end itemize @end defvr @defvr {Symbol macro} *inhibit-completion* Boolean. If this variable is non-@code{nil}, completion is inhibited. The completion character will be inserted as any other bound to self-insert. @end defvr @cindex hooks @defun register-hook hook function Register a hook. @var{hook} should be a keyword, one of the following: @itemize @item @code{:startup} hook is called just before @code{readline} prints the prompt. @item @code{:pre-input} hook is called after prompt has been printed and just before @code{readline} starts reading input characters. @item @code{:event} hook is called periodically when waiting for terminal input. By default, this will be called at most ten times a second if there is no keyboard input. @item @code{:signal} hook is called when a read system call is interrupted when @code{readline} is reading terminal input. @item @code{:inputp} hook is called when Readline need to determine whether or not there is available input on the current input source. If @var{function} returns @code{nil}, it means that there is no available input. @item @code{:lsmatches} hook is called to display list of completions. @var{function} must be able to take three arguments: list of completions, length of the list, and length of the longest completion in the list. It's up to the function how to display these completions. @end itemize Other values of @var{hook} will be ignored. @var{function} must be a function that takes no arguments and returns @code{nil} on success and @code{t} on failure. If @var{function} is @code{nil}, hook will be removed (or default function will be used). @end defun @cindex custom functions @defun register-function func function Register a function. @var{func} should be a keyword, one of the following: @itemize @item @code{:getc} function is used to get a character from the input stream, thus @var{function} should take pointer to C stream and return a character if this function is desired to be registered. In general, an application that registers @code{:getc} function should consider registering @code{:inputp} hook as well (see @code{register-hook}). @item @code{:redisplay} function is used to update the display with the current contents of the editing buffer, thus @var{function} should take no arguments and return @code{nil} on success and non-@code{nil} of failure. By default, it is set to @code{redisplay}, the default Readline redisplay function. @item @code{:prep-term} function is used to initialize the terminal, so @var{function} must be able to take one argument, a flag that says whether or not to use eight-bit characters. By default, @code{prep-terminal} is used. @item @code{:deprep-term} function is used to reset the terminal. This function should undo the effects of @code{:prep-term} function. @item @code{:complete} function is used to generate list of possible completions for given partially entered word. The function must be able to take three arguments: partially entered word, start index of the word in @var{*line-buffer*}, and end index of the word in the buffer. The function must return a list where first element is the actual completion (or part of completion if two or more completions share common prefix) and the rest arguments are possible completions. @end itemize Other values of @var{func} will be ignored. @var{function} must be a function, if @var{function} is @code{nil}, result is unpredictable. @end defun @node Work with Keymaps @chapter Work with Keymaps @cindex keymaps Keymaps tell Readline which function should it invoke when the user presses certain key. Readline provides some pre-existing keymaps and let you create your own and modify existing ones. @defvr {Symbol macro} +executing-keymap+ C pointer. This symbol macro is evaluated to the keymap in which the currently executing Readline function was found. @end defvr @defvr {Symbol macro} +binding-keymap+ C pointer. This symbol macro is evaluated to the keymap in which the last key binding occurred. @end defvr @defun make-keymap @code{&optional} bare Return a new keymap with self-inserting printing characters, the lowercase Meta characters bound to run their equivalents, and the Meta digits bound to produce numeric arguments. If @var{bare} is supplied and it's not @code{nil}, empty keymap will be returned. @end defun @defun copy-keymap keymap Return a new keymap which is a copy of @var{keymap}. @end defun @defun free-keymap keymap Free all storage associated with @var{keymap}. @end defun @defun get-keymap Return currently active keymap. @end defun @defun set-keymap keymap Make @var{keymap} currently active keymap. @end defun @defun get-keymap-by-name name Return the keymap matching @var{name}. @var{name} is one which would be supplied in a set keymap inputrc line. @end defun @defmac with-new-keymap form @code{&body} body Create new keymap evaluating @var{form}, bind symbol @code{keymap} to the result, then free it when control flow leaves @var{body}. @code{make-keymap} and @code{copy-keymap} can be used to produce new keymap. @end defmac @node Binding Keys @chapter Binding Keys Key sequences are associated with functions through the keymap. Here are the functions that may be of interest when working with keymaps. @defvr {Symbol macro} +executing-macro+ String. This symbol macro is evaluated to the text of any currently-executing macro. @end defvr @defvr {Symbol macro} +executing-key+ Character. The key that caused the dispatch to the currently-executing Readline function. @end defvr @defvr {Symbol macro} +executing-keyseq+ String. The full key sequence that caused the dispatch to the currently-executing Readline function. @end defvr @defvr {Symbol macro} +key-sequence-length+ Integer. The number of characters in @var{+executing-keyseq+}. @end defvr @defvr {Symbol macro} +dispatching+ Boolean. Set to a non-@code{nil} value if a function is being called from a key binding; @code{nil} otherwise. Application functions can test this to discover whether they were called directly or by Readline's dispatching mechanism. @end defvr @defun add-defun name function @code{&optional} key Add @var{name} to the list of named functions. Make @var{function} be the function that gets called. If @var{key} is not @code{nil} and it's a character, then bind it to function using @code{bind-key}. @var{function} must be able to take two arguments: integer representing its argument and character representing key that has invoked it. @end defun @defun bind-key key function @code{&key} keymap if-unbound Bind @var{key} to @var{function} in the currently active keymap. If @var{keymap} argument supplied, binding takes place in specified keymap. If @var{if-unbound} is supplied and it's not @code{nil}, @var{key} will be bound to @var{function} only if it's not already bound. @end defun @defun unbind-key key @code{&optional} keymap Unbind @var{key} in @var{keymap}. If @var{keymap} is not supplied or it's @code{nil}, @var{key} will be unbound in currently active keymap. The function returns @code{nil} on success and @code{t} on failure. @end defun @defun unbind-command command keymap Unbind all keys that are bound to @var{command} in @var{keymap}. @end defun @defun bind-keyseq keyseq function @code{&key} keymap if-unbound Bind the key sequence represented by the string @var{keyseq} to the function @var{function}, beginning in the current keymap. This makes new keymaps as necessary. If @var{keymap} is supplied and it's not @code{nil}, initial bindings are performed in @var{keymap}. If @var{if-unbound} is supplied and it's not @code{nil}, @var{keyseq} will be bound to @var{function} only if it's not already bound. The return value is @code{t} if @var{keyseq} is invalid and @code{nil} otherwise. @end defun @defun parse-and-bind line Parse @var{line} as if it had been read from the inputrc file and perform any key bindings and variable assignments found. @end defun @defun read-init-file filename Read keybindings and variable assignments from @var{filename}. @end defun @node Associating Function Names and Bindings @chapter Associating Function Names and Bindings Note that this section is stripped-down. Many functions are missing. It's because C functions take addresses of other functions as arguments. In cl-readline we use dynamic generation of callbacks, so once you have registered a new function, it's tricky to identify it later. Note that this problem is solvable, but hairy. If you need to use functions that are missing, open an issue and describe your problem. @defun function-dumper readable @code{&optional} filename append Print the Readline function names and the key sequences currently bound to them to stdout. If @var{readable} is non-@code{nil}, the list is formatted in such a way that it can be made part of an inputrc file and re-read. If @var{filename} is supplied and it's a string or path, output will be redirected to the file. @var{append} allows to append text to the file instead of overwriting it. @end defun @defun list-funmap-names @code{&optional} filename append Print the names of all bindable Readline functions to stdout. If @var{filename} is supplied and it's a string or path, output will be redirected to the file. @var{append} allows append text to the file instead of overwriting it. @end defun @defun funmap-names Return a list of known function names. The list is sorted. @end defun @defun add-funmap-entry name function Add @var{name} to the list of bindable Readline command names, and make @var{function} the function to be called when name is invoked. @end defun @node Allowing Undoing @chapter Allowing Undoing @cindex undoing If your function simply inserts text once, or deletes text once, and uses @code{insert-text} or @code{delete-text} to do it, then undoing is already done for you automatically. If you do multiple insertions or multiple deletions, or any combination of these operations, you should group them together into one operation. This is done with @code{undo-group} macro. @defun add-undo what start end text Remember how to undo an event (according to @var{what}). The affected text runs from @var{start} to @var{end}, and encompasses @var{text}. Possible values of @var{what} include: @code{:undo-delete}, @code{:undo-insert}, @code{:undo-begin}, and @code{:undo-end} @end defun @defun free-undo-list Free the existing undo list. @end defun @defun do-undo Undo the first thing on the undo list. Returns @code{nil} if there was nothing to undo, @code{t} if something was undone. @end defun @defun modifying start end Tell Readline to save the text between @var{start} and @var{end} as a single undo unit. It is assumed that you will subsequently modify that text. @end defun @defmac undo-group @code{&body} body All insertion and deletion inside this macro will be grouped together into one undo operation. @end defmac @node Redisplay @chapter Redisplay @defun redisplay Change what's displayed on the screen to reflect the current contents of @var{*line-buffer*}. @end defun @defun forced-update-display Force the line to be updated and redisplayed, whether or not Readline thinks the screen display is correct. @end defun @defun on-new-line @code{&optional} with-prompt Tell the update functions that we have moved onto a new (empty) line, usually after outputting a newline. When @var{with-prompt} is not @code{nil}, Readline will think that prompt is already displayed. This could be used by applications that want to output the prompt string themselves, but still need Readline to know the prompt string length for redisplay. This should be used together with @code{:already-prompted} keyword argument of @code{readline}. @end defun @defun reset-line-state Reset the display state to a clean state and redisplay the current line starting on a new line. @end defun @defun crlf Move the cursor to the start of the next screen line. @end defun @defun show-char char Display character @var{char} on outstream. If Readline has not been set to display meta characters directly, this will convert meta characters to a meta-prefixed key sequence. This is intended for use by applications which wish to do their own redisplay. @end defun @defun set-prompt prompt Make Readline use @var{prompt} for subsequent redisplay. This calls @code{expand-prompt} to expand the prompt and sets @var{+prompt+} to the result. @end defun @defmac with-message message save-prompt @code{&body} body Show message @var{message} in the echo area while executing @var{body}. If @var{save-prompt} is not @code{nil}, save prompt before showing the message and restore it before clearing the message. @end defmac @node Adding and modifying Text @chapter Adding and modifying Text Once a prompt is started, you can insert and delete text at the current cursor position. See also @code{crlf} and the section ``Moving the cursor''. @defun insert-text text Insert @var{text} into the line at the current cursor position. Return the number of characters inserted. @end defun @defun delete-text start end Delete the text between @var{start} and @var{end} in the current line. Return the number of characters deleted. @end defun @defun kill-text start end Copy the text between @var{start} and @var{end} in the current line to the kill ring, appending or prepending to the last kill if the last command was a kill command. The text is deleted. If @var{start} is less than @var{end}, the text is appended, otherwise prepended. If the last command was not a kill, a new kill ring slot is used. @end defun @node Character Input @chapter Character Input @defun read-key Return the next character available from Readline's current input stream. @end defun @defun stuff-char char Insert @var{char} into the Readline input stream. It will be ``read'' before Readline attempts to read characters from the terminal with @code{read-key}. Up to @code{512} characters may be pushed back. @code{stuff-char} returns @code{t} if the character was successfully inserted; @code{nil} otherwise. @end defun @defun execute-next char Make @var{char} be the next command to be executed when @code{read-key} is called. @end defun @defun clear-pending-input Negate the effect of any previous call to @code{execute-next}. This works only if the pending input has not already been read with @code{read-key}. @end defun @defun set-keyboard-input-timeout u While waiting for keyboard input in @code{read-key}, Readline will wait for @var{u} microseconds for input before calling any function assigned to @code{event-hook}. @var{u} must be greater than or equal to zero (a zero-length timeout is equivalent to a poll). The default waiting period is one-tenth of a second. Return the old timeout value. @end defun @node Moving the cursor @chapter Moving the cursor You can move the cursor by characters and words, or move to the beginning and end of the line. We also have commands to clear the line and the screen. Note that these functions bind readline commands, thus they must accept two arguments: @var{count} (defaults to 1) and @var{key} (the key identifier that fired this command). The key is not used in the Lisp functions. @defun backward-word @code{&optional} (count 1) Move backward COUNT words (1 by default). @end defun @defun forward-word @code{&optional} (count 1) Move forward COUNT word(s). @end defun @defun backward-char @code{&optional} (count 1) Move forward COUNT characters. @end defun @defun forward-char @code{&optional} (count 1) Move forward COUNT characters. @end defun @defun beginning-of-line Move to the beginning of the line. @end defun @defun end-of-line Move to the end of the line. @end defun @defun refresh-line Clear the current line. A numeric argument to C-l does this. @end defun @defun clear-screen C-l typed to a line without quoting clears the screen, and then reprints the prompt and the current input line. @end defun @defun clear-display Clear the screen and update the display." @end defun Here's an example to enter an opening @code{(} and a closing @code{)}, and move the cursor in between the parenthesis: @lisp (defun insert-parens (&optional count key) (rl:insert-text "()") (rl:backward-char)) (defun run-example () (rl:bind-keyseq "(" #'insert-parens) ;; this function must accept COUNT and KEY ;; start a prompt (rl:readline :prompt "go > ") ;; and now you can type "(". ) (run-example) @end lisp @node Terminal Management @chapter Terminal Management @defun prep-terminal eight-bit-input Modify the terminal settings for Readline's use, so @code{readline} can read a single character at a time from the keyboard. The @code{eight-bit-input} argument should be non-@code{nil} if Readline should read eight-bit input. @end defun @defun deprep-terminal Undo the effects of @code{prep-terminal}, leaving the terminal in the state in which it was before the most recent call to @code{prep-terminal}. @end defun @defun tty-set-default-bindings keymap Read the operating system's terminal editing characters (as would be displayed by stty) to their Readline equivalents. The bindings are performed in @var{keymap}. @end defun @defun tty-unset-default-bindings keymap Reset the bindings manipulated by @code{tty-set-default-bindings} so that the terminal editing characters are bound to @code{insert}. The bindings are performed in @var{keymap}. @end defun @defun reset-terminal terminal Reinitialize Readline's idea of the terminal settings using @var{terminal} as the terminal type (e.g., @code{"vt100"}). @end defun @node Utility Functions @chapter Utility Functions @defun replace-line text clear-undo Replace the contents of @var{*line-buffer*} with @var{text}. The point and mark are preserved, if possible. If @var{clear-undo} is non-@code{nil}, the undo list associated with the current line is cleared. @end defun @defun extend-line-buffer len Ensure that line buffer has enough space to hold @var{len} characters, possibly reallocating it if necessary. @end defun @defun initialize Initialize or re-initialize Readline's internal state. It's not strictly necessary to call this; @code{readline} calls it before reading any input. cl-readline also makes sure that Readline is always initialized when you use it. @end defun @defun ding Ring the terminal bell, obeying the setting of bell-style. @end defun @node Miscellaneous Functions @chapter Miscellaneous Functions @defun macro-dumper readable @code{&optional} filename append Print the key sequences bound to macros and their values, using the current keymap to stdout. If @code{readable} is non-@code{nil}, the list is formatted in such a way that it can be made part of an inputrc file and re-read. If @code{filename} is supplied and it's a string or path, output will be redirected to the file. @code{append} allows to append text to the file instead of overwriting it. @end defun @defun variable-bind variable value Make the Readline variable @var{variable} have @var{value}. This behaves as if the readline command @code{set variable value} had been executed in an inputrc file. @end defun @defun variable-value variable Return a string representing the value of the Readline variable @var{variable}. For Boolean variables, this string is either 'on' or 'off'. @end defun @defun variable-dumper readable @code{&optional} filename append Print the readline variable names and their current values to stdout. If readable is not @code{nil}, the list is formatted in such a way that it can be made part of an inputrc file and re-read. If @var{filename} is supplied and it's a string or path, output will be redirected to the file. @var{append} allows to append text to the file instead of overwriting it. @end defun @defun set-paren-blink-timeout micros Set the time interval (in microseconds) that Readline waits when showing a balancing character when @code{blink-matching-paren} has been enabled. The function returns previous value of the parameter. @end defun @defun clear-history Clear the history list by deleting all of the entries. @end defun @defun read-history filename Add the contents of filename to the history list, a line at a time. @end defun @defun write-history filename Write the current history to filename, overwriting filename if necessary. @end defun @node Signal Handling @chapter Signal Handling @cindex signals Signals are asynchronous events sent to a process by the Unix kernel, sometimes on behalf of another process. They are intended to indicate exceptional events, like a user pressing the interrupt key on his terminal, or a network connection being broken. There is a class of signals that can be sent to the process currently reading input from the keyboard. Since Readline changes the terminal attributes when it is called, it needs to perform special processing when such a signal is received in order to restore the terminal to a sane state, or provide application writers with functions to do so manually. Readline contains an internal signal handler that is installed for a number of signals (SIGINT, SIGQUIT, SIGTERM, SIGHUP, SIGALRM, SIGTSTP, SIGTTIN, and SIGTTOU). When one of these signals is received, the signal handler will reset the terminal attributes to those that were in effect before @code{readline} was called, reset the signal handling to what it was before @code{readline} was called, and resend the signal to the calling application. If and when the calling application's signal handler returns, Readline will reinitialize the terminal and continue to accept input. When a SIGINT is received, the Readline signal handler performs some additional work, which will cause any partially-entered line to be aborted (see the description of @code{free-line-state} below). There is an additional Readline signal handler, for SIGWINCH, which the kernel sends to a process whenever the terminal's size changes (for example, if a user resizes an xterm). The Readline SIGWINCH handler updates Readline's internal screen size information, and then calls any SIGWINCH signal handler the calling application has installed. Readline calls the application's SIGWINCH signal handler without resetting the terminal to its original state. If the application's signal handler does more than update its idea of the terminal size and return (for example, a longjmp back to a main processing loop), it must call @code{cleanup-after-signal} (described below), to restore the terminal state. Readline provides two variables that allow application writers to control whether or not it will catch certain signals and act on them when they are received. It is important that applications change the values of these variables only when calling @code{readline}, not in a signal handler, so Readline's internal signal state is not corrupted. @defvr {Symbol macro} *catch-signals* Boolean. If this variable is non-@code{nil}, Readline will install signal handlers for SIGINT, SIGQUIT, SIGTERM, SIGHUP, SIGALRM, SIGTSTP, SIGTTIN, and SIGTTOU. The default value of @var{*catch-signals*} is @code{t}. @end defvr @defvr {Symbol macro} *catch-sigwinch* If this variable is set to a non-@code{nil} value, Readline will install a signal handler for SIGWINCH. The default value of @var{*catch-sigwinch*} is @code{t}. @end defvr @defvr {Symbol macro} *change-environment* If this variable is set to a non-@code{nil} value, and Readline is handling SIGWINCH, Readline will modify the LINES and COLUMNS environment variables upon receipt of a SIGWINCH. The default value of @var{*change-environment*} is @code{t}. @end defvr @defun cleanup-after-signal This function will reset the state of the terminal to what it was before @code{readline} was called, and remove the Readline signal handlers for all signals, depending on the values of @var{*catch-signals*} and @var{*catch-sigwinch*}. @end defun @defun free-line-state This will free any partial state associated with the current input line (undo information, any partial history entry, any partially-entered keyboard macro, and any partially-entered numeric argument). This should be called before @code{cleanup-after-signal}. The Readline signal handler for SIGINT calls this to abort the current input line. @end defun @defun reset-after-signal This will reinitialize the terminal and reinstall any Readline signal handlers, depending on the values of @var{*catch-signals*} and @var{*catch-sigwinch*}. @end defun @defun echo-signal-char sig If an application wishes to install its own signal handlers, but still have readline display characters that generate signals, calling this function with @var{sig} set to @code{:sigint}, @code{:sigquit}, or @code{:sigtstp} will display the character generating that signal. @end defun @defun resize-terminal Update Readline's internal screen size by reading values from the kernel. @end defun @defun set-screen-size rows cols Set Readline's idea of the terminal size to @var{rows} rows and @var{cols} columns. If either rows or columns is less than or equal to @code{0}, Readline's idea of that terminal dimension is unchanged. @end defun @defun get-screen-size Return Readline's idea of the terminal's size. The function returns multiple values: number of rows and columns. @end defun @defun reset-screen-size Cause Readline to reobtain the screen size and recalculate its dimensions. @end defun @defun set-signals Install Readline's signal handler for SIGINT, SIGQUIT, SIGTERM, SIGHUP, SIGALRM, SIGTSTP, SIGTTIN, SIGTTOU, and SIGWINCH, depending on the values of @var{*catch-signals*} and @var{*catch-sigwinch*}. @end defun @defun clear-signals Remove all of the Readline signal handlers installed by @code{set-signals}. @end defun @node Example @chapter Example This program demonstrates some basic capacities of cl-readline. Note that you should run it in terminal, not via SLIME. See more at @url{https://github.com/vindarel/cl-readline-example}. @lisp ;;; Load some systems and define a package... (asdf:load-system :str) (asdf:load-system :cl-readline) (cl:defpackage :example (:use #:common-lisp) (:export #:run-example)) (in-package :example) ;;; Now let's define lists of verbs and fruits: (defvar *verbs* '("eat" "get" "throw" "quit")) (defvar *fruits* '("banana" "apple" "orange" "banana_two")) ;;; Define and register function that does custom completion: if the user enters ;;; a first word, it will be completed as a verb, and the second and later words will ;;; be completed as fruits. (defun custom-complete (text start end) (declare (ignore end)) (labels ((select-completions (list) (let ((els (remove-if-not (lambda (it) (str:starts-with? text it)) list))) (if (cdr els) (cons (str:prefix els) els) els)))) (if (zerop start) (select-completions *verbs*) (select-completions *fruits*)))) (rl:register-function :complete #'custom-complete) ;;; Let's also create a custom command and bind it to some key ;;; sequence so the user can invoke it. In this example the user can ;;; automagically insert the phrase 'inserted text' pressing ;;; Control-o. (defun print-some-text (arg key) (declare (ignore arg key)) (rl:insert-text "inserted text")) (rl:bind-keyseq "\\C-o" #'print-some-text) ;;; Let's write novelty-check, so if the actual line is equal to the most ;;; recent history line it will not be added to the history. (defun novelty-check (x y) (string/= (string-trim " " x) (string-trim " " y))) ;;; Finally, this is our main function. To exit from the loop, enter 'quit'. (defun run-example () ;; see cl-readline-example to see how to catch a C-c. (do ((i 0 (1+ i)) (text "")) ((string= "quit" (string-trim " " text))) (setf text (rl:readline :prompt (format nil "[~a]> " i) :add-history t :novelty-check #'novelty-check)))) @end lisp @node GNU Free Documentation License @appendix GNU Free Documentation License @include fdl.texi @node Concept Index @unnumbered Concept Index @printindex cp @node Function and Variable Index @unnumbered Function and Variable Index @printindex fn @bye
39,917
Common Lisp
.l
929
41.453175
134
0.786998
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
24427a9032e9b685b279cedbafc7ad420d6be0cf496a9d91ad2502aa55ccfd54
4,452
[ -1 ]
4,453
style.css
vindarel_cl-readline/doc/style.css
h1, .section, .subsection, .settitle { background-color: #d0e4fe } body { margin: 0 auto; max-width: 23cm; padding: 1em } hr { display: none }
143
Common Lisp
.l
3
46.666667
66
0.7
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
672745b2b305a11a7c3237c112f503032ca2db800389287c1f7c3f7e8d1c02fc
4,453
[ -1 ]
4,454
fdl.texi
vindarel_cl-readline/doc/fdl.texi
@c The GNU Free Documentation License. @center Version 1.3, 3 November 2008 @c This file is intended to be included within another document, @c hence no sectioning command or @node. @display Copyright @copyright{} 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. @uref{http://fsf.org/} Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @end display @enumerate 0 @item PREAMBLE The purpose of this License is to make a manual, textbook, or other functional and useful document @dfn{free} in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of ``copyleft'', which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. @item APPLICABILITY AND DEFINITIONS This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The ``Document'', below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as ``you''. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A ``Modified Version'' of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A ``Secondary Section'' is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The ``Invariant Sections'' are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The ``Cover Texts'' are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A ``Transparent'' copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not ``Transparent'' is called ``Opaque''. Examples of suitable formats for Transparent copies include plain @sc{ascii} without markup, Texinfo input format, La@TeX{} input format, @acronym{SGML} or @acronym{XML} using a publicly available @acronym{DTD}, and standard-conforming simple @acronym{HTML}, PostScript or @acronym{PDF} designed for human modification. Examples of transparent image formats include @acronym{PNG}, @acronym{XCF} and @acronym{JPG}. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, @acronym{SGML} or @acronym{XML} for which the @acronym{DTD} and/or processing tools are not generally available, and the machine-generated @acronym{HTML}, PostScript or @acronym{PDF} produced by some word processors for output purposes only. The ``Title Page'' means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, ``Title Page'' means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text. The ``publisher'' means any person or entity that distributes copies of the Document to the public. A section ``Entitled XYZ'' means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as ``Acknowledgements'', ``Dedications'', ``Endorsements'', or ``History''.) To ``Preserve the Title'' of such a section when you modify the Document means that it remains a section ``Entitled XYZ'' according to this definition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. @item VERBATIM COPYING You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. @item COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. @item MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: @enumerate A @item Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. @item List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. @item State on the Title page the name of the publisher of the Modified Version, as the publisher. @item Preserve all the copyright notices of the Document. @item Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. @item Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. @item Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. @item Include an unaltered copy of this License. @item Preserve the section Entitled ``History'', Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled ``History'' in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. @item Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the ``History'' section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. @item For any section Entitled ``Acknowledgements'' or ``Dedications'', Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. @item Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. @item Delete any section Entitled ``Endorsements''. Such a section may not be included in the Modified Version. @item Do not retitle any existing section to be Entitled ``Endorsements'' or to conflict in title with any Invariant Section. @item Preserve any Warranty Disclaimers. @end enumerate If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles. You may add a section Entitled ``Endorsements'', provided it contains nothing but endorsements of your Modified Version by various parties---for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. @item COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled ``History'' in the various original documents, forming one section Entitled ``History''; likewise combine any sections Entitled ``Acknowledgements'', and any sections Entitled ``Dedications''. You must delete all sections Entitled ``Endorsements.'' @item COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. @item AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an ``aggregate'' if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. @item TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled ``Acknowledgements'', ``Dedications'', or ``History'', the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. @item TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it. @item FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See @uref{http://www.gnu.org/copyleft/}. Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License ``or any later version'' applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document. @item RELICENSING ``Massive Multiauthor Collaboration Site'' (or ``MMC Site'') means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A ``Massive Multiauthor Collaboration'' (or ``MMC'') contained in the site means any set of copyrightable works thus published on the MMC site. ``CC-BY-SA'' means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. ``Incorporate'' means to publish or republish a Document, in whole or in part, as part of another Document. An MMC is ``eligible for relicensing'' if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing. @end enumerate @page @heading ADDENDUM: How to use this License for your documents To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: @smallexample @group Copyright (C) @var{year} @var{your name}. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. @end group @end smallexample If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the ``with@dots{}Texts.'' line with this: @smallexample @group with the Invariant Sections being @var{list their titles}, with the Front-Cover Texts being @var{list}, and with the Back-Cover Texts being @var{list}. @end group @end smallexample If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software. @c Local Variables: @c ispell-local-pdict: "ispell-dict" @c End:
23,565
Common Lisp
.l
421
54.710214
82
0.818119
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
617d842e56c4851a268cc3ba9e4d356e788599e3e18b49c38423082b0740c441
4,454
[ -1 ]
4,455
index.html
vindarel_cl-readline/doc/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- This manual describes the cl-readline Library (version 0.1.1, 18 June 2015), bindings to GNU Readline Library. This documentation is derived from original GNU Readline documentation by Brian Fox and Chet Ramey. Copyright (C) 2015 Mark Karpov, Brian Fox, Chet Ramey Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". --> <!-- Created on June 18, 2015 by texi2html 5.0 texi2html was written by: Lionel Cons <[email protected]> (original author) Karl Berry <[email protected]> Olaf Bachmann <[email protected]> and many others. Maintained by: Many creative people. Send bugs and suggestions to <[email protected]> --> <head> <title>cl-readline Library</title> <meta name="description" content="cl-readline Library"> <meta name="keywords" content="cl-readline Library"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="texi2html 5.0"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> <!-- a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smalllisp {margin-left: 3.2em} pre.display {font-family: serif} pre.format {font-family: serif} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: serif; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: serif; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:pre} span.nolinebreak {white-space:pre} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} h1, .section, .subsection, .settitle { background-color: #d0e4fe } body { margin: 0 auto; max-width: 23cm; padding: 1em } hr { display: none } --> </style> </head> <body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000"> <h1>cl-readline Library</h1> <h3 align="right">Edition 0.1.1, for <code>cl-readline Library</code> Version 0.1.1.</h3> <h3 align="right">June 2015</h3> <strong>Mark Karpov, Brian Fox, Chet Ramey</strong><br> <p>This manual describes the cl-readline Library (version 0.1.1, 18 June 2015), bindings to GNU Readline Library. </p> <p>This documentation is derived from original GNU Readline documentation by Brian Fox and Chet Ramey. </p> <p>Copyright &copy; 2015 Mark Karpov, Brian Fox, Chet Ramey </p> <blockquote> <p>Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled &ldquo;GNU Free Documentation License&rdquo;. </p> </blockquote> <hr> <a name="Top"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[ &lt; ]</td> <td valign="middle" align="left">[<a href="#Basic-Functionality" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="cl_002dreadline-Library"></a> <h1 class="top">cl-readline Library</h1> <p>This document describes cl-readline library, bindings to GNU Readline library. This program is distributed under GNU General Public License, version 3. </p> <p>All symbols described in this document live in <code>cl-readline</code> package, it has the following nicknames: <code>rl</code>. </p> <table class="menu" border="0" cellspacing="0"> <tr><td align="left" valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> Most basic functions and symbol macros. </td></tr> <tr><td align="left" valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> How to change behavior of cl-readline. </td></tr> <tr><td align="left" valign="top"><a href="#Work-with-Keymaps">3 Work with Keymaps</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> Modify existing keymaps and create new ones. </td></tr> <tr><td align="left" valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> How to change keymaps. </td></tr> <tr><td align="left" valign="top"><a href="#Associating-Function-Names-and-Bindings">5 Associating Function Names and Bindings</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> Translate function names to key sequences. </td></tr> <tr><td align="left" valign="top"><a href="#Allowing-Undoing">6 Allowing Undoing</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> How to make your functions undoable. </td></tr> <tr><td align="left" valign="top"><a href="#Redisplay">7 Redisplay</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> Functions to control line display. </td></tr> <tr><td align="left" valign="top"><a href="#Modifying-Text">8 Modifying Text</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> Functions to modify <var>*line-buffer*</var>. </td></tr> <tr><td align="left" valign="top"><a href="#Character-Input">9 Character Input</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> Functions to read keyboard input. </td></tr> <tr><td align="left" valign="top"><a href="#Terminal-Management">10 Terminal Management</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> Functions to manage terminal settings. </td></tr> <tr><td align="left" valign="top"><a href="#Utility-Functions">11 Utility Functions</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> Generally useful functions. </td></tr> <tr><td align="left" valign="top"><a href="#Miscellaneous-Functions">12 Miscellaneous Functions</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> Functions that don&rsquo;t fall into any category. </td></tr> <tr><td align="left" valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> How Readline behaves when it receives signals. </td></tr> <tr><td align="left" valign="top"><a href="#Example">14 Example</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> A complete example of cl-readline use. </td></tr> <tr><td align="left" valign="top"><a href="#GNU-Free-Documentation-License">Appendix A GNU Free Documentation License</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> License for copying this manual. </td></tr> <tr><td align="left" valign="top"><a href="#Concept-Index">Concept Index</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> Index of concepts described in this manual. </td></tr> <tr><td align="left" valign="top"><a href="#Function-and-Variable-Index">Function and Variable Index</a></td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> Index of externally visible functions and variables. </td></tr> </table> <hr size="6"> <a name="Basic-Functionality"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Top" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Hooks-and-Custom-Functions" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Hooks-and-Custom-Functions" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Basic-Functionality-1"></a> <h1 class="chapter">1 Basic Functionality</h1> <p>This section describes most basic functions and symbol-macros that represent underlying C variables. For every symbol macro we give data type it evaluates to. If name of a symbol macro is enclosed in plus signs (for example, <var>+prompt+</var>), it means that you should not (and, in fact, cannot) modify its value. Other symbol macros are setfable and you can set their values with <code>setf</code> macro. </p> <dl> <dt><a name="index-_002aline_002dbuffer_002a"></a>Symbol Macro: <strong>*line-buffer*</strong></dt> <dd><p>String. This is the line gathered so far. You are welcome to modify the contents of the line, but remember about undoing (see section <a href="#Allowing-Undoing">Allowing Undoing</a>). The function <code>extend-line-buffer</code> is available to increase the memory allocated to <var>*line-buffer*</var>. </p></dd></dl> <dl> <dt><a name="index-_002apoint_002a"></a>Symbol Macro: <strong>*point*</strong></dt> <dd><p>Integer. The offset of the current cursor position in <var>*line-buffer*</var> (the point). </p></dd></dl> <dl> <dt><a name="index-_002bend_002b"></a>Symbol Macro: <strong>+end+</strong></dt> <dd><p>Integer. The number of characters present in <var>*line-buffer*</var>. When <var>*point*</var> is at the end of the line, <var>*point*</var> and <var>+end+</var> are equal. </p></dd></dl> <dl> <dt><a name="index-_002amark_002a"></a>Symbol Macro: <strong>*mark*</strong></dt> <dd><p>Integer. The mark (saved position) in the current line. If set, the mark and point define a region. </p></dd></dl> <dl> <dt><a name="index-_002adone_002a"></a>Symbol Macro: <strong>*done*</strong></dt> <dd><p>Boolean. Setting this to a non-<code>nil</code> value causes Readline to return the current line immediately. </p></dd></dl> <dl> <dt><a name="index-_002bprompt_002b"></a>Symbol Macro: <strong>+prompt+</strong></dt> <dd><p>String. The prompt Readline uses. This is set from the argument to <code>readline</code>, and should not be assigned to directly. The <code>set-prompt</code> function may be used to modify the prompt string after calling <code>readline</code>. </p></dd></dl> <dl> <dt><a name="index-_002adisplay_002dprompt_002a"></a>Symbol Macro: <strong>*display-prompt*</strong></dt> <dd><p>String. The string displayed as the prompt. This is usually identical to <var>+prompt+</var>, but may be changed temporarily by functions that use the prompt string as a message area, such as incremental search. </p></dd></dl> <dl> <dt><a name="index-_002blibrary_002dversion_002b"></a>Symbol Macro: <strong>+library-version+</strong></dt> <dd><p>String. The version number of this revision of the library. </p></dd></dl> <dl> <dt><a name="index-_002breadline_002dversion_002b"></a>Symbol Macro: <strong>+readline-version+</strong></dt> <dd><p>Two integer values. Major and minor version numbers of Readline library. </p></dd></dl> <dl> <dt><a name="index-_002bgnu_002dreadline_002dp_002b"></a>Symbol Macro: <strong>+gnu-readline-p+</strong></dt> <dd><p>Boolean. Always evaluated to <code>t</code>, denoting that this is GNU readline rather than some emulation. </p></dd></dl> <dl> <dt><a name="index-_002areadline_002dname_002a"></a>Symbol Macro: <strong>*readline-name*</strong></dt> <dd><p>String. This symbol-macro should be set to a unique name by each application using Readline. The value allows conditional parsing of the inputrc file. </p></dd></dl> <a name="index-readline-state"></a> <dl> <dt><a name="index-_002breadline_002dstate_002b"></a>Symbol Macro: <strong>+readline-state+</strong></dt> <dd><p>List of keywords. This symbol macro is evaluated to a list containing keywords that denote state of Readline. The following flags are used: </p><ul> <li> <code>:initializing</code> &ndash; initializing; </li><li> <code>:initialized</code> &ndash; initialization done; </li><li> <code>:termprepped</code> &ndash; terminal is prepped; </li><li> <code>:readcmd</code> &ndash; reading a command key; </li><li> <code>:metanext</code> &ndash; reading input after ESC; </li><li> <code>:dispatching</code> &ndash; dispatching to a command; </li><li> <code>:moreinput</code> &ndash; reading more input in a command function; </li><li> <code>:isearch</code> &ndash; doing incremental search; </li><li> <code>:nsearch</code> &ndash; doing non-incremental search; </li><li> <code>:search</code> &ndash; doing a history search; </li><li> <code>:numericarg</code> &ndash; reading numeric argument; </li><li> <code>:macroinput</code> &ndash; getting input from a macro; </li><li> <code>:macrodef</code> &ndash; defining keyboard macro; </li><li> <code>:overwrite</code> &ndash; overwrite mode; </li><li> <code>:completing</code> &ndash; doing completion; </li><li> <code>:sighandler</code> &ndash; in readline sighandler; </li><li> <code>:undoing</code> &ndash; doing a undo; </li><li> <code>:inputpending</code> &ndash; <code>execute-next</code> called; </li><li> <code>:ttycsaved</code> &ndash; tty special chars saved; </li><li> <code>:callback</code> &ndash; using the callback interface; </li><li> <code>:vimotion</code> &ndash; reading vi motion argument; </li><li> <code>:multikey</code> &ndash; reading multiple-key command; </li><li> <code>:vicmdonce</code> &ndash; entered vi command at least once; </li><li> <code>:redisplaying</code> &ndash; undating terminal display; </li><li> <code>:done</code> &ndash; done; accepted line. </li></ul> </dd></dl> <dl> <dt><a name="index-_002bediting_002dmode_002b"></a>Symbol macro: <strong>+editing-mode+</strong></dt> <dd><p>Keyword. Evaluated to keyword denoting actual editing mode: <code>:emacs</code> or <code>:vi</code>. </p></dd></dl> <a name="index-readline_002c-function"></a> <dl> <dt><a name="index-readline"></a>Function: <strong>readline</strong><em> <code>&amp;key</code> prompt already-prompted num-chars erase-empty-line add-history novelty-check</em></dt> <dd><p>Get a line from user with editing. <var>prompt</var>, if supplied, is printed before reading of input. Non-<code>nil</code> value of <var>already-prompted</var> will tell Readline that the application has printed prompt already. However, <var>prompt</var> must be supplied in this case too, so redisplay functions can update the display properly. If <var>num-chars</var> argument is a positive number, Readline will return after accepting that many characters. If <var>erase-empty-line</var> is not <code>nil</code>, <code>readline</code> will completely erase the current line, including any prompt, any time a newline is typed as the only character on an otherwise-empty line. The cursor is moved to the beginning of the newly-blank line. Supplying <var>add-history</var> tells Readline that user&rsquo;s input should be added to history. However, blank lines don&rsquo;t get into history anyway. <var>novelty-check</var>, if given, must be a predicate that takes two strings: the actual line and the most recent history line. Only when the predicate evaluates to non-<code>nil</code> value new line will be added to the history. Return value on success is the actual string and <code>nil</code> on failure. </p></dd></dl> <hr> <a name="Hooks-and-Custom-Functions"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Basic-Functionality" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Basic-Functionality" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Work-with-Keymaps" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Work-with-Keymaps" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Hooks-and-Custom-Functions-1"></a> <h1 class="chapter">2 Hooks and Custom Functions</h1> <p>cl-readline provides ways to register custom functions, so you can rewrite some parts of Readline library in Lisp. </p> <dl> <dt><a name="index-_002abasic_002dword_002dbreak_002dcharacters_002a"></a>Symbol macro: <strong>*basic-word-break-characters*</strong></dt> <dd><p>String. The basic list of characters that signal a break between words for the completer routine. The default value of this variable is the characters which break words for completion in Bash. </p></dd></dl> <dl> <dt><a name="index-_002abasic_002dquote_002dcharacters_002a"></a>Symbol macro: <strong>*basic-quote-characters*</strong></dt> <dd><p>String. A list of quote characters which can cause a word break. </p></dd></dl> <dl> <dt><a name="index-_002acompleter_002dword_002dbreak_002dcharacters_002a"></a>Symbol macro: <strong>*completer-word-break-characters*</strong></dt> <dd><p>String. The list of characters that signal a break between words for <code>complete-internal</code>. The default list is the value of <var>*basic-word-break-characters*</var>. </p></dd></dl> <dl> <dt><a name="index-_002acompletion_002dquery_002ditems_002a"></a>Symbol macro: <strong>*completion-query-items*</strong></dt> <dd><p>Up to this many items will be displayed in response to a <code>possible-completions</code> call. After that, Readline asks the user if she is sure she wants to see them all. The default value is <code>100</code>. A negative value indicates that Readline should never ask the user. </p></dd></dl> <dl> <dt><a name="index-_002acompletion_002dappend_002dcharacter_002a"></a>Symbol macro: <strong>*completion-append-character*</strong></dt> <dd><p>Character. When a single completion alternative matches at the end of the command line, this character is appended to the inserted completion text. The default is a space character. Setting this to the null character prevents anything being appended automatically. This can be changed in application-specific completion functions to provide the &rsquo;most sensible word separator character&rsquo; according to an application-specific command line syntax specification. </p></dd></dl> <dl> <dt><a name="index-_002aignore_002dcompletion_002dduplicates_002a"></a>Symbol macro: <strong>*ignore-completion-duplicates*</strong></dt> <dd><p>Boolean. If non-<code>nil</code>, then duplicates in the matches are removed. The default is <code>t</code>. </p></dd></dl> <dl> <dt><a name="index-_002asort_002dcompletion_002dmatches_002a"></a>Symbol macro: <strong>*sort-completion-matches*</strong></dt> <dd><p>Boolean. If an application sets this variable to <code>nil</code>, Readline will not sort the list of completions (which implies that it cannot remove any duplicate completions). The default value is <code>t</code>, which means that Readline will sort the completions and, depending on the value of <var>*ignore-completion-duplicates*</var>, will attempt to remove duplicate matches. </p></dd></dl> <a name="index-completion-types"></a> <dl> <dt><a name="index-_002bcompletion_002dtype_002b"></a>Symbol macro: <strong>+completion-type+</strong></dt> <dd><p>Keyword. Set to a keyword describing the type of completion Readline is currently attempting. Possible values are: </p><ul> <li> <code>:standard-completion</code> tells Readline to do standard completion; </li><li> <code>:display-and-perform</code> means to display all possible completions if there is more than one, as well as performing partial completion; </li><li> <code>:insert-all</code> means insert all possible completions; </li><li> <code>:list-all</code> means list the possible completions; </li><li> <code>:not-list-cmn-prefix</code> is similar to <code>:display-and-perform</code> but possible completions are not listed if the possible completions share a common prefix. </li></ul> </dd></dl> <dl> <dt><a name="index-_002ainhibit_002dcompletion_002a"></a>Symbol macro: <strong>*inhibit-completion*</strong></dt> <dd><p>Boolean. If this variable is non-<code>nil</code>, completion is inhibited. The completion character will be inserted as any other bound to self-insert. </p></dd></dl> <a name="index-hooks"></a> <dl> <dt><a name="index-register_002dhook"></a>Function: <strong>register-hook</strong><em> hook function</em></dt> <dd><p>Register a hook. <var>hook</var> should be a keyword, one of the following: </p><ul> <li> <code>:startup</code> hook is called just before <code>readline</code> prints the prompt. </li><li> <code>:pre-input</code> hook is called after prompt has been printed and just before <code>readline</code> starts reading input characters. </li><li> <code>:event</code> hook is called periodically when waiting for terminal input. By default, this will be called at most ten times a second if there is no keyboard input. </li><li> <code>:signal</code> hook is called when a read system call is interrupted when <code>readline</code> is reading terminal input. </li><li> <code>:inputp</code> hook is called when Readline need to determine whether or not there is available input on the current input source. If <var>function</var> returns <code>nil</code>, it means that there is no available input. </li><li> <code>:lsmatches</code> hook is called to display list of completions. <var>function</var> must be able to take three arguments: list of completions, length of the list, and length of the longest completion in the list. It&rsquo;s up to the function how to display these completions. </li></ul> <p>Other values of <var>hook</var> will be ignored. </p> <p><var>function</var> must be a function that takes no arguments and returns <code>nil</code> on success and <code>t</code> on failure. If <var>function</var> is <code>nil</code>, hook will be removed (or default function will be used). </p></dd></dl> <a name="index-custom-functions"></a> <dl> <dt><a name="index-register_002dfunction"></a>Function: <strong>register-function</strong><em> func function</em></dt> <dd><p>Register a function. <var>func</var> should be a keyword, one of the following: </p><ul> <li> <code>:getc</code> function is used to get a character from the input stream, thus <var>function</var> should take pointer to C stream and return a character if this function is desired to be registered. In general, an application that registers <code>:getc</code> function should consider registering <code>:inputp</code> hook as well (see <code>register-hook</code>). </li><li> <code>:redisplay</code> function is used to update the display with the current contents of the editing buffer, thus <var>function</var> should take no arguments and return <code>nil</code> on success and non-<code>nil</code> of failure. By default, it is set to <code>redisplay</code>, the default Readline redisplay function. </li><li> <code>:prep-term</code> function is used to initialize the terminal, so <var>function</var> must be able to take one argument, a flag that says whether or not to use eight-bit characters. By default, <code>prep-terminal</code> is used. </li><li> <code>:deprep-term</code> function is used to reset the terminal. This function should undo the effects of <code>:prep-term</code> function. </li><li> <code>:complete</code> function is used to generate list of possible completions for given partially entered word. The function must be able to take three arguments: partially entered word, start index of the word in <var>*line-buffer*</var>, and end index of the word in the buffer. The function must return a list where first element is the actual completion (or part of completion if two or more completions share common prefix) and the rest arguments are possible completions. </li></ul> <p>Other values of <var>func</var> will be ignored. </p> <p><var>function</var> must be a function, if <var>function</var> is <code>nil</code>, result is unpredictable. </p></dd></dl> <hr> <a name="Work-with-Keymaps"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Hooks-and-Custom-Functions" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Hooks-and-Custom-Functions" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Binding-Keys" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Binding-Keys" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Work-with-Keymaps-1"></a> <h1 class="chapter">3 Work with Keymaps</h1> <a name="index-keymaps"></a> <p>Keymaps tell Readline which function should it invoke when the user presses certain key. Readline provides some pre-existing keymaps and let you create your own and modify existing ones. </p> <dl> <dt><a name="index-_002bexecuting_002dkeymap_002b"></a>Symbol macro: <strong>+executing-keymap+</strong></dt> <dd><p>C pointer. This symbol macro is evaluated to the keymap in which the currently executing Readline function was found. </p></dd></dl> <dl> <dt><a name="index-_002bbinding_002dkeymap_002b"></a>Symbol macro: <strong>+binding-keymap+</strong></dt> <dd><p>C pointer. This symbol macro is evaluated to the keymap in which the last key binding occurred. </p></dd></dl> <dl> <dt><a name="index-make_002dkeymap"></a>Function: <strong>make-keymap</strong><em> <code>&amp;optional</code> bare</em></dt> <dd><p>Return a new keymap with self-inserting printing characters, the lowercase Meta characters bound to run their equivalents, and the Meta digits bound to produce numeric arguments. If <var>bare</var> is supplied and it&rsquo;s not <code>nil</code>, empty keymap will be returned. </p></dd></dl> <dl> <dt><a name="index-copy_002dkeymap"></a>Function: <strong>copy-keymap</strong><em> keymap</em></dt> <dd><p>Return a new keymap which is a copy of <var>keymap</var>. </p></dd></dl> <dl> <dt><a name="index-free_002dkeymap"></a>Function: <strong>free-keymap</strong><em> keymap</em></dt> <dd><p>Free all storage associated with <var>keymap</var>. </p></dd></dl> <dl> <dt><a name="index-get_002dkeymap"></a>Function: <strong>get-keymap</strong></dt> <dd><p>Return currently active keymap. </p></dd></dl> <dl> <dt><a name="index-set_002dkeymap"></a>Function: <strong>set-keymap</strong><em> keymap</em></dt> <dd><p>Make <var>keymap</var> currently active keymap. </p></dd></dl> <dl> <dt><a name="index-get_002dkeymap_002dby_002dname"></a>Function: <strong>get-keymap-by-name</strong><em> name</em></dt> <dd><p>Return the keymap matching <var>name</var>. <var>name</var> is one which would be supplied in a set keymap inputrc line. </p></dd></dl> <dl> <dt><a name="index-with_002dnew_002dkeymap"></a>Macro: <strong>with-new-keymap</strong><em> form <code>&amp;body</code> body</em></dt> <dd><p>Create new keymap evaluating <var>form</var>, bind symbol <code>keymap</code> to the result, then free it when control flow leaves <var>body</var>. <code>make-keymap</code> and <code>copy-keymap</code> can be used to produce new keymap. </p></dd></dl> <hr> <a name="Binding-Keys"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Work-with-Keymaps" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Work-with-Keymaps" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Associating-Function-Names-and-Bindings" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Associating-Function-Names-and-Bindings" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Binding-Keys-1"></a> <h1 class="chapter">4 Binding Keys</h1> <p>Key sequences are associated with functions through the keymap. Here are the functions that may be of interest when working with keymaps. </p> <dl> <dt><a name="index-_002bexecuting_002dmacro_002b"></a>Symbol macro: <strong>+executing-macro+</strong></dt> <dd><p>String. This symbol macro is evaluated to the text of any currently-executing macro. </p></dd></dl> <dl> <dt><a name="index-_002bexecuting_002dkey_002b"></a>Symbol macro: <strong>+executing-key+</strong></dt> <dd><p>Character. The key that caused the dispatch to the currently-executing Readline function. </p></dd></dl> <dl> <dt><a name="index-_002bexecuting_002dkeyseq_002b"></a>Symbol macro: <strong>+executing-keyseq+</strong></dt> <dd><p>String. The full key sequence that caused the dispatch to the currently-executing Readline function. </p></dd></dl> <dl> <dt><a name="index-_002bkey_002dsequence_002dlength_002b"></a>Symbol macro: <strong>+key-sequence-length+</strong></dt> <dd><p>Integer. The number of characters in <var>+executing-keyseq+</var>. </p></dd></dl> <dl> <dt><a name="index-_002bdispatching_002b"></a>Symbol macro: <strong>+dispatching+</strong></dt> <dd><p>Boolean. Set to a non-<code>nil</code> value if a function is being called from a key binding; <code>nil</code> otherwise. Application functions can test this to discover whether they were called directly or by Readline&rsquo;s dispatching mechanism. </p></dd></dl> <dl> <dt><a name="index-add_002ddefun"></a>Function: <strong>add-defun</strong><em> name function <code>&amp;optional</code> key</em></dt> <dd><p>Add <var>name</var> to the list of named functions. Make <var>function</var> be the function that gets called. If <var>key</var> is not <code>nil</code> and it&rsquo;s a character, then bind it to function using <code>bind-key</code>. <var>function</var> must be able to take two arguments: integer representing its argument and character representing key that has invoked it. </p></dd></dl> <dl> <dt><a name="index-bind_002dkey"></a>Function: <strong>bind-key</strong><em> key function <code>&amp;key</code> keymap if-unbound</em></dt> <dd><p>Bind <var>key</var> to <var>function</var> in the currently active keymap. If <var>keymap</var> argument supplied, binding takes place in specified keymap. If <var>if-unbound</var> is supplied and it&rsquo;s not <code>nil</code>, <var>key</var> will be bound to <var>function</var> only if it&rsquo;s not already bound. </p></dd></dl> <dl> <dt><a name="index-unbind_002dkey"></a>Function: <strong>unbind-key</strong><em> key <code>&amp;optional</code> keymap</em></dt> <dd><p>Unbind <var>key</var> in <var>keymap</var>. If <var>keymap</var> is not supplied or it&rsquo;s <code>nil</code>, <var>key</var> will be unbound in currently active keymap. The function returns <code>nil</code> on success and <code>t</code> on failure. </p></dd></dl> <dl> <dt><a name="index-unbind_002dcommand"></a>Function: <strong>unbind-command</strong><em> command keymap</em></dt> <dd><p>Unbind all keys that are bound to <var>command</var> in <var>keymap</var>. </p></dd></dl> <dl> <dt><a name="index-bind_002dkeyseq"></a>Function: <strong>bind-keyseq</strong><em> keyseq function <code>&amp;key</code> keymap if-unbound</em></dt> <dd><p>Bind the key sequence represented by the string <var>keyseq</var> to the function <var>function</var>, beginning in the current keymap. This makes new keymaps as necessary. If <var>keymap</var> is supplied and it&rsquo;s not <code>nil</code>, initial bindings are performed in <var>keymap</var>. If <var>if-unbound</var> is supplied and it&rsquo;s not <code>nil</code>, <var>keyseq</var> will be bound to <var>function</var> only if it&rsquo;s not already bound. The return value is <code>t</code> if <var>keyseq</var> is invalid and <code>nil</code> otherwise. </p></dd></dl> <dl> <dt><a name="index-parse_002dand_002dbind"></a>Function: <strong>parse-and-bind</strong><em> line</em></dt> <dd><p>Parse <var>line</var> as if it had been read from the inputrc file and perform any key bindings and variable assignments found. </p></dd></dl> <dl> <dt><a name="index-read_002dinit_002dfile"></a>Function: <strong>read-init-file</strong><em> filename</em></dt> <dd><p>Read keybindings and variable assignments from <var>filename</var>. </p></dd></dl> <hr> <a name="Associating-Function-Names-and-Bindings"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Binding-Keys" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Binding-Keys" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Allowing-Undoing" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Allowing-Undoing" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Associating-Function-Names-and-Bindings-1"></a> <h1 class="chapter">5 Associating Function Names and Bindings</h1> <p>Note that this section is stripped-down. Many functions are missing. It&rsquo;s because C functions take addresses of other functions as arguments. In cl-readline we use dynamic generation of callbacks, so once you have registered a new function, it&rsquo;s tricky to identify it later. Note that this problem is solvable, but hairy. If you need to use functions that are missing, open an issue and describe your problem. </p> <dl> <dt><a name="index-function_002ddumper"></a>Function: <strong>function-dumper</strong><em> readable <code>&amp;optional</code> filename append</em></dt> <dd><p>Print the Readline function names and the key sequences currently bound to them to stdout. If <var>readable</var> is non-<code>nil</code>, the list is formatted in such a way that it can be made part of an inputrc file and re-read. If <var>filename</var> is supplied and it&rsquo;s a string or path, output will be redirected to the file. <var>append</var> allows to append text to the file instead of overwriting it. </p></dd></dl> <dl> <dt><a name="index-list_002dfunmap_002dnames"></a>Function: <strong>list-funmap-names</strong><em> <code>&amp;optional</code> filename append</em></dt> <dd><p>Print the names of all bindable Readline functions to stdout. If <var>filename</var> is supplied and it&rsquo;s a string or path, output will be redirected to the file. <var>append</var> allows append text to the file instead of overwriting it. </p></dd></dl> <dl> <dt><a name="index-funmap_002dnames"></a>Function: <strong>funmap-names</strong></dt> <dd><p>Return a list of known function names. The list is sorted. </p></dd></dl> <dl> <dt><a name="index-add_002dfunmap_002dentry"></a>Function: <strong>add-funmap-entry</strong><em> name function</em></dt> <dd><p>Add <var>name</var> to the list of bindable Readline command names, and make <var>function</var> the function to be called when name is invoked. </p></dd></dl> <hr> <a name="Allowing-Undoing"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Associating-Function-Names-and-Bindings" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Associating-Function-Names-and-Bindings" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Redisplay" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Redisplay" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Allowing-Undoing-1"></a> <h1 class="chapter">6 Allowing Undoing</h1> <a name="index-undoing"></a> <p>If your function simply inserts text once, or deletes text once, and uses <code>insert-text</code> or <code>delete-text</code> to do it, then undoing is already done for you automatically. </p> <p>If you do multiple insertions or multiple deletions, or any combination of these operations, you should group them together into one operation. This is done with <code>undo-group</code> macro. </p> <dl> <dt><a name="index-add_002dundo"></a>Function: <strong>add-undo</strong><em> what start end text</em></dt> <dd><p>Remember how to undo an event (according to <var>what</var>). The affected text runs from <var>start</var> to <var>end</var>, and encompasses <var>text</var>. Possible values of <var>what</var> include: <code>:undo-delete</code>, <code>:undo-insert</code>, <code>:undo-begin</code>, and <code>:undo-end</code> </p></dd></dl> <dl> <dt><a name="index-free_002dundo_002dlist"></a>Function: <strong>free-undo-list</strong></dt> <dd><p>Free the existing undo list. </p></dd></dl> <dl> <dt><a name="index-do_002dundo"></a>Function: <strong>do-undo</strong></dt> <dd><p>Undo the first thing on the undo list. Returns <code>nil</code> if there was nothing to undo, <code>t</code> if something was undone. </p></dd></dl> <dl> <dt><a name="index-modifying"></a>Function: <strong>modifying</strong><em> start end</em></dt> <dd><p>Tell Readline to save the text between <var>start</var> and <var>end</var> as a single undo unit. It is assumed that you will subsequently modify that text. </p></dd></dl> <dl> <dt><a name="index-undo_002dgroup"></a>Macro: <strong>undo-group</strong><em> <code>&amp;body</code> body</em></dt> <dd><p>All insertion and deletion inside this macro will be grouped together into one undo operation. </p></dd></dl> <hr> <a name="Redisplay"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Allowing-Undoing" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Allowing-Undoing" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Modifying-Text" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Modifying-Text" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Redisplay-1"></a> <h1 class="chapter">7 Redisplay</h1> <dl> <dt><a name="index-redisplay"></a>Function: <strong>redisplay</strong></dt> <dd><p>Change what&rsquo;s displayed on the screen to reflect the current contents of <var>*line-buffer*</var>. </p></dd></dl> <dl> <dt><a name="index-forced_002dupdate_002ddisplay"></a>Function: <strong>forced-update-display</strong></dt> <dd><p>Force the line to be updated and redisplayed, whether or not Readline thinks the screen display is correct. </p></dd></dl> <dl> <dt><a name="index-on_002dnew_002dline"></a>Function: <strong>on-new-line</strong><em> <code>&amp;optional</code> with-prompt</em></dt> <dd><p>Tell the update functions that we have moved onto a new (empty) line, usually after outputting a newline. When <var>with-prompt</var> is not <code>nil</code>, Readline will think that prompt is already displayed. This could be used by applications that want to output the prompt string themselves, but still need Readline to know the prompt string length for redisplay. This should be used together with <code>:already-prompted</code> keyword argument of <code>readline</code>. </p></dd></dl> <dl> <dt><a name="index-reset_002dline_002dstate"></a>Function: <strong>reset-line-state</strong></dt> <dd><p>Reset the display state to a clean state and redisplay the current line starting on a new line. </p></dd></dl> <dl> <dt><a name="index-cflr"></a>Function: <strong>cflr</strong></dt> <dd><p>Move the cursor to the start of the next screen line. </p></dd></dl> <dl> <dt><a name="index-show_002dchar"></a>Function: <strong>show-char</strong><em> char</em></dt> <dd><p>Display character <var>char</var> on outstream. If Readline has not been set to display meta characters directly, this will convert meta characters to a meta-prefixed key sequence. This is intended for use by applications which wish to do their own redisplay. </p></dd></dl> <dl> <dt><a name="index-set_002dprompt"></a>Function: <strong>set-prompt</strong><em> prompt</em></dt> <dd><p>Make Readline use <var>prompt</var> for subsequent redisplay. This calls <code>expand-prompt</code> to expand the prompt and sets <var>+prompt+</var> to the result. </p></dd></dl> <dl> <dt><a name="index-with_002dmessage"></a>Macro: <strong>with-message</strong><em> message save-prompt <code>&amp;body</code> body</em></dt> <dd><p>Show message <var>message</var> in the echo area while executing <var>body</var>. If <var>save-prompt</var> is not <code>nil</code>, save prompt before showing the message and restore it before clearing the message. </p></dd></dl> <hr> <a name="Modifying-Text"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Redisplay" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Redisplay" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Character-Input" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Character-Input" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Modifying-Text-1"></a> <h1 class="chapter">8 Modifying Text</h1> <dl> <dt><a name="index-insert_002dtext"></a>Function: <strong>insert-text</strong><em> text</em></dt> <dd><p>Insert <var>text</var> into the line at the current cursor position. Return the number of characters inserted. </p></dd></dl> <dl> <dt><a name="index-delete_002dtext"></a>Function: <strong>delete-text</strong><em> start end</em></dt> <dd><p>Delete the text between <var>start</var> and <var>end</var> in the current line. Return the number of characters deleted. </p></dd></dl> <dl> <dt><a name="index-kill_002dtext"></a>Function: <strong>kill-text</strong><em> start end</em></dt> <dd><p>Copy the text between <var>start</var> and <var>end</var> in the current line to the kill ring, appending or prepending to the last kill if the last command was a kill command. The text is deleted. If <var>start</var> is less than <var>end</var>, the text is appended, otherwise prepended. If the last command was not a kill, a new kill ring slot is used. </p></dd></dl> <hr> <a name="Character-Input"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Modifying-Text" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Modifying-Text" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Terminal-Management" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Terminal-Management" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Character-Input-1"></a> <h1 class="chapter">9 Character Input</h1> <dl> <dt><a name="index-read_002dkey"></a>Function: <strong>read-key</strong></dt> <dd><p>Return the next character available from Readline&rsquo;s current input stream. </p></dd></dl> <dl> <dt><a name="index-stuff_002dchar"></a>Function: <strong>stuff-char</strong><em> char</em></dt> <dd><p>Insert <var>char</var> into the Readline input stream. It will be «read» before Readline attempts to read characters from the terminal with <code>read-key</code>. Up to <code>512</code> characters may be pushed back. <code>stuff-char</code> returns <code>t</code> if the character was successfully inserted; <code>nil</code> otherwise. </p></dd></dl> <dl> <dt><a name="index-execute_002dnext"></a>Function: <strong>execute-next</strong><em> char</em></dt> <dd><p>Make <var>char</var> be the next command to be executed when <code>read-key</code> is called. </p></dd></dl> <dl> <dt><a name="index-clear_002dpending_002dinput"></a>Function: <strong>clear-pending-input</strong></dt> <dd><p>Negate the effect of any previous call to <code>execute-next</code>. This works only if the pending input has not already been read with <code>read-key</code>. </p></dd></dl> <dl> <dt><a name="index-set_002dkeyboard_002dinput_002dtimeout"></a>Function: <strong>set-keyboard-input-timeout</strong><em> u</em></dt> <dd><p>While waiting for keyboard input in <code>read-key</code>, Readline will wait for <var>u</var> microseconds for input before calling any function assigned to <code>event-hook</code>. <var>u</var> must be greater than or equal to zero (a zero-length timeout is equivalent to a poll). The default waiting period is one-tenth of a second. Return the old timeout value. </p></dd></dl> <hr> <a name="Terminal-Management"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Character-Input" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Character-Input" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Utility-Functions" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Utility-Functions" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Terminal-Management-1"></a> <h1 class="chapter">10 Terminal Management</h1> <dl> <dt><a name="index-prep_002dterminal"></a>Function: <strong>prep-terminal</strong><em> eight-bit-input</em></dt> <dd><p>Modify the terminal settings for Readline&rsquo;s use, so <code>readline</code> can read a single character at a time from the keyboard. The <code>eight-bit-input</code> argument should be non-<code>nil</code> if Readline should read eight-bit input. </p></dd></dl> <dl> <dt><a name="index-deprep_002dterminal"></a>Function: <strong>deprep-terminal</strong></dt> <dd><p>Undo the effects of <code>prep-terminal</code>, leaving the terminal in the state in which it was before the most recent call to <code>prep-terminal</code>. </p></dd></dl> <dl> <dt><a name="index-tty_002dset_002ddefault_002dbindings"></a>Function: <strong>tty-set-default-bindings</strong><em> keymap</em></dt> <dd><p>Read the operating system&rsquo;s terminal editing characters (as would be displayed by stty) to their Readline equivalents. The bindings are performed in <var>keymap</var>. </p></dd></dl> <dl> <dt><a name="index-tty_002dunset_002ddefault_002dbindings"></a>Function: <strong>tty-unset-default-bindings</strong><em> keymap</em></dt> <dd><p>Reset the bindings manipulated by <code>tty-set-default-bindings</code> so that the terminal editing characters are bound to <code>insert</code>. The bindings are performed in <var>keymap</var>. </p></dd></dl> <dl> <dt><a name="index-reset_002dterminal"></a>Function: <strong>reset-terminal</strong><em> terminal</em></dt> <dd><p>Reinitialize Readline&rsquo;s idea of the terminal settings using <var>terminal</var> as the terminal type (e.g., <code>&quot;vt100&quot;</code>). </p></dd></dl> <hr> <a name="Utility-Functions"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Terminal-Management" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Terminal-Management" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Miscellaneous-Functions" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Miscellaneous-Functions" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Utility-Functions-1"></a> <h1 class="chapter">11 Utility Functions</h1> <dl> <dt><a name="index-replace_002dline"></a>Function: <strong>replace-line</strong><em> text clear-undo</em></dt> <dd><p>Replace the contents of <var>*line-buffer*</var> with <var>text</var>. The point and mark are preserved, if possible. If <var>clear-undo</var> is non-<code>nil</code>, the undo list associated with the current line is cleared. </p></dd></dl> <dl> <dt><a name="index-extend_002dline_002dbuffer"></a>Function: <strong>extend-line-buffer</strong><em> len</em></dt> <dd><p>Ensure that line buffer has enough space to hold <var>len</var> characters, possibly reallocating it if necessary. </p></dd></dl> <dl> <dt><a name="index-initialize"></a>Function: <strong>initialize</strong></dt> <dd><p>Initialize or re-initialize Readline&rsquo;s internal state. It&rsquo;s not strictly necessary to call this; <code>readline</code> calls it before reading any input. cl-readline also makes sure that Readline is always initialized when you use it. </p></dd></dl> <dl> <dt><a name="index-ding"></a>Function: <strong>ding</strong></dt> <dd><p>Ring the terminal bell, obeying the setting of bell-style. </p></dd></dl> <hr> <a name="Miscellaneous-Functions"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Utility-Functions" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Utility-Functions" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Signal-Handling" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Signal-Handling" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Miscellaneous-Functions-1"></a> <h1 class="chapter">12 Miscellaneous Functions</h1> <dl> <dt><a name="index-macro_002ddumper"></a>Function: <strong>macro-dumper</strong><em> readable <code>&amp;optional</code> filename append</em></dt> <dd><p>Print the key sequences bound to macros and their values, using the current keymap to stdout. If <code>readable</code> is non-<code>nil</code>, the list is formatted in such a way that it can be made part of an inputrc file and re-read. If <code>filename</code> is supplied and it&rsquo;s a string or path, output will be redirected to the file. <code>append</code> allows to append text to the file instead of overwriting it. </p></dd></dl> <dl> <dt><a name="index-variable_002dbind"></a>Function: <strong>variable-bind</strong><em> variable value</em></dt> <dd><p>Make the Readline variable <var>variable</var> have <var>value</var>. This behaves as if the readline command <code>set variable value</code> had been executed in an inputrc file. </p></dd></dl> <dl> <dt><a name="index-variable_002dvalue"></a>Function: <strong>variable-value</strong><em> variable</em></dt> <dd><p>Return a string representing the value of the Readline variable <var>variable</var>. For Boolean variables, this string is either &rsquo;on&rsquo; or &rsquo;off&rsquo;. </p></dd></dl> <dl> <dt><a name="index-variable_002ddumper"></a>Function: <strong>variable-dumper</strong><em> readable <code>&amp;optional</code> filename append</em></dt> <dd><p>Print the readline variable names and their current values to stdout. If readable is not <code>nil</code>, the list is formatted in such a way that it can be made part of an inputrc file and re-read. If <var>filename</var> is supplied and it&rsquo;s a string or path, output will be redirected to the file. <var>append</var> allows to append text to the file instead of overwriting it. </p></dd></dl> <dl> <dt><a name="index-set_002dparen_002dblink_002dtimeout"></a>Function: <strong>set-paren-blink-timeout</strong><em> micros</em></dt> <dd><p>Set the time interval (in microseconds) that Readline waits when showing a balancing character when <code>blink-matching-paren</code> has been enabled. The function returns previous value of the parameter. </p></dd></dl> <dl> <dt><a name="index-clear_002dhistory"></a>Function: <strong>clear-history</strong></dt> <dd><p>Clear the history list by deleting all of the entries. </p></dd></dl> <hr> <a name="Signal-Handling"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Miscellaneous-Functions" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Miscellaneous-Functions" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Example" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Example" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Signal-Handling-1"></a> <h1 class="chapter">13 Signal Handling</h1> <a name="index-signals"></a> <p>Signals are asynchronous events sent to a process by the Unix kernel, sometimes on behalf of another process. They are intended to indicate exceptional events, like a user pressing the interrupt key on his terminal, or a network connection being broken. There is a class of signals that can be sent to the process currently reading input from the keyboard. Since Readline changes the terminal attributes when it is called, it needs to perform special processing when such a signal is received in order to restore the terminal to a sane state, or provide application writers with functions to do so manually. </p> <p>Readline contains an internal signal handler that is installed for a number of signals (SIGINT, SIGQUIT, SIGTERM, SIGHUP, SIGALRM, SIGTSTP, SIGTTIN, and SIGTTOU). When one of these signals is received, the signal handler will reset the terminal attributes to those that were in effect before <code>readline</code> was called, reset the signal handling to what it was before <code>readline</code> was called, and resend the signal to the calling application. If and when the calling application&rsquo;s signal handler returns, Readline will reinitialize the terminal and continue to accept input. When a SIGINT is received, the Readline signal handler performs some additional work, which will cause any partially-entered line to be aborted (see the description of <code>free-line-state</code> below). </p> <p>There is an additional Readline signal handler, for SIGWINCH, which the kernel sends to a process whenever the terminal&rsquo;s size changes (for example, if a user resizes an xterm). The Readline SIGWINCH handler updates Readline&rsquo;s internal screen size information, and then calls any SIGWINCH signal handler the calling application has installed. Readline calls the application&rsquo;s SIGWINCH signal handler without resetting the terminal to its original state. If the application&rsquo;s signal handler does more than update its idea of the terminal size and return (for example, a longjmp back to a main processing loop), it must call <code>cleanup-after-signal</code> (described below), to restore the terminal state. </p> <p>Readline provides two variables that allow application writers to control whether or not it will catch certain signals and act on them when they are received. It is important that applications change the values of these variables only when calling <code>readline</code>, not in a signal handler, so Readline&rsquo;s internal signal state is not corrupted. </p> <dl> <dt><a name="index-_002acatch_002dsignals_002a"></a>Symbol macro: <strong>*catch-signals*</strong></dt> <dd><p>Boolean. If this variable is non-<code>nil</code>, Readline will install signal handlers for SIGINT, SIGQUIT, SIGTERM, SIGHUP, SIGALRM, SIGTSTP, SIGTTIN, and SIGTTOU. The default value of <var>*catch-signals*</var> is <code>t</code>. </p></dd></dl> <dl> <dt><a name="index-_002acatch_002dsigwinch_002a"></a>Symbol macro: <strong>*catch-sigwinch*</strong></dt> <dd><p>If this variable is set to a non-<code>nil</code> value, Readline will install a signal handler for SIGWINCH. The default value of <var>*catch-sigwinch*</var> is <code>t</code>. </p></dd></dl> <dl> <dt><a name="index-_002achange_002denvironment_002a"></a>Symbol macro: <strong>*change-environment*</strong></dt> <dd><p>If this variable is set to a non-<code>nil</code> value, and Readline is handling SIGWINCH, Readline will modify the LINES and COLUMNS environment variables upon receipt of a SIGWINCH. The default value of <var>*change-environment*</var> is <code>t</code>. </p></dd></dl> <dl> <dt><a name="index-cleanup_002dafter_002dsignal"></a>Function: <strong>cleanup-after-signal</strong></dt> <dd><p>This function will reset the state of the terminal to what it was before <code>readline</code> was called, and remove the Readline signal handlers for all signals, depending on the values of <var>*catch-signals*</var> and <var>*catch-sigwinch*</var>. </p></dd></dl> <dl> <dt><a name="index-free_002dline_002dstate"></a>Function: <strong>free-line-state</strong></dt> <dd><p>This will free any partial state associated with the current input line (undo information, any partial history entry, any partially-entered keyboard macro, and any partially-entered numeric argument). This should be called before <code>cleanup-after-signal</code>. The Readline signal handler for SIGINT calls this to abort the current input line. </p></dd></dl> <dl> <dt><a name="index-reset_002dafter_002dsignal"></a>Function: <strong>reset-after-signal</strong></dt> <dd><p>This will reinitialize the terminal and reinstall any Readline signal handlers, depending on the values of <var>*catch-signals*</var> and <var>*catch-sigwinch*</var>. </p></dd></dl> <dl> <dt><a name="index-echo_002dsignal_002dchar"></a>Function: <strong>echo-signal-char</strong><em> sig</em></dt> <dd><p>If an application wishes to install its own signal handlers, but still have readline display characters that generate signals, calling this function with <var>sig</var> set to <code>:sigint</code>, <code>:sigquit</code>, or <code>:sigtstp</code> will display the character generating that signal. </p></dd></dl> <dl> <dt><a name="index-resize_002dterminal"></a>Function: <strong>resize-terminal</strong></dt> <dd><p>Update Readline&rsquo;s internal screen size by reading values from the kernel. </p></dd></dl> <dl> <dt><a name="index-set_002dscreen_002dsize"></a>Function: <strong>set-screen-size</strong><em> rows cols</em></dt> <dd><p>Set Readline&rsquo;s idea of the terminal size to <var>rows</var> rows and <var>cols</var> columns. If either rows or columns is less than or equal to <code>0</code>, Readline&rsquo;s idea of that terminal dimension is unchanged. </p></dd></dl> <dl> <dt><a name="index-get_002dscreen_002dsize"></a>Function: <strong>get-screen-size</strong></dt> <dd><p>Return Readline&rsquo;s idea of the terminal&rsquo;s size. The function returns multiple values: number of rows and columns. </p></dd></dl> <dl> <dt><a name="index-reset_002dscreen_002dsize"></a>Function: <strong>reset-screen-size</strong></dt> <dd><p>Cause Readline to reobtain the screen size and recalculate its dimensions. </p></dd></dl> <dl> <dt><a name="index-set_002dsignals"></a>Function: <strong>set-signals</strong></dt> <dd><p>Install Readline&rsquo;s signal handler for SIGINT, SIGQUIT, SIGTERM, SIGHUP, SIGALRM, SIGTSTP, SIGTTIN, SIGTTOU, and SIGWINCH, depending on the values of <var>*catch-signals*</var> and <var>*catch-sigwinch*</var>. </p></dd></dl> <dl> <dt><a name="index-clear_002dsignals"></a>Function: <strong>clear-signals</strong></dt> <dd><p>Remove all of the Readline signal handlers installed by <code>set-signals</code>. </p></dd></dl> <hr> <a name="Example"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Signal-Handling" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Signal-Handling" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#GNU-Free-Documentation-License" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#GNU-Free-Documentation-License" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Example-1"></a> <h1 class="chapter">14 Example</h1> <p>This program demonstrates some basic capacities of cl-readline. Note that you should run it in terminal, not via SLIME. </p> <div class="example"> <pre class="example">;;; Load some systems and define a package... (asdf:load-system :alexandria) (asdf:load-system :cl-readline) (cl:defpackage :example (:use #:common-lisp #:alexandria) (:export #:run-example)) (in-package :example) ;;; Now let's define lists of verbs and fruits: (defvar *verbs* '(&quot;eat&quot; &quot;get&quot; &quot;throw&quot; &quot;quit&quot;)) (defvar *fruits* '(&quot;banana&quot; &quot;apple&quot; &quot;orange&quot; &quot;banana_two&quot;)) ;;; Define and register function that does custom completion: if user enters ;;; first word, it will be completed as a verb, second and later words will ;;; be completed as fruits. (defun custom-complete (text start end) (declare (ignore end)) (labels ((common-prefix (items) (subseq (car items) 0 (position nil (mapcar (lambda (i) (every (lambda (x) (char= (char (car items) i) (char x i))) (cdr items))) (iota (reduce #'min (mapcar #'length items))))))) (select-completions (list) (let ((els (remove-if-not (curry #'starts-with-subseq text) list))) (if (cdr els) (cons (common-prefix els) els) els)))) (if (zerop start) (select-completions *verbs*) (select-completions *fruits*)))) (rl:register-function :complete #'custom-complete) ;;; Let's also create a custom command and bind it to some key sequence so ;;; user can invoke it. In this example user can automagically insert phrase ;;; 'inserted text' pressing Control-o. (defun print-some-text (arg key) (declare (ignore arg key)) (rl:insert-text &quot;inserted text&quot;)) (rl:bind-keyseq &quot;\\C-o&quot; #'print-some-text) ;;; Let's write novelty-check, so if the actual line is equal to the most ;;; recent history line it will not be added to the history. (defun novelty-check (x y) (string/= (string-trim &quot; &quot; x) (string-trim &quot; &quot; y))) ;;; Finally, this is our main function. To exit from the loop, enter 'quit'. (defun run-example () (do ((i 0 (1+ i)) (text &quot;&quot;)) ((string= &quot;quit&quot; (string-trim &quot; &quot; text))) (setf text (rl:readline :prompt (format nil &quot;[~a]&gt; &quot; i) :add-history t :novelty-check #'novelty-check)))) </pre></div> <hr> <a name="GNU-Free-Documentation-License"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Example" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Example" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="GNU-Free-Documentation-License-1"></a> <h1 class="appendix">Appendix A GNU Free Documentation License</h1> <p align="center">Version 1.3, 3 November 2008 </p> <div class="display"> <pre class="display">Copyright &copy; 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. <a href="http://fsf.org/">http://fsf.org/</a> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. </pre></div> <ol> <li> PREAMBLE <p>The purpose of this License is to make a manual, textbook, or other functional and useful document <em>free</em> in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. </p> <p>This License is a kind of &ldquo;copyleft&rdquo;, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. </p> <p>We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. </p> </li><li> APPLICABILITY AND DEFINITIONS <p>This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The &ldquo;Document&rdquo;, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as &ldquo;you&rdquo;. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. </p> <p>A &ldquo;Modified Version&rdquo; of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. </p> <p>A &ldquo;Secondary Section&rdquo; is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document&rsquo;s overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. </p> <p>The &ldquo;Invariant Sections&rdquo; are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. </p> <p>The &ldquo;Cover Texts&rdquo; are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. </p> <p>A &ldquo;Transparent&rdquo; copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not &ldquo;Transparent&rdquo; is called &ldquo;Opaque&rdquo;. </p> <p>Examples of suitable formats for Transparent copies include plain <small>ASCII</small> without markup, Texinfo input format, LaTeX input format, <acronym>SGML</acronym> or <acronym>XML</acronym> using a publicly available <acronym>DTD</acronym>, and standard-conforming simple <acronym>HTML</acronym>, PostScript or <acronym>PDF</acronym> designed for human modification. Examples of transparent image formats include <acronym>PNG</acronym>, <acronym>XCF</acronym> and <acronym>JPG</acronym>. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, <acronym>SGML</acronym> or <acronym>XML</acronym> for which the <acronym>DTD</acronym> and/or processing tools are not generally available, and the machine-generated <acronym>HTML</acronym>, PostScript or <acronym>PDF</acronym> produced by some word processors for output purposes only. </p> <p>The &ldquo;Title Page&rdquo; means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, &ldquo;Title Page&rdquo; means the text near the most prominent appearance of the work&rsquo;s title, preceding the beginning of the body of the text. </p> <p>The &ldquo;publisher&rdquo; means any person or entity that distributes copies of the Document to the public. </p> <p>A section &ldquo;Entitled XYZ&rdquo; means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as &ldquo;Acknowledgements&rdquo;, &ldquo;Dedications&rdquo;, &ldquo;Endorsements&rdquo;, or &ldquo;History&rdquo;.) To &ldquo;Preserve the Title&rdquo; of such a section when you modify the Document means that it remains a section &ldquo;Entitled XYZ&rdquo; according to this definition. </p> <p>The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. </p> </li><li> VERBATIM COPYING <p>You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. </p> <p>You may also lend copies, under the same conditions stated above, and you may publicly display copies. </p> </li><li> COPYING IN QUANTITY <p>If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document&rsquo;s license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. </p> <p>If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. </p> <p>If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. </p> <p>It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. </p> </li><li> MODIFICATIONS <p>You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: </p> <ol> <li> Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. </li><li> List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. </li><li> State on the Title page the name of the publisher of the Modified Version, as the publisher. </li><li> Preserve all the copyright notices of the Document. </li><li> Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. </li><li> Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. </li><li> Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document&rsquo;s license notice. </li><li> Include an unaltered copy of this License. </li><li> Preserve the section Entitled &ldquo;History&rdquo;, Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled &ldquo;History&rdquo; in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. </li><li> Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the &ldquo;History&rdquo; section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. </li><li> For any section Entitled &ldquo;Acknowledgements&rdquo; or &ldquo;Dedications&rdquo;, Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. </li><li> Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. </li><li> Delete any section Entitled &ldquo;Endorsements&rdquo;. Such a section may not be included in the Modified Version. </li><li> Do not retitle any existing section to be Entitled &ldquo;Endorsements&rdquo; or to conflict in title with any Invariant Section. </li><li> Preserve any Warranty Disclaimers. </li></ol> <p>If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version&rsquo;s license notice. These titles must be distinct from any other section titles. </p> <p>You may add a section Entitled &ldquo;Endorsements&rdquo;, provided it contains nothing but endorsements of your Modified Version by various parties&mdash;for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. </p> <p>You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. </p> <p>The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. </p> </li><li> COMBINING DOCUMENTS <p>You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. </p> <p>The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. </p> <p>In the combination, you must combine any sections Entitled &ldquo;History&rdquo; in the various original documents, forming one section Entitled &ldquo;History&rdquo;; likewise combine any sections Entitled &ldquo;Acknowledgements&rdquo;, and any sections Entitled &ldquo;Dedications&rdquo;. You must delete all sections Entitled &ldquo;Endorsements.&rdquo; </p> </li><li> COLLECTIONS OF DOCUMENTS <p>You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. </p> <p>You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. </p> </li><li> AGGREGATION WITH INDEPENDENT WORKS <p>A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an &ldquo;aggregate&rdquo; if the copyright resulting from the compilation is not used to limit the legal rights of the compilation&rsquo;s users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. </p> <p>If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document&rsquo;s Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. </p> </li><li> TRANSLATION <p>Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. </p> <p>If a section in the Document is Entitled &ldquo;Acknowledgements&rdquo;, &ldquo;Dedications&rdquo;, or &ldquo;History&rdquo;, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. </p> </li><li> TERMINATION <p>You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. </p> <p>However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. </p> <p>Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. </p> <p>Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it. </p> </li><li> FUTURE REVISIONS OF THIS LICENSE <p>The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See <a href="http://www.gnu.org/copyleft/">http://www.gnu.org/copyleft/</a>. </p> <p>Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License &ldquo;or any later version&rdquo; applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy&rsquo;s public statement of acceptance of a version permanently authorizes you to choose that version for the Document. </p> </li><li> RELICENSING <p>&ldquo;Massive Multiauthor Collaboration Site&rdquo; (or &ldquo;MMC Site&rdquo;) means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A &ldquo;Massive Multiauthor Collaboration&rdquo; (or &ldquo;MMC&rdquo;) contained in the site means any set of copyrightable works thus published on the MMC site. </p> <p>&ldquo;CC-BY-SA&rdquo; means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. </p> <p>&ldquo;Incorporate&rdquo; means to publish or republish a Document, in whole or in part, as part of another Document. </p> <p>An MMC is &ldquo;eligible for relicensing&rdquo; if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. </p> <p>The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing. </p> </li></ol> <a name="ADDENDUM_003a-How-to-use-this-License-for-your-documents"></a> <h2 class="heading">ADDENDUM: How to use this License for your documents</h2> <p>To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: </p> <div class="smallexample"> <pre class="smallexample"> Copyright (C) <var>year</var> <var>your name</var>. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. </pre></div> <p>If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the &ldquo;with&hellip;Texts.&rdquo; line with this: </p> <div class="smallexample"> <pre class="smallexample"> with the Invariant Sections being <var>list their titles</var>, with the Front-Cover Texts being <var>list</var>, and with the Back-Cover Texts being <var>list</var>. </pre></div> <p>If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. </p> <p>If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software. </p> <hr> <a name="Concept-Index"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#GNU-Free-Documentation-License" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#GNU-Free-Documentation-License" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[<a href="#Function-and-Variable-Index" title="Next section in reading order"> &gt; </a>]</td> <td valign="middle" align="left">[<a href="#Function-and-Variable-Index" title="Next chapter"> &gt;&gt; </a>]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Concept-Index-1"></a> <h1 class="unnumbered">Concept Index</h1> <table><tr><th valign="top">Jump to: &nbsp; </th><td><a class="summary-letter" href="#Concept-Index-1_cp_letter-C"><b>C</b></a> &nbsp; <a class="summary-letter" href="#Concept-Index-1_cp_letter-H"><b>H</b></a> &nbsp; <a class="summary-letter" href="#Concept-Index-1_cp_letter-K"><b>K</b></a> &nbsp; <a class="summary-letter" href="#Concept-Index-1_cp_letter-R"><b>R</b></a> &nbsp; <a class="summary-letter" href="#Concept-Index-1_cp_letter-S"><b>S</b></a> &nbsp; <a class="summary-letter" href="#Concept-Index-1_cp_letter-U"><b>U</b></a> &nbsp; </td></tr></table> <table class="index-cp" border="0"> <tr><td></td><th align="left">Index Entry</th><td>&nbsp;</td><th align="left"> Section</th></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Concept-Index-1_cp_letter-C">C</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-completion-types">completion types</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-custom-functions">custom functions</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Concept-Index-1_cp_letter-H">H</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-hooks">hooks</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Concept-Index-1_cp_letter-K">K</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-keymaps">keymaps</a></td><td>&nbsp;</td><td valign="top"><a href="#Work-with-Keymaps">3 Work with Keymaps</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Concept-Index-1_cp_letter-R">R</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-readline-state">readline state</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-readline_002c-function">readline, function</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Concept-Index-1_cp_letter-S">S</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-signals">signals</a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Concept-Index-1_cp_letter-U">U</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-undoing">undoing</a></td><td>&nbsp;</td><td valign="top"><a href="#Allowing-Undoing">6 Allowing Undoing</a></td></tr> <tr><td colspan="4"> <hr></td></tr> </table> <table><tr><th valign="top">Jump to: &nbsp; </th><td><a class="summary-letter" href="#Concept-Index-1_cp_letter-C"><b>C</b></a> &nbsp; <a class="summary-letter" href="#Concept-Index-1_cp_letter-H"><b>H</b></a> &nbsp; <a class="summary-letter" href="#Concept-Index-1_cp_letter-K"><b>K</b></a> &nbsp; <a class="summary-letter" href="#Concept-Index-1_cp_letter-R"><b>R</b></a> &nbsp; <a class="summary-letter" href="#Concept-Index-1_cp_letter-S"><b>S</b></a> &nbsp; <a class="summary-letter" href="#Concept-Index-1_cp_letter-U"><b>U</b></a> &nbsp; </td></tr></table> <hr> <a name="Function-and-Variable-Index"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Concept-Index" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Previous section in reading order"> &lt; </a>]</td> <td valign="middle" align="left">[<a href="#Top" title="Up section"> Up </a>]</td> <td valign="middle" align="left">[ &gt; ]</td> <td valign="middle" align="left">[ &gt;&gt; ]</td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left"> &nbsp; </td> <td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <a name="Function-and-Variable-Index-1"></a> <h1 class="unnumbered">Function and Variable Index</h1> <table><tr><th valign="top">Jump to: &nbsp; </th><td><a class="summary-letter" href="#Function-and-Variable-Index-1_fn_symbol-1"><b>*</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_symbol-2"><b>+</b></a> &nbsp; <br> <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-A"><b>A</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-B"><b>B</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-C"><b>C</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-D"><b>D</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-E"><b>E</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-F"><b>F</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-G"><b>G</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-I"><b>I</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-K"><b>K</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-L"><b>L</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-M"><b>M</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-O"><b>O</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-P"><b>P</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-R"><b>R</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-S"><b>S</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-T"><b>T</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-U"><b>U</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-V"><b>V</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-W"><b>W</b></a> &nbsp; </td></tr></table> <table class="index-fn" border="0"> <tr><td></td><th align="left">Index Entry</th><td>&nbsp;</td><th align="left"> Section</th></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_symbol-1">*</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-_002abasic_002dquote_002dcharacters_002a">*basic-quote-characters*</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002abasic_002dword_002dbreak_002dcharacters_002a">*basic-word-break-characters*</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002acatch_002dsignals_002a">*catch-signals*</a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002acatch_002dsigwinch_002a">*catch-sigwinch*</a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002achange_002denvironment_002a">*change-environment*</a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002acompleter_002dword_002dbreak_002dcharacters_002a">*completer-word-break-characters*</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002acompletion_002dappend_002dcharacter_002a">*completion-append-character*</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002acompletion_002dquery_002ditems_002a">*completion-query-items*</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002adisplay_002dprompt_002a">*display-prompt*</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002adone_002a">*done*</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002aignore_002dcompletion_002dduplicates_002a">*ignore-completion-duplicates*</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002ainhibit_002dcompletion_002a">*inhibit-completion*</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002aline_002dbuffer_002a">*line-buffer*</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002amark_002a">*mark*</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002apoint_002a">*point*</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002areadline_002dname_002a">*readline-name*</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002asort_002dcompletion_002dmatches_002a">*sort-completion-matches*</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_symbol-2">+</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bbinding_002dkeymap_002b">+binding-keymap+</a></td><td>&nbsp;</td><td valign="top"><a href="#Work-with-Keymaps">3 Work with Keymaps</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bcompletion_002dtype_002b">+completion-type+</a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bdispatching_002b">+dispatching+</a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bediting_002dmode_002b">+editing-mode+</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bend_002b">+end+</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bexecuting_002dkey_002b">+executing-key+</a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bexecuting_002dkeymap_002b">+executing-keymap+</a></td><td>&nbsp;</td><td valign="top"><a href="#Work-with-Keymaps">3 Work with Keymaps</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bexecuting_002dkeyseq_002b">+executing-keyseq+</a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bexecuting_002dmacro_002b">+executing-macro+</a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bgnu_002dreadline_002dp_002b">+gnu-readline-p+</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bkey_002dsequence_002dlength_002b">+key-sequence-length+</a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002blibrary_002dversion_002b">+library-version+</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002bprompt_002b">+prompt+</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002breadline_002dstate_002b">+readline-state+</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-_002breadline_002dversion_002b">+readline-version+</a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-A">A</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-add_002ddefun"><code>add-defun</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td></td><td valign="top"><a href="#index-add_002dfunmap_002dentry"><code>add-funmap-entry</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Associating-Function-Names-and-Bindings">5 Associating Function Names and Bindings</a></td></tr> <tr><td></td><td valign="top"><a href="#index-add_002dundo"><code>add-undo</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Allowing-Undoing">6 Allowing Undoing</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-B">B</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-bind_002dkey"><code>bind-key</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td></td><td valign="top"><a href="#index-bind_002dkeyseq"><code>bind-keyseq</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-C">C</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-cflr"><code>cflr</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Redisplay">7 Redisplay</a></td></tr> <tr><td></td><td valign="top"><a href="#index-cleanup_002dafter_002dsignal"><code>cleanup-after-signal</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td></td><td valign="top"><a href="#index-clear_002dhistory"><code>clear-history</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Miscellaneous-Functions">12 Miscellaneous Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-clear_002dpending_002dinput"><code>clear-pending-input</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Character-Input">9 Character Input</a></td></tr> <tr><td></td><td valign="top"><a href="#index-clear_002dsignals"><code>clear-signals</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td></td><td valign="top"><a href="#index-copy_002dkeymap"><code>copy-keymap</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Work-with-Keymaps">3 Work with Keymaps</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-D">D</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-delete_002dtext"><code>delete-text</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Modifying-Text">8 Modifying Text</a></td></tr> <tr><td></td><td valign="top"><a href="#index-deprep_002dterminal"><code>deprep-terminal</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Terminal-Management">10 Terminal Management</a></td></tr> <tr><td></td><td valign="top"><a href="#index-ding"><code>ding</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Utility-Functions">11 Utility Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-do_002dundo"><code>do-undo</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Allowing-Undoing">6 Allowing Undoing</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-E">E</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-echo_002dsignal_002dchar"><code>echo-signal-char</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td></td><td valign="top"><a href="#index-execute_002dnext"><code>execute-next</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Character-Input">9 Character Input</a></td></tr> <tr><td></td><td valign="top"><a href="#index-extend_002dline_002dbuffer"><code>extend-line-buffer</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Utility-Functions">11 Utility Functions</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-F">F</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-forced_002dupdate_002ddisplay"><code>forced-update-display</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Redisplay">7 Redisplay</a></td></tr> <tr><td></td><td valign="top"><a href="#index-free_002dkeymap"><code>free-keymap</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Work-with-Keymaps">3 Work with Keymaps</a></td></tr> <tr><td></td><td valign="top"><a href="#index-free_002dline_002dstate"><code>free-line-state</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td></td><td valign="top"><a href="#index-free_002dundo_002dlist"><code>free-undo-list</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Allowing-Undoing">6 Allowing Undoing</a></td></tr> <tr><td></td><td valign="top"><a href="#index-function_002ddumper"><code>function-dumper</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Associating-Function-Names-and-Bindings">5 Associating Function Names and Bindings</a></td></tr> <tr><td></td><td valign="top"><a href="#index-funmap_002dnames"><code>funmap-names</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Associating-Function-Names-and-Bindings">5 Associating Function Names and Bindings</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-G">G</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-get_002dkeymap"><code>get-keymap</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Work-with-Keymaps">3 Work with Keymaps</a></td></tr> <tr><td></td><td valign="top"><a href="#index-get_002dkeymap_002dby_002dname"><code>get-keymap-by-name</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Work-with-Keymaps">3 Work with Keymaps</a></td></tr> <tr><td></td><td valign="top"><a href="#index-get_002dscreen_002dsize"><code>get-screen-size</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-I">I</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-initialize"><code>initialize</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Utility-Functions">11 Utility Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-insert_002dtext"><code>insert-text</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Modifying-Text">8 Modifying Text</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-K">K</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-kill_002dtext"><code>kill-text</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Modifying-Text">8 Modifying Text</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-L">L</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-list_002dfunmap_002dnames"><code>list-funmap-names</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Associating-Function-Names-and-Bindings">5 Associating Function Names and Bindings</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-M">M</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-macro_002ddumper"><code>macro-dumper</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Miscellaneous-Functions">12 Miscellaneous Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-make_002dkeymap"><code>make-keymap</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Work-with-Keymaps">3 Work with Keymaps</a></td></tr> <tr><td></td><td valign="top"><a href="#index-modifying"><code>modifying</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Allowing-Undoing">6 Allowing Undoing</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-O">O</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-on_002dnew_002dline"><code>on-new-line</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Redisplay">7 Redisplay</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-P">P</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-parse_002dand_002dbind"><code>parse-and-bind</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td></td><td valign="top"><a href="#index-prep_002dterminal"><code>prep-terminal</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Terminal-Management">10 Terminal Management</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-R">R</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-read_002dinit_002dfile"><code>read-init-file</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td></td><td valign="top"><a href="#index-read_002dkey"><code>read-key</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Character-Input">9 Character Input</a></td></tr> <tr><td></td><td valign="top"><a href="#index-readline"><code>readline</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Basic-Functionality">1 Basic Functionality</a></td></tr> <tr><td></td><td valign="top"><a href="#index-redisplay"><code>redisplay</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Redisplay">7 Redisplay</a></td></tr> <tr><td></td><td valign="top"><a href="#index-register_002dfunction"><code>register-function</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-register_002dhook"><code>register-hook</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-replace_002dline"><code>replace-line</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Utility-Functions">11 Utility Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-reset_002dafter_002dsignal"><code>reset-after-signal</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td></td><td valign="top"><a href="#index-reset_002dline_002dstate"><code>reset-line-state</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Redisplay">7 Redisplay</a></td></tr> <tr><td></td><td valign="top"><a href="#index-reset_002dscreen_002dsize"><code>reset-screen-size</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td></td><td valign="top"><a href="#index-reset_002dterminal"><code>reset-terminal</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Terminal-Management">10 Terminal Management</a></td></tr> <tr><td></td><td valign="top"><a href="#index-resize_002dterminal"><code>resize-terminal</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-S">S</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-set_002dkeyboard_002dinput_002dtimeout"><code>set-keyboard-input-timeout</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Character-Input">9 Character Input</a></td></tr> <tr><td></td><td valign="top"><a href="#index-set_002dkeymap"><code>set-keymap</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Work-with-Keymaps">3 Work with Keymaps</a></td></tr> <tr><td></td><td valign="top"><a href="#index-set_002dparen_002dblink_002dtimeout"><code>set-paren-blink-timeout</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Miscellaneous-Functions">12 Miscellaneous Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-set_002dprompt"><code>set-prompt</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Redisplay">7 Redisplay</a></td></tr> <tr><td></td><td valign="top"><a href="#index-set_002dscreen_002dsize"><code>set-screen-size</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td></td><td valign="top"><a href="#index-set_002dsignals"><code>set-signals</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Signal-Handling">13 Signal Handling</a></td></tr> <tr><td></td><td valign="top"><a href="#index-show_002dchar"><code>show-char</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Redisplay">7 Redisplay</a></td></tr> <tr><td></td><td valign="top"><a href="#index-stuff_002dchar"><code>stuff-char</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Character-Input">9 Character Input</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-T">T</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-tty_002dset_002ddefault_002dbindings"><code>tty-set-default-bindings</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Terminal-Management">10 Terminal Management</a></td></tr> <tr><td></td><td valign="top"><a href="#index-tty_002dunset_002ddefault_002dbindings"><code>tty-unset-default-bindings</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Terminal-Management">10 Terminal Management</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-U">U</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-unbind_002dcommand"><code>unbind-command</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td></td><td valign="top"><a href="#index-unbind_002dkey"><code>unbind-key</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Binding-Keys">4 Binding Keys</a></td></tr> <tr><td></td><td valign="top"><a href="#index-undo_002dgroup"><code>undo-group</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Allowing-Undoing">6 Allowing Undoing</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-V">V</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-variable_002dbind"><code>variable-bind</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Miscellaneous-Functions">12 Miscellaneous Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-variable_002ddumper"><code>variable-dumper</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Miscellaneous-Functions">12 Miscellaneous Functions</a></td></tr> <tr><td></td><td valign="top"><a href="#index-variable_002dvalue"><code>variable-value</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Miscellaneous-Functions">12 Miscellaneous Functions</a></td></tr> <tr><td colspan="4"> <hr></td></tr> <tr><th><a name="Function-and-Variable-Index-1_fn_letter-W">W</a></th><td></td><td></td></tr> <tr><td></td><td valign="top"><a href="#index-with_002dmessage"><code>with-message</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Redisplay">7 Redisplay</a></td></tr> <tr><td></td><td valign="top"><a href="#index-with_002dnew_002dkeymap"><code>with-new-keymap</code></a></td><td>&nbsp;</td><td valign="top"><a href="#Work-with-Keymaps">3 Work with Keymaps</a></td></tr> <tr><td colspan="4"> <hr></td></tr> </table> <table><tr><th valign="top">Jump to: &nbsp; </th><td><a class="summary-letter" href="#Function-and-Variable-Index-1_fn_symbol-1"><b>*</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_symbol-2"><b>+</b></a> &nbsp; <br> <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-A"><b>A</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-B"><b>B</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-C"><b>C</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-D"><b>D</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-E"><b>E</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-F"><b>F</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-G"><b>G</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-I"><b>I</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-K"><b>K</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-L"><b>L</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-M"><b>M</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-O"><b>O</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-P"><b>P</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-R"><b>R</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-S"><b>S</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-T"><b>T</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-U"><b>U</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-V"><b>V</b></a> &nbsp; <a class="summary-letter" href="#Function-and-Variable-Index-1_fn_letter-W"><b>W</b></a> &nbsp; </td></tr></table> <hr size="6"> <a name="SEC_Contents"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <h1>Table of Contents</h1> <div class="contents"> <ul class="no-bullet"> <li><a name="toc-Basic-Functionality-1" href="#Basic-Functionality">1 Basic Functionality</a></li> <li><a name="toc-Hooks-and-Custom-Functions-1" href="#Hooks-and-Custom-Functions">2 Hooks and Custom Functions</a></li> <li><a name="toc-Work-with-Keymaps-1" href="#Work-with-Keymaps">3 Work with Keymaps</a></li> <li><a name="toc-Binding-Keys-1" href="#Binding-Keys">4 Binding Keys</a></li> <li><a name="toc-Associating-Function-Names-and-Bindings-1" href="#Associating-Function-Names-and-Bindings">5 Associating Function Names and Bindings</a></li> <li><a name="toc-Allowing-Undoing-1" href="#Allowing-Undoing">6 Allowing Undoing</a></li> <li><a name="toc-Redisplay-1" href="#Redisplay">7 Redisplay</a></li> <li><a name="toc-Modifying-Text-1" href="#Modifying-Text">8 Modifying Text</a></li> <li><a name="toc-Character-Input-1" href="#Character-Input">9 Character Input</a></li> <li><a name="toc-Terminal-Management-1" href="#Terminal-Management">10 Terminal Management</a></li> <li><a name="toc-Utility-Functions-1" href="#Utility-Functions">11 Utility Functions</a></li> <li><a name="toc-Miscellaneous-Functions-1" href="#Miscellaneous-Functions">12 Miscellaneous Functions</a></li> <li><a name="toc-Signal-Handling-1" href="#Signal-Handling">13 Signal Handling</a></li> <li><a name="toc-Example-1" href="#Example">14 Example</a></li> <li><a name="toc-GNU-Free-Documentation-License-1" href="#GNU-Free-Documentation-License">Appendix A GNU Free Documentation License</a></li> <li><a name="toc-Concept-Index-1" href="#Concept-Index">Concept Index</a></li> <li><a name="toc-Function-and-Variable-Index-1" href="#Function-and-Variable-Index">Function and Variable Index</a></li> </ul> </div> <hr> <a name="SEC_About"></a> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left">[<a href="#Top" title="Cover (top) of document">Top</a>]</td> <td valign="middle" align="left">[<a href="#SEC_Contents" title="Table of contents">Contents</a>]</td> <td valign="middle" align="left">[<a href="#Concept-Index" title="Index">Index</a>]</td> <td valign="middle" align="left">[<a href="#SEC_About" title="About (help)"> ? </a>]</td> </tr></table> <h1>About This Document</h1> <p> This document was generated on <i>June 18, 2015</i> using <a href="http://www.nongnu.org/texi2html/"><i>texi2html 5.0</i></a>. </p> <p> The buttons in the navigation panels have the following meaning: </p> <table border="1"> <tr> <th> Button </th> <th> Name </th> <th> Go to </th> <th> From 1.2.3 go to</th> </tr> <tr> <td align="center"> [ &lt;&lt; ] </td> <td align="center">FastBack</td> <td>Beginning of this chapter or previous chapter</td> <td>1</td> </tr> <tr> <td align="center"> [ &lt; ] </td> <td align="center">Back</td> <td>Previous section in reading order</td> <td>1.2.2</td> </tr> <tr> <td align="center"> [ Up ] </td> <td align="center">Up</td> <td>Up section</td> <td>1.2</td> </tr> <tr> <td align="center"> [ &gt; ] </td> <td align="center">Forward</td> <td>Next section in reading order</td> <td>1.2.4</td> </tr> <tr> <td align="center"> [ &gt;&gt; ] </td> <td align="center">FastForward</td> <td>Next chapter</td> <td>2</td> </tr> <tr> <td align="center"> [Top] </td> <td align="center">Top</td> <td>Cover (top) of document</td> <td> &nbsp; </td> </tr> <tr> <td align="center"> [Contents] </td> <td align="center">Contents</td> <td>Table of contents</td> <td> &nbsp; </td> </tr> <tr> <td align="center"> [Index] </td> <td align="center">Index</td> <td>Index</td> <td> &nbsp; </td> </tr> <tr> <td align="center"> [ ? ] </td> <td align="center">About</td> <td>About (help)</td> <td> &nbsp; </td> </tr> </table> <p> where the <strong> Example </strong> assumes that the current position is at <strong> Subsubsection One-Two-Three </strong> of a document of the following structure: </p> <ul> <li> 1. Section One <ul> <li>1.1 Subsection One-One <ul> <li>...</li> </ul> </li> <li>1.2 Subsection One-Two <ul> <li>1.2.1 Subsubsection One-Two-One</li> <li>1.2.2 Subsubsection One-Two-Two</li> <li>1.2.3 Subsubsection One-Two-Three &nbsp; &nbsp; <strong>&lt;== Current Position </strong></li> <li>1.2.4 Subsubsection One-Two-Four</li> </ul> </li> <li>1.3 Subsection One-Three <ul> <li>...</li> </ul> </li> <li>1.4 Subsection One-Four</li> </ul> </li> </ul> <hr> <p> <font size="-1"> This document was generated on <i>June 18, 2015</i> using <a href="http://www.nongnu.org/texi2html/"><i>texi2html 5.0</i></a>. </font> <br> </p> </body> </html>
136,405
Common Lisp
.l
2,231
59.603317
255
0.712201
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
2704ed147b4abe742a9ef93652aec530ae83e9d7413cfe5ceb3a2a4eeda58d09
4,455
[ -1 ]
4,457
vestigial.css
vindarel_cl-readline/doc/js/vestigial.css
pre { white-space: pre; background-color: #f8f8f8; border: 1px solid #ccc; font-size: 13px; line-height: 19px; overflow: auto; padding: 6px 10px; border-radius: 3px; } pre code {white-space: pre; margin: 0; padding: 0; background: none; border: none; overflow-x: auto; font-size: 13px;} code {margin: 0 2px; padding: 0 5px; white-space: nowrap; font-family: Consolas, "Liberation Mono", Courier, monospace; background: #f8f8f8; border: 1px solid #eaeaea; border-radius: 3px;} code.hl-highlighted .function.known {color: #a93;} code.hl-highlighted .function.known.special {color: #2a3;} code.hl-highlighted .keyword {color: #7aa;} code.hl-highlighted .keyword.known {color: #4bb;} code.hl-highlighted .symbol {color: #75a;} code.hl-highlighted .lambda-list {color: #966;} code.hl-highlighted .number {color: #800;} code.hl-highlighted .variable.known {color: #c3c;} code.hl-highlighted .variable.global {color: #939;} code.hl-highlighted .variable.constant {color: #229;} code.hl-highlighted .nil {color: #f00;} code.hl-highlighted .comment, code.hl-highlighted .comment *, code.hl-highlighted .comment .string {color: #aaa !important;} code.hl-highlighted .string, code.hl-highlighted .string * {color: #088 !important;} code.hl-highlighted .list.active {display: inline-block; background: #aefff7;}
1,304
Common Lisp
.l
17
75.470588
188
0.747467
vindarel/cl-readline
38
8
4
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
53ff34fcb4b46167db1348eaa36aec1128f1a81b245771c80a4e73f62a670cc8
4,457
[ -1 ]
4,472
osc-tests.lisp
zzkt_osc/osc-tests.lisp
;; -*- mode: lisp -*- ;; ;; Various tests for cl-osc using 5am ;; ;; Authors ;; - nik gaffney <[email protected]> (defpackage :osc/tests (:use :cl :osc :fiveam)) (in-package :osc/tests) ;; (in-package :osc) ;; (require "fiveam") ;; setup various test suites (def-suite synchroscope :description "OSC test suite(s).") (def-suite data-encoding :description "Test encoding and decoding of OSC data types." :in synchroscope) (def-suite message-encoding :description "Test encoding and decoding of OSC messages." :in synchroscope) (def-suite protocol-v1.0 :description "OSC v1.0 compatibility." :in synchroscope) (def-suite protocol-v1.1 :description "OSC v1.1 compatibility." :in synchroscope) (def-suite interoperability :description "Test interoperability (e.g. supercollider & pd)" :in synchroscope) ;; test todo ;; - negative floats, NaN +/- Inf, etc ;; - bignums ;; - blobs, and long args ;; - byte aligning 0,1,2,3,4 mod ;; - error catching, junk data ;; - edge cases? (in-suite data-encoding) (test osc-int32 "OSC int32 encoding tests." (is (equalp (osc::encode-int32 16843009) #(1 1 1 1))) (is (equalp (osc::decode-int32 #(127 255 255 255)) (osc::decode-uint32 #(127 255 255 255)))) (is (equalp (osc::encode-int32 -16843010) #(254 254 254 254))) (is (equalp (osc::decode-int32 #(127 255 255 255)) #x7FFFFFFF)) (is (equalp (osc::encode-int32 #xFFFFFFFF) #(255 255 255 255))) (is (equalp (osc::decode-int32 #(255 255 255 255)) -1)) (is (equalp (osc::decode-uint32 #(255 255 255 255)) #xFFFFFFFF))) (test osc-string "OSC string encoding tests." (is (equalp (osc::decode-string #(110 117 108 108 32 112 97 100 100 101 100 0)) "null padded")) (is (equalp (osc::encode-string "OSC string encoding test") #(79 83 67 32 115 116 114 105 110 103 32 101 110 99 111 100 105 110 103 32 116 101 115 116 0 0 0 0)))) ;; blob ;; (osc::encode-blob "THE BLOB") (test osc-blob "OSC blob encoding tests." (is (equalp (osc::encode-blob #(1 1 1 1)) #(0 0 0 4 1 1 1 1)))) (test osc-timetag "OSC timetag encoding tests." (is (equalp (osc::encode-timetag :now) #(0 0 0 0 0 0 0 1)))) (test osc-int64 "OSC int64 encoding tests." (is (equalp (osc::encode-int64 16843009) #(0 0 0 0 1 1 1 1))) (is (equalp (osc::decode-int64 #(1 1 1 1 1 1 1 1)) 72340172838076673)) (is (equalp (osc::encode-int64 -8000000000000000008) #(144 250 74 98 196 223 255 248))) (is (equalp (osc::decode-int64 #(254 1 254 1 254 1 254 1)) -143554428589179391))) ;; floating point tests ;; these tests cover only encoding and representation, not computation. (test osc-float32 "OSC float32 encoding tests." (is (equalp (osc::encode-float32 1.00001) #(63 128 0 84))) (is (equalp (osc::decode-float32 #(1 1 1 1)) 2.3694278s-38)) (is (equalp (osc::encode-float32 -2.3694278s33) #(246 233 164 196))) (is (equalp (osc::decode-float32 #(254 255 255 255)) -1.7014117s38)) (is (equalp (osc::decode-float32 #(127 255 255 255)) :NOT-A-NUMBER))) (test osc-float64 "OSC float64 encoding tests." (is (equalp (osc::encode-float64 23.1d0) #(64 55 25 153 153 153 153 154))) (is (equalp (osc::decode-float64 #(64 55 25 153 153 153 153 154)) 23.1d0)) (is (equalp (osc::decode-float64 #(1 1 1 1 1 1 1 1)) 7.748604185489348d-304)) (is (equalp (osc::decode-float64 #(128 0 0 0 0 0 0 0)) -0.0d0)) (is (equalp (osc::decode-float64 #(255 240 0 0 0 0 0 0)) :NEGATIVE-INFINITY)) (is (equalp (osc::decode-float64 #(255 255 255 255 0 0 0 0)) :NOT-A-NUMBER))) ;; #+sbcl (osc::decode-float32 #(127 255 255 255)) -> #<SINGLE-FLOAT quiet NaN> ;; see also -> https://github.com/Shinmera/float-features/ ;; single-float (defun f32b (s) (write-to-string (osc::encode-float32 s ) :base 2)) (defun f64b (s) (write-to-string (osc::encode-float64 s ) :base 2)) (test single-float "Various single floats of interest." (is (equalp (f32b 0.000000059604645s0) "#(110011 10000000 0 0)")) (is (equalp (f32b 0.000060975552s0) "#(111000 1111111 11000000 0)"))) (test float-features #+sbcl (pass (format nil "SBCL floating point modes: ~A~%" (sb-int:get-floating-point-modes)))) ;; empty messages tagged T, F, N, I (in-suite message-encoding) ;; messages (test osc-message-1 "OSC message encoding tests. address and single int." :suite 'message-encoding (is (equalp '("/test/int" -1) (osc:decode-message #(47 116 101 115 116 47 105 110 116 0 0 0 44 105 0 0 255 255 255 255))))) ;; check padding boundaries. 1-3 or 1-4? (test osc-t4 "OSC typetag encoding test. string, ints and floats." (is (equalp #(44 105 115 102 0 0 0 0) (osc::encode-typetags '(1 "terrr" 3.4))))) (test osc-t5 "OSC typetag encoding test. ints and floats." (is (equalp #(44 105 105 102 0 0 0 0) (osc::encode-typetags '(1 2 3.3))))) (test osc-t6 "OSC message decoding test. ints and floats." (is (equalp '("/test/one" 1 2 3.3) (osc:decode-message #(47 116 101 115 116 47 111 110 101 0 0 0 44 105 105 102 0 0 0 0 0 0 0 1 0 0 0 2 64 83 51 51))))) (test osc-t7 "OSC bundle decoding test. strings, ints and floats." (is (equalp '(#(0 0 0 0 0 0 0 1) ("/voices/0/tm/start" 0.0) ("/foo/stringmessage" "a" "few" "strings") ("/documentation/all-messages")) (osc:decode-bundle #(#x23 #x62 #x75 #x6e #x64 #x6c #x65 0 0 0 0 0 0 0 0 #x1 0 0 0 #x20 #x2f #x64 #x6f #x63 #x75 #x6d #x65 #x6e #x74 #x61 #x74 #x69 #x6f #x6e #x2f #x61 #x6c #x6c #x2d #x6d #x65 #x73 #x73 #x61 #x67 #x65 #x73 0 #x2c 0 0 0 0 0 0 #x2c #x2f #x66 #x6f #x6f #x2f #x73 #x74 #x72 #x69 #x6e #x67 #x6d #x65 #x73 #x73 #x61 #x67 #x65 0 0 #x2c #x73 #x73 #x73 0 0 0 0 #x61 0 0 0 #x66 #x65 #x77 0 #x73 #x74 #x72 #x69 #x6e #x67 #x73 0 0 0 0 #x1c #x2f #x76 #x6f #x69 #x63 #x65 #x73 #x2f #x30 #x2f #x74 #x6d #x2f #x73 #x74 #x61 #x72 #x74 0 0 #x2c #x66 0 0 0 0 0 0))))) (test osc-t8 "OSC message encoding test. blob." (is (equalp (osc::encode-message "/blob/x" #(1 2 3 4 5 6 7 8 9)) #(47 98 108 111 98 47 120 0 44 98 0 0 0 0 0 9 1 2 3 4 5 6 7 8 9 0 0 0)))) (test osc-t9 "OSC message decoding test. blob." (is (equalp '("/blob/x" #(1 2 3 4 5 6 7 8 9)) (osc::decode-message #(47 98 108 111 98 47 120 0 44 98 0 0 0 0 0 9 1 2 3 4 5 6 7 8 9 0 0 0))))) (test osc-t10 "OSC message decoding test. blob, int, string." (is (equalp '("/blob" #(1 29 32 43 54 66 78 81) "lop" 2) (osc:decode-message #(47 98 108 111 98 0 0 0 44 98 115 105 0 0 0 0 0 0 0 8 1 29 32 43 54 66 78 81 108 111 112 0 0 0 0 2))))) ;; (test osc-t11 ;; "OSC bundle decoding test." ;; (is (equalp ;; '(#(0 0 0 0 0 0 0 1) ;; ("/string/a/ling" "slink" "slonk" "slank") ;; ("/we/wo/w" 1 2 3.4) ;; ("/blob" #(1 29 32 43 54 66 78 81 90) "lop" -0.44)) ;; (osc:decode-bundle ;; #(35 98 117 110 100 108 101 0 0 0 0 0 0 0 0 1 0 0 0 40 47 98 108 111 98 0 0 0 ;; 44 98 115 102 0 0 0 0 0 0 0 9 1 29 32 43 54 66 78 81 90 0 0 0 108 111 112 0 ;; 190 225 71 174 0 0 0 32 47 119 101 47 119 111 47 119 0 0 0 0 44 105 105 102 0 ;; 0 0 0 0 0 0 1 0 0 0 2 64 89 153 154 0 0 0 48 47 115 116 114 105 110 103 47 97 ;; 47 108 105 110 103 0 0 44 115 115 115 0 0 0 0 115 108 105 110 107 0 0 0 115 ;; 108 111 110 107 0 0 0 115 108 97 110 107 0 0 0))))) ;; equalp but not eql (test osc-t13 "OSC message encoding test." (is (equalp (osc:encode-message "/asdasd" 3.6 4.5) #(47 97 115 100 97 115 100 0 44 102 102 0 64 102 102 102 64 144 0 0)))) ;; equal but not eql (test osc-t14 "OSC message decoding test." (is (equalp (osc:decode-message #(47 97 115 100 97 115 100 0 44 102 102 0 64 102 102 102 64 144 0 0)) (list "/asdasd" 3.6 4.5)))) ;; symmetrical? how much of a issue is this? (test osc-recode "OSC message encoding & decoding symmetry test." (let ((message (osc:decode-message #(47 97 115 100 97 115 100 0 44 102 102 0 64 102 102 102 64 144 0 0)))) (is (equalp message (osc:decode-message (apply #'osc:encode-message message)))))) ;; partially pathological string tests... (test osc-sp1 (is (equalp (osc:encode-message "/s/t0" "four") #(47 115 47 116 48 0 0 0 44 115 0 0 102 111 117 114 0 0 0 0))) (is (equalp (osc:decode-message #(47 115 47 116 48 0 0 0 44 115 0 0 102 111 117 114 0 0 0 0)) '("/s/t0" "four")))) (test osc-sp2 (is (equalp (osc:encode-message "/s/t0" 2 "xxxxx" 3) #(47 115 47 116 48 0 0 0 44 105 115 105 0 0 0 0 0 0 0 2 120 120 120 120 120 0 0 0 0 0 0 3))) (is (equalp (osc:decode-message #(47 115 47 116 48 0 0 0 44 105 115 105 0 0 0 0 0 0 0 2 120 120 120 120 120 0 0 0 0 0 0 3)) '("/s/t0" 2 "xxxxx" 3)))) ;; (test osc-t16 ;; "OSC message encoding & decoding symmetry test." ;; (let* ((packed-msg #(47 97 115 100 97 115 100 0 44 102 102 0 64 102 102 102 64 144 0 0)) ;; (cons-msg (osc:decode-message packed-msg))) ;; (is (equalp ;; packed-msg ;; (osc:encode-message (values-list cons-msg)))))) ;; v1.0 tests (in-suite protocol-v1.0) (test v1.0-required-types "OSC data encoding test. All required types for v1.0" (is (equalp #(0 0 0 3 116 101 115 116 0 0 0 0 67 82 0 0 0 0 0 4 1 2 3 4) (osc::encode-data '(3 "test" 2.1e2 #(1 2 3 4)))))) ;; v1.1. tests (in-suite protocol-v1.1) (test v1.1-required-data-types "OSC data encoding test. All required types for v1.1" (is (equalp #(44 105 104 115 102 100 98 0) (osc::encode-typetags '(3 4294967297 "test" 2.1e2 2.1d23 #(1 2 3 4) ;; (osc::encode-timetag :now) ))))) (test v1.1-keyword-typetags "OSC typetag encoding test." (is (equalp (osc::encode-typetags '(:true :false :null :impulse)) #(44 84 70 78 73 0 0 0)))) ;; (osc::encode-typetags '("s" 1)) ;; play nicely with others (in-suite interoperability) (test hex-strings "OSC data in hex." (is (equalp (osc::write-data-as-hex (osc::encode-string "hexadecimate")) "#(68 65 78 61 64 65 63 69 6D 61 74 65 0 0 0 0)")) (is (equalp (osc::decode-string #(#x68 #x65 #x78 #x61 #x64 #x65 #x63 #x69 #x6D #x61 #x74 #x65 #x0 #x0 #x0 #x0)) "hexadecimate"))) #| sc3 server 32 byte message: 2f (/) 6e (n) 5f (_) 73 (s) 65 (e) 74 (t) 0 () 0 () 2c (,) 69 (i) 73 (s) 66 (f) 0 () 0 () 0 () 0 () 0 () 0 () 1 () fffffff6 (?) 66 (f) 72 (r) 65 (e) 71 (q) 0 () 0 () 0 () 0 () 3f (?) ffffff80 (?) 0 () 0 () /n_set 502 "freq" 1.000000 |# (run! 'synchroscope)
11,630
Common Lisp
.lisp
324
30.185185
100
0.566969
zzkt/osc
37
8
7
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
d6acff444bef6141041936cd6746bbabadb327a60c7a4975f663169bb8cbbb88
4,472
[ -1 ]
4,474
osc.lisp
zzkt_osc/osc.lisp
;;; -*- mode: lisp -*- ;;; ;;; An implementation of the OSC (Open Sound Control) protocol ;;; ;;; Copyright (c) 2004 FoAM ;;; ;;; cl-osc is free software: you can redistribute it and/or modify it ;;; under the terms of the GNU General Public License as published by ;;; the Free Software Foundation, either version 3 of the License, or ;;; (at your option) any later version. ;;; ;;; Authors ;;; ;;; nik gaffney <[email protected]> and the listed AUTHORS ;;; ;;; Requirements ;;; ;;; depends on ieee-floats for float encoding and 5am for testing ;;; ;;; Commentary ;;; ;;; This is an implementation of the OSC protocol which is used ;;; for communication mostly amongst music programs and their attached ;;; musicians (eg. supercollider, max/pd, ableton, etc). ;;; ;;; The OSC V1.0 is supported, and there is partial support for V1.1 ;;; More details of the protocol can be found at ;;; http://OpenSoundControl.org ;;; ;;; see the README file for further details... ;;; ;;; Known BUGS/Issues ;;; - encoding a :symbol that is unbound or without symbol-value causes an error ;;; - unknown types are sent as 'blobs' which may or may not be an issue ;;; - malformed input -> exception (defpackage :osc (:use :cl) (:shadow :ieee-floats) (:documentation "OSC the 'Open Sound Control' protocol") (:export #:encode-message #:encode-bundle #:decode-message #:decode-bundle)) (in-package :osc) ;; (declaim (optimize (speed 3) (safety 1) (debug 3))) ;;;;;; ; ;; ; ; ; ; ; ; ; ;; ;; eNcoding OSC messages ;; ;;;; ;; ;; ; ; ;; ; ; ; ; (defun encode-bundle (data &optional timetag) "will encode an osc message, or list of messages as a bundle with an optional timetag (symbol or 64bit int). doesnt handle nested bundles" (cat '(35 98 117 110 100 108 101 0) ; #bundle (if timetag (encode-timetag timetag) (encode-timetag :now)) (if (listp (car data)) (apply #'cat (mapcar #'encode-bundle-elt data)) (encode-bundle-elt data)))) (defun encode-bundle-elt (data) (let ((message (apply #'encode-message data))) (cat (encode-int32 (length message)) message))) (defun encode-message (address &rest data) "encodes an osc message with the given address and data." (concatenate '(vector (unsigned-byte 8)) (encode-address address) (encode-typetags data) (encode-data data))) (defun encode-address (address) (cat (map 'vector #'char-code address) (string-padding address))) (defun encode-typetags (data) "Create a typetag string suitable for the given DATA. valid typetags according to the OSC 1.0 spec are ,i ,f ,s and ,b the OSC 1.1 spec includes ,h ,t ,d ,S ,T ,F ,N and ,I The following tags are written based on type check integer => i => #(105) => h => #(104) single-float => f => #(102) double-float => d => #(100) simple-string => s => #(115) * => b => #(98) The following tags are written based on :keywords in the data :true (or t) => T => #(84) :false => F => #(70) :null => N => #(78) :impulse => I => #(73) " (let ((lump (make-array 0 :adjustable t :fill-pointer t))) (macrolet ((write-to-vector (char) `(vector-push-extend (char-code ,char) lump))) (write-to-vector #\,) ;; #(44) (dolist (x data) (typecase x (integer (if (>= x 4294967296) (write-to-vector #\h) (write-to-vector #\i))) (single-float (write-to-vector #\f)) (double-float (write-to-vector #\d)) (simple-string (write-to-vector #\s)) ;; lisp semantics vs. OSC semantics (keyword (case x (:true (write-to-vector #\T)) (:false (write-to-vector #\F)) (:null (write-to-vector #\N)) (:impulse (write-to-vector #\I)))) (null (write-to-vector #\F)) ;; anything else is treated as a blob (t (write-to-vector #\b))))) (cat lump (pad (padding-length (length lump)))))) (defun encode-data (data) "Encode DATA in a format suitable for an OSC message." (let ((lump (make-array 0 :adjustable t :fill-pointer t))) (macrolet ((enc (f) `(setf lump (cat lump (,f x))))) (dolist (x data) (typecase x (integer (if (>= x 4294967296) (enc encode-int64) (enc encode-int32))) (single-float (enc encode-float32)) (double-float (enc encode-float64)) (simple-string (enc encode-string)) ;; -> timetag (t (enc encode-blob)))) lump))) ;;;;;; ; ;; ; ; ; ; ; ; ; ;; ;; decoding OSC messages ;; ;;; ;; ;; ; ; ; ; ; ; (defun decode-bundle (data) "Decode an OSC bundle into a list of decoded-messages. The first element is an osc-timetag." (let ((contents '())) (if (equalp 35 (elt data 0)) ;; a bundle begins with '#' (let ((timetag (subseq data 8 16)) (i 16) (bundle-length (length data))) (loop while (< i bundle-length) do (let ((mark (+ i 4)) (size (decode-int32 (subseq data i (+ i 4))))) (if (eq size 0) (setf bundle-length 0) (push (decode-bundle (subseq data mark (+ mark size))) contents)) (incf i (+ 4 size)))) (push timetag contents)) (decode-message data)))) (defun decode-message (message) "Reduce an OSC MESSAGE to an (address . data) pair." (declare (type (vector *) message)) (let ((x (position (char-code #\,) message))) (if (eq x NIL) (format t "Message contains no data.. ") (cons (decode-address (subseq message 0 x)) (decode-taged-data (subseq message x)))))) (defun decode-address (address) (coerce (map 'vector #'code-char (delete 0 address)) 'string)) (defun decode-taged-data (data) "Decode DATA encoded with typetags. NOTE: currently handles the following tags i => #(105) => int32 f => #(102) => float32 s => #(115) => string b => #(98) => blob h => #(104) => int64" (let ((div (position 0 data))) (let ((tags (subseq data 1 div)) (acc (subseq data (padded-length div))) (result '())) (map 'vector #'(lambda (x) (cond ((eq x (char-code #\i)) (push (decode-int32 (subseq acc 0 4)) result) (setf acc (subseq acc 4))) ((eq x (char-code #\h)) (push (decode-uint64 (subseq acc 0 8)) result) (setf acc (subseq acc 8))) ((eq x (char-code #\f)) (push (decode-float32 (subseq acc 0 4)) result) (setf acc (subseq acc 4))) ((eq x (char-code #\s)) (let ((pointer (padded-length (position 0 acc)))) (push (decode-string (subseq acc 0 pointer)) result) (setf acc (subseq acc pointer)))) ((eq x (char-code #\b)) (let* ((size (decode-int32 (subseq acc 0 4))) (bl (+ 4 size)) (end (+ bl (mod (- 4 bl) 4)))) ;; NOTE: cannot use (padded-length bl), as it is not the same algorithm. Blobs of 4, 8, 12 etc bytes should not be padded! (push (decode-blob (subseq acc 0 end)) result) (setf acc (subseq acc end)))) (t (error "unrecognised typetag ~a" x)))) tags) (nreverse result)))) ;;;;;; ;; ;; ; ; ; ; ; ;; ; ;; ;; Timetags ;; ;; - timetags can be encoded using a value, or the :now and :time keywords. the ;; keywords enable either a tag indicating 'immediate' execution, or ;; a tag containing the current time (which will most likely be in the past ;; of any receiver) to be created. ;; ;; - note: not well tested, and probably not accurate enough for syncronisation. ;; see also: CLHS 25.1.4 Time, and the NTP timestamp format. also needs to ;; convert from 2 32bit ints to 64bit fixed point value. ;; ;; - see this c.l.l thread to sync universal-time and internal-time ;; http://groups.google.com/group/comp.lang.lisp/browse_thread/thread/c207fef63a78d720/adc7442d2e4de5a0?lnk=gst&q=internal-real-time-sync&rnum=1#adc7442d2e4de5a0 ;; ;;;; ;; ; ; (defconstant +unix-epoch+ (encode-universal-time 0 0 0 1 1 1970 0)) (defun encode-timetag (utime &optional subseconds) "Encode an OSC timetag from a universal-time and 32bit 'sub-second' part. for an 'instantaneous' timetag use (encode-timetag :now) for a timetag with the current time use (encode-timetag :time)" (cond ;; a timetag of 1 will be interpreted as 'immediately' ((equalp utime :now) #(0 0 0 0 0 0 0 1)) ;; converts seconds since 19000101 to seconds since 19700101 ;; note: fractions of seconds are accurate, but not synchronised. ((equalp utime :time) (cat (encode-int32 (- (get-universal-time) +unix-epoch+)) (encode-int32 (round (* internal-time-units-per-second (second (multiple-value-list (floor (/ (get-internal-real-time) internal-time-units-per-second))))))))) ((integerp utime) (cat (encode-int32 (+ utime +unix-epoch+)) (encode-int32 subseconds))) (t (error "The time or subsecond given is not an integer.")))) (defun decode-timetag (timetag) "Decompose a TIMETAG into unix-time and subsecond." (list (decode-int32 (subseq timetag 0 4)) (decode-int32 (subseq timetag 4 8)))) ;;;;; ; ; ;; ;; ; ; ;; ;; dataformat en- de- cetera. ;; ;;; ;; ; ; ; ;; integers. 32 and 64 bit. signed and unsigned. (defmacro defint-decoder (num-of-octets &optional docstring) (let ((decoder-name (intern (format nil "~:@(decode-uint~)~D" (* 8 num-of-octets)))) (seq (gensym)) (int (gensym))) `(defun ,decoder-name (,seq) ,@(when docstring (list docstring)) (let* ((,int 0) ,@(loop for n below num-of-octets collect `(,int (dpb (aref ,seq ,n) (byte 8 (* 8 (- (1- ,num-of-octets) ,n))) ,int)))) ,int)))) (defmacro defint-encoder (num-of-octets &optional docstring) (let ((enc-name (intern (format nil "~:@(encode-int~)~D" (* 8 num-of-octets)))) (buf (gensym)) (int (gensym))) `(defun ,enc-name (,int) ,@(when docstring (list docstring)) (let ((,buf (make-array ,num-of-octets :element-type '(unsigned-byte 8)))) ,@(loop for n below num-of-octets collect `(setf (aref ,buf ,n) (ldb (byte 8 (* 8 (- (1- ,num-of-octets) ,n))) ,int))) ,buf)))) ;; generate functions decode-uint32 and decode-uint64 (defint-decoder 4 "4 byte -> 32 bit unsigned int") (defint-decoder 8 "8 byte -> 64 bit unsigned int") ;; generate functions encode-int32 and encode-int64 (defint-encoder 4 "Convert an integer into a sequence of 4 bytes in network byte order.") (defint-encoder 8 "Convert an integer into a sequence of 8 bytes in network byte order.") (defun decode-int32 (s) "4 byte -> 32 bit int -> two's complement (in network byte order)" (let ((i (decode-uint32 s))) (if (>= i (expt 2 31)) (- (- (expt 2 32) i)) i))) (defun decode-int64 (s) "8 byte -> 64 bit int -> two's complement (in network byte order)" (let ((i (decode-uint64 s))) (if (>= i (expt 2 63)) (- (- (expt 2 64) i)) i))) ;; floats are encoded using ieee-floats library for brevity and compatibility ;; - https://ieee-floats.common-lisp.dev/ ;; ;; It should be possible to use 32 and 64 bit floats in most common lisp environments. ;; An implementation specific encoder/decoder can be used where available. (declaim (inline ieee-floats:encode-float32 ieee-floats:decode-float32 ieee-floats:encode-float64 ieee-floats:decode-float64)) (ieee-floats:make-float-converters ieee-floats:encode-float32 ieee-floats:decode-float32 8 23 t) (ieee-floats:make-float-converters ieee-floats:encode-float64 ieee-floats:decode-float64 11 52 t) (defun encode-float32 (f) "Encode an ieee754 float as a 4 byte vector." #+sbcl (encode-int32 (sb-kernel:single-float-bits f)) #-sbcl (encode-int32 (ieee-floats:encode-float32 f))) (defun decode-float32 (v) "Convert a vector of 4 bytes in network byte order into an ieee754 float." (ieee-floats:decode-float32 (decode-uint32 v))) (defun encode-float64 (d) "Encode an ieee754 float as a 8 byte vector." (encode-int64 (ieee-floats:encode-float64 d))) (defun decode-float64 (v) "Convert a vector of 8 bytes in network byte order into an ieee754 float." (ieee-floats:decode-float64 (decode-uint64 v))) ;; osc-strings are unsigned bytes, padded to a 4 byte boundary (defun decode-string (data) "Convert a binary vector to a string and remove any trailing #\nul characters." (string-trim '(#\nul) (coerce (map 'vector #'code-char data) 'string))) (defun encode-string (string) "Encode a STRING as a vector of character-codes padded to 4 byte boundary." (cat (map 'vector #'char-code string) (string-padding string))) ;; blobs are binary data, consisting of a length (int32) and bytes which are ;; padded to a 4 byte boundary. (defun decode-blob (blob) "Decode a BLOB as a vector of unsigned bytes." (let ((size (decode-int32 (subseq blob 0 4)))) (subseq blob 4 (+ 4 size)))) (defun encode-blob (blob) "Encode BLOB as a vector." (let ((bl (length blob))) (cat (encode-int32 bl) blob (pad (mod (- 4 bl) 4))))) ;; NOTE: cannot use (padding-length bl), as it is not the same algorithm. Blobs of 4, 8, 12 etc bytes should not be padded! ;; utility functions for osc-string/padding/slonking ;; NOTE: string padding is treated differently between v1.0 and v1.1 (defun write-data-as-hex (data) "Write OSC data (represented as vector) as string in base 16." (write-to-string data :base 16)) (defun cat (&rest catatac) "Concatenate items into a byte vector." (apply #'concatenate '(vector (unsigned-byte 8)) catatac)) (defun padding-length (s) "Return the length of padding required for a given length of string." (declare (type fixnum s)) (- 4 (mod s 4))) (defun padded-length (s) "Return the length of an osc-string made from a given length of string." (declare (type fixnum s)) (+ s (- 4 (mod s 4)))) (defun string-padding (string) "Return the padding required for a given osc string." (declare (type simple-string string)) (pad (padding-length (length string)))) (defun pad (n) "Make a sequence of the required number of #\Nul characters." (declare (type fixnum n)) (make-array n :initial-element 0 :fill-pointer n)) (provide :osc) ;; end
15,632
Common Lisp
.lisp
379
33.662269
163
0.583788
zzkt/osc
37
8
7
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
2c5289033672f4d8443a9cf0c60e531a27377dcc718932c1efe555316f2598d9
4,474
[ -1 ]
4,475
osc.asd
zzkt_osc/osc.asd
;; -*- mode: lisp -*- (in-package :asdf-user) (defsystem "osc" :description "The Open Sound Control protocol, aka OSC" :author "nik gaffney <[email protected]>" :depends-on ("ieee-floats") :version "0.9.1" :licence "GPL v3" :components ((:file "osc")) :in-order-to ((test-op (test-op "osc/tests")))) ;; regression testing. can be ignored/disabled at run time if required (defsystem "osc/tests" :description "Tests for OSC library." :depends-on ("osc" "fiveam") :components ((:file "osc-tests")) :perform (test-op (o c) (uiop:symbol-call :fiveam '#:run! :synchroscope)))
606
Common Lisp
.asd
17
32.058824
70
0.65247
zzkt/osc
37
8
7
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
7dc918e001ba4c486d5960b3c26268c60cb40bf869304f1958f828534fa7a9f0
4,475
[ -1 ]
4,480
ci.yaml
zzkt_osc/.github/workflows/ci.yaml
name: CI # details & description at http://3bb.cc/blog/2020/09/11/github-ci/ # and/or https://github.com/roswell/roswell/wiki/GitHub-Actions # Controls when the action will run. Triggers the workflow on push for any branch, and # pull requests to master on: push: pull_request: branches: [ endless, core ] # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: test: name: ${{ matrix.lisp }} on ${{ matrix.os }} strategy: matrix: # current ccl-bin has a flaky zip file, so roswell can't install it. # Specify a version that works for now. lisp: [ sbcl-bin, ccl-bin, ecl ] os: [ windows-latest, ubuntu-latest, macos-latest ] include: # - os: ubuntu-latest # lisp: allegro - os: windows-latest lisp: sbcl-bin exclude: - os: windows-latest lisp: ecl - os: macos-latest lisp: ccl-bin # run the job on every combination of "lisp" and "os" above runs-on: ${{ matrix.os }} # default to msys2 shell on windows, since roswell install-for-ci.sh tries to install using pacman defaults: run: shell: ${{ fromJSON('[ "bash", "msys2 {0}" ]') [ matrix.os == 'windows-latest' ] }} steps: # use setup-msys2 - uses: msys2/setup-msys2@v2 if: matrix.os == 'windows-latest' with: path-type: inherit # list any extra packages we want installed # for example the following would be enough for us to build sbcl # from git: # install: 'git base-devel unzip mingw-w64-x86_64-gcc mingw64/mingw-w64-x86_64-zlib' # tell git not to convert line endings # change roswell install dir and add it to path - name: windows specific settings if: matrix.os == 'windows-latest' run: | git config --global core.autocrlf false echo "ROSWELL_INSTALL_DIR=$HOME/ros" >> $GITHUB_ENV echo "$HOME/ros/bin" >> $GITHUB_PATH # Check out your repository under $GITHUB_WORKSPACE, so your job can access it - uses: actions/checkout@v4 - name: cache .roswell id: cache-dot-roswell uses: actions/cache@v4 with: path: ~/.roswell key: ${{ runner.os }}-dot-roswell-${{ matrix.lisp }}-${{ hashFiles('**/*.asd') }} restore-keys: | ${{ runner.os }}-dot-roswell-${{ matrix.lisp }}- ${{ runner.os }}-dot-roswell- - name: install roswell # always run install, since it does some global installs and setup that isn't cached env: LISP: ${{ matrix.lisp }} run: curl -L https://raw.githubusercontent.com/roswell/roswell/master/scripts/install-for-ci.sh | sh -x - name: run lisp continue-on-error: true run: | ros -e '(format t "~a:~a on ~a~%...~%~%" (lisp-implementation-type) (lisp-implementation-version) (machine-type))' ros -e '(format t " fixnum bits:~a~%" (integer-length most-positive-fixnum))' ros -e "(ql:quickload 'fiveam)" ros -e "(ql:quickload 'trivial-features)" -e '(format t "features = ~s~%" *features*)' - name: update ql dist if we have one cached run: ros -e "(ql:update-all-dists :prompt nil)" - name: load code and run tests run: | ros -e '(handler-bind (#+asdf3.2(asdf:bad-SYSTEM-NAME (function MUFFLE-WARNING))) (handler-case (ql:quickload :osc) (error (a) (format t "caught error ~s~%~a~%" a a) (uiop:quit 123))))' -e '(asdf:test-system :osc)'
3,545
Common Lisp
.l
81
36.530864
222
0.621252
zzkt/osc
37
8
7
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
b5ce0a6ba20d28e189c41c3eb7775bd93814736fe3ef682b78293fa393fee32a
4,480
[ -1 ]
4,495
isolated-cl.lisp
kanru_cl-isolated/isolated-cl.lisp
;;;; Isolated --- A isolated environment for evaluating Common Lisp ;;;; expressions ;; Copyright (C) 2014, 2020 Kan-Ru Chen <[email protected]> ;; Copyright (C) 2012-2013 Teemu Likonen <[email protected]> ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public ;; License along with this program. If not, see ;; <http://www.gnu.org/licenses/>. (cl:defpackage #:isolated-cl (:use)) (cl:in-package #:isolated-cl) (cl:declaim (cl:optimize (cl:safety 3))) ;;; Helpers for defining, importing and exporting (cl:defmacro import-export-symbols (cl:&body symbols) `(cl:loop :for symbol :in ',symbols :do (cl:shadowing-import (cl:list symbol)) (cl:export (cl:list symbol)))) (cl:defmacro sdefparameter (name initial-value) `(cl:progn (cl:export (cl:list ',name)) (cl:defparameter ,name ,initial-value))) (cl:defmacro sdefun (name lambda-list cl:&body body) `(cl:progn (cl:setf (cl:get ',name :isolated-locked) cl:t) (cl:export (cl:list ',name)) (cl:defun ,name ,lambda-list ,@body))) (cl:defmacro sdefmacro (name lambda-list cl:&body body) `(cl:progn (cl:setf (cl:get ',name :isolated-locked) cl:t) (cl:export (cl:list ',name)) (cl:defmacro ,name ,lambda-list ,@body))) (cl:defmacro disabled-features (cl:&body symbols) `(cl:loop :for symbol :in ',symbols :do (cl:setf (cl:get symbol :isolated-locked) cl:t) (cl:export (cl:list symbol)) (cl:let ((name (cl:symbol-name symbol))) (cl:setf (cl:macro-function symbol) (cl:lambda (cl:&rest ignored) (cl:declare (cl:ignore ignored)) `(cl:error 'isolated-impl:disabled-feature :name ,name)) (cl:symbol-function symbol) (cl:lambda (cl:&rest ignored) (cl:declare (cl:ignore ignored)) (cl:error 'isolated-impl:disabled-feature :name name))) (cl:eval `(cl:defsetf ,symbol (cl:&rest ignored) (values-ignored) (cl:declare (cl:ignore ignored values-ignored)) `(cl:error 'isolated-impl:disabled-feature :name ,,name)))))) ;;; General (import-export-symbols cl:&allow-other-keys cl:&aux cl:&body cl:&environment cl:&key cl:&optional cl:&rest cl:&whole) ;;; The Evaluation and Compilation Dictionary (import-export-symbols cl:lambda cl:quote cl:special-operator-p cl:constantp) (disabled-features compile eval-when load-time-value compiler-macro-function define-compiler-macro macro-function macroexpand macroexpand-1 define-symbol-macro symbol-macrolet proclaim declaim the declare locally) (sdefun eval (form) (cl:values-list (isolated-impl:translate-form (cl:multiple-value-list (cl:eval (isolated-impl:translate-form form)))))) (sdefmacro defmacro (name lambda-list cl:&body body) (cl:if (cl:get name :isolated-locked) (cl:error 'cl:package-error :package cl:nil) `(cl:defmacro ,name ,lambda-list ,@body))) ;;; The Types and Classes Dictionary (import-export-symbols cl:nil cl:boolean cl:function cl:compiled-function cl:generic-function cl:standard-generic-function cl:class cl:built-in-class cl:structure-class cl:standard-class cl:method cl:standard-method cl:structure-object cl:standard-object cl:method-combination cl:t cl:satisfies ;; cl:member Also a function. Imported later. cl:not cl:and cl:or cl:values cl:eql cl:coerce cl:subtypep cl:type-of cl:typep cl:type-error-datum cl:type-error-expected-type) (disabled-features deftype) ;;; The Data and Control Flow Dictionary (import-export-symbols cl:apply cl:fboundp cl:flet cl:labels cl:macrolet cl:funcall cl:function cl:functionp cl:compiled-function-p cl:call-arguments-limit cl:lambda-list-keywords cl:lambda-parameters-limit cl:defparameter cl:defvar cl:destructuring-bind cl:let cl:let* cl:progv cl:setq cl:psetq cl:block cl:go cl:return-from cl:return cl:tagbody cl:nil cl:not cl:t cl:eq cl:eql cl:equal cl:equalp cl:identity cl:complement cl:constantly cl:every cl:some cl:notevery cl:notany cl:and cl:cond cl:if cl:or cl:when cl:unless cl:case cl:ccase cl:ecase cl:typecase cl:ctypecase cl:etypecase cl:multiple-value-bind cl:multiple-value-list cl:multiple-value-prog1 cl:multiple-value-setq cl:values cl:values-list cl:multiple-values-limit cl:nth-value cl:prog cl:prog* cl:prog1 cl:prog2 cl:progn cl:setf cl:psetf cl:shiftf cl:rotatef) (disabled-features fdefinition fmakunbound function-lambda-expression defconstant define-modify-macro defsetf define-setf-expander get-setf-expansion unwind-protect catch throw) (sdefmacro defun (name lambda-list cl:&body body) (cl:if (cl:or (cl:and (cl:symbolp name) (cl:get name :isolated-locked)) (cl:and (cl:consp name) (cl:eql (cl:first name) 'cl:setf) (cl:get (cl:second name) :isolated-locked))) (cl:error 'cl:package-error :package cl:nil) `(cl:defun ,name ,lambda-list ,@body))) ;;; The Iteration Dictionary (import-export-symbols cl:do cl:do* cl:dotimes cl:dolist) (disabled-features loop) ;;; The Objects Dictionary (import-export-symbols cl:class-of) (disabled-features function-keywords ensure-generic-function allocate-instance reinitialize-instance shared-initialize update-instance-for-different-class update-instance-for-redefined-class change-class slot-boundp slot-exists-p slot-makunbound slot-missing slot-unbound slot-value method-qualifiers no-applicable-method remove-method make-instance make-instances-obsolete make-load-form make-load-form-saving-slots with-accessors with-slots defclass defgeneric defmethod find-class next-method-p call-method make-method call-next-method compute-applicable-methods define-method-combination find-method add-method initialize-instance class-name unbound-slot-instance) ;;; The Structures Dictionary (disabled-features defstruct copy-structure) ;;; The Conditions Dictionary (import-export-symbols cl:restart) (disabled-features cell-error-name assert error cerror check-type invalid-method-error method-combination-error signal simple-condition-format-control simple-condition-format-arguments warn invoke-debugger break handler-bind handler-case ignore-errors define-condition make-condition compute-restarts find-restart invoke-restart invoke-restart-interactively restart-bind restart-case restart-name with-condition-restarts with-simple-restart abort continue muffle-warning store-value use-value) ;;; The Symbols Dictionary (import-export-symbols cl:symbol cl:keyword cl:symbolp cl:keywordp cl:symbol-name cl:boundp) (disabled-features make-symbol copy-symbol gensym gentemp symbol-function symbol-package symbol-plist symbol-value get remprop makunbound set) ;;; The Packages Dictionary (disabled-features export find-symbol find-package find-all-symbols import list-all-packages rename-package shadow shadowing-import delete-package make-package with-package-iterator unexport unintern in-package unuse-package use-package defpackage do-symbols do-external-symbols do-all-symbols intern package-name package-nicknames package-shadowing-symbols package-use-list package-used-by-list packagep package-error-package) ;;; The Numbers Dictionary (import-export-symbols cl:number cl:complex cl:real cl:float cl:short-float cl:single-float cl:double-float cl:long-float cl:rational cl:ratio cl:integer cl:signed-byte cl:unsigned-byte cl:mod cl:bit cl:fixnum cl:bignum cl:= cl:/= cl:< cl:> cl:<= cl:>= cl:max cl:min cl:minusp cl:plusp cl:zerop cl:floor cl:ffloor cl:ceiling cl:fceiling cl:truncate cl:ftruncate cl:round cl:fround cl:sin cl:cos cl:tan cl:asin cl:acos cl:atan cl:pi cl:sinh cl:cosh cl:tanh cl:asinh cl:acosh cl:atanh cl:1+ cl:1- cl:abs cl:evenp cl:oddp cl:exp cl:expt cl:gcd cl:incf cl:decf cl:lcm cl:log cl:mod cl:rem cl:signum cl:sqrt cl:isqrt cl:random-state cl:make-random-state cl:random cl:random-state-p cl:*random-state* cl:numberp cl:cis cl:complex cl:complexp cl:conjugate cl:phase cl:realpart cl:imagpart cl:upgraded-complex-part-type cl:realp cl:numerator cl:denominator cl:rational cl:rationalize cl:rationalp cl:ash cl:integer-length cl:integerp cl:parse-integer cl:boole cl:boole-1 cl:boole-2 cl:boole-and cl:boole-andc1 cl:boole-andc2 cl:boole-c1 cl:boole-c2 cl:boole-clr cl:boole-eqv cl:boole-ior cl:boole-nand cl:boole-nor cl:boole-orc1 cl:boole-orc2 cl:boole-set cl:boole-xor cl:logand cl:logandc1 cl:logandc2 cl:logeqv cl:logior cl:lognand cl:lognor cl:lognot cl:logorc1 cl:logorc2 cl:logxor cl:logbitp cl:logcount cl:logtest cl:byte cl:byte-size cl:byte-position cl:deposit-field cl:dpb cl:ldb cl:ldb-test cl:mask-field cl:most-positive-fixnum cl:most-negative-fixnum cl:decode-float cl:scale-float cl:float-radix cl:float-sign cl:float-digits cl:float-precision cl:integer-decode-float cl:float cl:floatp cl:most-positive-short-float cl:least-positive-short-float cl:least-positive-normalized-short-float cl:most-positive-double-float cl:least-positive-double-float cl:least-positive-normalized-double-float cl:most-positive-long-float cl:least-positive-long-float cl:least-positive-normalized-long-float cl:most-positive-single-float cl:least-positive-single-float cl:least-positive-normalized-single-float cl:most-negative-short-float cl:least-negative-short-float cl:least-negative-normalized-short-float cl:most-negative-single-float cl:least-negative-single-float cl:least-negative-normalized-single-float cl:most-negative-double-float cl:least-negative-double-float cl:least-negative-normalized-double-float cl:most-negative-long-float cl:least-negative-long-float cl:least-negative-normalized-long-float cl:short-float-epsilon cl:short-float-negative-epsilon cl:single-float-epsilon cl:single-float-negative-epsilon cl:double-float-epsilon cl:double-float-negative-epsilon cl:long-float-epsilon cl:long-float-negative-epsilon) (disabled-features arithmetic-error-operands arithmetic-error-operation) ;;; The Characters Dictionary (import-export-symbols cl:character cl:base-char cl:standard-char cl:extended-char cl:char= cl:char/= cl:char< cl:char> cl:char<= cl:char>= cl:char-equal cl:char-not-equal cl:char-lessp cl:char-greaterp cl:char-not-greaterp cl:char-not-lessp cl:characterp cl:alpha-char-p cl:alphanumericp cl:digit-char cl:digit-char-p cl:graphic-char-p cl:standard-char-p cl:char-upcase cl:char-downcase cl:upper-case-p cl:lower-case-p cl:both-case-p cl:char-code cl:char-int cl:code-char cl:char-code-limit cl:char-name cl:name-char) ;;; The Conses Dictionary (import-export-symbols cl:list cl:null cl:cons cl:atom cl:cons cl:consp cl:atom cl:rplaca cl:rplacd cl:car cl:cdr cl:caar cl:cadr cl:cdar cl:cddr cl:caaar cl:caadr cl:cadar cl:caddr cl:cdaar cl:cdadr cl:cddar cl:cdddr cl:caaaar cl:caaadr cl:caadar cl:caaddr cl:cadaar cl:cadadr cl:caddar cl:cadddr cl:cdaaar cl:cdaadr cl:cdadar cl:cdaddr cl:cddaar cl:cddadr cl:cdddar cl:cddddr cl:copy-tree cl:sublis cl:nsublis cl:subst cl:subst-if cl:subst-if-not cl:nsubst cl:nsubst-if cl:nsubst-if-not cl:tree-equal cl:copy-list cl:list cl:list* cl:list-length cl:listp cl:make-list cl:push cl:pop cl:first cl:second cl:third cl:fourth cl:fifth cl:sixth cl:seventh cl:eighth cl:ninth cl:tenth cl:nth cl:endp cl:null cl:nconc cl:append cl:revappend cl:nreconc cl:butlast cl:nbutlast cl:last cl:ldiff cl:tailp cl:nthcdr cl:rest cl:member cl:member-if cl:member-if-not cl:mapc cl:mapcar cl:mapcan cl:mapcan cl:mapl cl:maplist cl:mapcon cl:acons cl:assoc cl:assoc-if cl:assoc-if-not cl:copy-alist cl:pairlis cl:rassoc cl:rassoc-if cl:rassoc-if-not cl:get-properties cl:getf cl:remf cl:intersection cl:nintersection cl:adjoin cl:pushnew cl:set-difference cl:nset-difference cl:set-exclusive-or cl:nset-exclusive-or cl:subsetp cl:union cl:nunion) ;;; The Arrays Dictionary (import-export-symbols cl:array cl:simple-array cl:vector cl:simple-vector cl:bit-vector cl:simple-bit-vector cl:make-array cl:adjust-array cl:adjustable-array-p cl:aref cl:array-dimension cl:array-dimensions cl:array-element-type cl:array-has-fill-pointer-p cl:array-displacement cl:array-in-bounds-p cl:array-rank cl:array-row-major-index cl:array-total-size cl:arrayp cl:fill-pointer cl:row-major-aref cl:upgraded-array-element-type cl:array-dimension-limit cl:array-rank-limit cl:array-total-size-limit cl:simple-vector-p cl:svref cl:vector-pop cl:vector-push cl:vector-push-extend cl:vectorp cl:bit cl:sbit cl:bit-and cl:bit-andc1 cl:bit-andc2 cl:bit-eqv cl:bit-ior cl:bit-nand cl:bit-nor cl:bit-not cl:bit-orc1 cl:bit-orc2 cl:bit-xor cl:bit-vector-p cl:simple-bit-vector-p) ;;; The Strings Dictionary (import-export-symbols cl:string cl:base-string cl:simple-base-string cl:simple-string-p cl:char cl:schar cl:string-upcase cl:string-downcase cl:string-capitalize cl:nstring-upcase cl:nstring-downcase cl:nstring-capitalize cl:string-trim cl:string-left-trim cl:string-right-trim cl:string= cl:string/= cl:string< cl:string> cl:string<= cl:string>= cl:string-equal cl:string-not-equal cl:string-lessp cl:string-greaterp cl:string-not-greaterp cl:string-not-lessp cl:stringp cl:make-string) ;;; The Sequence Dictionary (import-export-symbols cl:sequence cl:copy-seq cl:elt cl:fill cl:make-sequence cl:subseq cl:map cl:map-into cl:reduce cl:count cl:count-if cl:count-if-not cl:length cl:reverse cl:nreverse cl:sort cl:stable-sort cl:find cl:find-if cl:find-if-not cl:position cl:position-if cl:position-if-not cl:search cl:mismatch cl:replace cl:substitute cl:substitute-if cl:substitute-if-not cl:nsubstitute cl:nsubstitute-if cl:nsubstitute-if-not cl:concatenate cl:merge cl:remove cl:remove-if cl:remove-if-not cl:delete cl:delete-if cl:delete-if-not cl:remove-duplicates cl:delete-duplicates) ;;; The Hash Tables Dictionary (import-export-symbols cl:hash-table cl:make-hash-table cl:hash-table-p cl:hash-table-count cl:hash-table-rehash-size cl:hash-table-rehash-threshold cl:hash-table-size cl:hash-table-test cl:gethash cl:remhash cl:maphash cl:with-hash-table-iterator cl:clrhash cl:sxhash) ;;; The Filenames Dictionary (import-export-symbols cl:pathname cl:make-pathname cl:pathnamep cl:pathname-directory cl:pathname-name cl:pathname-type cl:pathname-version cl:namestring cl:file-namestring cl:directory-namestring cl:parse-namestring cl:wild-pathname-p cl:pathname-match-p cl:translate-pathname cl:merge-pathnames) (disabled-features pathname-host pathname-device load-logical-pathname-translations logical-pathname-translations logical-pathname host-namestring enough-namestring translate-logical-pathname) ;;; The Files Dictionary (disabled-features directory probe-file ensure-directories-exist truename file-author file-write-date rename-file delete-file file-error-pathname) ;;; The Stream Dictionary (import-export-symbols cl:stream cl:broadcast-stream cl:concatenated-stream cl:echo-stream cl:file-stream cl:string-stream cl:synonym-stream cl:two-way-stream cl:input-stream-p cl:output-stream-p cl:interactive-stream-p cl:open-stream-p cl:stream-element-type cl:streamp cl:peek-char cl:read-char cl:read-char-no-hang cl:terpri cl:fresh-line cl:unread-char cl:write-char cl:read-line cl:write-string cl:write-line cl:read-sequence cl:write-sequence cl:file-position cl:close cl:listen cl:clear-input cl:finish-output cl:force-output cl:clear-output cl:with-input-from-string cl:with-output-to-string) (disabled-features read-byte write-byte file-length file-string-length open stream-external-format with-open-file with-open-stream y-or-n-p yes-or-no-p make-synonym-stream synonym-stream-symbol broadcast-stream-streams make-broadcast-stream make-two-way-stream two-way-stream-input-stream two-way-stream-output-stream make-echo-stream concatenated-stream-streams make-concatenated-stream make-string-input-stream make-string-output-stream stream-error-stream) ;;; The Printer Dictionary (import-export-symbols cl:write cl:prin1 cl:print cl:pprint cl:princ cl:write-to-string cl:prin1-to-string cl:princ-to-string) (disabled-features copy-pprint-dispatch formatter pprint-dispatch pprint-exit-if-list-exhausted pprint-fill pprint-linear pprint-tabular pprint-indent pprint-logical-block pprint-newline pprint-pop pprint-tab print-object print-unreadable-object set-ppring-dispatch print-not-readable-object format) ;;; The Reader Dictionary (disabled-features copy-readtable make-dispatch-macro-character read-preserving-whitespace read-delimited-list readtable-case readtablep set-dispatch-macro-character get-dispatch-macro-character set-macro-character get-macro-character set-syntax-from-char with-standard-io-syntax) (sdefun read (cl:&rest args) (cl:values-list (isolated-impl:translate-form (cl:multiple-value-list (cl:apply #'cl:read args))))) (sdefun read-from-string (cl:&rest args) (cl:values-list (isolated-impl:translate-form (cl:multiple-value-list (cl:apply #'cl:read-from-string args))))) ;;; The System Construction Dictionary (disabled-features compile-file compile-file-pathname load with-compilation-unit provide require) ;;; The Environment Dictionary (import-export-symbols cl:decode-universal-time cl:encode-universal-time cl:get-universal-time cl:get-decoded-time cl:sleep cl:lisp-implementation-type cl:lisp-implementation-version) (disabled-features apropos apropos-list describe describe-object trace untrace step time get-internal-real-time get-internal-run-time disassemble documentation room ed inspect dribble short-site-name long-site-name machine-instance machine-type machine-version software-type software-version) (sdefun user-homedir-pathname (cl:&optional ignored) (cl:declare (cl:ignore ignored)) isolated-impl:*isolated-homedir-pathname*)
18,822
Common Lisp
.lisp
355
48.583099
79
0.760563
kanru/cl-isolated
39
3
2
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
f99b74841a6e1a4508eb24c84adb8a569f32c4228bab2247656947fb052d082e
4,495
[ -1 ]
4,496
isolated-impl.lisp
kanru_cl-isolated/isolated-impl.lisp
;;;; Isolated --- A isolated environment for evaluating Common Lisp ;;;; expressions ;; Copyright (C) 2014, 2020 Kan-Ru Chen <[email protected]> ;; Copyright (C) 2012-2013 Teemu Likonen <[email protected]> ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public ;; License along with this program. If not, see ;; <http://www.gnu.org/licenses/>. (defpackage #:isolated-impl (:use #:cl) (:import-from #:alexandria #:with-gensyms #:circular-tree-p) (:export #:*env* #:*isolated-homedir-pathname* #:with-isolated-env #:translate-form #:isolated-error #:disabled-feature)) (in-package #:isolated-impl) (declaim (optimize (safety 3))) (defvar *env* "ISOLATED/LOCAL") (defvar *isolated-homedir-pathname* (make-pathname :directory '(:absolute "home" "isolated") :name nil :type nil)) (defvar *max-elements* 500) (define-condition isolated-error (error) nil (:report "Isolated error.")) (define-condition unsupported-type (isolated-error) ((type :initarg :type :reader unsupported-type)) (:report (lambda (c s) (format s "Type ~A is not supported." (unsupported-type c))))) (define-condition disabled-feature (isolated-error) ((name :initarg :name :reader disabled-feature-name)) (:report (lambda (c s) (format s "The feature ~A is disabled." (disabled-feature-name c))))) (define-condition circular-list (isolated-error) nil (:report "Circular list was detected.")) (define-condition dimension-error (isolated-error) nil (:report (lambda (c s) (declare (ignore c)) (format s "Array or list dimensions too large (max ~D elements)." *max-elements*)))) (defmacro with-isolated-env (&body body) (with-gensyms (input output two-way) `(with-open-stream (,input (make-string-input-stream "This is the standard input stream!")) (with-open-stream (,output (make-broadcast-stream)) (with-open-stream (,two-way (make-two-way-stream ,input ,output)) (with-standard-io-syntax (let ((*standard-output* ,output) (*error-output* ,output) (*trace-output* ,output) (*standard-input* ,input) (*debug-io* ,two-way) (*query-io* ,two-way) (*terminal-io* ,two-way) (*package* (find-package *env*)) (*features* nil) (*print-length* 50) (*print-level* 10) (*print-readably* nil) (*read-eval* nil) (*default-pathname-defaults* *isolated-homedir-pathname*)) ,@body))))))) (defvar *allowed-extra-symbols* nil) (defun translate-form (form) (when (and (consp form) (circular-tree-p form)) (error 'circular-list)) (let ((cons-count 0)) (labels ((translate (form) (typecase form (cons (if (> (incf cons-count) *max-elements*) (error 'dimension-error) (cons (translate (car form)) (translate (cdr form))))) (number form) (character form) (pathname form) (array (if (> (array-total-size form) *max-elements*) (error 'dimension-error) (let ((arr (make-array (array-dimensions form) :element-type (array-element-type form)))) (dotimes (i (array-total-size arr) arr) (setf (row-major-aref arr i) (translate-form (row-major-aref form i))))))) (keyword form) (symbol (if (member form *allowed-extra-symbols*) form (intern (symbol-name form) *env*))) (t (error 'unsupported-type :type (type-of form)))))) (translate form))))
4,738
Common Lisp
.lisp
101
34.70297
79
0.559256
kanru/cl-isolated
39
3
2
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
9e70b859fc79d865965595f1596e0e84c5b0c7849b253b7da733259b9beb9805
4,496
[ -1 ]
4,497
isolated.asd
kanru_cl-isolated/isolated.asd
(asdf:defsystem :isolated :version "1.1" :author "Kan-Ru Chen <[email protected]>" :licence "AGPLv3+" :description "A isolated environment for Common Lisp code evaluation" :depends-on (:alexandria) :components ((:file "isolated-impl") (:file "isolated-cl" :depends-on ("isolated-impl")) (:file "isolated" :depends-on ("isolated-impl"))))
357
Common Lisp
.asd
10
32.7
71
0.700288
kanru/cl-isolated
39
3
2
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
4c747e5610f31413aa3217f62f9268e875455d341ecd5923c980857946412080
4,497
[ -1 ]
4,517
g30_dash.lisp
m365fw_vesc_m365_dash/g30_dash.lisp
; G30 dashboard compability lisp script v1.0 by AKA13 and 1zuna ; UART Wiring: red=5V black=GND yellow=COM-TX (UART-HDX) green=COM-RX (button)+3.3V with 1K Resistor ; Guide (German): https://rollerplausch.com/threads/vesc-controller-einbau-1s-pro2-g30.6032/ ; Tested on VESC 6.05 on G30D w/ MKS 84100HP and MP2 300A VESC ; -> User parameters (change these to your needs) (def software-adc 1) (def min-adc-throttle 0.1) (def min-adc-brake 0.1) (def show-batt-in-idle 1) (def min-speed 1) (def button-safety-speed (/ 0.1 3.6)) ; disabling button above 0.1 km/h (due to safety reasons) ; Speed modes (km/h, watts, current scale) (def eco-speed (/ 7 3.6)) (def eco-current 0.6) (def eco-watts 400) (def eco-fw 0) (def drive-speed (/ 17 3.6)) (def drive-current 0.7) (def drive-watts 500) (def drive-fw 0) (def sport-speed (/ 21 3.6)) (def sport-current 1.0) (def sport-watts 700) (def sport-fw 0) ; Secret speed modes. To enable, press the button 2 times while holding break and throttle at the same time. (def secret-enabled 1) (def secret-eco-speed (/ 27 3.6)) (def secret-eco-current 0.8) (def secret-eco-watts 1200) (def secret-eco-fw 0) (def secret-drive-speed (/ 47 3.6)) (def secret-drive-current 0.9) (def secret-drive-watts 1500) (def secret-drive-fw 0) (def secret-sport-speed (/ 1000 3.6)) ; 1000 km/h easy (def secret-sport-current 1.0) (def secret-sport-watts 1500000) (def secret-sport-fw 10) ; -> Code starts here (DO NOT CHANGE ANYTHING BELOW THIS LINE IF YOU DON'T KNOW WHAT YOU ARE DOING) ; Load VESC CAN code serer (import "pkg@://vesc_packages/lib_code_server/code_server.vescpkg" 'code-server) (read-eval-program code-server) ; Packet handling (uart-start 115200 'half-duplex) (gpio-configure 'pin-rx 'pin-mode-in-pu) (define tx-frame (array-create 15)) (bufset-u16 tx-frame 0 0x5AA5) ;Ninebot protocol (bufset-u8 tx-frame 2 0x06) ;Payload length is 5 bytes (bufset-u16 tx-frame 3 0x2021) ; Packet is from ESC to BLE (bufset-u16 tx-frame 5 0x6400) ; Packet is from ESC to BLE (def uart-buf (array-create 64)) ; Button handling (def presstime (systime)) (def presses 0) ; Mode states (def off 0) (def lock 0) (def speedmode 4) (def light 0) (def unlock 0) ; Sound feedback (def feedback 0) (if (= software-adc 1) (app-adc-detach 3 1) (app-adc-detach 3 0) ) (defun adc-input(buffer) ; Frame 0x65 { (let ((current-speed (* (get-speed) 3.6)) (throttle (/(bufget-u8 uart-buf 5) 77.2)) ; 255/3.3 = 77.2 (brake (/(bufget-u8 uart-buf 6) 77.2))) { (if (< throttle 0) (setf throttle 0)) (if (> throttle 3.3) (setf throttle 3.3)) (if (< brake 0) (setf brake 0)) (if (> brake 3.3) (setf brake 3.3)) ; Pass through throttle and brake to VESC (app-adc-override 0 throttle) (app-adc-override 1 brake) } ) } ) (defun handle-features() { (if (or (or (= off 1) (= lock 1) (< (* (get-speed) 3.6) min-speed))) (if (not (app-is-output-disabled)) ; Disable output when scooter is turned off { (app-adc-override 0 0) (app-adc-override 1 0) (app-disable-output -1) (set-current 0) ;(loopforeach i (can-list-devs) ; (canset-current i 0) ;) } ) (if (app-is-output-disabled) ; Enable output when scooter is turned on (app-disable-output 0) ) ) (if (= lock 1) { (set-current-rel 0) ; No current input when locked (if (> (* (get-speed) 3.6) min-speed) (set-brake-rel 1) ; Full power brake (set-brake-rel 0) ; No brake ) } ) } ) (defun update-dash(buffer) ; Frame 0x64 { (var current-speed (* (l-speed) 3.6)) (var battery (*(get-batt) 100)) ; mode field (1=drive, 2=eco, 4=sport, 8=charge, 16=off, 32=lock) (if (= off 1) (bufset-u8 tx-frame 7 16) (if (= lock 1) (bufset-u8 tx-frame 7 32) ; lock display (if (or (> (get-temp-fet) 60) (> (get-temp-mot) 60)) ; temp icon will show up above 60 degree (bufset-u8 tx-frame 7 (+ 128 speedmode)) (bufset-u8 tx-frame 7 speedmode) ) ) ) ; batt field (bufset-u8 tx-frame 8 battery) ; light field (if (= off 0) (bufset-u8 tx-frame 9 light) (bufset-u8 tx-frame 9 0) ) ; beep field (if (= lock 1) (if (> current-speed min-speed) (bufset-u8 tx-frame 10 1) ; beep lock (bufset-u8 tx-frame 10 0)) (if (> feedback 0) { (bufset-u8 tx-frame 10 1) (set 'feedback (- feedback 1)) } (bufset-u8 tx-frame 10 0) ) ) ; speed field (if (= (+ show-batt-in-idle unlock) 2) (if (> current-speed 1) (bufset-u8 tx-frame 11 current-speed) (bufset-u8 tx-frame 11 battery)) (bufset-u8 tx-frame 11 current-speed) ) ; error field (bufset-u8 tx-frame 12 (get-fault)) ; calc crc (var crcout 0) (looprange i 2 13 (set 'crcout (+ crcout (bufget-u8 tx-frame i)))) (set 'crcout (bitwise-xor crcout 0xFFFF)) (bufset-u8 tx-frame 13 crcout) (bufset-u8 tx-frame 14 (shr crcout 8)) ; write (uart-write tx-frame) } ) (defun read-frames() (loopwhile t { (uart-read-bytes uart-buf 3 0) (if (= (bufget-u16 uart-buf 0) 0x5aa5) { (var len (bufget-u8 uart-buf 2)) (var crc len) (if (and (> len 0) (< len 60)) ; max 64 bytes { (uart-read-bytes uart-buf (+ len 6) 0) ;read remaining 6 bytes + payload, overwrite buffer (let ((code (bufget-u8 uart-buf 2)) (checksum (bufget-u16 uart-buf (+ len 4)))) { (looprange i 0 (+ len 4) (set 'crc (+ crc (bufget-u8 uart-buf i)))) (if (= checksum (bitwise-and (+ (shr (bitwise-xor crc 0xFFFF) 8) (shl (bitwise-xor crc 0xFFFF) 8)) 65535)) ;If the calculated checksum matches with sent checksum, forward comman (handle-frame code) ) } ) } ) } ) } ) ) (defun handle-frame(code) { (if (and (= code 0x65) (= software-adc 1)) (adc-input uart-buf) ) (if(= code 0x64) (update-dash uart-buf) ) } ) (defun handle-button() (if (= presses 1) ; single press (if (= off 1) ; is it off? turn on scooter again { (set 'off 0) ; turn on (set 'feedback 1) ; beep feedback (set 'unlock 0) ; Disable unlock on turn off (apply-mode) ; Apply mode on start-up (stats-reset) ; reset stats when turning on } (set 'light (bitwise-xor light 1)) ; toggle light ) (if (>= presses 2) ; double press { (if (> (get-adc-decoded 1) min-adc-brake) ; if brake is pressed (if (and (= secret-enabled 1) (> (get-adc-decoded 0) min-adc-throttle)) { (set 'unlock (bitwise-xor unlock 1)) (set 'feedback 2) ; beep 2x (apply-mode) } { (set 'unlock 0) (apply-mode) (set 'lock (bitwise-xor lock 1)) ; lock on or off (set 'feedback 1) ; beep feedback } ) { (if (= lock 0) { (cond ((= speedmode 1) (set 'speedmode 4)) ((= speedmode 2) (set 'speedmode 1)) ((= speedmode 4) (set 'speedmode 2)) ) (apply-mode) } ) } ) } ) ) ) (defun handle-holding-button() { (if (= (+ lock off) 0) ; it is locked and off? { (set 'unlock 0) ; Disable unlock on turn off (apply-mode) (set 'off 1) ; turn off (set 'light 0) ; turn off light (set 'feedback 1) ; beep feedback } ) } ) (defun reset-button() { (set 'presstime (systime)) ; reset press time again (set 'presses 0) } ) ; Speed mode implementation (defun apply-mode() (if (= unlock 0) (if (= speedmode 1) (configure-speed drive-speed drive-watts drive-current drive-fw) (if (= speedmode 2) (configure-speed eco-speed eco-watts eco-current eco-fw) (if (= speedmode 4) (configure-speed sport-speed sport-watts sport-current sport-fw) ) ) ) (if (= speedmode 1) (configure-speed secret-drive-speed secret-drive-watts secret-drive-current secret-drive-fw) (if (= speedmode 2) (configure-speed secret-eco-speed secret-eco-watts secret-eco-current secret-eco-fw) (if (= speedmode 4) (configure-speed secret-sport-speed secret-sport-watts secret-sport-current secret-sport-fw) ) ) ) ) ) (defun configure-speed(speed watts current fw) { (set-param 'max-speed speed) (set-param 'l-watt-max watts) (set-param 'l-current-max-scale current) (set-param 'foc-fw-current-max fw) } ) (defun set-param (param value) { (conf-set param value) (loopforeach id (can-list-devs) (looprange i 0 5 { (if (eq (rcode-run id 0.1 `(conf-set (quote ,param) ,value)) t) (break t)) false }) ) } ) (defun l-speed() { (var l-speed (get-speed)) (loopforeach i (can-list-devs) { (var l-can-speed (canget-speed i)) (if (< l-can-speed l-speed) (set 'l-speed l-can-speed) ) } ) l-speed } ) (defun button-logic() { ; Assume button is not pressed by default (var buttonold 0) (loopwhile t { (var button (gpio-read 'pin-rx)) (sleep 0.05) ; wait 50 ms to debounce (var buttonconfirm (gpio-read 'pin-rx)) (if (not (= button buttonconfirm)) (set 'button 0) ) (if (> buttonold button) { (set 'presses (+ presses 1)) (set 'presstime (systime)) } (button-apply button) ) (set 'buttonold button) (handle-features) } ) } ) (defun button-apply(button) { (var time-passed (- (systime) presstime)) (var is-active (or (= off 1) (<= (get-speed) button-safety-speed))) (if (> time-passed 2500) ; after 2500 ms (if (= button 0) ; check button is still pressed (if (> time-passed 6000) ; long press after 6000 ms { (if is-active (handle-holding-button) ) (reset-button) ; reset button } ) (if (> presses 0) ; if presses > 0 { (if is-active (handle-button) ; handle button presses ) (reset-button) ; reset button } ) ) ) } ) ; Apply mode on start-up (apply-mode) ; Spawn UART reading frames thread (spawn 150 read-frames) (button-logic) ; Start button logic in main thread - this will block the main thread
13,301
Common Lisp
.lisp
383
22.383812
213
0.476591
m365fw/vesc_m365_dash
30
6
1
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
7c6702e7e422799e93761cef467ee820133fb31a6462e1701f40fbd75154abb6
4,517
[ -1 ]
4,518
m365_dash.lisp
m365fw_vesc_m365_dash/m365_dash.lisp
; M365 dashboard compability lisp script v1.0 by Netzpfuscher and 1zuna ; UART Wiring: red=5V black=GND yellow=COM-TX (UART-HDX) green=COM-RX (button)+3.3V with 1K Resistor ; Guide (German): https://rollerplausch.com/threads/vesc-controller-einbau-1s-pro2-g30.6032/ ; -> User parameters (change these to your needs) (def software-adc 1) (def min-adc-throttle 0.1) (def min-adc-brake 0.1) (def show-batt-in-idle 1) (def min-speed 1) (def button-safety-speed (/ 0.1 3.6)) ; disabling button above 0.1 km/h (due to safety reasons) ; Speed modes (km/h, watts, current scale) (def eco-speed (/ 7 3.6)) (def eco-current 0.6) (def eco-watts 400) (def eco-fw 0) (def drive-speed (/ 17 3.6)) (def drive-current 0.7) (def drive-watts 500) (def drive-fw 0) (def sport-speed (/ 21 3.6)) (def sport-current 1.0) (def sport-watts 700) (def sport-fw 0) ; Secret speed modes. To enable, press the button 2 times while holding break and throttle at the same time. (def secret-enabled 1) (def secret-eco-speed (/ 27 3.6)) (def secret-eco-current 0.8) (def secret-eco-watts 1200) (def secret-eco-fw 0) (def secret-drive-speed (/ 47 3.6)) (def secret-drive-current 0.9) (def secret-drive-watts 1500) (def secret-drive-fw 0) (def secret-sport-speed (/ 1000 3.6)) ; 1000 km/h easy (def secret-sport-current 1.0) (def secret-sport-watts 1500000) (def secret-sport-fw 10) ; -> Code starts here (DO NOT CHANGE ANYTHING BELOW THIS LINE IF YOU DON'T KNOW WHAT YOU ARE DOING) ; Load VESC CAN code serer (import "pkg@://vesc_packages/lib_code_server/code_server.vescpkg" 'code-server) (read-eval-program code-server) ; Packet handling (uart-start 115200 'half-duplex) (gpio-configure 'pin-rx 'pin-mode-in-pu) (def tx-frame (array-create 14)) (bufset-u16 tx-frame 0 0x55AA) (bufset-u16 tx-frame 2 0x0821) (bufset-u16 tx-frame 4 0x6400) (def uart-buf (array-create 64)) ; Button handling (def presstime (systime)) (def presses 0) ; Mode states (def off 0) (def lock 0) (def speedmode 4) (def light 0) (def unlock 0) ; Sound feedback (def feedback 0) (if (= software-adc 1) (app-adc-detach 3 1) (app-adc-detach 3 0) ) (defun adc-input(buffer) ; Frame 0x65 { (let ((current-speed (* (get-speed) 3.6)) (throttle (/(bufget-u8 uart-buf 4) 77.2)) ; 255/3.3 = 77.2 (brake (/(bufget-u8 uart-buf 5) 77.2))) { (if (< throttle 0) (setf throttle 0)) (if (> throttle 3.3) (setf throttle 3.3)) (if (< brake 0) (setf brake 0)) (if (> brake 3.3) (setf brake 3.3)) ; Pass through throttle and brake to VESC (app-adc-override 0 throttle) (app-adc-override 1 brake) } ) } ) (defun handle-features() { (if (or (or (= off 1) (= lock 1) (< (* (get-speed) 3.6) min-speed))) (if (not (app-is-output-disabled)) ; Disable output when scooter is turned off { (app-adc-override 0 0) (app-adc-override 1 0) (app-disable-output -1) (set-current 0) ;(loopforeach i (can-list-devs) ; (canset-current i 0) ;) } ) (if (app-is-output-disabled) ; Enable output when scooter is turned on (app-disable-output 0) ) ) (if (= lock 1) { (set-current-rel 0) ; No current input when locked (if (> (* (get-speed) 3.6) min-speed) (set-brake-rel 1) ; Full power brake (set-brake-rel 0) ; No brake ) } ) } ) (defun update-dash(buffer) ; Frame 0x64 { (var current-speed (* (l-speed) 3.6)) (var battery (*(get-batt) 100)) ; mode field (1=drive, 2=eco, 4=sport, 8=charge, 16=off, 32=lock) (if (= off 1) (bufset-u8 tx-frame 6 16) (if (= lock 1) (bufset-u8 tx-frame 6 32) ; lock display (if (or (> (get-temp-fet) 60) (> (get-temp-mot) 60)) ; temp icon will show up above 60 degree (bufset-u8 tx-frame 6 (+ 128 speedmode)) (bufset-u8 tx-frame 6 speedmode) ) ) ) ; batt field (bufset-u8 tx-frame 7 battery) ; light field (if (= off 0) (bufset-u8 tx-frame 8 light) (bufset-u8 tx-frame 8 0) ) ; beep field (if (= lock 1) (if (> current-speed min-speed) (bufset-u8 tx-frame 9 1) ; beep lock (bufset-u8 tx-frame 9 0)) (if (> feedback 0) { (bufset-u8 tx-frame 9 1) (set 'feedback (- feedback 1)) } (bufset-u8 tx-frame 9 0) ) ) ; speed field (if (= (+ show-batt-in-idle unlock) 2) (if (> current-speed 1) (bufset-u8 tx-frame 10 current-speed) (bufset-u8 tx-frame 10 battery)) (bufset-u8 tx-frame 10 current-speed) ) ; error field (bufset-u8 tx-frame 11 (get-fault)) ; calc crc (var crc 0) (looprange i 2 12 (set 'crc (+ crc (bufget-u8 tx-frame i)))) (var c-out (bitwise-xor crc 0xFFFF)) (bufset-u8 tx-frame 12 c-out) (bufset-u8 tx-frame 13 (shr c-out 8)) ; write (uart-write tx-frame) } ) (defun read-frames() (loopwhile t { (uart-read-bytes uart-buf 3 0) (if (= (bufget-u16 uart-buf 0) 0x55aa) { (var len (bufget-u8 uart-buf 2)) (var crc len) (if (and (> len 0) (< len 60)) ; max 64 bytes { (uart-read-bytes uart-buf (+ len 4) 0) (looprange i 0 len (set 'crc (+ crc (bufget-u8 uart-buf i)))) (if (=(+(shl(bufget-u8 uart-buf (+ len 2))8) (bufget-u8 uart-buf (+ len 1))) (bitwise-xor crc 0xFFFF)) (handle-frame (bufget-u8 uart-buf 1)) ) } ) } ) } ) ) (defun handle-frame(code) { (if (and (= code 0x65) (= software-adc 1)) (adc-input uart-buf) ) (update-dash uart-buf) } ) (defun handle-button() (if (= presses 1) ; single press (if (= off 1) ; is it off? turn on scooter again { (set 'off 0) ; turn on (set 'feedback 1) ; beep feedback (set 'unlock 0) ; Disable unlock on turn off (apply-mode) ; Apply mode on start-up (stats-reset) ; reset stats when turning on } (set 'light (bitwise-xor light 1)) ; toggle light ) (if (>= presses 2) ; double press { (if (> (get-adc-decoded 1) min-adc-brake) ; if brake is pressed (if (and (= secret-enabled 1) (> (get-adc-decoded 0) min-adc-throttle)) { (set 'unlock (bitwise-xor unlock 1)) (set 'feedback 2) ; beep 2x (apply-mode) } { (set 'unlock 0) (apply-mode) (set 'lock (bitwise-xor lock 1)) ; lock on or off (set 'feedback 1) ; beep feedback } ) { (if (= lock 0) { (cond ((= speedmode 1) (set 'speedmode 4)) ((= speedmode 2) (set 'speedmode 1)) ((= speedmode 4) (set 'speedmode 2)) ) (apply-mode) } ) } ) } ) ) ) (defun handle-holding-button() { (if (= (+ lock off) 0) ; it is locked and off? { (set 'unlock 0) ; Disable unlock on turn off (apply-mode) (set 'off 1) ; turn off (set 'light 0) ; turn off light (set 'feedback 1) ; beep feedback } ) } ) (defun reset-button() { (set 'presstime (systime)) ; reset press time again (set 'presses 0) } ) ; Speed mode implementation (defun apply-mode() (if (= unlock 0) (if (= speedmode 1) (configure-speed drive-speed drive-watts drive-current drive-fw) (if (= speedmode 2) (configure-speed eco-speed eco-watts eco-current eco-fw) (if (= speedmode 4) (configure-speed sport-speed sport-watts sport-current sport-fw) ) ) ) (if (= speedmode 1) (configure-speed secret-drive-speed secret-drive-watts secret-drive-current secret-drive-fw) (if (= speedmode 2) (configure-speed secret-eco-speed secret-eco-watts secret-eco-current secret-eco-fw) (if (= speedmode 4) (configure-speed secret-sport-speed secret-sport-watts secret-sport-current secret-sport-fw) ) ) ) ) ) (defun configure-speed(speed watts current fw) { (set-param 'max-speed speed) (set-param 'l-watt-max watts) (set-param 'l-current-max-scale current) (set-param 'foc-fw-current-max fw) } ) (defun set-param (param value) { (conf-set param value) (loopforeach id (can-list-devs) (looprange i 0 5 { (if (eq (rcode-run id 0.1 `(conf-set (quote ,param) ,value)) t) (break t)) false }) ) } ) (defun l-speed() { (var l-speed (get-speed)) (loopforeach i (can-list-devs) { (var l-can-speed (canget-speed i)) (if (< l-can-speed l-speed) (set 'l-speed l-can-speed) ) } ) l-speed } ) (defun button-logic() { ; Assume button is not pressed by default (var buttonold 0) (loopwhile t { (var button (gpio-read 'pin-rx)) (sleep 0.05) ; wait 50 ms to debounce (var buttonconfirm (gpio-read 'pin-rx)) (if (not (= button buttonconfirm)) (set 'button 0) ) (if (> buttonold button) { (set 'presses (+ presses 1)) (set 'presstime (systime)) } (button-apply button) ) (set 'buttonold button) (handle-features) } ) } ) (defun button-apply(button) { (var time-passed (- (systime) presstime)) (var is-active (or (= off 1) (<= (get-speed) button-safety-speed))) (if (> time-passed 2500) ; after 2500 ms (if (= button 0) ; check button is still pressed (if (> time-passed 6000) ; long press after 6000 ms { (if is-active (handle-holding-button) ) (reset-button) ; reset button } ) (if (> presses 0) ; if presses > 0 { (if is-active (handle-button) ; handle button presses ) (reset-button) ; reset button } ) ) ) } ) ; Apply mode on start-up (apply-mode) ; Spawn UART reading frames thread (spawn 150 read-frames) (button-logic) ; Start button logic in main thread - this will block the main thread
12,673
Common Lisp
.lisp
376
21.683511
130
0.472895
m365fw/vesc_m365_dash
30
6
1
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
d6ad5575ef8ff47a93a0f199c875170f2b36bb49388a0621f538dbabea6a0156
4,518
[ -1 ]
4,519
sasch_turbo_awd.lisp
m365fw_vesc_m365_dash/customs/sasch_turbo_awd.lisp
; M365 dashboard compability lisp script for Sasch Turbo v0.5 by Netzpfuscher and 1zuna ; UART Wiring: red=5V black=GND yellow=COM-TX (UART-HDX) green=COM-RX (button)+3.3V with 1K Resistor ; Guide (German): https://rollerplausch.com/threads/vesc-controller-einbau-1s-pro2-g30.6032/ ; Tested on VESC 6.0 on PRO2 w/ Makerbase 75100 Alu PCB ; **** User parameters **** ;Calibrate throttle min max (define cal-thr-lo 41.0) (define cal-thr-hi 167.0) (define thr-deadzone 0.05) ;Calibrate brake min max (define cal-brk-lo 39.0) (define cal-brk-hi 179.0) (define brk-deadzone 0.05) (define brk-minspeed 1) (define light-default 0) (define show-faults 1) (define show-batt-in-idle 1) (define min-speed 1) (define button-safety-speed (/ 0.1 3.6)) ; disabling button above 0.1 km/h (due to safety reasons) ; Speed modes with MAX KM/H and MAX WATTS (define eco-speed (/ 7 3.6)) (define eco-current 0.6) (define eco-watts 400) (define drive-speed (/ 17 3.6)) (define drive-current 0.7) (define drive-watts 500) (define sport-speed (/ 21 3.6)) ; or 400 (define sport-current 1.0) (define sport-watts 700) ; or 1500000 (define secret-enabled 1) (define secret-eco-speed (/ 25 3.6)) (define secret-eco-current 0.6) (define secret-eco-watts 1500000) (define secret-drive-speed (/ 45 3.6)) (define secret-drive-current 0.8) (define secret-drive-watts 1500000) (define secret-sport-speed (/ 400 3.6)) (define secret-sport-current 1.0) (define secret-sport-watts 1500000) ; Set slave controller (define slave-can 15) ; **** Code section **** (uart-start 115200 'half-duplex) (gpio-configure 'pin-rx 'pin-mode-in-pu) (define tx-frame (array-create 14)) (bufset-u16 tx-frame 0 0x55AA) (bufset-u16 tx-frame 2 0x0821) (bufset-u16 tx-frame 4 0x6400) (define uart-buf (array-create type-byte 64)) (define current-speed 0) (define throttle-in 0) (define throttle 0) (define brake-in 0) (define brake 0) (define buttonold 0) (define light 0) (setvar 'light light-default) (define c-out 0) (define code 0) ; Button handling (define presstime (systime)) (define presses 0) ; Mode states (define off 0) (define lock 0) (define speedmode 4) (define unlock 0) ; Sound feedback (define feedback 0) (defun adc-input(buffer) ; Frame 0x65 (progn (setvar 'current-speed (* (get-speed) 3.6)) ; Throttle (setvar 'throttle-in (bufget-u8 uart-buf 4)) (setvar 'throttle (/(- throttle-in cal-thr-lo) cal-thr-hi)) (if (< throttle thr-deadzone) (setvar 'throttle 0) ) (if (> throttle 1) (setvar 'throttle 1) ) ; Brake (setvar 'brake-in (bufget-u8 uart-buf 5)) (setvar 'brake (/(- brake-in cal-brk-lo) cal-brk-hi)) (if(< brake brk-deadzone) (setvar 'brake 0) ) (if (< current-speed brk-minspeed) (setvar 'brake 0) ) (if (> brake 1) (setvar 'brake 1) ) (if (= (+ off lock) 0) (progn ; Driving mode (if (> current-speed min-speed) (progn (set-current-rel throttle) (if (= unlock 1) (canset-current-rel slave-can throttle) (canset-current-rel slave-can 0) ) ) (progn (set-current-rel 0) (canset-current-rel slave-can 0) ) ) (if (not (= brake 0)) (progn (set-brake-rel brake) (canset-brake-rel slave-can brake) ) ) ) (progn (set-current-rel 0) ; No throttle input when off or locked (canset-current-rel slave-can 0) (if (= lock 1) ; Check if it is locked (if (> current-speed min-speed) ; Brake when being pushed while locked (set-brake-rel 1) ; Full power brake (set-brake-rel 0) ; No brake ) (set-brake-rel 0) ; No brake input when off ) ) ) ) ) (defun update-dash(buffer) ; Frame 0x64 (progn ; mode field (1=drive, 2=eco, 4=sport, 8=charge, 16=off, 32=lock) (if (= off 1) (bufset-u8 tx-frame 6 16) (if (= lock 1) (bufset-u8 tx-frame 6 32) ; lock display (if (< (get-temp-fet) 60) ; temp icon will show up above 60 degree (bufset-u8 tx-frame 6 speedmode) (bufset-u8 tx-frame 6 (+ 128 speedmode)) ) ) ) ; batt field (bufset-u8 tx-frame 7 (*(get-batt) 100)) ; light field (if (= off 0) (bufset-u8 tx-frame 8 light) (bufset-u8 tx-frame 8 0) ) ; beep field (if (= lock 1) (if (> (* (get-speed) 3.6) min-speed) (bufset-u8 tx-frame 9 1) ; beep lock (bufset-u8 tx-frame 9 0)) (if (> feedback 0) (progn (bufset-u8 tx-frame 9 1) (setvar 'feedback (- feedback 1)) ) (bufset-u8 tx-frame 9 0) ) ) ; speed field (if (= (+ show-batt-in-idle unlock) 2) (if (> (* (get-speed) 3.6) 1) (bufset-u8 tx-frame 10 (* (get-speed) 3.6)) (bufset-u8 tx-frame 10 (*(get-batt) 100))) (bufset-u8 tx-frame 10 (* (get-speed) 3.6)) ) ; error field (if (= show-faults 1) (bufset-u8 tx-frame 11 (get-fault)) ) ; calc crc (setvar 'crc 0) (looprange i 2 12 (setvar 'crc (+ crc (bufget-u8 tx-frame i)))) (setvar 'c-out (bitwise-xor crc 0xFFFF)) (bufset-u8 tx-frame 12 c-out) (bufset-u8 tx-frame 13 (shr c-out 8)) ; write (uart-write tx-frame) ) ) (defun read-frames() (loopwhile t (progn (uart-read-bytes uart-buf 3 0) (if (= (bufget-u16 uart-buf 0) 0x55aa) (progn (setvar 'len (bufget-u8 uart-buf 2)) (setvar 'crc len) (if (and (> len 0) (< len 60)) ; max 64 bytes (progn (uart-read-bytes uart-buf (+ len 4) 0) (looprange i 0 len (setvar 'crc (+ crc (bufget-u8 uart-buf i)))) (if (=(+(shl(bufget-u8 uart-buf (+ len 2))8) (bufget-u8 uart-buf (+ len 1))) (bitwise-xor crc 0xFFFF)) (handle-frame (bufget-u8 uart-buf 1)) ) ) ) ) ) ) ) ) (defun handle-frame(code) (progn (if(= code 0x65) (adc-input uart-buf) ) ;(if(= code 0x64) (update-dash uart-buf) ;) ) ) (defun handle-button() (if (= presses 1) ; single press (if (= off 1) ; is it off? turn on scooter again (progn (setvar 'off 0) ; turn on (setvar 'feedback 1) ; beep feedback (setvar 'unlock 0) ; Disable unlock on turn off (apply-mode) ; Apply mode on start-up (stats-reset) ; reset stats when turning on ) (setvar 'light (bitwise-xor light 1)) ; toggle light ) (if (= presses 2) ; double press (progn (if (= speedmode 1) (progn (setvar 'speedmode 4) ) (if (= speedmode 2) (progn (setvar 'speedmode 1) ) (if (or (= speedmode 4)) (setvar 'speedmode 2) ) ) ) (apply-mode) ) (if (= presses 3) ; double press (if (and (= secret-enabled 1) (> (/(- throttle-in cal-thr-lo) cal-thr-hi) thr-deadzone)) (progn (setvar 'unlock (bitwise-xor unlock 1)) (setvar 'feedback 2) ; beep 2x (apply-mode) ) (progn (setvar 'lock (bitwise-xor lock 1)) ; lock on or off (setvar 'feedback 1) ; beep feedback ) ) ) ) ) ) (defun handle-holding-button() (progn (if (= (+ lock off) 0) ; it is locked and off? (progn (setvar 'unlock 0) ; Disable unlock on turn off (apply-mode) (setvar 'off 1) ; turn off (setvar 'feedback 1) ; beep feedback ) ) ) ) (defun reset-button() (progn (setvar 'presstime (systime)) ; reset press time again (setvar 'presses 0) ) ) ; Speed mode implementation (defun apply-mode() (if (= unlock 0) (if (= speedmode 1) (configure-speed drive-speed drive-watts drive-current) (if (= speedmode 2) (configure-speed eco-speed eco-watts eco-current) (if (= speedmode 4) (configure-speed sport-speed sport-watts sport-current) ) ) ) (if (= speedmode 1) (configure-speed secret-drive-speed secret-drive-watts secret-drive-current) (if (= speedmode 2) (configure-speed secret-eco-speed secret-eco-watts secret-eco-current) (if (= speedmode 4) (configure-speed secret-sport-speed secret-sport-watts secret-sport-current) ) ) ) ) ) (defun configure-speed(speed watts current) (progn (conf-set 'max-speed speed) (conf-set 'l-watt-max watts) (conf-set 'l-current-max-scale current) (can-cmd slave-can (str-merge "(conf-set 'max-speed " (str-from-n speed) ")")) (can-cmd slave-can (str-merge "(conf-set 'l-watt-max " (str-from-n watts) ")")) (can-cmd slave-can (str-merge "(conf-set 'l-current-max-scale " (str-from-n current) ")")) ) ) ; Apply mode on start-up (apply-mode) ; Spawn UART reading frames thread (spawn 150 read-frames) (loopwhile t (progn (if (> buttonold (gpio-read 'pin-rx)) (progn (setvar 'presses (+ presses 1)) (setvar 'presstime (systime)) ) (if (> (- (systime) presstime) 2500) ; after 2500 ms (if (= (gpio-read 'pin-rx) 0) ; check button is still pressed (if (> (- (systime) presstime) 6000) ; long press after 6000 ms (progn (if (<= (get-speed) button-safety-speed) (handle-holding-button) ) (reset-button) ; reset button ) ) (progn ; when button not pressed (if (> presses 0) ; if presses > 0 (progn (if (<= (get-speed) button-safety-speed) (handle-button) ; handle button presses ) (reset-button) ; reset button ) ) ) ) ) ) (setvar 'buttonold (gpio-read 'pin-rx)) (sleep 0.05) ; Recude load on the CPU ) )
12,151
Common Lisp
.lisp
351
22.598291
130
0.484588
m365fw/vesc_m365_dash
30
6
1
GPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
ef6ed4c144e72f18066e432335d0c3f56b168d9ca99b8a75817052fce08a1736
4,519
[ -1 ]
4,538
run.lisp
OpenBookStore_openbookstore/run.lisp
" Usage: sbcl --load run.lisp This loads the project's asd, loads the quicklisp dependencies, and starts the web server. Then, we are given the lisp prompt: we can interact with the running application. Another solution to run the app is to run the executable (see README). " (require "asdf") ;; for Docker (load "openbookstore.asd") (ql:quickload "openbookstore") (in-package :openbookstore/web) (handler-bind ((error (lambda (c) (format *error-output* "~&An error occured: ~a~&" c) (format *error-output* "~&Backtrace:~&") (trivial-backtrace:print-backtrace c)) ;; XXX: quit also kills the current lisp process, which is ;; annoying when developing with a REPL. ;; (uiop:quit 1) )) (start-app :port (or (ignore-errors (parse-integer (uiop:getenv "OBS_PORT"))) *port*)))
947
Common Lisp
.lisp
22
34.136364
81
0.607843
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
bc2289bb5d608c928947435c591457cc51aad6b41b9a9894cd928a60a1ce493c
4,538
[ -1 ]
4,539
database.lisp
OpenBookStore_openbookstore/src/database.lisp
(in-package :openbookstore.models) ;; ;; DB connection, migrations. ;; (defparameter *tables* '(book place place-copies contact contact-copies basket basket-copies user role user-role role-copy sell sold-cards shelf payment-method )) (defun connect (&optional (db-name (db-name))) "Connect to the DB." ;; also use mito:*connection* (log:debug "connecting to ~a~&" (db-name)) (force-output) (setf *db* (mito:connect-toplevel :sqlite3 :database-name db-name))) (defun ensure-tables-exist () (unless mito::*connection* (connect)) (mapcar #'mito:ensure-table-exists *tables*)) (defun migrate-all () "Migrate the Book table after we changed the class definition." ;; We'd rather use a "with-connexion" style to drop the connection afterwards. ;; Use mito:*auto-migration-mode* to nil to delete migration intermediate tables used with sqlite3. (unless mito::*connection* (connect)) (mapcar #'mito:migrate-table *tables*)) (defun bootstrap-base-roles () (define-role :visitor ()) (define-role :vendor (:visitor)) (define-role :editor (:vendor)) (define-role :admin (:editor)) t) (defun initialize-database () (ensure-tables-exist) (bootstrap-base-roles))
1,548
Common Lisp
.lisp
45
24.511111
101
0.563126
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
7aab5de3ecda4dfdac922e6a47f2e45eda77590b19049e85689f746c9170c2b7
4,539
[ -1 ]
4,540
i18n.lisp
OpenBookStore_openbookstore/src/i18n.lisp
(defpackage :bookshops.i18n (:use :cl) (:import-from :gettext #:*current-locale*) (:export #:_ #:n_ #:*current-locale* #:list-loaded-locales #:set-locale #:with-locale #:update-djula.pot) (:documentation "Internationalisation utilities")) (in-package :bookshops.i18n) (setf (gettext:textdomain) "openbookstore") (gettext:setup-gettext #.*package* "openbookstore") ;; Only preload the translations into the image if we're not deployed yet. (unless (deploy:deployed-p) (format *debug-io* "~%gettext: reading all *.mo files...") (gettext:preload-catalogs ;; Tell gettext where to find the .mo files #.(asdf:system-relative-pathname :openbookstore "locale/")) (format *debug-io* "done.~&")) ;; Run this when developping to reload the translations #+ (or) (progn ;; Clear gettext's cache (clrhash gettext::*catalog-cache*) (gettext:preload-catalogs ;; Tell gettext where to find the .mo files #.(asdf:system-relative-pathname :openbookstore "locale/"))) ;; Run this to see the list of loaded message for a specific locale #+ (or) (gettext::catalog-messages (gethash '("fr_fr" :LC_MESSAGES "openbookstore") gettext::*catalog-cache*)) ;; Test the translation of a string #+ (or) (with-locale ("fr_fr") (_ "Please login to continue")) #+ (or) (set-locale "fr_fr") #+ (or) *current-locale* (defun list-loaded-locales () "Get the list of locales loaded in gettext's cache." (remove-duplicates (mapcar #'first (alexandria:hash-table-keys gettext::*catalog-cache*)) :test #'string=)) (defun set-locale (locale) "Setf gettext:*current-locale* and djula:*current-language* if LOCALE seems valid." ;; It is valid to set the locale to nil. (when (and locale (not (member locale (list-loaded-locales) :test 'string=))) (error "Locale not valid or not available: ~s" locale)) (setf *current-locale* locale djula:*current-language* locale)) (defmacro with-locale ((locale) &body body) "Calls BODY with gettext:*current-locale* and djula:*current-language* set to LOCALE." `(let (*current-locale* djula:*current-language*) (set-locale ,locale) ,@body)) ;; (trace _) ;; (trace djula:translate gettext:gettext* gettext::lookup) ;; (_ "hi") #| This could technically be just (mapcan #'djula.locale:file-template-translate-strings (djula:list-asdf-system-templates "openbookstore" "src/web/templates")) But I (fstamour) made it just a bit more complex in order to keep track of the source (just the filename) of each translatable strings. Hence why the hash-table returned is named `locations`. |# (defun extract-translate-strings () "Extract all {_ ... _} string from the djula templates." (loop :with locations = (make-hash-table :test 'equal) :for path :in (djula:list-asdf-system-templates "openbookstore" "src/web/templates") :for strings = (djula.locale:file-template-translate-strings path) :do (loop :for string :in strings :unless (gethash string locations) :do (setf (gethash string locations) path)) :finally (return locations))) (defun update-djula.pot () "Update djula.pot from *.html files." (with-open-file (s (asdf:system-relative-pathname "openbookstore" "locale/templates/LC_MESSAGES/djula.pot") :direction :output :if-exists :supersede :if-does-not-exist :create) (let* ((locations (extract-translate-strings)) (strings (alexandria:hash-table-keys locations))) (loop :for string :in strings :for location = (gethash string locations) :do (format s "~%#: ~a~%#, lisp-format~%msgid ~s~%msgstr \"\" ~%" (enough-namestring location (asdf:system-relative-pathname "openbookstore" "")) string)))))
3,905
Common Lisp
.lisp
100
33.87
109
0.670719
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
17bf18fe62de0385ab2728d5100ecb714234ad399d609db0bcf8acc1c97d73bf
4,540
[ -1 ]
4,541
bookshops.lisp
OpenBookStore_openbookstore/src/bookshops.lisp
(in-package :openbookstore) (defun init () "Init i18n, connect to the DB,..." (openbookstore.models:connect) ;; Disabled until we ship the translation files into the binary release. ;; (i18n-load) (log:config :error)) (defun handle-parser-error (c) (format t "Argument error: ~a~&" (opts:option c)) ;; XXX: probably don't quit. (uiop:quit 1)) (defparameter +version+ (let ((version (asdf/component:component-version (asdf:find-system :openbookstore))) (directory (asdf:system-source-directory :openbookstore))) (or (ignore-errors (uiop:with-current-directory (directory) (multiple-value-bind (current-commit) (uiop:run-program (list "git" "describe" "--always") :output '(:string :stripped t)) (concatenate 'string version (format nil "-~a" current-commit))))) version)) "The version number as in the asd appended with the current commit id.") (defparameter *default-datasource* :fr "The default datasource to where search for books, by ISBN or keywords. Defaults to the french scraper.") (defvar *datasource* "french" "The current datasource for this command-line query. Use --datasource on the CLI to change it. Available options: france, argentina, dilicom (for French profesionals).") (defun search-books (query &key (datasource *default-datasource*)) "Search on datasources, get a list of hash-tables, transform them to book objects, and check if some already exist in our DB. In that case, update them. - DATASOURCE: where to search for books, by ISBN or keywords. Defaults to the french one (:fr). See *default-datasource*. Return: a list of BOOK objects." (let ((res (datasources:search-books query :datasource datasource))) (loop for bk in res collect (find-existing (make-book :title (access bk :title) :isbn (access bk :isbn) :authors (access bk :authors) :details-url (access bk :details-url) :cover-url (access bk :cover-url) :publisher (access bk :publisher) :date-publication (access bk :date-publication) :price (access bk :price) :datasource (access bk :datasource)) :update t)))) (defun print-system-info (&optional (stream t)) ;; see also https://github.com/40ants/cl-info (format stream "~&OS: ~a ~a~&" (software-type) (software-version)) (format stream "~&Lisp: ~a ~a~&" (lisp-implementation-type) (lisp-implementation-version)) #+asdf (format stream "~&ASDF: ~a~&" (asdf:asdf-version)) #-asdf (format stream "NO ASDF!") ;; #+quicklisp ;; (format stream "~&Quicklisp: ~a~&" (ql-dist:all-dists)) ;; not for release? #-quicklisp (format stream "!! Quicklisp is not installed !!")) (defun main () ;; Read the ini-style config file. ;; It is searched for: at the project root, at ~/.config/.replic.conf and at ~/.replic.conf. ;; It reads the "default" section. ;; ;; [default] ;; confirm-exit = false ;; (replic.config:apply-config) (unless (uiop:file-exists-p (openbookstore.models::db-name)) (uiop:format! t "Creating the database into ~a...~&" (openbookstore.models::db-name)) (openbookstore.models::initialize-database)) (opts:define-opts (:name :help :description "print this help and exit." :short #\h :long "help") (:name :version :description "print the version number and exit." :short #\v :long "version") (:name :verbose :description "print debug info." :short #\V :long "verbose") (:name :interactive :description "enter the interactive prompt." :short #\i :long "interactive") (:name :web :description "run the web application." :short #\w :long "web") (:name :port :arg-parser #'parse-integer :description "set the port for the web server. You can also use the OBS_PORT environment variable." :short #\p :long "port") (:name :datasource :arg-parser #'identity :description "Choose the datasource to search books on. Available choices are: France, Argentina, Dilicom (for France too)." :short #\s :long "datasource") (:name :manage :arg-parser #'identity :description "Run a management command, such as createsuperuser" :long "manage")) (multiple-value-bind (options free-args) (handler-bind ((error #'handle-parser-error)) (opts:get-opts)) (format t "OpenBookStore version ~a~&" +version+) (when (getf options :version) (print-system-info) (uiop:quit)) (when (getf options :help) (opts:describe) (uiop:quit)) (when (getf options :verbose) (print-system-info)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Management commands. ;; Create a superuser with admin rights. (when (getf options :manage) (let ((command (getf options :manage))) (when (equal "createsuperuser" (str:downcase (str:trim command))) (format t "Initializing...~&") ;; Connect to the DB. (init) (uiop:format! t "Running management command ~a…~&" command) ;; XXX: avoid circular dependencies: ;; we now want to call bookshops.manager, but this package relies on models, ;; we can't load it before. Fix. (eval (read-from-string "(bookshops.manager::add-superuser)"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Run the interactive terminal application. (when (getf options :datasource) (format t "datasource: ~a" (getf options :datasource)) (let ((datasource (str:downcase (getf options :datasource)))) (cond ((str:starts-with-p "fr" datasource) (setf *datasource* :fr)) ((str:starts-with-p "ar" datasource) (setf *datasource* :ar)) ((str:starts-with-p "dilicom" datasource) (setf *datasource* :dilicom)) (t (log:info "Using default datasource: ~a" *default-datasource*) (setf *datasource* *default-datasource*))))) (when (getf options :interactive) (format t "Initializing...~&") (init) (setf replic:*prompt* (cl-ansi-text:green "openbookstore > ")) (setf replic:*prompt-prefix* (format nil "(~a) " (name (default-place)))) ;; create commands from the exported functions and variables. (replic.completion:functions-to-commands :replic.base) (setf replic:*help-preamble* "With cl-bookshops you can search for books by keywords or isbn, add some to your stock and explore it.") (replic.completion:functions-to-commands :bookshops.commands) (replic.completion:functions-to-commands :bookshops.manager) ;; define completions. ;; (push '("add" . *results*) replic:*args-completions*) (replic:repl) (handler-case (when free-args (search-books (str:join " " free-args) :datasource *datasource*)) (error (c) (progn (format *error-output* "~a~&" c) (uiop:quit 1))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Run the web app. (when (getf options :web) (handler-case (progn (openbookstore/web::start-app :port (or (getf options :port) (ignore-errors (parse-integer (uiop:getenv "OBS_PORT"))) openbookstore/web::*port*)) ;; Without this, the binary exits immediately after having ;; run the web server in its thread. (bt:join-thread (find-if (lambda (th) (search "hunchentoot" (bt:thread-name th))) (bt:all-threads)))) (usocket:address-in-use-error () (format *error-output* "This port is already taken. You can use the --port option or the OBS_PORT environment variable to specify a new port.~&")) #+sbcl (sb-sys:interactive-interrupt () (format *error-output* "~&Bye!~&") (uiop:quit)) (error (c) (format *error-output* "~&An error occured: ~a~&" c) ;; XXX: quit also kills the current lisp process, which is ;; annoying when developing with a REPL. ;; (uiop:quit 1) ))) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Search on data sources, print results and exit. ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (when free-args (init) (openbookstore.models::pprint-books (search-books (str:join " " free-args) :datasource *datasource*))) )) (defun run () "Call main, print a backtrace if an error occurs." (handler-bind ((error (lambda (c) (format *error-output* "~&An error occured: ~a~&" c) (format *error-output* "~&Backtrace:~&") (trivial-backtrace:print-backtrace c)))) (main)))
9,608
Common Lisp
.lisp
210
35.82381
156
0.565766
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
824633a75740e90ff99d2d730159804919375add4be7b5793861cda30f33b87c
4,541
[ -1 ]
4,542
termp.lisp
OpenBookStore_openbookstore/src/termp.lisp
(in-package :bookshops.utils) ;; Are we running inside a real terminal window? Unbound by default. (defvar *termp*) ;; copy-pasted from ;; https://github.com/vindarel/termp (defun termp (&key force) "Return T if we run on a terminal. This must fail on Slime (on Emacs' default shell prompt) and succeed on a Lisp in a terminal window." (if (and (not force) (boundp '*termp*)) *termp* (setf *termp* (not (equalp "dumb" (uiop:getenv "TERM")))))) (defun quit (&optional (status 0) message) "If we are in a real terminal, really quit. Otherwise, error out." (cond ((termp) (when message (format t "~a~&" message)) (uiop:quit status)) (t (error (or message "termp: not on a terminal, not quitting.~&")))))
769
Common Lisp
.lisp
21
32.380952
103
0.656797
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
64b6b4b6900c8d81860b269f6b6d170651b14d5cc3dce5281a50fb8afecd365b
4,542
[ -1 ]
4,543
utils.lisp
OpenBookStore_openbookstore/src/utils.lisp
(defpackage :bookshops.utils (:use :cl :parse-float :bookshops.parameters) (:export #:isbn-p #:asciify #:clean-isbn #:extract-float #:ensure-float #:price-float-to-integer #:format-date #:parse-iso-date ;; local-time extras #:yesterday #:tomorrow ) (:documentation "Utilities that do not depend on models.")) (in-package :bookshops.utils) (defparameter *isbn-accepted-lengths* '(13)) (defun isbn-p (code) "Return `t' if the given code (a string) looks like an ISBN (13 digits)." (let ((code (str:replace-all "-" "" code))) (and (member (length code) *isbn-accepted-lengths*) (str:digitp code)))) #+nil (progn (assert (isbn-p "978-4567-890123"))) (defun clean-isbn (isbn) "Clean this ISBN of accepted symbols in the user form, but unwanted in the DB (\"-\")." (str:replace-all "-" "" isbn)) (defun extract-float (s) "Extract a float from the given string. See also EXTRACT-PRICE-AS-CENTS in the Argentinian scraper." (check-type s string) (ignore-errors ;; the regexp should be enough, given we parse a known html beforehand. (parse-float (ppcre:scan-to-strings "-?\\d+.?\\d*" s) :type 'double-float))) ;; XXX: copied from scraper-fr (defun ensure-integer (number) "Return this number as an integer (TRUNCATE and discard decimals). If it isn't a number, return 0. Typically, for a price that is parsed as a float, NUMBER should be the price in cents (x 100), and we return it as an integer. - number: float Return: an integer or 0." ;; warn: copied to model-utils.lisp. The scraper module should stay completely independant of ;; the application code. (if (and number (not (equalp number 0)) (numberp number)) (truncate number) (progn ;; log or warning? Both! (log:warn "Could not parse ~s to an integer price." number) 0))) (defun ensure-float (param) "Return a double float from this param, if possible. If it is a string, parse it for a double float." (when param (typecase param (string (or (ignore-errors (parse-float:parse-float param :type 'double-float)) 0.0d0)) (integer (coerce param 'double-float)) (float param) (t (error (format nil "ensure-float error: the parameter ~a is of type ~a and we don't know how to make it a double-float." param (type-of param))))))) (defun price-float-to-integer (s/float) "From a string or a (double) float, return an integer, the price in cents (x100). Use this before updating a book object." (ensure-integer (* 100 (ensure-float s/float)))) ;; TODO Make a test #+(or) (progn (assert (= 990 (price-float-to-integer "9.90"))) (assert (= 990 (price-float-to-integer 9.90d0))) ;; Beware of single floats: (assert (= 989 (price-float-to-integer 9.90))) ;; Commas don't work: (assert (= 0 (price-float-to-integer "9,90")))) (defun format-date (date) "Format the given date with the default date format (yyyy-mm-dd). Return a string." (local-time:format-timestring nil date :format +date-y-m-d+)) (defun parse-iso-date (date) "Dates returned from javascript are often ISO format" (let ((année (parse-integer date :start 0 :end 4)) (mois (parse-integer date :start 5 :end 7)) (jour (parse-integer date :start 8 :end 10))) (local-time:encode-timestamp 0 0 0 0 jour mois année :timezone local-time:+utc-zone+))) (defun asciify (string) (str:downcase (slug:asciify string))) (defun yesterday () "Returns a timestamp representing the day before today." (local-time:timestamp- (local-time:today) 1 :day)) (defun x-days-ago (x) (local-time:timestamp- (local-time:today) x :day)) (defun tomorrow () "Returns a timestamp representing the day after today." (local-time:timestamp+ (local-time:today) 1 :day))
3,964
Common Lisp
.lisp
100
34.37
157
0.658943
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
b046e7ba9c9a6ed3769b2e00baea855af2c4672de47bbd31ce2af6c4bd2bff7a
4,543
[ -1 ]
4,544
authentication.lisp
OpenBookStore_openbookstore/src/authentication.lisp
(in-package #:openbookstore.models) #| Create a superuser: (create-superuser name email password) Create a normal user: (openbookstore.models::create-user "Joe Blogg" "[email protected]" "i<3books") Give him rights: (add-role user :admin) Bootstrap roles: see database.lisp bootstrap-base-roles. |# (defclass user (mito-auth:has-secure-password) ((name :col-type (:varchar 60) :initarg :name :accessor user-name) (email :col-type (:varchar 255) :initarg :email :accessor user-email)) (:metaclass mito:dao-table-class)) (defclass role () ((name :col-type (:varchar 50) :initarg :name :inflate (alexandria:compose #'alexandria:make-keyword #'string-upcase) :deflate #'string-downcase :accessor role-name)) (:metaclass mito:dao-table-class) (:primary-key name) (:auto-pk nil) (:record-timestamps nil)) (defclass user-role () ((user :col-type user :initarg :user :accessor user-role-user) (role :col-type role :initarg :role :accessor user-role-role)) (:metaclass mito:dao-table-class) (:primary-key user role) (:auto-pk nil) (:record-timestamps nil)) (defclass role-copy () ((primary-role :col-type role :initarg :primary-role :accessor primary-role) (inherited-role :col-type role :initarg :inherited-role :accessor inherited-role)) (:metaclass mito:dao-table-class) (:primary-key primary-role inherited-role) (:auto-pk nil) (:record-timestamps nil)) (defun create-user (name email password) (mito:create-dao 'user :name name :email email :password password)) (defun create-superuser (name email password) "Create a user with the admin role." (let ((user (create-user name email password))) (add-role user :admin))) (defun create-role (name) (or (mito:find-dao 'role :name name) (mito:create-dao 'role :name name))) (defun %find-role-from-keyword (role-name) "Return a role object from a keyword and throw an error if an associated role cannot be found" (let ((role (mito:find-dao 'role :name role-name))) (assert role (role) "There is no role named ~a" role-name) role)) (defgeneric add-role (user role) (:documentation "Add the given role to this user. ROLE is either a role object or a symbol. An example role is ':admin`.") (:method ((user user) (role role)) (or (mito:find-dao 'user-role :user user :role role) (mito:create-dao 'user-role :user user :role role))) (:method ((user user) (role-name symbol)) (let ((role (%find-role-from-keyword role-name))) (add-role user role)))) (defgeneric inherit-role (primary-role inherited-role) (:method ((primary-role role) (inherited-role role)) (or (mito:find-dao 'role-copy :primary-role primary-role :inherited-role inherited-role) (mito:create-dao 'role-copy :primary-role primary-role :inherited-role inherited-role))) (:method ((primary-role-name symbol) (inherited-role-name symbol)) (let ((primary-role (%find-role-from-keyword primary-role-name)) (inherited-role (%find-role-from-keyword inherited-role-name))) (inherit-role primary-role inherited-role)))) ;;; We deal with all roles as keywords only once they are within the context of can. (defmethod can:user-roles ((user user)) "This is somewhat inefficent and would be better if user-role was a view with a union between role-copy and role, however I have struggled to make mito work with such a view. It is permitted for a role to appear more than once in the result." (labels ((all-roles (role) (list* role (loop :for role :in (mito:retrieve-dao 'role-copy :primary-role role) :append (all-roles (inherited-role role)))))) ;; here we move down the inheritance hierarchy by navigating the role-copy table ;; recursively until we reach the end of each branch and have collected all the roles. (let ((direct-roles (mapcar #'user-role-role (mito:retrieve-dao 'user-role :user user)))) (mapcar #'role-name (loop :for role :in direct-roles :append (all-roles role)))))) (defun login (name/email password) "Return the user if the credentials are correct, otherwise nil." (let ((user (or (mito:find-dao 'user :email name/email) (mito:find-dao 'user :name name/email)))) (when (and user (mito-auth:auth user password)) user))) (defun get-user (name) "Return the user with the given username" (mito:find-dao 'user :name name)) (defmacro define-role (name (&rest inherits)) `(progn (create-role ',name) ,@(loop :for role :in inherits :collect `(inherit-role ',name ',role)))) (defmacro define-role-access (resource action role) `(defmethod can:resource-allowed-p ((resource (eql ',resource)) (action (eql ',action)) (role (eql ',role))) (declare (ignore resource action role)) t)) (defun search-user (key value) "Finds a user by its name or mail" (mito:find-dao 'user key value)) (defun is-superuser (user) "Detects if user is a superuser" (find :admin (can:user-roles user))) (defun list-admin-users (&key (pprint-result nil)) "List all user with role :admin" (mapcan (lambda (user) (and (is-superuser user) (list (if pprint-result (format nil "User: ~a Email: ~a" (user-name user) (user-email user)) user)))) (mito:select-dao 'user))) (defun remove-user (user) (mito:delete-dao user))
5,801
Common Lisp
.lisp
136
35.691176
124
0.64779
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
1c364f8101dc617f3765fbeb770dc5130e90340db9f4be6acd802043d6d50970
4,544
[ -1 ]
4,545
packages.lisp
OpenBookStore_openbookstore/src/packages.lisp
;; XXX: all packages are not here, ;; see also bookshops.lisp, paramaters.lisp (and more?). (uiop:define-package openbookstore.models (:use :cl :cl-ansi-text) (:import-from :access :access) (:import-from :parse-number :parse-number) (:import-from :serapeum :dict) (:import-from :bookshops.i18n :_) (:export :connect :add-to :ensure-tables-exist :bootstrap-base-roles ;; book accessors :name :book :make-book :publisher :find-book :find-by :find-existing :find-book-noisbn :last-books :title :details-url :authors :cover-url :isbn :price :print-book :print-book-details :print-obj :count-book :date-publication ;; book methods :save-book :create-book :quantity :set-quantity :delete-books :delete-obj :delete-objects ;; places :place :place-copies :place-copies-book :make-place :create-place :current-place :save-place :print-place :find-places :find-place-by :default-place :add-to :remove-from :move :*current-place* :place-copy-quantity ;; lists, baskets :find-baskets :print-basket ;; authentication :user :user-name :role :user-role-user :user-role-role :role-copy :primary-role :inherited-role :create-user :create-role :create-contact :find-contacts :find-contact-by :print-contact :add-role :inherit-role :login :define-role-access ;; utils :print-quantity-red-green :negative-quantities :erase-metaclass-from :make-sale :list-of-books :list-of-search-results) (:local-nicknames (#:parameters #:bookshops.parameters) (#:utils #:bookshops.utils) (#:a #:alexandria))) (uiop:define-package openbookstore (:use :cl :cl-ansi-text :parse-float :log4cl ;; :bookshops.utils) (:import-from :openbookstore.models :default-place ;; accessors :publisher :title :price :authors :name ;; functions :make-book :find-existing) (:import-from :bookshops.datasources.scraper-fr :books) ;; libs (:import-from :access :access) (:export :main :i18n-load :init ;; book accessors :publisher :title :price :authors :name ;; functions :books :search-books :run) (:local-nicknames (#:dilicom #:bookshops.datasources.dilicom) (#:fr #:bookshops.datasources.scraper-fr) (#:datasources #:bookshops.datasources.main) (#:a #:alexandria)) (:documentation "CLI interface")) (uiop:define-package openbookstore/web (:use :cl) (:import-from :easy-routes :defroute) (:import-from :access :access) (:import-from :serapeum :dict) (:import-from :parse-number :parse-number) (:local-nicknames (#:dilicom #:bookshops.datasources.dilicom) (#:fr #:bookshops.datasources.scraper-fr) (#:argentina #:bookshops.datasources.scraper-argentina) (#:models #:openbookstore.models) (#:utils #:bookshops.utils) (#:a #:alexandria)))
3,847
Common Lisp
.lisp
126
19.5
76
0.518489
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
57758eb0204a15aa8df574b266b52275a41c8e23b146c5de7d30f78f23330590
4,545
[ -1 ]
4,546
parameters.lisp
OpenBookStore_openbookstore/src/parameters.lisp
(defpackage :bookshops.parameters (:use :cl) (:export :+date-y-m-d+)) (in-package :bookshops.parameters) (defparameter +date-y-m-d+ '(:year "-" (:month 2) "-" (:day 2)))
176
Common Lisp
.lisp
5
33
64
0.639053
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
074d8b25619d6a907c0097c51d4da41e71ca392534cbecf53b46bec4ae6f228c
4,546
[ -1 ]
4,547
bookshops-iup.lisp
OpenBookStore_openbookstore/src/iup/bookshops-iup.lisp
(eval-when (:compile-toplevel) (ql:quickload :iup)) (defpackage :bookshops.iup (:use :cl :openbookstore.models) (:import-from :openbookstore :books :authors :editor :price) (:export :main)) (in-package :bookshops.iup) (defun hello () (iup:with-iup () (let* ((label (iup:label :title (format nil "Hello, World!~%IUP ~A~%~A ~A" (iup:version) (lisp-implementation-type) (lisp-implementation-version)))) (button (iup:button :title "Click me" :expand :yes :tip "yes, click me" :action (lambda (handle) (declare (ignorable handle)) (iup:message "title" "button clicked") iup:+default+))) (vbox (iup:vbox (list label button) :gap "10" :margin "10x10" :alignment :acenter)) (dialog (iup:dialog vbox :title "Hello, World!"))) (iup:show dialog) (iup:main-loop)))) (defun counter () (iup:with-iup () (let* ((counter (iup:label :title 0)) (label (iup:label :title (format nil "The button was clicked ~a time(s)." (iup:attribute counter :title)))) (button (iup:button :title "Click me" :expand :yes :tip "yes, click me" :action (lambda (handle) (declare (ignorable handle)) (setf (iup:attribute counter :title) (1+ (iup:attribute counter :title 'number))) (setf (iup:attribute label :title) (format nil "The button was clicked ~a times." (iup:attribute counter :title))) iup:+default+))) (vbox (iup:vbox (list label button) :gap "10" :margin "10x10" :alignment :acenter)) (dialog (iup:dialog vbox :title "Counter"))) (iup:show dialog) (iup:main-loop)))) (defun run-counter () #+sbcl (sb-int:with-float-traps-masked (:divide-by-zero :invalid) (counter))) (defun gridexample () (iup:with-iup () (let* ((books (find-book)) (flat-results (mapcan (lambda (bk) (list (title bk) (authors bk))) books)) (button (iup:flat-button :expand :yes :canfocus :no)) (label (iup:label :expand :horizontal :title "#x00000" :alignment "ACENTER:ACENTER")) (r (iup:val :expand :horizontal :min 0 :max 255)) (g (iup:val :expand :horizontal :min 0 :max 255)) (b (iup:val :expand :horizontal :min 0 :max 255)) (vbox (iup:vbox (list (iup:grid-box (loop for elt in flat-results collect (iup:label :title elt)) ;; (list (iup:label :title "&Red") ;; (iup:label :title "foo") ;; (iup:label :title "&Green") g ;; (iup:label :title "&Blue") b) :numdiv 2 :expandchildren "HORIZONTAL" :cgapcol 10 :cgaplin 5) button label) :cmargin 5 :cgap 5 :margin "x5")) (dialog (iup:dialog vbox :title "Color Mixer Example" :size "QUARTERxQUARTER"))) (loop :with action := (format t "~a ~a ~a ~a ~a" r g b button label) :for handle :in (list r g b) :do (setf (iup:callback handle :valuechanged_cb) action)) (iup:show dialog) (iup:main-loop)))) (defun grid () #-sbcl (hello) #+sbcl (sb-int:with-float-traps-masked (:divide-by-zero :invalid) (gridexample))) (defun bookslist () (iup:with-iup () (let* ((books (find-book)) (frame (iup:frame (iup:vbox (loop for list in (list (iup:list :value 1 :tip "List 1" :multiple :yes)) do (loop for i from 1 upto 10 do (setf (iup:attribute list i) (format nil "~A" (title (elt books (+ i 10)))))) collect list)) :title "IUP List")) (dialog (iup:dialog frame :menu "menu" :title "OpenBookstore"))) (iup:map dialog) (iup:show dialog) (iup:main-loop)))) (defun list-test () (iup:with-iup () (let* ((list-1 (iup:list :tip "List 1" ;; tooltip :expand :yes ;; multiple selection :multiple :yes)) (list-2 (iup:list :value 2 ;; default index of the selected row :expand :yes :tip "List 2")) (list-3 (iup:list :value 9 :tip "List 3" :expand :yes)) (frame (iup:frame (iup:hbox (progn ;; display a list of integers. (loop for i from 1 upto 10 do (setf (iup:attribute list-1 i) (format nil "~A" i)) do (setf (iup:attribute list-2 i) (format nil "~A" (+ i 10))) do (setf (iup:attribute list-3 i) (format nil "~A" (+ i 50)))) ;; vbox wants a list of widgets. (list list-1 list-2 list-3))) :title "IUP List")) (dialog (iup:dialog frame :menu "menu" :title "List example"))) (iup:map dialog) (iup:show dialog) (iup:main-loop)))) (defun run-list-test () #-sbcl (hello) #+sbcl (sb-int:with-float-traps-masked (:divide-by-zero :invalid) (list-test))) (defun main () #-sbcl (hello) #+sbcl (sb-int:with-float-traps-masked (:divide-by-zero :invalid) (restart-case (bookslist) (connect-db () :report "Connect to the DB" (openbookstore.models:connect) (main)))))
6,898
Common Lisp
.lisp
161
25.335404
103
0.425108
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
f932642d686d2a5a50ba9d6b1189df01b9613aca954b78aa6cccf77ab97be9fe
4,547
[ -1 ]
4,548
models.lisp
OpenBookStore_openbookstore/src/models/models.lisp
(in-package :openbookstore.models) (export '(*print-details*)) #| Usage: (connect) (make-book :title "antigone" :datasource "xxx") (save-book *) (find-dao 'book) ;; => #<Book antigone> Design notes ============ A book's title, authors and publisher fields also get a -ascii equivalent (without accentuated letters). The ascii field is used for searches. This method was thought the most portable. |# (defparameter *db-name* nil) (defun db-name () "Get our DB full path name. During development or when running from sources, get the path relative to where openbookstore is installed. When running from a binary release, search a db.db file on the current directory." (when *db-name* (return-from db-name *db-name*)) (if (deploy:deployed-p) ;; Get or create at the current runtime directory. ;; XXX: search on other locations such as ~/.config/openbookstore/ (merge-pathnames (deploy:runtime-directory) "db.db") ;; Get it at the project root. (asdf:system-relative-pathname :openbookstore "db.db"))) (defparameter *db* nil "DB connection object, returned by (connect).") (defvar *current-place* nil "The current place we manipulate the books from.") (setf str:*ellipsis* "(…)") ;; ;; DB tables definition. ;; ;; col-types: ;; varchar, text, integer, serial, bigserial, binary, ;; timestamp, (or ... :null), relationship. (defclass book () ;; "Book class. Use make-book to create an object ;; (do not export and use book directly, use make-book). ;; ;; After modification, run (migrate-all) ;; ;; - create a date: (local-time:now) ;; " ((title :accessor title :initarg :title :initform nil :type string :col-type (:varchar 128)) (title-ascii :accessor title-ascii :initform nil :type (or string null) :col-type (or (:varchar 128) :null) :documentation "The title, normalized to not contain accentuated letters or special characters. To search a card by title we'll normalize the search query and search against this column. This is the most portable solution.") (isbn :accessor isbn :initarg :isbn :initform nil :type (or string null) :col-type (or (:varchar 128) :null)) (price :accessor price :initarg :price ;; we don't default it to 0 (nil denotes a missing field), ;; and it might be useful for other objects. :initform nil :type (or integer null) ;; integer: for compatibility. Otherwise, Mito is strict about float and fails. :col-type (or :integer :null)) (authors :accessor authors :initarg :authors ;TODO: relationship :initform nil :col-type (or (:varchar 128) :null)) (authors-ascii :accessor authors-ascii :initform nil :col-type (or (:varchar 128) :null) :documentation "Normalized representation of authors, without accentuated letters.") (datasource :accessor datasource :initarg :datasource :initform nil :type (or string null) ;; how to use a variable for 128 ? ;; we get datasource VARCHAR(+varchar-length+) NOT NULL, :col-type (or (:varchar 128) :null) :documentation "The source name (website) we took bibliographic information from.") (details-url :accessor details-url :initarg :details-url :initform nil :type (or string null) :col-type (or (:varchar 128) :null) :documentation "Link to the book's page on its datasource.") (date-publication :accessor date-publication :initarg :date-publication :initform nil :col-type (or (:varchar 128) :null)) (publisher :accessor publisher :initarg :publisher :initform nil :type (or string null) :col-type (or (:varchar 128) :null)) (publisher-ascii :accessor publisher-ascii :initform nil :type (or string null) :col-type (or (:varchar 128) :null)) (shelf :accessor shelf :initform nil :col-type (or :null shelf) :documentation "Shelf") (cover-url :accessor cover-url :initarg :cover-url :initform nil :type (or string null) :col-type (or (:varchar 1024) :null)) (review :accessor review :initarg :review :initform nil :type (or string null) :col-type (or :text :null))) (:metaclass mito:dao-table-class) (:documentation "A book represents the book entity, not the physical object. It may not have an isbn. A book is stored in one or many places.")) (defgeneric title (obj) (:documentation "Title of a book.") (:method (obj) ;; nothing (for erronous print-objects to work). )) (defmethod title ((book book)) (slot-value book 'title)) (defmethod (setf title) :after (val (book book)) "After setting a book's title, set also its title ASCII representation (used for searches)." ;; note: obviously these setf methods are not called if we use slot-value directly. ;: XXX: here tests will be welcome to catch other cases where they would not be called. (log:debug "updating title-ascii too") (setf (title-ascii book) (utils::asciify (slot-value book 'title)))) (defmethod (setf authors) :after (val (book book)) (log:debug "updating authors-ascii too") (setf (authors-ascii book) (bookshops.utils::asciify (slot-value book 'authors)))) (defmethod (setf publisher) :after (val (book book)) (log:debug "updating publisher-ascii too") (setf (publisher-ascii book) (bookshops.utils::asciify (slot-value book 'publisher)))) (defgeneric price (obj) (:documentation "Return the price of the current object. Return 0 if nil.")) (defmethod price ((book book)) (cond ((null (slot-value book 'price)) ;; should not happen now with the initform to 0. 0) (t (slot-value book 'price)))) (defmethod (setf price) (price (book book)) "Set the price of this book." ;; TODO: do something to transform float to int x 100 ? (setf (slot-value book 'price) price)) (defmethod print-object ((book book) stream) (print-unreadable-object (book stream :type t) (with-accessors ((id mito:object-id) (title title) (shelf shelf)) book (format stream "~a - ~a. SHELF: ~a" id title (name shelf))))) (defun pprint-books (results) "Pretty print this list of books, as rows." (let ((i (length results))) (mapcar (lambda (it) (format t "~2@a- ~a, ~a~t~$ ~tstock: x~a~&" i (blue (title it)) (authors it) (price it) (print-quantity-red-green (quantity it))) (format t "~t ed: ~a, ~a~&" (publisher it) (isbn it)) (decf i)) (reverse results)))) (defclass place () ((name ;; accessor as generic, for the intermediate class too. :initarg :name :initform nil :col-type (:varchar 128))) (:metaclass mito:dao-table-class) (:documentation "Where the books are stored. It could be a temporary place, like a stand, or a friend's. We are allowed to sell from certain places, not from others.")) (defgeneric name (obj) (:documentation "Name of this object.") (:method (obj) ;; nothing )) (defmethod name ((place place)) (slot-value place 'name)) (defmethod (setf name) (val (place place)) (setf (slot-value place 'name) val)) ;; Intermediate table for the book <-> place many-to-many relationship. (defclass place-copies () ((book :accessor place-copies-book :initarg :book :initform nil :col-type book) (place :accessor place :initarg :place :initform nil :col-type place) (quantity :accessor place-copy-quantity :initform 0 :col-type (or (:integer) :null))) (:metaclass mito:dao-table-class) (:documentation "Intermediate table between books and places. Specifies the quantity in the given place.")) (defmethod print-object ((pc place-copies) stream) (print-unreadable-object (pc stream :type t) (with-slots (quantity) pc (format stream "book \"~a\" in \"~a\", x~a" (str:shorten 20 (title pc)) (name (place pc)) quantity)))) (defmethod title ((it place-copies)) (if (place-copies-book it) (title (place-copies-book it)) "<no book>")) (defmethod name ((it place-copies)) (name (place it))) (defmethod price ((place place)) (reduce #'+ (mapcar #'price (place-books place)))) (defun make-place (name) "Create a Place object (don't save in the DB)." (make-instance 'place :name name)) (defun save-place (place) (mito:insert-dao place)) (defun create-place (name) "Create and save a `place' object in DB." (mito:create-dao 'place :name name)) (defun default-place () "Return the default place (the first created one by default). If none exist, create one." ;TODO: do that once at startup and bind a variable. (when (mito.connection:connected-p) ;; Check the connection because of setf *current-place* in commands package. ;; Or initialize it elsewhere. (if (= 0 (mito:count-dao 'place)) (create-place "home") (first (mito:select-dao 'place (sxql:order-by (:asc :id))))))) (defun current-place () "Return the current place, set it with the default one if needed." ;; since it wasn't initialized, see above. (or *current-place* (setf *current-place* (default-place)))) (defun find-places (&optional query) "If query (list of strings), return places matching this name. Otherwise, return all places." (if query (progn ;; xxx should be same interface as find-book (unless (consp query) (setf query (cons query nil))) (mito:select-dao 'place (sxql:where (:like :name (str:concat "%" (str:join "%" query) "%"))))) (mito:select-dao 'place))) (defun find-place-by (key val) "Find a place by key. " (when val (mito:find-dao 'place key val))) (defmethod print-object ((place place) stream) (print-unreadable-object (place stream :type t) (format stream "~a" (name place)))) (defparameter *print-details* nil "Print some lists with details.") (defun print-place (place &key (stream t) (details *print-details*)) "Print the name of the place and its number of books. If :details is t, print a paginated list of its books." (format stream "~2a - ~40a~t x~3a/ ~3a total: ~3a~&" (mito:object-id place) (name place) (length (place-books place)) (reduce #'+ (mapcar #'place-copy-quantity (place-books place))) (price place)) (when details (format stream "~a~&" (mapcar #'print-book (place-books place))))) (defmethod print-obj ((obj place) &optional (stream t)) (print-place obj :stream stream)) (defun place-books (place) (mapcar #'place-copies-book (mito:select-dao 'place-copies (sxql:where (:= :place place))))) (defun book-places (bk) (mapcar #'place (mito:select-dao 'place-copies (sxql:where (:= :book bk))))) (defun book-places-quantities (bk) "Return the intermediate objects place-copies, so than we can know how many copies of this book are in what places." (mito:select-dao 'place-copies (sxql:where (:= :book bk)))) (defun add-to (place bk &key (quantity 1)) "Add the given book to this place. Return the quantity. nil means it is not present." (assert place) (assert bk) (unless (mito:object-id bk) (error "The book ~a is not saved in DB." bk)) (let ((existing (mito:find-dao 'place-copies :place place :book bk)) place-copy) (if existing (progn (log:info "The book ~a exists in ~a." bk place) (incf (place-copy-quantity existing) quantity) (mito:save-dao existing) (quantity existing)) (progn (log:info "~a doesn't exist in ~a yet, let's add it.~&" bk place) (setf place-copy (make-instance 'place-copies :place place :book bk :quantity quantity)) (mito:insert-dao place-copy) (quantity bk))))) (defun remove-from (place bk &key (quantity 1)) "Remove the given book from this place. Return the quantity. If the book was never in the original place, don't remove it. Otherwise, it can end in a negative quantity." (unless (mito:object-id bk) (error "The book ~a is not saved in the DB." bk)) (let ((existing (mito:find-dao 'place-copies :place place :book bk)) qty) (if existing (progn (setf qty (quantity existing)) (setf (quantity existing) (decf qty quantity)) (mito:save-dao existing) ;; (when (minusp qty) ;; (format t "~a" (red (format nil "mmh, you now have a negative stock of \"~a\"" (title bk))))) qty) (progn (format t "Will not remove the book ~a from ~a, it doesn't exist there.~&" bk place) nil)))) (defun print-quantity-red-green (qty) "If qty is > 0, print in green. If < 0, in red." ;; Always use colors, for the strings to be the same length. Helps in calcuting the padding. (cond ((= 0 qty) (cl-ansi-text:white (prin1-to-string qty))) ((< qty 0) (cl-ansi-text:red (prin1-to-string qty))) ((> qty 0) (cl-ansi-text:green (prin1-to-string qty))))) (defun print-book (book &optional (stream t)) "Print to stream a user-readable output." ;; xxx: print as a nice table. ;; ~30a = substring 20 + ansi colors markers. ;; ~12@a = justify on the right, count colors markers. (format stream "~&~4@a- ~40a ~20a ~20a ~8@a x~6@a~&" ;; ^ ^ T ^ A ^ Shelf ;; yeah I know. (prin1-to-string (mito:object-id book)) ;; shorten to shorter string because of ansi color. (cl-ansi-text:blue (str:shorten 30 (title book))) (str:shorten 20 (or (authors book) "")) (str:shorten 20 (or (name (shelf book)) "")) (str:shorten 8 (format nil "~$" (price book))) (print-quantity-red-green (quantity book)))) (defmethod print-obj ((obj book) &optional (stream t)) (print-book obj stream)) (defun print-book-repartition (bk) "Print a list of places where this book exists with its quantity. bk: book object or id (int). Example output: 1 - default place x1 2 - second place x-2 " (when (integerp bk) (setf bk (mito:find-dao 'book :id bk))) (let ((bk-places (mito:select-dao 'place-copies (sxql:where (:= :book bk))))) (if bk-places (progn (format t "----------~&") (format t "In places:~%") (format t "----------~%") (mapc (lambda (it) (format t "~2a - ~40a ~t x~a~&" (mito:object-id (place it)) (name (place it)) (print-quantity-red-green (quantity it)))) bk-places)) (format t "~%This book is not registered in any place.~&")))) (defun print-book-details (bk) (cond ((integerp bk) (setf bk (mito:find-dao 'book :id bk))) ((stringp bk) ;; What with two similar titles? ;; Mito takes the first one. (setf bk (mito:find-dao 'book :title bk)))) (if bk (progn (format t "~a x ~a~&" (cl-ansi-text:blue (title bk)) (quantity bk)) (format t "~t~a~&" (authors bk)) (format t "~tisbn: ~a~&" (isbn bk)) (format t "~t~a~&" (price bk)) (format t "~tcover: ~a~&" (cover-url bk)) (print-book-repartition bk)) (format t "There is no such book with id ~a~&" bk))) (defun make-book (&key title isbn authors details-url cover-url publisher date-publication price datasource shelf shelf-id new-shelf-name) "Create a Book instance. Not yet saved on DB. XXX: my newer methods are not consistent. Authors are saved as a string, not as related objects. - shelf-id: get existing shelf from this ID - shelf: shelf object - new-shelf-name (string): optional name to create a new shelf." (let ((shelf-obj (or shelf (when shelf-id (find-shelf-by :id shelf-id)) (when (and new-shelf-name (stringp new-shelf-name)) (make-shelf new-shelf-name)))) (book (make-instance 'book :datasource datasource :details-url details-url :cover-url cover-url :title title :title-ascii (bookshops.utils::asciify title) :isbn isbn :authors authors :authors-ascii (bookshops.utils::asciify authors) :publisher publisher :publisher-ascii (bookshops.utils::asciify publisher) :price (utils:ensure-float price) :date-publication date-publication))) (when shelf-obj (setf (shelf book) shelf-obj)) book)) (defun create-book (&rest initargs) "Create a book and save it. CAUTION: you must provide title-ascii and authors-ascii. Or use make-book and save-book that will infer them." (unless (member :title-ascii initargs) (warn "create-book: you probably forgot to give title-ascii.")) (unless (member :authors-ascii initargs) (warn "create-book: you probably forgot to give authors-ascii.")) ;; (apply #'mito:create-dao 'book initargs)) (defun save-book (book) "Save this book in DB. If it already exists, return the existing book. Otherwise, return the new one." ;; logging (let ((existing (find-by :isbn (isbn book)))) (if existing (progn (log:info "book of isbn " (isbn book) " is already in stock.") (mito:save-dao existing) existing) (progn (let ((new (mito:insert-dao book))) (log:info "creating new book") (mito:save-dao new) new))))) (defun find-by (key val) "Find a book by slot. Example: (find-by :isbn xxx). Return only the first matching result." (when val (mito:find-dao 'book key val))) (defun update-book (book bk) "Update and save the book object with this bk data." (loop for slot in '(:price :date-publication :publisher :details-url :datasource :cover-url) if (not (equal (access book slot) (access bk slot))) do (log:debug "updating ~a~&" slot) do (setf (access book slot) (access bk slot)) do (mito:save-dao book)) book) (defun update-book-with (book fields) "Update this book instance with new data. In addition, update related fields implicetily, such as the title-ascii. Do NOT save the object in DB yet. fields: plist with (:field-name value). Example: (update-book-with (find-by :id 87) '((:title \"new title\"))) " ;; XXX: update-book does save the object in DB… (setf (title book) (car (access:access fields :title)) (title-ascii book) (utils:asciify (car (access:access fields :title))) (isbn book) (car (access:access fields :isbn)) (price book) (car (access:access fields :price)) (authors book) (car (access:access fields :authors)) (shelf book) (car (access:access fields :shelf))) book) (defun find-existing (bk &key update) "bk: a book object. Check in the DB if it already exists. Update its fields. Return a book object." (when bk (let ((existing (find-by :isbn (isbn bk)))) (if existing (if update (update-book existing bk) existing) bk)))) (defun %build-sxql-words-query (query) "Return an expression for Mito's select-dao :when (using SxQL). Used to compose queries in find-book. We want to search the words of the query in both the title and the authors field. (%build-sxql-words-query \"hello world love\") ;; => (:AND (:OR (:LIKE :TITLE-ASCII \"%hello%\") (:LIKE :AUTHORS-ASCII \"%hello%\")) (:OR (:LIKE :TITLE-ASCII \"%world%\") (:LIKE :AUTHORS-ASCII \"%world%\"))) (:OR (:LIKE :TITLE-ASCII \"%love%\") (:LIKE :AUTHORS-ASCII \"%love%\"))) " (if (str:non-blank-string-p query) (loop for word in (str:words query) :collect `(:or (:like :title-ascii ,(str:concat "%" word "%")) (:like :authors-ascii ,(str:concat "%" word "%")))) '())) (defun %build-sxql-shelf-query (shelf) "If shelf is not NIL, return an expression for Mito's select-dao (using SxQL). We search by the object ID." ;; I was having a difficulty extending an existing macro. ;; Instead of writing a bigger one, decomposing the query building made it easier. (if shelf `(:= :shelf_id ,(mito:object-id shelf)) '())) (defun %merge-queries (q1 q2) "Merge two SxQL queries to one, joined by a AND. One query can be NIL but one query must not be NIL, or else the SQL query will fail. Please do your checks beforehand. Example: (%merge-queries '(:= :SHELF_ID 1) '()) ;; => (:= :SHELF_ID 1) Search cards with shelf_id to 1 AND whose title contains \"alice\": => (:and (:= :shelf_id 1) (:like :title … )) " (cond ((null q1) q2) ((null q2) q1) (t `(:and ,q1 ,q2)))) (defun %merge-intersperse-and (q1 q2) "For all clauses of q1, intersperse each one with a :AND and q2. Join everything with a :AND. Used to search for books by a shelf id AND by keywords of the titles (or the authors). See quick test in source. q1 is a list of clauses: ((:OR (:LIKE :TITLE-ASCII \"%kan%\") (:LIKE :AUTHORS-ASCII \"%kan%\")) (:OR (:LIKE :TITLE-ASCII \"%foo%\") (:LIKE :AUTHORS-ASCII \"%foo%\"))) thus it is not ready to be given to SxQL, we must join them with a :AND or something else. Example: (find-book :query \"antigone\") => many results (find-book :query \"antigone roy\") => (#<BOOK Une Antigone à Kandahar. SHELF: nil>) (filtered by author: Roy) (find-book :query \"antigone\" :shelf #<SHELF 3 - Littérature>) => (#<BOOK Antigone. SHELF: Littérature>) (filtered by shelf) " (assert (not (null q2))) `(:and ,@(loop for query in q1 collect `(:and ,query ,q2)))) #+(or) (let ((words-query '((:OR (:LIKE :TITLE-ASCII "%kan%") (:LIKE :AUTHORS-ASCII "%kan%")) (:OR (:LIKE :TITLE-ASCII "%foo%") (:LIKE :AUTHORS-ASCII "%foo%")))) (shelf-query '(:= :SHELF_ID 3))) (assert (equal (%merge-intersperse-and words-query shelf-query) '(:AND (:AND ;; word query first clause: (:OR (:LIKE :TITLE-ASCII "%kan%") (:LIKE :AUTHORS-ASCII "%kan%")) ;; AND-ed with shelf query: (:= :SHELF_ID 3)) (:AND ;; word query second clause: (:OR (:LIKE :TITLE-ASCII "%foo%") (:LIKE :AUTHORS-ASCII "%foo%")) ;; shelf query again. (:= :SHELF_ID 3))) ))) (defun %join-and (q1) "join list of clauses with a :AND. Useful to join the clauses of a text query together, when we don't need to join them with another filter (shelf)." `(:and ,@(loop for clause in q1 collect clause))) (defun find-book (&key query shelf (order :desc) (limit 50)) "Return a list of book objects. If a query string is given, filter by the ascii title and authors. Filter also by: - shelf (object) Parameters: - order: :desc (default) or :asc - limit: 50" (when (str:blankp query) (setf query nil)) (let ((shelf-query (%build-sxql-shelf-query shelf)) (words-query (%build-sxql-words-query query))) (log:debug shelf-query words-query) (mito:select-dao 'book (cond ;; text query AND shelf: we must compose the queries ;; and "AND" them together. ((and query shelf) (sxql:where (%merge-intersperse-and words-query shelf-query))) ;; Only a text query. ((and query (not shelf)) (sxql:where (%join-and words-query))) ;; Only a shelf query. ((and shelf (not query)) (sxql:where shelf-query))) ;; No query nor shelf? It works and returns all the books, and ;; still obeys the limit and order. (sxql:limit limit) (sxql:order-by `(,order :created-at))))) (defun last-books (&key (order :asc)) "" (mito:select-dao 'book (sxql:order-by `(,order :created-at)))) (defun find-book-noisbn () (mito:select-dao 'book (sxql:where (:is-null :isbn)))) (defun count-book () "" (mito:count-dao 'book)) (defgeneric quantity (obj) (:documentation "Quantity of the given book, or the number of books in the given place.")) (defun total-quantities () "Total number of cards in all places. Sums all quantities." (let ((places (find-places))) (loop for place in places sum (openbookstore.models:quantity place)))) (defmethod quantity ((book book)) "Sum of the quantities in all places." (if (mito:object-id book) (let ((place-copies (mito:select-dao 'place-copies (sxql:where (:= :book book))))) (reduce #'+ (mapcar #'place-copy-quantity place-copies))) ;; if book not saved in db. 0)) (defmethod (setf quantity) (val (book book)) (error "Please add or remove copies from a place instead of setting the quantity directly.")) (defmethod quantity ((place place)) "Quantity of books in this place." (reduce #'+ (mapcar #'place-copy-quantity (mito:select-dao 'place-copies (sxql:where (:= :place place)))))) (defmethod quantity ((pc place-copies)) ;; XXX: test the change from quantity of place to place-copy-quantity (place-copy-quantity pc)) ;; (defmethod (setf quantity) (val (pc place-copies)) ;; (setf (quantity pc) val)) (defun set-quantity (book nb) "Set the quantity of this book into the default place." (assert (numberp nb)) (add-to (default-place) book :quantity nb)) (defgeneric (setf quantity) (val obj)) (defmethod (setf quantity) (val (obj place-copies)) (error "Please use proper methods to add copies to a place, or use the accessor instead.")) ;; ;; Authors ;; ;; Class currently unused. Authors are stored as strings in books. ;; Actually, even the professional books DB (at least FEL à la demande) ;; doesn't represent authors objects. ;; And, throughout the application, the focused, most important object is the book. ;; We little need to get all books of an author (and in that case, we can make a search, see ABStock). ;; (defclass author () ;; ((name :accessor name ;; :initarg :name ;; :initform nil ;; :col-type (:varchar 128))) ;; (:metaclass dao-table-class)) ;; (defmethod print-object ((author author) stream) ;; (print-unreadable-object (author stream :type t) ;; (format stream "~a" (slot-value author 'name)))) ;; ;; Delete ;; (defun delete-matching (kw) "Delete the books whose titles match kw." (delete-books (find-book :query kw))) (defun delete-books (bklist) "Delete this list of books." (mapcar #'mito:delete-dao bklist)) (defun delete-books-without-authors (&key simulate) "Delete books without authors." (let ((to-delete (mito:select-dao 'book (sxql:where (:is-null :authors))))) (log:info "deleting ~a books with no authors" (length to-delete)) (unless simulate (mapcar #'mito:delete-dao to-delete)))) (defgeneric delete-obj (obj) (:method (obj) (let ((place-copies (mito:select-dao 'place-copies (sxql:where (:= :book obj))))) (mapcar #'mito:delete-dao place-copies) (mito:delete-dao obj)))) (defmethod delete-obj ((place place)) (let ((place-copies (mito:select-dao 'place-copies (sxql:where (:= :place place))))) (mapcar #'mito:delete-dao place-copies) (mito:delete-dao place))) (defun delete-objects (objlist) (mapcar #'delete-obj objlist)) ;; ;; Move from place to place ;; ;; use current-place, new command "inside <place>" ? (defun move (bk to &key (quantity 1) (from (current-place))) "Move a book from the actual place (the default one) to another one. If :from is specified, move from this place." (log:info from (mito:object-id from) to (mito:object-id to)) (if (= (mito:object-id from) (mito:object-id to)) (format t (_ "No need to move this book from and to the same place (~a).~&") (name to)) (when (remove-from from bk :quantity quantity) (add-to to bk :quantity quantity) (format t "Moved ~a cop~:@p of '~a' from ~a to ~a.~&" quantity (title bk) (name from) (name to))))) ;; ;; Some stats, observing the stock. ;; (defun negative-quantities () "Return a list of place-copies where the book's quantity is negative." (mito:select-dao 'place-copies (sxql:where (:< :quantity 0)))) ;; ;; utils ;; (defun erase-metaclass-from (class) "Needed to change the metaclass, e.g. add mito." ;; https://stackoverflow.com/questions/38811931/how-to-change-classs-metaclass (setf (find-class class) nil)) ;; ;; useful type definitions ;; (defun list-of-type-p (type list) (and (listp list) (every (a:rcurry #'typep type) list))) (defun list-of-books-p (list) (list-of-type-p 'book list)) (deftype list-of-books () `(satisfies list-of-books-p)) (defun book-hash-p (obj) (and (hash-table-p obj) (let ((keys (a:hash-table-keys obj))) (every (lambda (x) (member x keys)) '(:title :isbn))))) (deftype book-hash () `(satisfies book-hash-p)) (defun list-of-search-results-p (list) (list-of-type-p 'book-hash list)) (deftype list-of-search-results () `(satisfies book-hash-p))
30,205
Common Lisp
.lisp
776
32.58634
228
0.622685
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
241b69aaabe17aa8a024e43def6d4f41f0159dcebd4b341bd82198bcb6967b47
4,548
[ -1 ]
4,549
models-utils.lisp
OpenBookStore_openbookstore/src/models/models-utils.lisp
(in-package :openbookstore.models) (defun data2books (data) "Transform search results to a list of book objects." (loop for elt in data collect (make-book :title (str:sentence-case (access elt :title)) :isbn (access elt :isbn) :authors (str:title-case (access elt :authors)) :price (access elt :price) :details-url (access elt :details-url) :cover-url (access elt :cover-url) :publisher (str:title-case (access elt :publisher)) :date-publication (access elt :date-publication) :datasource (access elt :datasource) ))) (defun check-in-stock (data &key shelf-id) "DATA is not a list of book objects (but currently a hash-table). Add an IN-STOCK field by looking up there ISBN. Set the book shelf (Receive page). Ideally, we would not modify it if it already has a shelf, AND we would send a notification to the user." ;; 1 query to get the ones in stock. (setf data (alexandria:ensure-list data)) (let* ((in-stock (mito:select-dao 'book (sxql:where (:in :isbn (print (remove-if #'null (mapcar (lambda (it) (access it :isbn)) data))))))) (shelf (when shelf-id (openbookstore.models::find-shelf-by :id shelf-id)))) ;; Add :in-stock to matches only. (loop for book in (print in-stock) for elt = (find (isbn book) data :key (lambda (it) (access it :isbn)) :test #'string-equal) ;; do (format t "book isbn: ~a, elt found: ~a~&, quantity in stock: ~a" (isbn book) elt (quantity book)) do (setf (access elt :in-stock) (quantity book)) do (setf (access elt :id) (mito:object-id book)) ;; Set the shelf. ;; In next iterations: don't change it if it is already set, ;; AND display a message to te user. do (if shelf (progn (log:info "--- this book already has a shelf. Btw, our shelf is " shelf) (setf (shelf book) shelf) (mito:save-dao book) (setf (access elt :shelf) shelf)) (progn (log:info "--- No shelf. Set it to " shelf) (setf (shelf book) shelf) (mito:save-dao book) (setf (access elt :shelf) shelf))) ) data)) (defun ensure-integer (number) "Return this number as an integer (TRUNCATE and discard decimals). If it isn't a number, return 0. Typically, for a price that is parsed as a float, NUMBER should be the price x 100, and we return it as an integer. - number: float Return: an integer or 0." (if (and number (not (equalp number 0)) (numberp number)) (truncate number) (progn ;; log or warning? Both! (log:warn "Could not parse ~s to an integer price." number) 0))) ;; usage: #+(or) (progn (assert (= 1495 (ensure-integer (* 100 14.95)))) (assert (= 0 (ensure-integer "foo"))))
3,438
Common Lisp
.lisp
83
28.879518
111
0.520921
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
d818fd85162eff2c0364c1850aeaff6664a3b39205b0c804907001122cb85d59
4,549
[ -1 ]
4,550
baskets.lisp
OpenBookStore_openbookstore/src/models/baskets.lisp
(in-package :openbookstore.models) (export '(find-baskets)) (defclass basket () ((name :initarg :name :accessor name :col-type (:varchar 128))) (:metaclass mito:dao-table-class) (:documentation "A list of cards, independent from the stock (DB). Adding and deleting cards of baskets doesn't modify the stock.")) (defclass basket-copies () ((book :accessor basket-copies-book :initarg :book :col-type book) (basket :accessor basket-copies-basket :initarg :basket :col-type basket) (quantity :accessor basket-copies-quantity :initform 0 :col-type (or (:integer) :null))) (:metaclass mito:dao-table-class) (:documentation "Intermediate table between books and baskets. Specifies the quantity in the given basket.")) (defmethod print-object ((obj basket) stream) (print-unreadable-object (obj stream :type t) (format stream "~a" (name obj)))) (defun basket-books (basket) (mapcar #'basket-copies-book (mito:select-dao 'basket-copies (sxql:where (:= :basket basket))))) (defun create-basket (name) "Create a `basket' object in the DB." (mito:create-dao 'basket :name name)) (defun find-baskets (&optional name) (if name (error 'not-implemented) (mito:select-dao 'basket))) (defun print-basket (basket &key (stream t)) "Print the name of the basket and its number of books. With details, print the list of books." (format stream "~2a - ~40a~t x~3a/ ~3a~&" (mito:object-id basket) (name basket) (length (basket-books basket)) ;XXX: not length, count. (reduce #'+ (mapcar #'quantity (basket-books basket)))) (when *print-details* (let ((books (basket-books basket))) (if books (mapcar #'print-book books) (format stream "This basket is empty.~&")))))
1,850
Common Lisp
.lisp
52
30.576923
68
0.66555
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
bff9824450296973ff945c5f31aec163228fd4fd1499d3279b65246b79e1c66b
4,550
[ -1 ]
4,551
shelves.lisp
OpenBookStore_openbookstore/src/models/shelves.lisp
(in-package :openbookstore.models) (defclass shelf () ((name :initarg :shelf :accessor name :initform "" :col-type (or :null (:varchar 128))) (name-ascii :accessor name-ascii ;; no initarg, done an instance initialization. :initform nil :col-type (or :null (:varchar 128)))) (:metaclass mito:dao-table-class) (:unique-keys name) (:documentation "Shelves are categories for cards, but they have a physical location in the bookstore. A Card has only one shelf.")) (defmethod initialize-instance :after ((obj shelf) &key) "Create the shelf's name-ascii, just after the shelf instance is created, but before it is initialized with the initargs and initforms." (with-slots (name) obj (let ((name-ascii (utils:asciify name))) (setf (name-ascii obj) name-ascii)))) (defmethod print-object ((obj shelf) stream) (print-unreadable-object (obj stream :type t) (with-accessors ((name name)) obj (format stream "~a - ~a" (mito:object-id obj) name)))) (defun make-shelf (name) "Get or create a new shelf in DB. Check if a shelf with that name already exists. The check is done with a lowercase and ascii version of the name. Return two values: T if the shelf exists or was created, T if the shelf was created." ;; Doing that because mito:save-dao with a name constraint error would throw ;; a sql error, not a very precise condition. (when (str:blankp name) (error "Could not create a shelf with a blank name.")) (let* ((name-ascii (utils:asciify name)) (existing (mito:find-dao 'shelf :name-ascii name-ascii))) (if existing (progn (log:info "~&A shelf with that name (~a) (but lowercase and in ascii (~a) already exists. Do nothing.~&" name name-ascii) (values t nil)) (values (mito:save-dao (make-instance 'shelf :name name)) t)))) (defun shelves-names (&key query) "Return a list of shelves names. For the terminal autocompletion." (mapcar #'name (find-shelf :query query))) (defun find-shelf (&key query name-ascii (order-by :name-ascii) (order :asc) (limit 50)) "Return a list of book objects. If a query string is given, filter by the ascii name. By default, sorted alphabetically by name-ascii. You don't really need to use name-ascii, use FIND-SHELF-BY :name-ascii val" ;; Took inspiration from find-book. Beginning to have a pattern… ;; Added order-by (assert (member order (list :asc :desc)) nil "~&Wrong :order choice. Please use either :asc or :desc (default). You might want to change the :order-by field.~&Example: (find-shelf :order: asc :order-by :name-ascii)~&") (mito:select-dao 'shelf (when (str:non-blank-string-p query) (sxql:where `(:and (:like :name-ascii ,(str:concat "%" (str:downcase query) "%"))))) (when (str:non-blank-string-p name-ascii) (sxql:where (:= :name-ascii name-ascii))) (sxql:limit limit) (sxql:order-by `(,order ,order-by)))) (defun find-shelf-by (key val) (when val (mito:find-dao 'shelf key val))) ;;; Devel (defun ensure-shelf-name-ascii () "Parse all rows and ensure they have an ascii name. A mismatch can happen during development. Mostly because I added the field when rows already existed. Should not happen from now! should not…" (loop for shelf in (mito:select-dao 'shelf) if (and (name shelf) (str:blankp (name-ascii shelf))) do (format t "setting name-ascii for ~a…~&" shelf) (setf (name-ascii shelf) (utils:asciify (name shelf))) (mito:save-dao shelf) finally (return t)))
3,660
Common Lisp
.lisp
80
40.4125
220
0.673968
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
3454a72e0a2633e4e50c689bcecbd91de9a24c4579d154bcb92ff0fb08dc8a8d
4,551
[ -1 ]
4,552
contacts.lisp
OpenBookStore_openbookstore/src/models/contacts.lisp
(in-package :openbookstore.models) ;; see exports below. ;; A contact is like a place, except we know it is a person (useful for completion). ;; Books at someone's place aren't in at home now. (defclass contact (place) () (:metaclass mito:dao-table-class)) ;; (defclass contact-copies (place-copies) ;; ((max-time ;; :col-type :integer ;; :initform 60 ;; days ;; :accessor max-time)) ;; (:metaclass dao-table-class)) (defclass contact-copies () ;; XXX: use dao-table-mixin, do not inherit from place-copies, or maybe factorize book and quantity, not place and contact (we'll get place of id 1 instead of the contact). ;; Not inheriting = having to define the methods (title, name, quantity). ;; Update <2023-12-22 Fri> uh what does that old comment mean? ;; I simplified the accessor names to simply book, contact, quantity, and defined title and name. All is well… ((book :accessor book :initarg :book :initform nil :col-type book) (contact :accessor contact :initarg :contact :initform nil :col-type contact) (quantity :accessor quantity :initform 0 :col-type (or (:integer) :null)) (max-time :col-type :integer :initform 60 ;; days :accessor max-time) (due-date :col-type (or :null :timestamp) ;; null needed for a successfull Mito migration. :initform (local-time:timestamp+ (local-time:now) 60 :day) :accessor due-date :documentation "Date when the loan should end and the book come back.")) (:metaclass mito:dao-table-class)) ;; Other generic functions to shorten chaining to common elements: ;; use (title <contact-copies>) instead of (title (book <contact-copies>)). (defmethod title ((it contact-copies)) (title (book it))) (defmethod name ((it contact-copies)) (name (contact it))) (defmethod print-object ((contact contact) stream) (print-unreadable-object (contact stream :type t) (format stream "~a" (name contact)))) (defmethod print-object ((it contact-copies) stream) (print-unreadable-object (it stream :type t) (format stream "~a lended to ~a on ~a" (title it) (name it) (mito:object-created-at it)))) (defun make-contact (name) "Make a new contact (no DB registration)." (make-instance 'contact :name name)) (defun create-contact (name) "Create a new contact (with DB registration)." (mito:create-dao 'contact :name name)) (defun find-contacts (&optional query) "If query (list of strings), return contacts matching this name. Otherwise, return all contacts." ;; xxx: factorize with find-places (if query (progn ;; xxx should be same interface as find-book (unless (consp query) (setf query (cons query nil))) (mito:select-dao 'contact (sxql:where (:like :name (str:concat "%" (str:join "%" query) "%"))))) (mito:select-dao 'contact))) (defun find-contact-by (key val) (when val (mito:select-dao 'contact (sxql:where (:= key val))))) (defun find-contacts-copies (&key contact) "Return the list of borrowed books, most recent last. If `contact' is given, filter by this contact." ;; (warn "Exclude loans with a quantity at 0 ?") (remove-if-not #'book (mito:select-dao 'contact-copies (when contact (sxql:where (:= :contact contact))) (sxql:order-by :object-created)))) (defun find-contact-loans (contact) "Find this contact's borrowed books." (declare (type contact contact)) ;; I initially wrote the following function. Some refactoring might be needed. (find-contacts-copies :contact contact)) (defun find-book-loans (book) "Find who borrowed this book." (mito:select-dao 'contact-copies (when book (sxql:where (:= :book book))) (sxql:order-by :object-created))) #+(or) (find-book-loans (third (openbookstore.models::find-book :query "comprendre"))) (defgeneric loan-too-long-p (obj) (:documentation "Return t if this loan bypasses the number of days allowed.")) (defmethod loan-too-long-p (obj) (error "no method for this type: ~a" (type-of obj)) ) (defmethod loan-too-long-p ((obj contact-copies)) (let* ((now (local-time:now)) (time-difference (ltd:timestamp-difference (mito:object-created-at obj) now))) (> (abs (ltd:duration-as time-difference :day)) (max-time obj)))) (defgeneric loan-danger-p (obj) (:documentation "Return t if the loan is approching the maximum time allowed.")) (defmethod loan-danger-p ((obj contact-copies)) (let* ((now (local-time:now)) (danger-days 10) (diff (ltd:timestamp-difference (mito:object-created-at obj) now))) (> (abs (ltd:duration-as diff :day)) (- (max-time obj) danger-days)))) (defun princ-color-flags (what loan) "Return `what` (a string) with red ansi colors if the loan is too long, yellow if danger. To print with `format t`." (if (loan-too-long-p loan) (cl-ansi-text:red (princ-to-string what)) (progn (if (loan-danger-p loan) (cl-ansi-text:yellow (princ-to-string what)) what)))) (defun print-borrowed-book (book) ;; unused. (format t "~2a- ~40a borrowed on ~a~&" (mito:object-id book) (title book) (mito:object-created-at book))) (defun print-borrowed-books (contact) (let ((title-length 40)) (mapcar (lambda (it) (let ((book (book it))) (if book (format t "~t~2a- ~va since ~a~&" (mito:object-id book) title-length (str:prune title-length (title it)) (princ-color-flags (utils:format-date (mito:object-created-at it)) it)) (format t "no book for ~a?" it)))) (mito:select-dao 'contact-copies (sxql:where (:= :contact contact)))))) (defun print-contact (contact &key (stream t) (details *print-details*)) "Print the given contact, the books she borrowed and if it's been too long." ;; format-object method ? (let* ((title-length 40) (padding (+ title-length 9))) (format stream "~2a - ~va~t ~&" (mito:object-id contact) padding (cl-ansi-text:cyan (str:prune title-length (name contact))) ;; (length (contact-books contact)) ) (when details (print-borrowed-books contact)))) ;; ;; Commands ;; (defun lend (book contact &key (quantity 1)) "Lend this book to this contact." ;; xxx: modeled after add-to. (assert book) (assert contact) (unless (mito:object-id book) (error "The book ~a is not saved in DB." book)) (let ((existing (mito:find-dao 'contact-copies :contact contact :book book)) contact-copy) (if existing (progn (log:info "The book ~a was already lended to ~a." book contact) (incf (quantity existing) quantity) (mito:save-dao existing) (quantity existing)) (progn (log:info "~a wasn't lended' to ~a yet, let's do it.~&" book contact) (setf contact-copy (make-instance 'contact-copies :contact contact :book book :quantity quantity)) (mito:insert-dao contact-copy) (quantity contact-copy))))) (defun print-loans (&key name) "Print who borrowed what book and since when (most recent last). If `name', filter by this contact." (let* ((contact (first (when name (find-contacts name)))) (copies (if contact (find-contacts-copies :contact contact) (find-contacts-copies))) (title-length 40) (padding (+ title-length 9))) ;; color escape strings. (mapcar (lambda (copy) (let ((book (book copy))) (if book (format t "~2a- ~va since ~a by ~a~&" (mito:object-id book) padding (cl-ansi-text:blue (str:prune title-length (title copy))) (princ-color-flags (utils:format-date (mito:object-created-at copy)) copy) (name copy)) (format t "no book for copy ~a?" copy)))) copies) ;; We return a list of copies, not contact-copies, for the command level, ;; to get pagination completion right. (mapcar #'book copies))) (defun find-loans (&key (limit 20) (order :asc)) (remove-if-not #'book (mito:select-dao 'contact-copies (sxql:limit limit) (sxql:order-by `(,order :due-date))))) (defun outdated-loans (&key (limit 20) (order :asc)) "Return a list of loans whose due date is exhausted (lower than today). Filter out loans whose card is null." (remove-if-not #'book (mito:select-dao 'contact-copies (sxql:where (:< :due-date (local-time:now))) (sxql:limit limit) (sxql:order-by `(,order :due-date))))) (defun loans-without-cards () "Find loans without a card. Should not happen, but can happen during development when a card is deleted." (remove-if #'book (mito:select-dao 'contact-copies))) (defun count-outdated-loans () "Return the number (integer) of outdated loans." ;; Uses LENGTH instead of a proper SQL count. (length (outdated-loans :limit 1000000))) (defun receive (book &optional contact) "Return this book. In case of ambiguity, give the contact as optional argument." (declare (ignorable contact)) (let ((copies (mito:select-dao 'contact-copies ;; How to chain queries, to filter on contact only if given ? (sxql:where (:= :book book))))) (case (length copies) (0 (format t "It seems that this book was not lended to anyone.~&")) (1 (let* ((copy (first copies)) (quantity (quantity copy))) (decf (quantity copy)) (mito:save-dao copy) ;; Delete records back to 0 ? We're not handling history yet, but rather no. (if (> quantity 1) (format t "~a still has ~a cop~@:p of this book.~&" (name copy) (quantity copy)) (format t "We got '~a' back from ~a, ok.~&." (str:prune 30 (title copy)) (name copy))) (quantity copy))) (t (error "This book was borrowed by more than one contact at the same time. Not implemented yet. But it should be."))))) ;; ;; Interactive, development stuff ;; ;; We can compile the following ourselves, it is ignored at compile time. #+nil (defvar *contact* (find-dao 'contact)) #+nil (defvar *thule* (first (find-book :query "thule"))) ;; ;; Export ;; (export '(make-contact create-contact find-contacts find-contact-by print-contact lend loans receive ))
11,337
Common Lisp
.lisp
278
32.435252
174
0.598621
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
dfba5e7f982aa1d180de29e05a2024aeed9d0b7a44517009ad124b5baebe8ef0
4,552
[ -1 ]
4,553
sell.lisp
OpenBookStore_openbookstore/src/models/sell.lisp
(in-package :openbookstore.models) (defclass sell () ((cancelled :accessor sell-cancelled :initarg :cancelled :initform nil :type :bool :col-type :boolean :documentation "If the sale has been cancelled") (date :accessor date :initarg :date :type :date-stamp :col-type :datestamp :documentation "Date of the sale") (client :accessor sell-client :initarg :client :initform nil :col-type (or (:varchar 128) :null) ;TODO: should be link to client table? :documentation "Name of customer") (payment-method-id :accessor payment-method-id :initarg :payment-method-id :initform -1 :col-type :integer :documentation "ID used for this payment method. We currently don't store all the payment methods in a table because: they will quite change depending on the user, they might change in time, we are not so interested about them. We want to compute totals per payment method and show totals in the UI.") (payment-method-name :accessor payment-method-name :initarg :payment-method-name :initform "" :col-type (or (:varchar 128) :null) :documentation "Name of the payment method used for this transaction. NOTE: we should allow up to 3 payment methods.")) (:metaclass mito:dao-table-class) (:documentation "Represents a sale on a specific date of a number of books to a client.")) (defmethod print-object ((obj sell) stream) (print-unreadable-object (obj stream :type t) (format stream "#~a" (or ;; let's be defensive! (ignore-errors (mito:object-id obj)) "<error getting object ID>")))) (defclass sold-cards () ((card :accessor card :col-type book) (sell :accessor sell :col-type sell) (quantity :accessor quantity :initform 0 :col-type :integer :documentation "Quantity of this book sold in this transaction. Can be a negative number.") (sold-price :accessor sold-price :initarg :sold-price :initform nil :col-type (or :float :null)) (current-price :accessor current-price :initarg :current-price :initform nil :col-type (or :float :null) :documentation "Book list price at time of sale") ) (:metaclass mito:dao-table-class) (:documentation "A many-to-many connection table representing books sold. Card field is a link to the book that was sold. Sell field is a link to the transaction in which it was sold.")) (defmethod print-object ((obj sold-cards) stream) (print-unreadable-object (obj stream :type t) (with-accessors ((card card)) obj (format stream "#~a for card ~a (#~a)" (mito:object-id obj) (or (ignore-errors (title card)) "<error getting card's title !>") (or (ignore-errors (mito:object-id card)) "<error getting the card ID!>"))))) (defclass payment-method () ((sell :col-type sell) (name :accessor payment-name :initarg :name :initform nil :col-type (or (:varchar 128) :null)) (count-for-revenue :accessor count-for-revenue :initarg :count-for-revenue :initform t :col-type :boolean :documentation "If false, show this transaction in the history but don't count it in the revenue.")) (:metaclass mito:dao-table-class) (:documentation "Payment method that was used to complete a Sell.")) (defun make-sale (&key books payment client date payment-method-id payment-method-name) "Create one sell with the given books (list of alist with ID, PRICE, QUANTITY). For each book, create a SOLD-CARD row. Only BOOKs is required. Example: (make-sale :books '(((:ID . 45) (:QUANTITY . 2) (:PRICE . 13.72)) ((:ID . 15) (:QUANTITY . 2) (:PRICE . 41)))) " (let* ((date (or date (local-time:now))) (sale (make-instance 'sell :client client :date date :payment-method-id payment-method-id :payment-method-name payment-method-name)) (payment (make-instance 'payment-method :sell sale :name payment)) (bookobjs (mapcar (lambda (book) (let ((card (find-by :id (access book :id)))) (unless card (error "Book not found!")) (make-instance 'sold-cards :current-price (price card) :sold-price (access book :price) :quantity (access book :quantity) :card card :sell sale))) books))) (mito:save-dao sale) (mito:save-dao payment) ;XXX: why save the payment? This leaked threw a PR review. (mapc #'mito:save-dao bookobjs) (dolist (sold bookobjs) (add-to (default-place) (card sold) :quantity (- (quantity sold)))) sale)) #+(or) (make-sale :books '(((:ID . 45) (:QUANTITY . 2) (:PRICE . 13.72)) ((:ID . 15) (:QUANTITY . 2) (:PRICE . 41)))) (defun find-sell (&key (order :asc) (limit 400) max-date min-date) "Find sell objects. Return: a list of SELL objects ORDER: :asc or :desc LIMIT: maximum objects to return (defaults to 400). MIN-DATE: a local-time date. Find the sells from and including this date. MAX-DATE: find sells up to and including this date." ;; TODO: search soldcards, group by sell_id, colorize. (mito:select-dao 'sell (when min-date (sxql:where (:>= :created-at min-date))) (when max-date (sxql:where (:<= :created-at ;; need to add one day to include today (local-time:timestamp+ max-date 1 :day)))) (sxql:order-by `(,order :created-at)) (sxql:limit limit))) (defun find-soldcards (&key (order :asc) (limit 400) sell sell-id) "Find soldcards objects (sells details). If SELL or SELL-ID is not nil, filter by the sell ID. Limit results to LIMIT (last 400 transactions by default). Return: a list of SOLD-CARDS objects. Example: (find-soldcards :order :desc :sell-id 19)" ;; TODO: views to show by month and day, with no limit.. (mito:select-dao 'sold-cards (when sell-id (sxql:where (:= :sell-id sell-id))) (when sell (sxql:where (:= :sell sell))) (sxql:order-by `(,order :created_at)) (sxql:limit limit))) (defun group-sells-and-soldcards (&key (order :asc) (limit 400) min-date max-date) "Find soldcard objects between MIN-DATE and MAX-DATE (both including). The goal is to show sells in the history: one line per sold card, but they should be grouped by sells. We want to show the sell ID only once. Return a list of dict with: - sell-id - sell object - created-ad: date of the sell - soldcard: the soldcard objects (it's about 1 sold item), which contains the price sold, the quantity sold, etc. - first-sell-item: used for display. We want to show the sell ID and date only for the first soldcard of this sell. - item-group: T or NIL, used for display (different colors for each sell)." ;; NOTE: we don't have a backlink from a SELL to its SOLD-CARDS ? (let ((sells (find-sell :order order :limit limit :min-date min-date :max-date max-date))) (alexandria:flatten (loop for sell in sells for sell-id = (mito:object-id sell) for item-group = t then (not item-group) ;; used to color each group of sells. collect (loop for soldcard in (find-soldcards :sell-id (mito:object-id sell)) for first-sell-item = t then nil collect (dict :sell-id sell-id :first-sell-item first-sell-item :item-group item-group :sell sell :created-at (mito:object-created-at sell) :soldcard soldcard)))))) #+(or) (group-sells-and-soldcards :min-date (utils:yesterday) :max-date (local-time:today))
8,382
Common Lisp
.lisp
191
34.445026
305
0.603949
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
22c9f1cfd44a68c30cbdda59db4d96117e0ad209cfa3336424878e06cbca950d
4,553
[ -1 ]
4,554
scraper-fr.lisp
OpenBookStore_openbookstore/src/datasources/scraper-fr.lisp
(defpackage bookshops.datasources.scraper-fr (:use :cl :cl-ansi-text :parse-float :log4cl) (:export :books) (:documentation "Search for books by ISBN or keywords on a french website. Return a list of hash-tables. Don't create Book objects from openbookstore.models here.")) (in-package :bookshops.datasources.scraper-fr) ;; This scraper does not use the base-scraper class and methods (which was created later). ;; Print hash-tables readably (used for debug logs). (serapeum:toggle-pretty-print-hash-table t) (defparameter *french-search* "http://www.librairie-de-paris.fr/listeliv.php?MOTS={QUERY}&SUPPORT=&RECHERCHE=simple&TRI=&DISPOCHE=&RAYONS=&LIVREANCIEN=2&CSR=" "French source of books. The {query} string will be replaced by the list of '+' separated search keywords.") (defparameter *url-base* "http://www.librairie-de-paris.fr" ;; no trailing / for now plz. "Base url.") (defparameter *datasource* *french-search* "The default data source.") (defvar *last-results* nil "List of last results by `books` (objects).") (defparameter *debug* nil "xxx: just use (log:debug)") ;; Conditions. (define-condition parse-warning (simple-warning) ((data :initarg :data :initform nil :accessor parse-warning-data :documentation "The element we are trying to parse (ex: the price).") (message :initarg :message :initform "" :accessor parse-warning-message)) (:report (lambda (c stream) (format stream "scraper warning: ~a" (parse-warning-message c))))) (define-condition price-parse-warning (parse-warning) () (:report (lambda (c stream) (declare (ignorable c)) (format stream "scraper warning")))) ;; bad: copied from utils.lisp. (defun extract-float (s) "Extract a double float from the given string. Use a double float to delay floating point errors. A simple (* 100 9.90), to turn a price into an integer, is not 990. Using a double is OK. Return: a double float, or NIL on error." (check-type s string) (ignore-errors ;; The regexp should be enough for this scraper, we parse a known HTML. ;; It will need to be adapted for other scrapers. ;; parse-float has :junk-allowed t, but a regexp is a bit more solid. ;; Example: ;; (parse-float:parse-float "price 9.90 euros" :junk-allowed t) ;; => NIL (parse-float (ppcre:scan-to-strings "-?\\d+.?\\d*" s) :type 'double-float))) #+(or) (progn (assert (= 9.90d0 (extract-float "9.90 €"))) (assert (= 990 (* 100 9.90d0)))) ;; try 9.90: rounding error. (defun get-url (url) "Http get this url. Function mocked in unit tests." (log:info url) (dex:get url)) (defun parse (request) "Parse with plump, return a plump node. Function mocked in unit test." (plump:parse request)) (defun select (selector parsed) "Find nodes with CSS selector from a plump-parsed node." (lquery:$ selector parsed)) (lquery:define-lquery-list-function elt0 (vector) (elt vector 0)) (defun node-selector-to-text (selector node &key selector2) " Take a CSS selector (str), a plump node, extract and clean the result." (declare (ignorable selector2)) (let* ((nodes (clss:select selector node)) res txt) (setf nodes (coerce nodes 'list)) (when (not (null nodes)) (setf res (first nodes)) (setf txt (plump:text res)) (str:trim txt)))) (defmacro with-log-error ((name) &body body) `(handler-case (progn ,@body) (error (c) (format *error-output* "could not parse ~a: ~a." ,name c)))) (defun parse-title (node) (with-log-error (:title) (node-selector-to-text ".livre_titre" node))) (defun parse-authors (node) (with-log-error (:authors) (lquery:$ node ".livre_auteur a" (attr :title) (elt0)))) (defun ensure-integer (number) "Return this number as an integer (TRUNCATE and discard decimals). If it isn't a number, return 0. Typically, for a price that is parsed as a float, NUMBER should be the price in cents (x 100), and we return it as an integer. - number: float Return: an integer or 0." ;; warn: copied to model-utils.lisp. The scraper module should stay completely independant of ;; the application code. (if (and number (not (equalp number 0)) (numberp number)) (truncate number) (progn ;; log or warning? Both! (log:warn "Could not parse ~s to an integer price." number) (signal (make-condition 'parse-warning :message (format nil "fr scraper: could not transform ~S to an integer. Returning 0." number) :data number)) 0))) ;; usage: #+(or) (progn (assert (= 1495 (ensure-integer (* 100 14.95)))) (handler-case (assert (= 0 (ensure-integer "foo"))) (warning (c) (princ c) (print (parse-warning-data c))))) (defun parse-price (node) "Extract the price. `node': plump node." (let ((price (extract-float (node-selector-to-text ".item_prix" node)))) (let ((res (ensure-integer (* 100 price)))) (log:info "Price ~s is parsed as: ~s~&" price res) res) )) (defun parse-publisher (node) (with-log-error (:publisher) (node-selector-to-text ".editeur" node))) (defun parse-isbn (node) (str:trim (first (last (str:lines (node-selector-to-text ".editeur-collection-parution" node)))))) (defun parse-publication-date (node) (with-log-error (:publication-date) (node-selector-to-text ".MiseEnLigne" node))) (defun parse-cover-url (node) (with-log-error (:cover) (lquery:$ node ".zone_image img" (attr "data-original") (elt0)))) (defun parse-details-url (node) "Extract the url to the book online information. https://www.librairie-de-paris.fr/livre/9782742720682-antigone-henry-bauchau/" (with-log-error (:details-url) (str:concat *url-base* (lquery:$ node ".livre_titre a" (attr :href) (elt0))))) (defun make-book (&key title isbn datasource cover-url authors details-url price publisher date-publication) "Create a hash-table with these slots. Don't rely on the models in the data scrapers. tip: access the fields easily with the access library." (serapeum:dict :title title :isbn isbn :datasource datasource :cover-url cover-url :authors authors :details-url details-url :price price :publisher publisher :date-publication date-publication)) (defun book-info (node) "Takes a plump node and returns a list of book objects with: title, authors, price, publisher, date of publication, etc." (let ((title (parse-title node)) (authors (parse-authors node)) (price (parse-price node)) (publisher (parse-publisher node)) (date-publication (parse-publication-date node)) (isbn (parse-isbn node)) (cover-url (parse-cover-url node)) (details-url (parse-details-url node)) bk) ;; Every field of this dict must be present in search.html ;; for the add-or-create and quick-add-stock forms, where we save ;; the book to our DB. (setf bk (make-book :title title :isbn isbn :datasource "fr:librairiedeparis" :cover-url cover-url :authors authors :details-url details-url :price price :publisher publisher :date-publication date-publication)) bk)) (defun build-url (query &key (source *datasource*) (encode t)) "Build the search url with the query terms in it. Encode the search terms (if `:encode' is true, the default). - query: a str (possibly many words). Return the url (a str). " (let* ((words (str:words query)) (joined (str:join "+" words)) (encoded? (if encode (quri:url-encode joined) joined))) (str:replace-all "{QUERY}" encoded? source))) (defparameter *last-parsing-res* nil "for debug pursposes.") (defun books (query) "From a search query (str), return a list of book objects (with a title, a price, a date-publication, authors,...)." (let* ((url (build-url query)) (req (get-url url)) (parsed (parse req)) ;; one node ;: XXX: clss can be replaced by lQuery. (node (clss:select ".resultsList" parsed)) ;; direct children: (res (clss:select "> li" node))) (setf *last-parsing-res* (coerce res 'list)) (setf *last-results* (map 'list #'book-info res))))
8,802
Common Lisp
.lisp
216
34.013889
167
0.637449
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
f7a9035360b3c7b40493d21b23fbcf6fcb5c001852ef9ab1e278384a162af983
4,554
[ -1 ]
4,555
scraper-argentina.lisp
OpenBookStore_openbookstore/src/datasources/scraper-argentina.lisp
(uiop:define-package bookshops.datasources.scraper-argentina (:use :cl :cl-ansi-text :parse-float :log4cl) (:export :books :get-scraper) (:documentation "Search for books by ISBN or keywords. Return a list of hash-tables (dict). The exported function is BOOKS. We currently get data by scraping the site https://cuspide.com. Usage: Create an instance of this scraper: (defparameter *argentina-scraper* (make-instance 'scraper-argentina)) Call the BOOKS function with this scraper object: (books *argentina-scraper* \"antigona\") ")) ;;TODO: extract ISBN ;; https://www.cuspide.com/resultados.aspx?c=antigona&por=pal (in-package :bookshops.datasources.scraper-argentina) (defparameter *scraper-argentina* nil "Current scraper.") (defun get-scraper () "Get or create a scraper instance for Argentina." (if *scraper-argentina* *scraper-argentina* (setf *scraper-argentina* (make-instance 'bookshops.datasources.base-scraper::scraper-argentina)))) (defun make-argentina-scraper () (make-instance 'bookshops.datasources.base-scraper::scraper-argentina)) ;;; ;;; Change package to define our scraper. ;;; (in-package :bookshops.datasources.base-scraper) (defclass scraper-argentina (base-scraper) ((datasource-name :initform "Cuspide.com - Argentina") (url-base :initarg :url-base :initform "https://www.cuspide.com" :accessor url-base :type string :documentation "The base URL of the target website, sans trailing /. Example: http://www.librairie-de-paris.fr") (url-search :initarg :url-search :initform "https://www.cuspide.com/resultados.aspx?c={QUERY}&por=pal" :accessor url-search :type string :documentation "The URL, with query placeholders, that runs a search on the distant website. Placeholders include: - {QUERY} : most of the times, must be replaced with '+' separated search terms. Example: 'lisp+book'") ;; Now some internal data, CSS selectors to parse the results. (css-container :initform "#ctl00_ContentPlaceHolder1_cotenedorLibros" :initarg :css-container :documentation "A CSS selector that wraps the books. Must return 1 node (or 0).") (css-elements :initarg :css-elements :initform ".libro" :documentation "A CSS selector that finds all book elements, once we have the node from css-container.") ;; Now find all possible book data: (css-title :initarg :css-title :initform ".md-datos h1" :documentation "Inside each element found by css-card, a CSS selector to find the title.") (css-author :initarg :css-author :initform ".autor a" :documentation "CSS selector to find the author(s) inside each card found by css-card.") (css-price :initarg :css-price :initform ".precio") (css-isbn :initarg :css-isbn :initform ".md-datos h1 a" :documentation "Important field, it is required.") (css-cover-url :initarg :css-cover-url :initform "figure img[src]" :documentation "CSS selector to find the book's cover URL. Sometimes it is full URL, sometimes it is a relative URL, to concatenate to the url-base.") (css-details-url :initarg :css-details-url :initform "figure a[href]" :documentation "CSS selector to find the book's details page URL. Often, it is a relative result so we have to concatenate url-base to this result.") ;; TODO: editorial, publication-date (css-currency :initarg :css-currency :initform ".precio span" :documentation "Optional. Set the default currency for this scraper with CURRENCY.") (currency-symbol :initarg :currency-symbol :initform "AR$" :documentation "The default currency symbol. Example: AR$ 1.500") )) (defun extract-price-as-cents (s) "Extract the price as an integer from the given string, for prices represented like 1.500,00 (Argentinian prices). Return: an integer, or NIL on error." (check-type s string) ;; thanks @mmontone on Gitter. (labels ((round-amount (amount &optional (divisor 1)) (multiple-value-bind (quotient remainder) (truncate (/ amount divisor)) (if (>= (abs remainder) 1/2) (+ quotient (truncate (signum remainder))) quotient))) (parse-amount (string &optional (decimals 2)) "Parse an amount" (setf string (remove (code-char 160) string)) (setf string (remove #\Space string)) (setf string (substitute #\. #\, string)) (let ((decs (or (position #\. (reverse string)) 0))) (round-amount (* (expt 10 decimals) (/ (parse-integer (remove #\. string)) (expt 10 decs)))))) (extract-price (s) "Cleanup the string: from AR$ 1.500,00 remove \"AR$\"" (ppcre:scan-to-strings "\\d+.?\\d+,?\\d*" s))) (handler-case ;; The regexp we use in the french scraper is NOT enough for this one, ;; the prices represented as 1.500,00 can NOT be parsed with the parse-float library. (parse-amount (extract-price s)) (error (c) (log:warn "Could not parse price in ~S: ~a" s c))))) #+test(extract-price-as-cents "22") #+test(extract-price-as-cents "22.50") #+test(extract-price-as-cents "22.5066") #+test(extract-price-as-cents "1.500,00") #+test(extract-price-as-cents "2.500,90") #+test(extract-price-as-cents "1.000,00") #+test (assert (extract-price-as-cents "AR$ 1.000,00")) #| May be useful: (defun decimal (number &optional (decimals 2)) (* number (expt 10 decimals))) #+test(decimal 22) (defun format-amount (amount &optional (decimals 2)) "Format an amount" (multiple-value-bind (basic cents) (truncate amount (expt 10 decimals)) (format nil "~a,~a" basic (abs cents)))) #+test(format-amount 3300) #+test(format-amount 3345) #+test(format-amount 99999) |# ;; Title: OK, enough with CSS selector. ;; (defmethod parse-title (scraper node)) (defmethod parse-authors ((scraper scraper-argentina) node) (with-log-error (:authors) ;; slot-value is overriden by lquery, can't use it inside $ (let ((css (slot-value scraper 'css-author))) (str:trim (lquery:$ node css (elt0) (text)))))) (defmethod parse-price ((scraper scraper-argentina) node) "Extract the price. `node': plump node. Return: integer, the price as cents (real price multiplied by 100)." (extract-price-as-cents (node-selector-to-text (slot-value scraper 'css-price) node))) ;; (defmethod parse-publication-date (scraper node) ;; (with-log-error (:publication-date) ;; (ignore-errors ;; ;; ;TODO: ;; (node-selector-to-text (slot-value scraper 'css-publication-date) node)))) (defmethod parse-cover-url ((scraper scraper-argentina) node) (with-log-error (:cover) (let ((css (slot-value scraper 'css-cover-url))) (lquery:$ node css (elt0) (attr "src"))))) ;; OK ;; (defmethod parse-details-url (scraper node)) (defun probably-isbn (s) (when s (and (str:starts-with-p "9" s) (member (length s) '(10 13))))) #+(or) (progn (assert (probably-isbn "9782806284082")) (not (probably-isbn "Libro"))) (defmethod parse-isbn (scraper node) "Extract the ISBN from the search results. It is given in the HREF of the title." (with-log-error (:isbn) (let ((css (slot-value scraper 'css-isbn))) ;; We get "/Libro/9788415510529/Antigona" ;; Extract the ISBN, and be a bit lax on its position, just in case. (find-if #'probably-isbn (str:split "/" (lquery:$ node css (elt0) (attr "href")))))))
7,933
Common Lisp
.lisp
169
39.83432
168
0.64967
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
b6db439b6d9b11466c817c4ec0389379e06629fa332e1aaf137fc2f7acafe89f
4,555
[ -1 ]
4,556
dilicom.lisp
OpenBookStore_openbookstore/src/datasources/dilicom.lisp
(defpackage bookshops.datasources.dilicom (:use :cl) (:export :search-books :available-p) (:documentation "Search books by ISBN (and ISBN only, no free search) with the \"FEL à la demande\" by Dilicom, the professional provider. You must set your *user* and *password*: (setf bookshops.datasources.dilicom::*user* \"user\" bookshops.datasources.dilicom::*password* \"password\") It will be possible to set them in environment variables and in the config file.")) (in-package :bookshops.datasources.dilicom) #| SOAP request to the Dilicom web service (FEL à la demande). We can query ISBNs and we can't do a free search by keyword. The gist of it is: - a POST request with the right header, user and password - XML processing with lQuery to extract the books information. - return a hash-table with keys being title, authors, price, isbn, etc. TODO: password and user in config.lisp |# (defvar *user* nil "Dilicom user GSN (numbers)") (defvar *password* nil "Dilicom user's password.") (defun available-p () "Is Dilicom configured and likely to be available?" (and *user* *password*)) ;XXX: merged upstream in str. (defun replace-pairs (pairs str) "Replace all associations in pairs (plist) and return a new string. Example: (replace-pairs (list \"{{phone}}\" \"987\") \"call {{phone}}\") => \"call 987\"" (assert (consp pairs)) (dotimes (i (- (length pairs) 1)) (setf str (str:replace-all (nth i pairs) (nth (incf i) pairs) str))) str) (defun create-soap-content (isbns) (assert (and *user* *password*)) (when isbns (let ((ean13s (with-output-to-string (s) (loop for isbn in isbns do (format s "<ean13s>~a</ean13s>" isbn))))) (replace-pairs (list "USER" *user* "PASSWORD" *password* "EAN13S" ean13s) ;; beware, there must be no space around the placeholders, ;; or the SOAP service fails. "<?xml version='1.0' encoding='utf-8'?> <soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap-env:Body><ns0:demandeFicheProduit xmlns:ns0=\"http://fel.ws.accelya.com/\"><demandeur>USER</demandeur><motDePasse>PASSWORD</motDePasse>EAN13S<multiple>false</multiple></ns0:demandeFicheProduit></soap-env:Body></soap-env:Envelope>")))) (defun soap-request (isbns) "Create the SOAP request body from a list of ISBNs (strings) and send the POST request to Dilicom's WSDL server." (dexador:post "http://websfel.centprod.com/v2/DemandeFicheProduit" :headers '(("Content-Type" . "text/xml; charset=utf-8")) :content (create-soap-content isbns))) (defun query (q) (lquery:$ (initialize (soap-request q)) "elemReponse")) (defun print-hash-entry (key value) (format t "~S: ~S~%" key value)) (defun print-book (ht) (log:info "~&Book:~&") (maphash #'print-hash-entry ht)) (lquery:define-lquery-list-function elt0 (vector) (elt vector 0)) (defun read-price (s) "From a string return a float." (handler-case (/ (parse-integer s) 1000.0) (error (c) (log:warn "Error while decoding dilicom price: ~a" c)))) #+nil (assert (= 16.50 (read-price "0016500"))) (defun search-books (isbns &key debug) (loop for elt across (query isbns) for book = (make-hash-table) do (setf (gethash :datasource book) "dilicom") do (setf (gethash :details-url book) nil) do (setf (gethash :title book) (str:capitalize (lquery:$ elt "libstd" (text) (elt0)))) do (setf (gethash :authors book) (str:title-case (lquery:$ elt "auteur" (text) (elt0)))) do (setf (gethash :isbn book) (lquery:$ elt "ean13" (text) (elt0))) do (setf (gethash :publisher book) (str:title-case (lquery:$ elt "edit" (text) (elt0)))) do (setf (gethash :distributor book) (lquery:$ elt "gcddistrib" (text) (elt0))) do (setf (gethash :date-publication book) (lquery:$ elt "dtparu" (text) (elt0))) ;; theme: currently unused do (setf (gethash :theme book) (lquery:$ elt "theme" (text) (elt0))) ;; Price do (setf (gethash :price book) (read-price (lquery:$ elt "prix" (text) (elt0)))) ;; availability: currently unused. do (setf (gethash :availability book) (lquery:$ elt "codedispo" (text) (elt0))) do (when debug (print-book book)) collect book)) ;; and voilà.
4,644
Common Lisp
.lisp
108
36.092593
320
0.629465
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
e6d1ac2e7fccbcfc15fab68a61ec4a96def35415afd4724acbe8d85d98b5dfde
4,556
[ -1 ]
4,557
dilicom-flat-text.lisp
OpenBookStore_openbookstore/src/datasources/dilicom-flat-text.lisp
(defpackage #:bookshops.datasources.dilicom-flat-text (:use #:cl) (:export #:parse-line #:parse-file) (:import-from #:local-time #:encode-timestamp #:+utc-zone+) (:import-from #:alexandria #:make-keyword #:ensure-list) (:import-from #:str #:trim-right) (:import-from #:split-sequence #:split-sequence) (:documentation "Status: UNUSED. This is a parser of Dilicom's FORMAT PLAT text files to extract the bibliographic information. This format is used by the 'FEL à la demande' by FTP. The WEB SERVICE uses another format, and is already functioning. We aimed to interface with the Belgium data provider, La Banque du Livre (its own entity, but technically dependent of the french Dilicom). Unfortunately, Jason's work can not be used because, despite their claims, the FEL by FTP has a long latency, of the order of seconds, sometimes more than 20 seconds. Our software is modeled after quick response times, for the bookseller to scan books at hands and see their data instantly. This works with the WEB SERVICE, but not the FTP. I spare you the communication problems but, in the end, when we at least got a FTP access and demonstrated the latency to the user support, we did not carry on working on this code. Future work: La Banque du Livre might deploy the WEB SERVICE in 2021.")) (in-package #:bookshops.datasources.dilicom-flat-text) (defparameter +source-name+ "dilicom-flat-text") (defstruct (field-info (:constructor make-field-info (name start end &optional (parser #'identity) (representation nil)))) "Contains information for Dilicom FEL plain-text fields. start/end are zero-indexed, end-exclusive because that's how indexing in lisp (and most languages) works, while the specification is 1-indexed, end-inclusive because that's common vernacular (in both French and English). In short, start should be 1 less than the specification, end should be the same, and the start of the following field should be the same as the end of the previous field" name start end parser representation) (defun parse-date (string) "Parses date in Dilicom FEL plain-text format: YYYYMMDD" (let ((année (parse-integer string :start 0 :end 4)) (mois (parse-integer string :start 4 :end 6)) (jour (parse-integer string :start 6 :end 8))) (encode-timestamp 0 0 0 0 jour mois année :timezone +utc-zone+))) (defun format-by-100 (stream value) (format stream "~D.~2,'0D" (floor value 100) (mod value 100))) (defparameter *basic-fields* (list (make-field-info :code 0 1 #'identity (lambda (x) (ecase (make-keyword x) (:c :created) (:m :modified) (:s :deleted) (:e :extracted)))) (make-field-info :ean-13 1 14 #'identity) (make-field-info :gencod 14 27 #'identity) (make-field-info :date-publication 27 35 #'parse-date) (make-field-info :availability 35 36 #'parse-integer (lambda (x) (case x (1 :available) (2 :not-yet-published) (3 :reprint) (4 :temporarily-unavailable) (5 :no-longer-available) (6 :permanently-off-market ) (7 :indefinitely-out-of-print) (8 :to-reappear ) (9 :removed-from-print) (t nil)))) ;; This is an enum see (p. 18 of FPL) (make-field-info :price-type 36 37 #'parse-integer) (make-field-info :price 37 45 #'parse-integer (lambda (x) (format nil "~A ~C" (format-by-100 nil (round x 10)) #\Euro_Sign))) ;; "livre scolaire" is a specific legal term related to libraries (make-field-info :school-book 45 47 #'identity (lambda (x) (ecase (char x 0) (#\1 t) (#\0 nil)))) (make-field-info :tva-rate-1 47 51 #'parse-integer) (make-field-info :before-tax-amount-1 51 59 #'parse-integer) (make-field-info :tva-rate-2 59 63 #'parse-integer) (make-field-info :before-tax-amount-2 63 71 #'parse-integer) (make-field-info :tva-rate-3 71 75 #'parse-integer) (make-field-info :before-tax-amount-3 75 83 #'parse-integer) ;; This is an enum (p. 22 of FPL) (make-field-info :return-code 83 84 #'parse-integer) (make-field-info :commandable 84 85 #'identity (lambda (x) (ecase (character x) (#\1 t) (#\0 nil)))) ;; I *think* this will always be either #\I or blank, but not sure (make-field-info :impression-demande 85 86 #'character) ;; 1 = Tout public ;; 2 = Réservé aux enseignants (make-field-info :public 86 88 #'parse-integer (lambda (x) (ecase x (1 :public) (2 :reserved)))) ;; This is also an enum (p.16 FPL) (make-field-info :removal-reason 88 90 #'parse-integer) ;; Reserved 90 94 (make-field-info :publication-date 94 102 #'parse-date) ;; Also an enum (p. 19) (make-field-info :product-type 102 104 #'parse-integer) (make-field-info :end-of-marketing 104 112 #'parse-date) (make-field-info :standard-description 112 142 #'trim-right) (make-field-info :checkout-description 142 162 #'trim-right) ;; Also an enum (p. 18) (make-field-info :présentation-magasin 162 164 #'parse-integer) (make-field-info :thickness 164 168 #'parse-integer (lambda (x) (format nil "~Dmm" x))) (make-field-info :width 168 172 #'parse-integer (lambda (x) (format nil "~Dmm" x))) (make-field-info :height 172 176 #'parse-integer (lambda (x) (format nil "~Dmm" x))) (make-field-info :weight 176 183 #'parse-integer (lambda (x) (format nil "~Dg" x))) (make-field-info :libellé-étendu 183 283 #'trim-right) (make-field-info :publisher 283 298 #'trim-right) (make-field-info :collection 298 313 #'trim-right) ;; per FPL p 5, multiple authors are split with a "/" character (make-field-info :authors 313 333 #'trim-right (lambda (x) (split-sequence #\/ x))) (make-field-info :présentation-éditeur 333 335 #'trim-right) (make-field-info :isbn 335 345 #'identity) (make-field-info :référence-fournisseur 345 357 #'trim-right) (make-field-info :collection-sérielle 357 367 #'trim-right) (make-field-info :théme 367 371 #'parse-integer) (make-field-info :isbn-éditeur 371 379 #'trim-right) ;; Table : ;; 2 = Annule et remplace le produit lié (B remplace A) ;; 4 = Est remplacé par le produit lié (A est remplacé par B) (make-field-info :lien-entre-les-codes 379 380 #'parse-integer) (make-field-info :ean-produit-lié 380 393 #'identity) (make-field-info :peut-être-commandé 393 394 (lambda (x) (ecase (character x) (#\0 nil) (#\1 t)))) (make-field-info :type-lot 394 395 (lambda (x) (ecase (character x) (#\0 nil) (#\1 t)))) ;; yet another enumerated field. (p. 22) (make-field-info :symbolisation 395 396 #'parse-integer) (make-field-info :produit-périssable 396 397 #'parse-integer) (make-field-info :nombre-références 397 401 #'parse-integer)) "A list of all the field-info structures for the dilicom basic fields") (defun parse-line (line) ;; per FEL Plain-text, lines are either 401 or 484 ;; implied is a #\Return at the end-of-the line ;; making 402 or 485 (unless (member (length line) '(402 485)) (error 'parse-error)) (when (> (length line) 402) (warn "DILICOM Checkout fields not supported")) (loop with result = (make-hash-table) for field in *basic-fields* do (with-slots (name start end parser representation) field ;(print name) (terpri) (let ((raw-value (subseq line start end))) (unless (every (lambda (X) (eql x #\Space)) raw-value) (if (null representation) (setf (gethash name result) (funcall parser raw-value)) (let* ((parsed-value (funcall parser raw-value)) (repr-value (funcall representation parsed-value))) (setf (gethash (make-keyword (format nil "~A-REPR" name)) result) repr-value (gethash name result) repr-value (gethash (make-keyword (format nil "~A-RAW" name)) result) parsed-value)))))) finally (return result))) (defun ensure-external-fields (parsed-line) "This ensures certain fields will exist in the output to match the fields in the old dilicomScaper.py " (setf (gethash :publishers parsed-line) (ensure-list (gethash :publisher parsed-line)) (gethash :price-currency parsed-line) #\Euro_Sign (gethash :price-divisor parsed-line) 1000 (gethash :publishers-repr parsed-line) (gethash :publisher parsed-line) (gethash :source-name parsed-line) (copy-seq +source-name+) ;; no img ;; no summary ;; no search-terms ) parsed-line) (defun parse-file (path) (with-open-file (f path) (loop for line = (read-line f nil nil) while line collect (ensure-external-fields (parse-line line)))))
9,719
Common Lisp
.lisp
193
40.393782
342
0.611866
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
a3944fb0aef882641937274c62566fdd6426a613418619eb83bd7d2edf70002c
4,557
[ -1 ]
4,558
base-scraper.lisp
OpenBookStore_openbookstore/src/datasources/base-scraper.lisp
(defpackage bookshops.datasources.base-scraper (:use :cl :cl-ansi-text :parse-float :log4cl) (:import-from :serapeum :dict) (:import-from :access :access) (:export :books) (:documentation "Search for books by ISBN or keywords on a website. Return a list of hash-tables. Don't create Book objects from openbookstore.models here.")) (in-package :bookshops.datasources.base-scraper) ;; For Argentina: ;; ;; - cuspide.com: looks complete enough. Doesn't show the ISBN inline in the search results, but it appears in the book's details URL, we can extract it. ;; - doesn't show the publisher in search results, it appears on the book's page. ;; ;; - https://www.libreriadonquijote.com.ar : no ISBN. ;; ;; - https://mercadolibre.com/ ;; Print hash-tables readably (used for debug logs). (serapeum:toggle-pretty-print-hash-table t) (defclass base-scraper () ((datasource-name :initarg :datasource-name :initform "" :documentation "The human-readable name of this data source.") (url-base :initarg :url-base :initform "" :accessor url-base :type string :documentation "The base URL of the target website, sans trailing /. Example: http://www.librairie-de-paris.fr") (url-search :initarg :url-search :initform "" :accessor url-search :type string :documentation "The URL, with query placeholders, that runs a search on the distant website. Placeholders include: - {QUERY} : most of the times, must be replaced with '+' separated search terms. Example: 'lisp+book' Example: http://www.librairie-de-paris.fr/listeliv.php?MOTS={QUERY}&SUPPORT=&RECHERCHE=simple&TRI=&DISPOCHE=&RAYONS=&LIVREANCIEN=2&CSR=") (%last-results :initform (list) :type list :documentation "For dev purposes. Contains the results of the last search.") ;; Now some internal data, CSS selectors to parse the results. (css-container :initform "#ctl00_ContentPlaceHolder1_cotenedorLibros" :initarg :css-container :documentation "A CSS selector that wraps the books. Must return 1 node (or 0).") (css-elements :initarg :css-elements :initform ".libro" :documentation "A CSS selector that finds all book elements, once we have the node from css-container.") ;; Now find all possible book data: (css-title :initarg :css-title :initform ".md-datos h1" :documentation "Inside each element found by css-card, a CSS selector to find the title.") (css-author :initarg :css-author :initform ".autor a" :documentation "CSS selector to find the author(s) inside each card found by css-card.") (css-price :initarg :css-price :initform ".precio") (css-isbn :initarg :css-isbn :initform ".isbn" :documentation "Important field, it is required.") (css-cover-url :initarg :css-cover-url :initform "figure img[src]" :documentation "CSS selector to find the book's cover URL. Sometimes it is full URL, sometimes it is a relative URL, to concatenate to the url-base.") (css-details-url :initarg :css-details-url :initform "figure a[href]" :documentation "CSS selector to find the book's details page URL. Often, it is a relative result so we have to concatenate url-base to this result.") ;; TODO: editorial, publication-date (css-currency :initarg :css-currency :initform ".precio span" :documentation "Optional. Set the default currency for this scraper with CURRENCY.") (currency-symbol :initarg :currency-symbol :initform "AR$" :documentation "The default currency symbol. Example: AR$ 1.500") )) (defmethod print-object ((obj base-scraper) stream) (print-unreadable-object (obj stream :type t) (with-accessors ((url-base url-base)) obj (format stream "Base scraper for ~a" url-base)))) (defun make-base-scraper (name &key url-base url-search) (make-instance 'base-scraper :datasource-name name :url-search url-search :url-base url-base)) ;;; ;;; Conditions. ;;; (define-condition parse-warning (simple-warning) ((data :initarg :data :initform nil :accessor parse-warning-data :documentation "The element we are trying to parse (ex: the price).") (message :initarg :message :initform "" :accessor parse-warning-message)) (:report (lambda (c stream) (format stream "scraper warning: ~a" (parse-warning-message c))))) (define-condition price-parse-warning (parse-warning) () (:report (lambda (c stream) (declare (ignorable c)) (format stream "scraper warning")))) (defun get-url (url) "Http GET this url. Function mocked in unit tests." (log:info url) (dex:get url)) (function-cache:defcached get-url-with-cache (url) "Http GET this url. Cache results" (log:info url) (dex:get url)) ;; (defun parse (request) ;; "Parse with plump, return a plump node. ;; Function mocked in unit test." ;; (plump:parse request)) (defmethod parse ((scraper base-scraper) request) "Parse with Plump." (declare (ignorable scraper)) (plump:parse request)) (defun select (selector parsed) "Find nodes with CSS selector from a plump-parsed node." (lquery:$ selector parsed)) (lquery:define-lquery-list-function elt0 (vector) (elt vector 0)) (defun node-selector-to-text (selector node &key selector2) "Take a CSS selector (str), a plump node, extract and clean the result." (declare (ignorable selector2)) (let* ((nodes (clss:select selector node)) res txt) (setf nodes (coerce nodes 'list)) (when (not (null nodes)) (setf res (first nodes)) (setf txt (plump:text res)) (str:trim txt)))) (defmacro with-log-error ((name) &body body) `(handler-case (progn ,@body) (error (c) (format *error-output* "could not parse ~a: ~a." ,name c) nil))) (defmethod parse-title (scraper node) (with-log-error (:title) (node-selector-to-text (slot-value scraper 'css-title) node))) (defmethod parse-authors (scraper node) (with-log-error (:authors) ;; slot-value is overriden by lquery, can't use it inside $ (let ((css (slot-value scraper 'css-author))) (str:trim (lquery:$ node css (elt0) (text)))))) (defun ensure-integer (number) "Return this number as an integer (TRUNCATE and discard decimals). If it isn't a number, return 0. Typically, for a price that is parsed as a float, NUMBER should be the price in cents (x 100), and we return it as an integer. - number: float Return: an integer or 0." ;; warn: copied to model-utils.lisp. The scraper module should stay completely independant of ;; the application code. (if (and number (not (equalp number 0)) (numberp number)) (truncate number) (progn ;; log or warning? Both! (log:warn "Could not parse ~s to an integer price." number) (signal (make-condition 'parse-warning :message (format nil "fr scraper: could not transform ~S to an integer. Returning 0." number) :data number)) 0))) (defmethod parse-price (scraper node) "Extract the price. `node': plump node. Return: integer, the price as cents (real price multiplied by 100)." (uiop:not-implemented-error "parse-price: prices must be returned as integers (cents). Take care of that function for each parser. See existing scrapers for reference and how to handle different price representations.")) (defmethod parse-publisher (scraper node) (with-log-error (:publisher) (ignore-errors ;;TODO: (let ((css (slot-value scraper 'css-publisher))) (node-selector-to-text css node))))) (defmethod parse-isbn (scraper node) (str:trim (first (last (str:lines (node-selector-to-text (slot-value scraper 'css-isbn) node)))))) (defmethod parse-publication-date (scraper node) (with-log-error (:publication-date) (ignore-errors ;; ;TODO: (node-selector-to-text (slot-value scraper 'css-publication-date) node)))) (defmethod parse-cover-url (scraper node) (with-log-error (:cover) (let ((css (slot-value scraper 'css-cover-url))) ;; use (elt0) ? (lquery:$ node css (elt0) (attr "src"))))) (defmethod parse-details-url (scraper node) "Extract the url to the book online information. https://www.librairie-de-paris.fr/livre/9782742720682-antigone-henry-bauchau/" (with-log-error (:details-url) (let ((css (slot-value scraper 'css-details-url))) ;; Beware we don't have a double // in the URL. (str:concat (url-base scraper) (lquery:$ node css (attr :href) (elt0)))))) (defun make-book (&key title isbn datasource cover-url authors details-url price publisher date-publication) "Create a hash-table with these slots. Don't rely on the models in the data scrapers. tip: access the fields easily with the access library." (dict :title title :isbn isbn :datasource datasource :cover-url cover-url :authors authors :details-url details-url :price price :publisher publisher :date-publication date-publication)) (defmethod book-info (scraper node) "Takes a plump node and returns a list of book objects with: title, authors, price, publisher, date of publication, etc." (let ((title (parse-title scraper node)) (authors (parse-authors scraper node)) (price (parse-price scraper node)) (publisher (parse-publisher scraper node)) (date-publication (parse-publication-date scraper node)) (isbn (parse-isbn scraper node)) (cover-url (parse-cover-url scraper node)) (details-url (parse-details-url scraper node)) bk) ;; Every field of this dict must be present in search.html ;; for the add-or-create and quick-add-stock forms, where we save ;; the book to our DB. (setf bk (make-book :title title :isbn isbn :datasource (slot-value scraper 'datasource-name) :cover-url cover-url :authors authors :details-url details-url :price price :publisher publisher :date-publication date-publication)) bk)) (defmethod build-url (scraper query &key (encode t)) "Build the search url with the query terms in it. URL-encode the search terms (if `:encode' is true, the default). - query: a str (possibly many words, they will be '+'-separated.). Return the URL (a string)." (let* ((words (str:words query)) (joined (str:join "+" words)) (encoded? (if encode (quri:url-encode joined) joined))) (str:replace-all "{QUERY}" encoded? (url-search scraper)))) (defparameter *devel-mode* nil "Set to T to be in devel mode. What it does: - cache the HTTP requests. See: toggle-dev-mode") (defun toggle-dev-mode (&optional (state nil state-p)) (if state-p (setf *devel-mode* state) (setf *devel-mode* (not *devel-mode*)))) (defparameter *last-parsing-res* nil "for debug pursposes.") (defparameter *last-results* nil "for debug pursposes.") (defparameter *node* nil "a node to inspect, for development purposes.") (defmethod books-container ((scraper base-scraper) root) (clss:select (slot-value scraper 'css-container) root)) (defmethod books-elements ((scraper base-scraper) root) "From this Plump root DOM object, return a vector of DOM elements that contain a book." (check-type root plump-dom:root) (clss:select (slot-value scraper 'css-elements) root)) (defmethod books (scraper query) "From a search query (str), return a list of book objects (with a title, a price, a date-publication, authors,...)." (let* ((url (build-url scraper query)) (get-function (if *devel-mode* #'get-url-with-cache #'get-url)) (req (funcall get-function url)) (parsed (parse scraper req)) ;; one node ;; XXX: clss can be replaced by lQuery. (node (clss:select (slot-value scraper 'css-container) parsed)) ;; direct children: (res (clss:select (slot-value scraper 'css-elements) node))) (setf *last-parsing-res* (coerce res 'list)) (setf *last-results* (map 'list (lambda (it) (book-info scraper it)) res))))
12,972
Common Lisp
.lisp
286
37.685315
168
0.646481
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
2028fb9d0b25056c1b9ee0e2dbfea3407bb863cd31ad12c5cd7d9c819ad2f43b
4,558
[ -1 ]
4,559
datasources.lisp
OpenBookStore_openbookstore/src/datasources/datasources.lisp
(uiop:define-package bookshops.datasources.main (:use :cl :cl-ansi-text :parse-float :log4cl) (:export :search-books) (:documentation "Search for books by ISBN or keywords on the given datasource (French scraper, Argitinian scraper…).")) (in-package :bookshops.datasources.main) (defun search-books (query &key (datasource :fr)) "Dispatch this search query to the appropriate `DATASOURCE'. Available sources: - :fr or any string starting with \"fr\" -> french scraper - :arg or any string -> argentinian scraper - :dilicom -> dilicom connector." (cond ((or (equal :fr datasource) (str:starts-with-p "fr" datasource)) (bookshops.datasources.scraper-fr:books query)) ((or (equal :dilicom datasource) (equal "dilicom" datasource)) (bookshops.datasources.dilicom:search-books query)) ((or (equal :ar datasource) (str:starts-with-p "ar" datasource)) ;; We don't use the same mechanism as the french datasource: ;; get a scraper instance and call the generic BOOKS function. (funcall #'bookshops.datasources.base-scraper:books (bookshops.datasources.scraper-argentina:get-scraper) query)) (t (warn "Unknown books datasource: ~S. Trying with the default one." datasource) (bookshops.datasources.scraper-fr:books query))))
1,354
Common Lisp
.lisp
31
38.258065
123
0.700303
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
5d9e65094498c40a5799425f0b23eb8d7a2d6ae2eadb15374e37fcda673a7ea2
4,559
[ -1 ]
4,560
clil-themes.lisp
OpenBookStore_openbookstore/src/datasources/clil-themes.lisp
(defpackage bookshops.datasources.themes-clil (:use :cl) (:documentation "Mapping of CLIL themes, the book classification. We use it to guess the best shelf for a new book. Generate better mapping files.")) #| parse-themes-file Parses *themes-file*, data from Dilicom. Print the hierarchy of themes on standard output: level 1: 3000 -> SCOLAIRE level 2: 3001 -> SCOLAIRE -> Pré-scolaire et primaire level 3: 3002 -> SCOLAIRE -> Pré-scolaire et primaire -> Pré-scolaire et maternelle level 3: 3003 -> SCOLAIRE -> Pré-scolaire et primaire -> Élémentaire level 2: 3004 -> SCOLAIRE -> Manuels scolaires Secondaire Général level 3: 3005 -> SCOLAIRE -> Manuels scolaires Secondaire Général -> Collège level 3: 3006 -> SCOLAIRE -> Manuels scolaires Secondaire Général -> Lycée général … Generate two files: - theme-names.csv contains the mapping code -> name - theme-hierarchies.csv contains the mapping code -> level 1 code -> … -> level 4 code (so the first code repeats itself once) 3000;3000;;; 3001;3000;3001;; 3002;3000;3001;3002; |# (in-package :bookshops.datasources.themes-clil) (defparameter *themes-file* "themes-clil.csv" "File: from Dilicom's 319-TABLE DE CLASSIFICATION DES THEMES CLIL.xlsx, transformed to CSV, edited to remove the first comma of each line, that shouldn't be there.") (defun parse-themes-file (&key (file *themes-file*) (start 0) end (write-to-files t)) "For each theme number, associate the names of its level 1, 2, 3 and 4. Example: 3744 -> 3722 Jeunesse / 3744 Fiction Jeunesse / <blank> 3746 -> 3722 Jeunesse / 3744 Fiction Jeunesse / 3746 Histoire" (let* ((lines (uiop:read-file-lines file)) current-l1 current-l1-name current-l2 current-l2-name current-l3 current-l3-name current-l4 current-l4-name) (with-open-file (theme-names "theme-names.csv" :direction :output :if-exists :supersede) ;; Hierarchies: theme -> parents ;; theme number ; level 1 ; level 2 ; level 2 ; level 4 (with-open-file (theme-hierarchies "theme-hierarchies.csv" :direction :output :if-exists :supersede) (with-open-file (theme-hierarchies-names "theme-hierarchies-names.csv" :direction :output :if-exists :supersede) (loop for line in (subseq lines (or start 0) (or end (length lines))) for columns = (str:split ";" line) ;; Only one theme number is given on each line. for level-1 = (elt columns 0) for level-2 = (elt columns 1) for level-3 = (elt columns 2) for level-4 = (elt columns 3) for name = (elt columns 4) when (not (str:blankp level-1)) do (progn (setf current-l1 level-1) (setf current-l1-name name) (format t "~%~a: ~a~&" level-1 name) ;; Save to files. (format theme-names "~&~a;~a" level-1 name) ;; Try a yaml representation (when write-to-files (format theme-hierarchies-names "~&~a;~a" level-1 name) (format theme-names "~&-~a;~a" level-1 name) (format theme-hierarchies "~&~a;~a;;;" level-1 level-1))) when (not (str:blankp level-2)) do (progn (setf current-l2 level-2) (setf current-l2-name name) (format t "~&~a: ~a / ~a~&" level-2 current-l1-name name) (when write-to-files (format theme-hierarchies-names "~&~a: ~a / ~a~&" level-2 current-l1-name name) (format theme-names "~&~a;~a" level-2 name) (format theme-hierarchies "~&~a;~a;~a;;" level-2 current-l1 level-2))) when (not (str:blankp level-3)) do (progn (setf current-l3 level-3) (setf current-l3-name name) (format t "~&~a: ~a / ~a / ~a~&" level-3 current-l1-name current-l2-name name) (when write-to-files (format theme-hierarchies-names "~&~a: ~a / ~a / ~a~&" level-3 current-l1-name current-l2-name name) (format theme-names "~&~a;~a" level-3 name) (format theme-hierarchies "~&~a;~a;~a;~a;" level-3 current-l1 current-l2 level-3))) when (not (str:blankp level-4)) do (progn (setf current-l4 level-4) (setf current-l4-name name) (format t "~&~a: ~a / ~a / ~a / ~a~&" level-4 current-l1-name current-l2-name current-l3-name name) (when write-to-files (format theme-names "~&~a;~a" level-4 name) (format theme-hierarchies "~&~a;~a;~a;~a;~a" level-4 current-l1 current-l2 current-l3 level-4)))))))))
5,759
Common Lisp
.lisp
111
35.009009
167
0.504458
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
e1121fbfda65d63ec720ff0ce10122991c96564150a82b5af2f622e0372cc61b
4,560
[ -1 ]
4,561
gui.lisp
OpenBookStore_openbookstore/src/gui/gui.lisp
(defpackage :bookshops.gui (:use :cl :nodgui) (:import-from :openbookstore :books :authors :publisher :price) (:import-from :openbookstore.models :find-book :last-books) (:export :main)) (in-package :bookshops.gui) (defparameter +results-columns-width+ nil "Width of the treeview columns. List of integers.") (setf +results-columns-width+ '(300 200 200 80)) (defparameter *search-function* #'books "Function that accepts one argument, the text of the search input. Results are displayed in the tree. For now clicking on the side menu doesn't change widgets but only this function.") (defun side-menu () "Side menu: buttons to switch to Stock, Search,…" (let* ((frame (make-instance 'frame)) (btn-stock (make-instance 'button :master frame :text "Stock" :command (lambda () ;; Searching our stock should have more inputs ;; (author, sorting,...) (setf *search-function* #'find-book)))) (btn-search (make-instance 'button :master frame :text "Search" :command (lambda () (setf *search-function* #'books)))) (row 0)) (grid btn-stock row 0 :sticky "w") (grid btn-search (incf row) 0 :sticky "w") frame)) (defun search-tree () "Search input and display search results in a scrollable tree." (let* ((frame (make-instance 'frame)) (searchbox (grid (make-instance 'entry :width 50 :master frame) 0 0 :sticky "we" :padx 5 :pady 5)) (tree (make-instance 'scrolled-treeview :master frame ;; These are the second and third columns. :columns (list "authors" "publisher" "price") :columns-width +results-columns-width+)) (button (make-instance 'button :master frame :text "OK" :command (lambda () (format t "the treeview selection is: ~a~&" (treeview-get-selection tree)) (format t "text is: ~a~&" (text searchbox)) ;; There is an error with "latin capital letters" ;; when searching "tears of steel". ;; => escape tildes in title. Fixed in nodgui. (insert-results tree (funcall *search-function* (text searchbox))))))) (insert-results tree (last-books)) ;; Name the first column: (treeview-heading tree +treeview-first-column-id+ :text "title") (print :RST) (grid searchbox 0 0 :sticky "we") (grid button 0 1 ;; stick to the right (east). :sticky "e") (grid tree 1 0 ;; so the button doesn't have a column by itself. :columnspan 2 ;; sticky by all sides, for resizing to do something. :sticky "nsew") (format t "returning frame ~a~&" frame) frame)) (defun insert-results (tree results) "Insert torrents last results into that treeview." ;; Clear content. ;; this needs nodgui newer than feb, 24th 2019 ;; with commit c9ae0ec389. (treeview-delete-all tree) (loop for result in results do (treeview-insert-item tree ;; title is only a nodgui generic method. :text (bookshops:title result) ;; xxx: numbers stick to the left instead of the right. ;; note: repetition in the ordering and naming of columns. :column-values (list (authors result) (publisher result) (price result))))) (defun main () "Connect to the database and start the main GUI." (openbookstore.models:connect) (with-nodgui () (wm-title *tk* "OpenBookStore") (minsize *tk* 500 170) ;; For resizing to do something: weight > 0 (grid-columnconfigure *tk* 0 :weight 1) (let ((row 0) (col 0)) (declare (ignorable row)) (grid (side-menu) 0 col :sticky "nsew") (grid (search-tree) 0 (incf col) :sticky "nsew"))))
5,140
Common Lisp
.lisp
111
28.36036
186
0.466919
OpenBookStore/openbookstore
34
5
0
AGPL-3.0
9/19/2024, 11:26:19 AM (Europe/Amsterdam)
00281bd875866559864c9d99974b92293334441de09a4938db7b70ffd4d0de08
4,561
[ -1 ]