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
sequencelengths
1
47
652
control-boxes.lisp
cac-t-u-s_om-sharp/src/visual-language/boxes/control-boxes.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;=============================================================================== ; CONTROL BOXES ; INFLUENCE THE EVALUATION ORDER ;=============================================================================== (in-package :om) ; The functions IF, AND, OR in this file are special function that are presented ; in the packages as special-boxes. ;;;------------------------ ;;; IF ;;;------------------------ (defclass OMIFBoxCall (OMFunBoxcall) ()) (defmethod special-box-p ((name (eql 'if))) t) (defmethod get-box-class ((self (eql 'if))) 'OMIFBoxCall) (defmethod get-icon-id ((self OMIFBoxCall)) :cond) (defmethod box-type ((self OMIFBoxCall)) :special) (defmethod omNG-make-special-box ((reference (eql 'if)) pos &optional (init-args nil args-supplied-p)) (omNG-make-new-boxcall reference pos init-args)) (defmethod create-box-inputs ((self OMIFBoxCall)) (call-next-method)) (defmethod boxcall-value ((self OMIFBoxCall)) (let ((test (omNG-box-value (first (inputs self))))) (if test (omNG-box-value (second (inputs self))) (and (third (inputs self)) (omNG-box-value (third (inputs self))))))) (defmethod gen-code-for-call ((self OMIFBoxCall) &optional args) (if args `(if ,(car args) ,(second args) ,(third args)) `(if ,(gen-code (first (inputs self))) ,(gen-code (second (inputs self))) ,(gen-code (third (inputs self)))))) (setf (documentation 'if 'function) "Conditional statement: Syntax: (IF <predicate> <then> &optional <else>). - If <predicate> evaluates to non-null, eval <then> input and return the result. - If not, eval and return <else> input, or return NIL. ") ;;; compatibility (defmethod function-changed-name ((reference (eql 'omif))) 'if) ;;;------------------------ ;;; LOGICAL CONTROLS (AND/OR) ;;;------------------------ (defclass OMAndBoxCall (OMFunBoxcall) ()) (defmethod get-box-class ((self (eql 'and))) 'OMAndBoxCall) (defclass OMOrBoxCall (OMFunBoxcall) ()) (defmethod get-box-class ((self (eql 'or))) 'OMOrBoxCall) (defmethod special-box-p ((name (eql 'and))) t) (defmethod special-box-p ((name (eql 'or))) t) (defmethod get-icon-id ((self OMAndBoxCall)) :and) (defmethod get-icon-id ((self OMOrBoxCall)) :or) (defmethod box-type ((self OMAndBoxCall)) :special) (defmethod box-type ((self OMOrBoxCall)) :special) (defmethod omNG-make-special-box ((reference (eql 'and)) pos &optional init-args) (omNG-make-new-boxcall reference pos init-args)) (defmethod omNG-make-special-box ((reference (eql 'or)) pos &optional init-args) (omNG-make-new-boxcall reference pos init-args)) (defmethod boxcall-value ((self OMAndBoxCall)) (let ((rep t)) (loop while rep for inp in (inputs self) do (setf rep (omNG-box-value inp))) rep)) (defmethod boxcall-value ((self OMorBoxCall)) (let ((rep nil)) (loop while (not rep) for inp in (inputs self) do (setf rep (omNG-box-value inp))) rep)) (defmethod gen-code-for-call ((self OMAndBoxCall) &optional args) (let ((arguments (or args (gen-code-inputs self)))) `(and ,.arguments))) (defmethod gen-code-for-call ((self OMOrBoxCall) &optional args) (let ((arguments (or args (gen-code-inputs self)))) `(or ,.arguments))) (setf (documentation 'and 'function) "Evaluate inputs in order, left to right. - If any eval to NIL, quit and return NIL. - Else, return the value(s) of the last input.") (setf (documentation 'or 'function) "Evaluate inputs in order, left to right. - If any eval to non-NIL, quit and return that (single) value. - If the last input is reached, return whatever value(s) it returns.") ;;; compatibility (defmethod function-changed-name ((reference (eql 'omand))) 'and) (defmethod function-changed-name ((reference (eql 'omor))) 'or) (defmethod function-changed-name ((reference (eql 'conditional))) 'or)
4,595
Common Lisp
.lisp
97
44.56701
102
0.61892
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1cfe53509609d4c3b8f5de6b34b08c370666a81c37a4b12da3f578d124313618
652
[ -1 ]
653
system-boxes.lisp
cac-t-u-s_om-sharp/src/visual-language/boxes/system-boxes.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;=============================================================================== ;SYSTEM BOXES ;=============================================================================== (in-package :om) (add-preference :general :print-system-output "Print System Outputs" :bool t "Redirect command-line system outputs to the Listener") (defmethod* om-shell ((command-line string) &key (open-shell-window nil)) :icon 'shell :indoc '("a system command line") :initvals '("") :doc "Sends <command-line> (a string) to the system. If <open-shell-window> the command will be executed in a special shell window. Otherwise the output is printed in the Listener window." (if open-shell-window (progn (om-lisp::om-open-shell) (om-lisp::om-send-command-to-shell command-line)) (om-cmd-line command-line))) (defun om-cmd-line (str) (oa::om-command-line str (om::get-pref-value :general :print-system-output)))
1,672
Common Lisp
.lisp
32
49.875
135
0.526928
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
59d2c41e64f273a02a7bbec8deb35a2e806d88b66b497d426f7af194179dc330
653
[ -1 ]
654
send-receive-route.lisp
cac-t-u-s_om-sharp/src/visual-language/boxes/send-receive-route.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;========================================================================== ;;; BOXES WITH SPECIFIC BEHAVIOURS FOR REACTIVE PROCESSES ;;;========================================================================== (in-package :om) ;;;===================================== ;;; SEND/RECEIVE INTERNAL ;;; WORKS WITH REACTIVE PROGRAMS ;;;===================================== (defmethod* send ((self t) &optional (target :om)) :initvals '(nil :om) :indoc '("something to send" "a target label") :doc "Sends <self> out for being received by RECEIVE boxes initialized with the <target> label." (let ((boxes (find-receive-boxes target))) (mapcar #'(lambda (b) (setf (value b) (list self)) (self-notify b nil)) boxes) (length boxes))) (defmethod* receive (targetname) :initvals '(:om) :indoc '("a target label") :doc "Receives data sent through SEND with the <targetname> label." t) ;;; for compat when loading old patches (defmethod function-changed-name ((reference (eql 'om-receive))) 'receive) (defmethod function-changed-name ((reference (eql 'om-send))) 'send) (defclass ReactiveReceiveBox (OMGFBoxCall) ()) (defmethod boxclass-from-function-name ((self (eql 'receive))) 'ReactiveReceiveBox) (defmethod boxcall-value ((self ReactiveReceiveBox)) (let ((inval (omng-box-value (car (inputs self))))) (unless (equal inval (value (car (inputs self)))) (print (format nil "RECEIVE ID SET TO: ~A" inval)) (setf (value (car (inputs self))) inval))) (car (current-box-value self))) (defmethod patch-editors ((self t)) nil) (defmethod patch-editors ((self OMEditorWindow)) (when (subtypep (type-of (editor self)) 'patch-editor) (list (editor self)))) (defun find-boxes (type) (loop for win in (om-get-all-windows 'OMEditorWindow) append (loop for ed in (patch-editors win) append (loop for b in (boxes (object ed)) when (equal type (reference b)) collect b)))) (defun find-receive-boxes (target) (let ((boxes (find-boxes 'receive))) (remove-if-not #'(lambda (b) (equal (omng-box-value (nth 0 (inputs b))) target)) boxes))) ;;;===================================== ;;; ROUTE ;;; WORKS WITH REACTIVE PROGRAMS ;;;===================================== ;;; todo: check for undo/redo (defun test-match (data test) (if (functionp test) (funcall test data) (equal test data))) (defmethod* route (input &rest test) :indoc '("input data" "test-value or function") :doc "ROUTE sets its various outputs' values to <input> when <input> satisfies the test of the corresponding inputs, or to NIL otherwise. The <test> can be a simple value (equality test) or a function (lambda) of 1 argument. If the box output connections are reactive, reactive notifications will be send for non-NIL outputs. The inputs left with :default will output value only if none other tests succeeded. The first output always outputs <input>. " (let* ((match nil) (outputs (loop for route-item in test collect (if (equal route-item :default) :default (let ((test-result (test-match input route-item))) (when test-result (setf match t) input)))))) ;;; fill in the ":default" items (setf outputs (loop for out in outputs collect (if (equal out :default) (if match nil input) out))) (values-list (copy-list (cons input outputs))) )) (defclass ReactiveRouteBox (RouteBox) ((routed-o :initform nil :accessor routed-o))) (defmethod boxclass-from-function-name ((self (eql 'route))) 'ReactiveRouteBox) (defmethod more-optional-input ((self ReactiveRouteBox) &key name (value nil val-supplied-p) doc reactive) (declare (ignore name doc)) (unless nil ; (inputs self) (add-optional-input self :name "test" :value (if val-supplied-p value :default) :doc "test-value or function" :reactive reactive) t)) ;;; (does nothing if there is no memory) (defmethod boxcall-value ((self ReactiveRouteBox)) (let ((new-values (multiple-value-list (call-next-method)))) (setf (routed-o self) (loop for v in new-values for i = 0 then (+ i 1) when v collect i)) (values-list new-values))) ;;; NOTIFY ONLY THE ROUTED OUTPUT ;;; (can just check in values if there is no memory) (defmethod OMR-Notify ((self ReactiveRouteBox) &optional input-name) (unless (push-tag self) (setf (push-tag self) t) (omNG-box-value self) (setf (gen-lock self) t) (let ((listeners (loop for o in (outputs self) for n = 0 then (1+ n) when (and (reactive o) (find n (routed-o self) :test '=)) append (loop for c in (connections o) when (reactive (to c)) collect (box (to c)))))) (mapcar 'omr-notify listeners)) (setf (gen-lock self) nil) ))
5,983
Common Lisp
.lisp
131
38.534351
139
0.564866
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
7c6801732d9fe69e280679d817f19c13e387e3484517299b0bc1dfeb129fcbe2
654
[ -1 ]
655
mem-collect.lisp
cac-t-u-s_om-sharp/src/visual-language/boxes/mem-collect.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;================================== ;;; BOXES WITH MEMORY ;;; - MEM ;;; - COLLECT ;;; - TIME-COLLECT ;;; - ACCUM ;;;================================== (in-package :om) (defclass OMPatchComponentWithMemory (OMPatchComponent) ((mem-var :initform (gentemp "MEM-") :accessor mem-var))) (defmethod get-patch-component-box-def-color ((self OMPatchComponentWithMemory)) (om-make-color 0.82 0.7 0.7)) ;;;------------------------------------------------------------------------------------------ ;;; DELAY: 'mem' ;;; returns previous evaluation(s) on the right output ;;; the 'size' of memory can be expressed in number of cells (int) or in seconds (float) ;;; !! MEM is not a global variable: it has a limited scope inside its containing patch ;;;------------------------------------------------------------------------------------------ (defmethod special-box-p ((name (eql 'mem))) t) (defclass OMMemory (OMPatchComponentWithMemory) ((size :initform 1 :accessor size) (timer-var :initform nil :accessor timer-var) (timetag :initform nil :accessor timetag)) (:documentation "Memory: Return the input on first output, and the result of N previous evaluations on a second output.")) (defclass OMMemoryBox (OMPatchComponentBox) ()) (defmethod initialize-instance :after ((self OMMemory) &rest initargs) (setf (timer-var self) (intern (string+ (symbol-name (mem-var self)) "-TIMER"))) (eval `(defvar ,(timer-var self) nil))) (defmethod get-box-class ((self OMMemory)) 'OMMemoryBox) (defmethod box-symbol ((self OMMemory)) 'mem) (defmethod get-icon-id ((self OMMemoryBox)) :mem) (defmethod object-name-in-inspector ((self OMMemoryBox)) "MEMORY/DELAY box") (defmethod special-item-reference-class ((item (eql 'mem))) 'OMMemory) (defmethod box-draw ((self OMMemoryBox) frame) (when (integerp (size (reference self))) (let ((fill-ratio (/ (length (cadr (value self))) (max 1 (size (reference self)))))) (om-draw-rect (- (w frame) 8) (- (h frame) 5) 6 (- (* (- (h frame) 10) fill-ratio)) :fill t) )) ;; (om-draw-string 10 20 (format nil "~A" (value self))) ) (defmethod omNG-make-special-box ((reference (eql 'mem)) pos &optional init-args) (let* ((name (car (list! init-args))) (memory (make-instance 'OMMemory :name (if name (string name) "mem")))) (omNG-make-new-boxcall memory pos))) (defmethod create-box-inputs ((self OMMemoryBox)) (list (make-instance 'box-input :box self :value NIL :name "data to record in memory") (make-instance 'box-input :box self :value NIL :name "size of memory"))) (defmethod create-box-outputs ((self OMMemoryBox)) (list (make-instance 'box-output :box self :value NIL :name "current value") (make-instance 'box-output :box self :value NIL :name "previous value(s)"))) ;;; ALWAYS IN "EV-ONCE" MODE (defmethod omNG-box-value ((self OMMemoryBox) &optional (numout 0)) (unless (equal (ev-once-flag self) (get-ev-once-flag *ev-once-context*)) (let ((inval (omng-box-value (car (inputs self)))) (size (omng-box-value (cadr (inputs self))))) (setf (ev-once-flag self) (get-ev-once-flag *ev-once-context*)) (setf (size (reference self)) size) ;;; this is just for display (setf (value self) (cond ((integerp size) (let ((new-memory (if (consp (value self)) ;; already something in value (cons (car (value self)) (list! (cadr (value self)))) nil))) (list inval ;;; first-n values of memory (if (< (length new-memory) size) new-memory (subseq new-memory 0 size))))) ((floatp size) (list inval ;;; values received since last time-window started (if (or (null (timetag (reference self))) ;;; fresh memory (> (om-get-internal-time) (+ (* size 1000) (timetag (reference self))))) ;;; time out (progn (setf (timetag (reference self)) (om-get-internal-time)) (list inval)) (cons inval (list! (cadr (value self))))) )) (t (list inval (car (value self)))))) )) (return-value self numout)) #| (defmethod gen-code ((self OMMemoryBox) &optional (numout 0)) (let* ((global-var (mem-var (reference self))) (global-timer (timer-var (reference self))) (local-name (intern (string+ (symbol-name global-var) "-LOCAL"))) (first-call (not (check-let-statement local-name :global)))) (when first-call (let ((new-val (gen-code (car (inputs self)))) (mem-size (gen-code (cadr (inputs self))))) (push-let-statement `(,local-name (setf ,global-var ,(cond ((integerp mem-size) `(list ,new-val (first-n (cons (car ,global-var) (list! (cadr ,global-var))) ,mem-size))) ((floatp mem-size) `(list ,new-val ;;; values received since last time-window started (if (or (null ,global-timer) ;;; fresh memory (> (om-get-internal-time) (+ ,(* mem-size 1000) ,global-timer))) ;;; time out (progn (setf ,global-timer (om-get-internal-time)) (list ,new-val)) (cons ,new-val (list! (cadr ,global-var)))) )) (t `(list ,new-val (car ,global-var)))))) :global) )) `(nth ,numout ,local-name) )) |# (defmethod gen-code ((self OMMemoryBox) &optional (numout 0)) (let* ((global-var (mem-var (reference self))) (global-timer (timer-var (reference self))) (local-name (intern (string+ (symbol-name global-var) "-LOCAL"))) (first-call (not (check-let-statement local-name :global)))) (if first-call ;;; mem is always in a sort of ev-once mode (let ((mem-size (gen-code (cadr (inputs self)))) (new-val (gen-code (car (inputs self))))) (push-let-statement `(,local-name nil) :global) `(PROGN (setf ,local-name ,(cond ((integerp mem-size) `(list ,new-val (first-n (cons (car ,local-name) (list! (cadr ,local-name))) ,mem-size))) ((floatp mem-size) `(list ,new-val ;;; values received since last time-window started (if (or (null ,global-timer) ;;; fresh memory (> (om-get-internal-time) (+ ,(* mem-size 1000) ,global-timer))) ;;; time out (progn (setf ,global-timer (om-get-internal-time)) (list ,new-val)) (cons ,new-val (list! (cadr ,local-name)))) )) (t `(list ,new-val (car ,local-name))))) (nth ,numout ,local-name)) ) `(nth ,numout ,local-name) ))) ;;;------------------------------------------------------------------------------------------ ;;; COLLECT ;;;------------------------------------------------------------------------------------------ (defmethod special-box-p ((name (eql 'collect))) t) (defmethod special-item-reference-class ((item (eql 'collect))) 'OMCollect) (defclass OMCollect (OMPatchComponentWithMemory) () (:documentation "Collect data in an local memory. Inputs: - Collected value - When t: trigger reactive notification through outputs. - Initial value. Outputs: - Collect from input 1 and return this value - Return current state of memory - Initialize memory with input 3.")) (defclass OMCollectBox (OMPatchComponentBox) ()) (defmethod get-box-class ((self OMCollect)) 'OMCollectBox) (defmethod box-symbol ((self OMCollect)) 'collect) (defmethod get-icon-id ((self OMCollectBox)) :mem) (defmethod object-name-in-inspector ((self OMCollectBox)) "COLLECTOR box") (defmethod omNG-make-special-box ((reference (eql 'collect)) pos &optional init-args) (let ((name (car (list! init-args)))) (omNG-make-new-boxcall (make-instance 'OMCollect :name (if name (string name) "collect")) pos))) (defmethod create-box-inputs ((self OMCollectBox)) (list (make-instance 'box-input :box self :value NIL :name "data-in" :doc-string "(collected in memory)") (make-instance 'box-input :box self :value T :name "push" :doc-string "propagates reactive notification to the data-out outlet") (make-instance 'box-input :box self :value NIL :name "init" :doc-string "reinitializes memory"))) (defmethod create-box-outputs ((self OMCollectBox)) (list (make-instance 'box-output :box self :value NIL :name "collect" :doc-string "collects and outputs data-in") (make-instance 'box-output :box self :value NIL :name "data-out" :doc-string "get collected data") (make-instance 'box-output :box self :value NIL :name "init" :doc-string "reinitializes memory"))) ;;; COLLECT DOESN'T RESPOND TO EV-ONCE AT ALL: CAN BE CALLED SEVERAL TIMES (defmethod omNG-box-value ((self OMCollectBox) &optional (numout 0)) (unless nil ;;; (equal (ev-once-flag self) (get-ev-once-flag *ev-once-context*)) (unless (value self) (setf (value self) (list nil))) (case numout ;;; collect (0 (let ((inval (omng-box-value (nth 0 (inputs self))))) (push inval (car (value self))))) ;;; output ; does nothing to the memory (1 NIL) ;;; init with the value in (2 (let ((initval (omng-box-value (nth 2 (inputs self))))) (setf (car (value self)) (if (equal initval t) NIL (list! (om-copy initval)))))) )) (return-value self numout)) (defmethod return-value ((self OMCollectBox) &optional (numout 0)) (case numout ;;; last pushed (0 (caar (value self))) ;;; output ; does nothing to the memory (1 (reverse (car (value self)))) ;;; init (2 nil) )) ;;; called in reactive mode (defmethod current-box-value ((self OMCollectBox) &optional (numout nil)) (if numout (return-value self numout) (value self))) ;;; REACTIVE BEHAVIOUR ;;; NOTIFY ONLY IF PUSH COMES IN ;;; stops reactive notification, ;;; performs evaluations if needed ;;; continue or not... (defmethod OMR-Notify ((self OMCollectBox) &optional input-name) (unless nil ; (push-tag self) ;; allow several push at different inputs (setf (push-tag self) t) (cond ((string-equal input-name "data-in") (omNG-box-value self 0)) ((string-equal input-name "init") (omNG-box-value self 2)) ((string-equal input-name "push") (let ((listeners (get-listeners self))) (when listeners (setf (gen-lock self) t) (loop for listener in listeners do (omr-notify (car listener) (cadr listener))) (setf (gen-lock self) nil)))) ))) ;;; COMPILED FORM (defmethod gen-code ((self OMCollectBox) &optional (numout 0)) ;(print (list (mem-var (reference self)) "gen-code collect - stack = " *let-list-stack*)) (let* ((global-var (mem-var (reference self))) (local-name (intern (string+ (symbol-name global-var) "-LOCAL"))) (first-call (not (check-let-statement local-name :global)))) (when first-call (let ((init-val (gen-code (nth 2 (inputs self))))) (push-let-statement `(,local-name ,(if (or (null init-val) (equal init-val t)) nil `(list ,init-val))) :global))) (case numout ;;; collect (0 `(let ((collect-val ,(gen-code (nth 0 (inputs self))))) (pushr collect-val ,local-name) collect-val)) ;;; output (1 local-name) ;;; init with the value in (2 `(let ((init-val ,(gen-code (nth 2 (inputs self))))) (setf ,local-name (if (equal init-val t) nil init-val)) init-val)) ))) ;;;------------------------------------------------------------------------------------------ ;;; TIMED-COLLECT ;;; just like a collect but uses a delay to group data in a same chunk ;;; also return times for the different chuncks ;;;------------------------------------------------------------------------------------------ (defmethod special-box-p ((name (eql 'tcollect))) t) (defmethod special-item-reference-class ((item (eql 'tcollect))) 'OMTimedCollect) (defclass OMTimedCollect (OMCollect) ((timer-var :initform nil :accessor timer-var) (last-tt :initform nil :accessor last-tt) (first-tt :initform nil :accessor first-tt)) (:documentation "Collect data like COLLECT, segmenting data it into chuncks using an internal timer (<delay>).")) (defclass OMTimedCollectBox (OMCollectBox) ()) (defmethod initialize-instance :after ((self OMTimedCollect) &rest initargs) (setf (timer-var self) (intern (string+ (symbol-name (mem-var self)) "-TIMER"))) (eval `(defvar ,(timer-var self) nil))) (defmethod get-box-class ((self OMTimedCollect)) 'OMTimedCollectBox) (defmethod box-symbol ((self OMTimedCollect)) 'tcollect) (defmethod get-icon-id ((self OMTimedCollectBox)) :mem) (defmethod object-name-in-inspector ((self OMTimedCollectBox)) "TIMED COLLECTOR box") (defmethod omNG-make-special-box ((reference (eql 'tcollect)) pos &optional init-args) (let ((name (car (list! init-args)))) (omNG-make-new-boxcall (make-instance 'OMTimedCollect :name (if name (string name) "tcollect")) pos))) (defmethod create-box-inputs ((self OMTimedCollectBox)) (append (call-next-method) (list (make-instance 'box-input :box self :value 0 :name "delay" :doc-string "delay for collect in a same chunck (ms)")))) (defmethod create-box-outputs ((self OMTimedCollectBox)) (append (call-next-method) (list (make-instance 'box-output :box self :value NIL :name "time-list" :doc-string "get time-list of collection")) )) ;;; COLLECT DOESN'T RESPOND TO EV-ONCE AT ALL: CAN BE CALLED SEVERAL TIMES (defmethod omNG-box-value ((self OMTimedCollectBox) &optional (numout 0)) (unless nil ;;; (equal (ev-once-flag self) (get-ev-once-flag *ev-once-context*)) (cond ((null (value self)) (setf (value self) (list nil nil))) ((= 1 (length (value self))) (setf (value self) (list (car (value self)) nil)))) (case numout ;;; collect (0 (let ((inval (omng-box-value (nth 0 (inputs self)))) (delta (omng-box-value (nth 3 (inputs self)))) (curr-t (om-get-internal-time))) (unless (first-tt (reference self)) (setf (first-tt (reference self)) curr-t)) (if (or (null (last-tt (reference self))) ;;; fresh memory (> curr-t (+ delta (last-tt (reference self))))) ;;; time out (progn ;;; new chunk (setf (last-tt (reference self)) curr-t) (push (list inval) (car (value self))) (push (- curr-t (first-tt (reference self))) (cadr (value self)))) ;;; push in current chunk (push inval (car (car (value self))))) )) ;;; output - does nothing to the memory (1 NIL) ;;; time-values - does nothing to the memory (3 NIL) ;;; init with the value in (2 (let ((initval (omng-box-value (nth 2 (inputs self))))) (if (equal initval t) ;;; reset (setf (car (value self)) NIL (cadr (value self)) NIL (first-tt (reference self)) NIL (last-tt (reference self)) NIL) ;;; reset/init (let ((curr-t (om-get-internal-time))) (setf (car (value self)) (list! (om-copy initval)) (cadr (value self)) (list 0) (first-tt (reference self)) curr-t (last-tt (reference self)) curr-t) )))) )) (return-value self numout)) (defmethod return-value ((self OMTimedCollectBox) &optional (numout 0)) (case numout ;;; last pushed (0 (caar (value self))) ;;; output ; does nothing to the memory (1 (reverse (car (value self)))) ;;; init (2 nil) ;;; time values (3 (reverse (cadr (value self)))) )) ;; REACTIVE BEHAVIOUR ;; calls the method from OMCollectBox ; (defmethod OMR-Notify ((self OMCollectBox) &optional input-name) (call-next-method)) ;;; COMPILED FORM (defmethod gen-code ((self OMTimedCollectBox) &optional (numout 0)) (let* ((global-var (mem-var (reference self))) (global-timer (timer-var (reference self))) (local-name (intern (string+ (symbol-name global-var) "-LOCAL"))) (first-call (not (check-let-statement local-name :global)))) (when first-call (let ((init-val (gen-code (nth 2 (inputs self))))) (push-let-statement `(,local-name ,(if (or (null init-val) (equal init-val t)) `(list nil nil) `(list (list ,init-val) (list 0)))) :global))) (case numout ;;; collect (0 `(let ((collect-val ,(gen-code (nth 0 (inputs self)))) (delta ,(gen-code (nth 3 (inputs self)))) (curr-t (om-get-internal-time))) (if (print (or (null ,global-timer) ;;; fresh memory (> curr-t (+ (cadr ,global-timer) delta)))) ;;; time out (progn (when (null ,global-timer) (setf ,global-timer (list curr-t nil))) (setf (cadr ,global-timer) curr-t) (push (list collect-val) (car ,local-name)) (push (- curr-t (car ,global-timer)) (cadr ,local-name))) ;;; else: push in current chunk (push collect-val (car (car ,local-name))) ) collect-val)) ;;; output (1 `(reverse (car ,local-name))) ;;; init with the value in (2 `(let ((init-val ,(gen-code (nth 2 (inputs self))))) (setf ,local-name (if (equal init-val t) (list nil nil) `(list (list ,init-val) (list 0)))) (setf ,global-timer nil) init-val)) ;; times (3 `(reverse (cadr ,local-name))) ))) ;;;------------------------------------------------------------------------------------------ ;;; ACCUM ;;; MORE ADVANCED COLLECTION... ;;;------------------------------------------------------------------------------------------ (defmethod special-box-p ((name (eql 'accum))) t) (defmethod special-item-reference-class ((item (eql 'accum))) 'OMAccum) (defclass OMAccum (OMCollect) () (:documentation "A collector with free accumulation strategy (= how to combine new collected values with current state of the memory). Inputs: - Collected value - Accum function - Initial state. Outputs: - Collect from input 1 and return this value - Return current state of memory - Initialize memory with input 3. The default value for the accumulation function substitutes the current memory with the incoming value.")) (defclass OMAccumBox (OMCollectBox) ()) (defmethod get-box-class ((self OMAccum)) 'OMAccumBox) (defmethod box-symbol ((self OMAccum)) 'accum) (defmethod object-name-in-inspector ((self OMAccumBox)) "ACCUMULATOR box") (defmethod omNG-make-special-box ((reference (eql 'accum)) pos &optional init-args) (let ((name (car (list! init-args)))) (omNG-make-new-boxcall (make-instance 'OMAccum :name (if name (string name) "accum")) pos))) ;;; a default accumulation function (defun substitute-value (old new) (declare (ignore old)) new) (defmethod create-box-inputs ((self OMAccumBox)) (list (make-instance 'box-input :box self :value NIL :name "data-in" :doc-string "(acumulated in memory)") (make-instance 'box-input :box self :value 'substitute-value :name "accum-function" :doc-string "accumulation function (a function of 2 arguments)") (make-instance 'box-input :box self :value NIL :name "init" :doc-string "intializes memory with this value"))) (defmethod omNG-box-value ((self OMAccumBox) &optional (numout 0)) (unless nil ;;; (equal (ev-once-flag self) (get-ev-once-flag *ev-once-context*)) (unless (value self) (setf (value self) (list (omng-box-value (nth 2 (inputs self)))))) (case numout ;;; ACCUM ;;; this is the only difference with collect (0 (let ((inval (omng-box-value (nth 0 (inputs self)))) (accum-fun (or (omng-box-value (nth 1 (inputs self))) #'substitute-value))) (setf (car (value self)) (funcall accum-fun (car (value self)) inval)) )) ;;; output ; does nothing to the memory (1 NIL) ;;; init with the value in (2 (let ((initval (omng-box-value (nth 2 (inputs self))))) (setf (car (value self)) (if (equal initval t) NIL (om-copy initval))))) )) (return-value self numout)) (defmethod return-value ((self OMAccumBox) &optional (numout 0)) (case numout ;;; last pushed (0 (car (value self))) ;;; output ; does nothing to the memory (1 (car (value self))) ;;; init (2 (car (value self))) )) ;;; COMPILED FORM (defmethod gen-code ((self OMAccumBox) &optional (numout 0)) ;(print (list (mem-var (reference self)) "gen-code collect - stack = " *let-list-stack*)) (let* ((global-var (mem-var (reference self))) (local-name (intern (string+ (symbol-name global-var) "-LOCAL"))) (first-call (not (check-let-statement local-name :global)))) ; (print (list "gen-code" local-name first-call)) (when first-call (let ((init-val (gen-code (nth 2 (inputs self))))) (push-let-statement `(,local-name ,(if (equal init-val t) nil init-val)) :global))) (case numout ;;; collect (0 `(let ((accum-val ,(gen-code (nth 0 (inputs self)))) (accum-fun ,(gen-code (nth 1 (inputs self))))) (setf ,local-name (funcall accum-fun ,local-name accum-val)) ,local-name)) ;;; output (1 local-name) ;;; init with the value in (2 `(let ((init-val ,(gen-code (nth 2 (inputs self))))) (setf ,local-name (if (equal init-val t) nil init-val)) init-val)) )))
24,525
Common Lisp
.lisp
518
37.361004
136
0.545435
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
f63875c16622ef2fd1ac3c7b13214778a29f114fa81fd51585c64fefe944cf3f
655
[ -1 ]
656
repeat-n.lisp
cac-t-u-s_om-sharp/src/visual-language/boxes/repeat-n.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;---------------------------------- ;;; REPEAT-N: A COMPACT LOOP UTILITY ;;; SIMULATES N EVALUATIONS OF ITS INPUT ;;;---------------------------------- (in-package :om) ;;; EQUIVALENT FUNCTION IN LISP CODE: (defmacro repeat-n (body count) `(loop for ,(gensym) from 1 to ,count collect ,body)) (defclass Repeater (OMPatchComponent) ((n-iter :accessor n-iter :initform 0 :initarg :n-iter) (scope :accessor scope :initform :local :initarg :scope)) (:documentation "Evaluate its main input <N> times. Retrun a list with all results. The <scope> input (optional) determines the behaviour of the 'EVAL-ONCE' mechanism during the iteration: - :local reset the eval-once context at each iteration (each iteration is considered as a separate 'eval') - :global set a single global context for the <N> iterations.")) ;;; since we defined the repeat-n the package browser will look for it ;;; as reference for documentation. (setf (documentation 'repeat-n 'function) (class-documentation 'Repeater)) (defclass OMRepeatNBoxCall (OMPatchComponentBox) ()) (defmethod special-box-p ((name (eql 'repeat-n))) t) (defmethod get-box-class ((self Repeater)) 'OMRepeatNBoxCall) (defmethod get-icon-id ((self OMRepeatNBoxCall)) :repeat) (defmethod object-name-in-inspector ((self OMRepeatNBoxCall)) "REPEAT-N box") ;;; returns the default value (defmethod next-optional-input ((self OMRepeatNBoxCall)) (<= (length (inputs self)) 2)) (defmethod more-optional-input ((self OMRepeatNBoxCall) &key name (value nil val-supplied-p) doc reactive) (declare (ignore name doc)) (add-optional-input self :name "scope" :value (if val-supplied-p value :local) :reactive reactive) t) (defmethod get-input-menu ((self OMRepeatNBoxCall) name) (when (string-equal name "scope") '(("global" :global) ("local" :local)) )) ;;; as compared to other OMPatchComponentBox, REPEAT-N has a lock option (defmethod valid-property-p ((self OMRepeatNBoxCall) (prop-id (eql :lock))) t) (defmethod get-properties-list ((self OMRepeatNBoxCall)) (add-properties (call-next-method) "Execution" `((:lock "Lock state (b/1)" ,(lock-modes-for-box self) lock-state)))) (defmethod box-symbol ((self Repeater)) 'repeat-n) (defmethod omNG-make-special-box ((reference (eql 'repeat-n)) pos &optional init-args) (omNG-make-new-boxcall (make-instance 'Repeater :name "repeat-n" :n-iter (if (integerp (car init-args)) (car init-args) 0)) pos '(:icon-pos :left))) (defmethod create-box-inputs ((self OMRepeatNBoxCall)) (list (make-instance 'box-input :box self :value NIL :name "self" :doc-string "program to repeat") (make-instance 'box-input :box self :value (n-iter (reference self)) :name "num" :doc-string "number of times"))) (defmethod create-box-outputs ((self OMRepeatNBoxCall)) (list (make-instance 'box-output :box self :value NIL :name "collected results"))) (defmethod get-ev-once-flag ((self OMRepeatNBoxCall)) (list self (n-iter (reference self)))) (defmethod boxcall-value ((self OMRepeatNBoxCall)) (let ((n (omNG-box-value (cadr (inputs self)))) (scope (if (third (inputs self)) (omNG-box-value (third (inputs self))) (scope (reference self)))) (old-context *ev-once-context*)) (unwind-protect (progn (setf (n-iter (reference self)) 0) ;;; creates a new context: (when (equal scope :local) (setf *ev-once-context* self)) (loop for i from 1 to n do (setf (n-iter (reference self)) (1+ (n-iter (reference self)))) collect (omNG-box-value (car (inputs self)))) ) ;;; restores previous context after iteration: (when (equal scope :local) (setf *ev-once-context* old-context)) ) )) ;;; known issue: the compiled version does not behave the same with regards to ev-once behaviour ;;; in first-level patch the value is stored between evaluations and after, while in compiled version the variables are scoped. ;;; update 25/03/2019: I think this is fixed now => otherwise try to single out an example (defmethod gen-code-for-call ((self OMRepeatNBoxCall) &optional args) (let ((scope (if (third (inputs self)) (eval (gen-code (third (inputs self)))) (scope (reference self))))) (if (equal scope :global) (let* ((body (gen-code (car (inputs self))))) `(loop for i from 1 to ,(gen-code (cadr (inputs self))) collect ;;; keep this for a new context at each iteration: ; (let* ,(output-current-let-context) ,body) ;;; ... or use this for a global context: (progn ,body) ) ) ;;; :local (progn ;;; a new context will be created at each iteration: (let ((n (gen-code (cadr (inputs self))))) (push-let-context) (unwind-protect (let* ((body (gen-code (car (inputs self))))) `(loop for i from 1 to ,n collect ;;; new context at each iteration: (let* ,(output-current-let-context) ,body) )) (pop-let-context) )) )) )) ;;; NO LAMBDA OR OTHER FUNKY EVAL MODES FOR SPECIAL BOXES LIKE THIS... ;;; (the following code should work though...) #| (defmethod box-lambda-value ((self OMRepeatNBoxCall)) (multiple-value-bind (new-symbs args) (get-args-eval-curry self #'(lambda (input) `(omNG-box-value ,input))) (let ((arglist (apply 'append args))) ;;; flat the arg-list (for keywords etc.) (eval `#'(lambda ,new-symbs (setf (n-iter ,(reference self)) 0) (setf *ev-once-context* ,self) (loop for i from 1 to ,(cadr arglist) do (setf (n-iter ,(reference self)) (1+ (n-iter ,(reference self)))) collect ,(car arglist)) ))))) (defmethod gen-code-lambda ((self OMRepeatNBoxCall) &optional numout) (declare (ignore numout)) (let ((oldletlist *let-list*)) (setf *let-list* nil) (multiple-value-bind (new-symbs args) (get-args-eval-curry self #'gen-code) (let* ((body (caar args)) (code `#'(lambda ,new-symbs (loop for i from 1 to ,(caadr args) collect (let* ,(reverse *let-list*) ,body))))) (setf *let-list* oldletlist) code)) )) |#
7,451
Common Lisp
.lisp
164
37.95122
127
0.593452
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
88aa202a2e586cbffc0f4aac09831dc85fc9474d6699c2489fd2b26189423ce2
656
[ -1 ]
657
init-do.lisp
cac-t-u-s_om-sharp/src/visual-language/boxes/init-do.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;==================== ;;; INIT-DO ;;;==================== ;;; A general box that evaluates prior to the execution of the patch ;;; Much of its behaviour is similar to the "OUT" boxes, except that ;;; it is not returning anything out ;;; it is also useful to use along with iterator to do something before to start a loop (defclass OMPatchInit (OMPatchComponent) () (:documentation "A box that evaluates prior to the execution of the patch. Can be used along with iterators to do something before to start a loop.")) (defclass OMPatchInitBox (OMPatchComponentBox) ()) (defmethod special-box-p ((name (eql 'init-do))) t) (defmethod get-box-class ((self OMPatchInit)) 'OMPatchInitBox) (defmethod box-symbol ((self OMPatchInit)) 'init-do) (defmethod special-item-reference-class ((item (eql 'init-do))) 'OMPatchInit) (defmethod get-icon-id ((self OMPatchInitBox)) :s-play) (defmethod object-name-in-inspector ((self OMPatchInitBox)) "INIT CALL box") (defmethod omNG-make-special-box ((reference (eql 'init-do)) pos &optional init-args) (let ((name (car (list! init-args)))) (omNG-make-new-boxcall (make-instance 'OMPatchInit :name (if name (string name) "init-do")) pos init-args))) (defmethod create-box-inputs ((self OMPatchInitBox)) (list (make-instance 'box-input :box self :value NIL :name "action"))) (defmethod get-input-doc ((self OMPatchInitBox) name) "to do before to evaluate patch outputs") (defmethod next-optional-input ((self OMPatchInitBox)) t) (defmethod more-optional-input ((self OMPatchInitBox) &key name (value nil val-supplied-p) doc reactive) (declare (ignore name doc)) (add-optional-input self :name "action to do before to evaluate patch outputs" :value (if val-supplied-p value nil) :reactive reactive) t)
2,584
Common Lisp
.lisp
50
48.76
104
0.633188
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
33cabb0550c4d964a5709b4f36b7469068690dfc4e498602ea5f023631aaada1
657
[ -1 ]
658
file-stream.lisp
cac-t-u-s_om-sharp/src/visual-language/tools/file-stream.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;================================== ;;; VISUAL PROGRAMMIN WITH FILE I/O ;;; EQUIVALENT TO OM6's FILE-BOX (but much simpler!) ;;; ================================== (defclass fstream (om-cleanup-mixin) ((fpath :accessor fpath :initarg :fpath :initform nil) (fs :accessor fs :initarg :fs :initform nil) (open? :accessor open? :initarg :open? :initform nil))) (defmethod om-cleanup ((self fstream)) (when (open? self) (close (fs self)) (setf (open? self) nil))) (defmethod* open-file-stream (path &key (direction :io) (if-exists :supersede)) :initvals '(nil :io :supersede) :indoc '("a valid pathname" "stream direction (read/write)" "behaviour if the file exists") :menuins '((1 (("read" :input) ("write" :output) ("read/write" :io))) (2 (("rename" :rename) ("supersede" :supersede) ("overwrite" :overwrite) ("append" :append)))) :icon :file :doc "Opens a file stream where other functions can read and write." (make-instance 'fstream :fs (open path :direction direction :if-exists if-exists) :fpath path :open? t) ) ;;; COMPAT WITH OM6 FILE-BOX: STREAM FILE ACCESS (R/W) (defmethod streamfile (path) (om-beep-msg "WARNING: STREAMFILE IS NOW DEPRECATED. SEE 'OPEN-FILE-STREAM' / 'CLOSE-FILE-STREAM'.") (fs (open-file-stream path))) (defmethod (setf filetype) (type box) nil) (defmethod (setf direction) (type box) nil) (defmethod (setf if-ex) (type box) nil) (defmethod* close-file-stream ((self fstream)) :indoc '("a valid pathname" "stream direction (read/write)" "behaviour if the file exists") :icon :file :doc "Closes a file stream created by open-file-stream. Returns the file path. Open FILE-STREAMs are automatically closed when they are not used anymore by the Common Lisp garbage collection system, however, it is recommended to close them explicitely as soon as they are not needed in order to limit the number of streams open." (om-cleanup self) (fpath self)) ;;; R/W BOXES (defmethod* file-write-line ((line string) (stream fstream)) :indoc '("a line to write" "a file pointer") :icon :write :doc "Writes <line> in <stream> as a new line (i.e. with a line return). <stream> is a file pointer created by open-file-stream." (write-line line (fs stream))) (defmethod* file-write-line ((line symbol) (stream fstream)) (write-line (string line) (fs stream))) (defmethod* file-write-line ((line number) (stream fstream)) (write-line (format nil "~D" line) (fs stream))) (defmethod* file-write-line ((line character) (stream fstream)) (write-line (string line) (fs stream))) (defmethod* file-write-line ((line t) (stream fstream)) (om-print "Only write numbers and strings" "file-write-line")) ;;============ (defmethod* file-write ((line t) (stream fstream)) :indoc '("something to write" "a file pointer") :icon :write :doc "Writes <line> in <stream> (with no additional line return). <stream> is a file pointer represented created by open-file-stream." (om-print "Only write numbers symbols and strings" "file-write")) (defmethod* file-write ((line string) (stream fstream)) (write-string line (fs stream))) (defmethod* file-write ((line symbol) (stream fstream)) (write-string (string line) (fs stream))) (defmethod* file-write ((line number) (stream fstream)) (write-string (format nil "~D" line) (fs stream))) (defmethod* file-write ((line character) (stream fstream)) (write-char line (fs stream))) ;;============ (defmethod* file-read-line ((stream fstream)) :indoc '("a file pointer") :icon :write :doc "Reads a line in <stream>. <stream> is a file pointer created by open-file-stream." (read-line (fs stream) nil nil)) (defmethod* file-eof-p ((stream fstream)) :indoc '("a file pointer") :icon :write :doc "Check if <stream> is at the end of the file. <stream> is a file pointer created by open-file-stream." (om-stream-eof-p (fs stream)))
4,706
Common Lisp
.lisp
97
45.525773
250
0.643857
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
037254045cf060d1e8d31ba3e1ff3bb0a7614f29f180ec0902bee48d80a1a8cf
658
[ -1 ]
659
networking.lisp
cac-t-u-s_om-sharp/src/visual-language/tools/networking.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;==================== ;; UDP API WRAPPERS ;;==================== (defun om-send-udp (port host message) (let ((outs (comm+:connect-to-udp-server host port))) (comm+:send-message outs message) (comm+:close-datagram outs) message)) ;; ((host port server) (host port server) ...) (defparameter *running-udp-servers* nil) (defmethod notify-udp-server-stopped ((self t) server) nil) (defun om-start-udp-server (port host function &optional name owner) (let ((srv (find (list host port) *running-udp-servers* :test #'(lambda (h-p s) (and (string-equal (car h-p) (car s)) (= (cadr h-p) (cadr s))))))) (when (and srv (om-y-or-n-dialog (format NIL "Another UDP server is running on port ~D.~%Stop this server ?" port))) (notify-udp-server-stopped (fourth srv) (third srv)) (om-stop-udp-server (third srv)) (setf srv nil)) (unless srv (let ((server (comm+:start-udp-server :address host :service port :function function :process-name (or name (format nil "UDP receive server on ~S ~S" host port))))) (when server (push (list host port server owner) *running-udp-servers*) server))))) (defun om-stop-udp-server (server) (when server (setf *running-udp-servers* (remove server *running-udp-servers* :key 'third)) (comm+:stop-udp-server server :wait t))) ;;==================== ;; RECEIVE BOX ;;==================== ;; (defmethod allow-lock-button ((self ReceiveBox)) nil) (defclass OMReceiveBox (OMGFBoxcall) ((state :initform nil :accessor state) (process :initform nil :accessor process))) ;;; ARGS = BOX ARGS (defmethod start-receive-process ((self t)) nil) ;;,; ARGS = BOX PROCESS (defmethod stop-receive-process ((self t)) nil) (defmethod stop-box ((self OMReceiveBox)) (when (stop-receive-process (reference self)) (funcall (stop-receive-process (reference self)) self (process self))) (setf (process self) nil) (setf (state self) nil) (when (frame self) (om-invalidate-view (frame self)))) (defmethod notify-udp-server-stopped ((self OMReceiveBox) server) (stop-box self)) (defmethod start-box ((self OMReceiveBox)) (when (state self) (stop-box self)) (when (start-receive-process (reference self)) (let ((args (mapcar 'omng-box-value (inputs self)))) (setf (process self) (funcall (start-receive-process (reference self)) self args)))) (setf (state self) (if (process self) t nil)) (when (frame self) (om-invalidate-view (frame self)))) (defmethod omNG-box-value ((self OMReceiveBox) &optional (numout 0)) (current-box-value self numout)) (defmethod set-delivered-value ((box OMReceiveBox) msg &rest more-values) (setf (value box) (cons msg more-values))) (defmethod set-reactive ((box OMReceiveBox) val) (call-next-method) (if val (start-box box) (stop-box box))) (defmethod set-delivered-value :after ((box OMReceiveBox) msg &rest more-values) (self-notify box nil)) (defmethod omng-delete ((box OMReceiveBox)) (stop-box box) (call-next-method)) (defmethod boxframe-draw-contents ((self OMBoxFrame) (box OMReceiveBox)) (call-next-method) (when (state box) (om-draw-rounded-rect 0 0 (w self) (h self) :color (om-make-color 0.6 0.5 0. 0.3) :fill t :round 4) )) (defmethod box-menu-context ((self OMReceiveBox)) (list (list (om-make-menu-item (if (state self) "Stop receive" "Start receive") (if (state self) #'(lambda () (stop-box self)) #'(lambda () (start-box self))) )))) ;;==================== ;; UDP SEND / RECEIVE ;;==================== (defmethod* udp-send (msg host port) :initvals '(nil "127.0.0.1" 3000) :indoc '("message" "IP address" "port number") :doc "Sends the message (<msg>) port <port> of <host>. Note: default host 127.0.0.1 is the 'localhost', i.e. the message is send to the local computer address. " (when (om-send-udp port host msg) t)) (defmethod* udp-receive (port msg-processing &optional (host "localhost")) :indoc '("port number" "incoming message processing patch" "an IP address") :initvals '(3000 nil "localhost") :doc "A local UDP server. Use 'R' to set the box reactive and activate/deactivate the server. When the server is on, UDP-RECEIVE waits for messages on port <port> and calls <msg-processing> with the message as parameter. <msg-processing> must be a patch in mode 'lambda' with 1 input corresponding to a message. This patch should handle and process the incoming messages. By default the server is only local. Set <host> to your current IP address to allow messages to be sent from the network. " t) (defmethod boxclass-from-function-name ((self (eql 'udp-receive))) 'OMReceiveBox) ; utilities to process incoming messages ; (to use in the receive-fun) (defmethod process-message (message (fun OMPatch)) (apply (intern (string (compiled-fun-name fun)) :om) (list message))) (defmethod process-message (message (fun null)) message) (defmethod process-message (message (fun function)) (apply fun (list message))) (defmethod process-message (message (fun symbol)) (when (fboundp fun) (apply fun (list message)))) (defun udp-start-receive (box args) (let ((port (car args)) (fun (cadr args)) (host (or (caddr args) "localhost"))) (if (and port (numberp port)) (progn (om-print (format nil "Start UDP receive server on ~A ~D" host port) "UDP") (om-start-udp-server port host #'(lambda (msg) ;(print (format nil "UDP RECEIVE= ~A" msg)) (let ((delivered (process-message msg fun))) (set-delivered-value box delivered)) nil ) nil box)) (om-beep-msg (format nil "Error - bad port number for UDP-RECEIVE: ~A" port)) ))) (defun udp-stop-receive (box process) (declare (ignore box)) (when process (om-stop-udp-server process) (om-print (format nil "Stop ~A" (om-process-name process)) "UDP"))) (defmethod start-receive-process ((self (eql 'udp-receive))) 'udp-start-receive) (defmethod stop-receive-process ((self (eql 'udp-receive))) 'udp-stop-receive)
7,235
Common Lisp
.lisp
151
41.655629
126
0.613022
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
2186ca5b593e639a7972ab28ef4d202e7ef29105752b2c7b5fb8d7978b443a9e
659
[ -1 ]
660
data-structures.lisp
cac-t-u-s_om-sharp/src/visual-language/tools/data-structures.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;==================== ;;; SIMULATION OF VARIABLES ;;;==================== (defclass* store (named-object) ((value :initform nil :initarg :value :accessor value :documentation "the value of the variable")) (:icon :store) (:documentation "A general storage class used to simulate variables. Can be associated to global variables. The slot <value> can contain any kind of data, including instances of other classes. It can be accessed (get/set) using the methods get-slot / set-slot or using the SLOTS box (type 'store slots'). ") ) (defmethod get-cache-display-for-text ((self store) box) (declare (ignore box)) (if (listp (value self)) (if (null (value self)) '(("" "[empty]")) (loop for obj in (value self) for i = 0 then (1+ i) collect (list (format nil "[~D]" i) obj))) `(("" ,(value self))) )) ;;;==================== ;;; COPY ;;;==================== (defmethod* clone ((self t)) :indoc '("object") :outdoc '("copy") :icon :clone :doc "Makes and returns a copy of an object." (om-copy self)) ;;;==================== ;;; SET/GET SLOTS VALUES ;;; [DEPRECATED] ;;;==================== ;;;; Alternatively we could use set-slot-val to call standard accessors here... (defmethod* get-slot ((object t) (slot symbol)) :initvals '(nil nil) :indoc '("object" "slot name") :doc "Returns the value of an object's slot. <object> must be an object instance (e.g. the first output of a factory box). <slot> is the name of an existing slot of the corresponding class's slots. Warning : It is advised not to use GET-SLOT with some in-built objects, which have particular internal slots value management. In this case, prefer the get/set slots mechanism provided by the SLOTS boxes (type '<class-name> slots')." (if (slot-exists-p object slot) (slot-value object (intern-pack (string slot) (symbol-package (type-of object)))) (om-beep-msg "SLOT ~A does not exist in class ~A" slot (type-of object)))) (defmethod* get-slot ((object list) (slot symbol)) (loop for item in object collect (get-slot item slot))) (defmethod* set-slot ((object t) (slot symbol) (value t)) :initvals '(nil nil nil) :indoc '("object" "slot" "value") :doc "Modifies the value of an object's slot. <object> must be an object instance (e.g. the first output of a factory box, or the output of an instance or global variable box). <slot> is a slot name corresponding to one of the corresponding classe's slots. <value> is the new value to set in the <slot> field of <object> Returns the modified object <object>. Warning : It is advised not to use SET-SLOT with predefined objects, which have particular internal slots value management. Use rather the get/set slots mechanism provided by the SLOTS boxes (type '<class-name> slots'). " (if (slot-exists-p object slot) (setf (slot-value object (intern (string slot) (symbol-package (type-of object)))) value) (om-beep-msg "SLOT ~A does not exist in class ~A" slot (type-of object)))) (defmethod* set-slot ((object list) (slot symbol) (value t)) (loop for item in object do (set-slot item slot value))) ;;;======================================== ;;; MAP UTIL ;;;======================================== (defmethod map-list (function list &rest other-list) (apply 'mapcar (append (list function list) other-list) ) ) ;;;======================================== ;;; UTILITY TO TEST TYPE AND DISPATCH VALUES ;;;======================================== (defmethod* test-type ((self t) &rest types) :indoc '("object" "type(s)") :doc "Tests the type of an object. Add as many types as needed using the optional inputs. Types are symbol tested sequentially (left to right) with the Lisp SUBTYPEP function. The object is returned only on the output corresponding to the first type or (subtype) match. It is returned on the first output in case of negative match. " (let ((rep (position (type-of self) types :test 'subtypep)) (outs (make-list (length types)))) (values-list (if rep (progn (setf (nth rep outs) self) (cons nil outs)) (cons self outs))))) ;;; special box : add inputs and outputs symmetrically (defclass RouteBox (OMGFBoxCall) ()) (defmethod boxclass-from-function-name ((self (eql 'test-type))) 'RouteBox) (defmethod add-optional-input ((self RouteBox) &key name value doc reactive) (declare (ignore value doc reactive)) (call-next-method) (set-box-outputs self (append (outputs self) (list (make-instance 'box-optional-output :name (format nil "~A~D" name (length (outputs self))) :box self :doc-string "positive-test"))))) (defmethod remove-one-optional-input ((self RouteBox)) (when (call-next-method) (remove-one-output self (car (last (outputs self))))))
5,813
Common Lisp
.lisp
121
43.057851
130
0.602863
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
30eb9ecff229962baa81c1a7978c0e4e89b2f2dcbc7298ba5c0dfcd0ff6125b3
660
[ -1 ]
661
file-utils.lisp
cac-t-u-s_om-sharp/src/visual-language/tools/file-utils.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;========= ; USER FILES ;;;========= (defun default-folder (name &optional reference-path) (let ((ref-path (or reference-path (om-make-pathname :directory (append (pathname-directory (om-user-home)) '("Documents" "OM#")) :host (pathname-host (om-user-home))) ))) (check-folder (om-make-pathname :device (pathname-device ref-path) :host (pathname-host ref-path) :directory (append (pathname-directory ref-path) (list name)) :host (pathname-host ref-path))))) (defun def-input-folder () (default-folder "in-files")) (defun def-output-folder () (default-folder "out-files")) (defun def-temp-folder () (default-folder "temp-files")) (add-preference-module :files "Files and folders") (add-preference-section :files "Default Folders" "Used by the functions infile/outfile/tmpfile and as default path by the file chooser dialog") (add-preference :files :in-file "Input files" :folder 'def-input-folder) (add-preference :files :out-file "Output files" :folder 'def-output-folder) (add-preference :files :tmp-file "Temporary files" :folder 'def-temp-folder) (add-preference-section :files "Misc.") (add-preference :files :delete-tmp-files "Auto-cleanup temporary files" :bool nil) (add-preference :files :file-exists-ation "If output file exists..." '(replace auto-rename) 'replace) (add-preference-section :files "Search path" '("Search paths are used to find embedded sub-patches / abstractions when loading patches." "Empty/NIL means that the search is only relative to the top-level patch.")) (add-preference :files :search-path "Main search folder" :folder nil) (add-preference :files :search-path-2 "Search folder #2" :folder nil) (add-preference :files :search-path-3 "Search folder #3" :folder nil) (add-preference :files :search-path-4 "Search folder #4" :folder nil) (add-preference :files :search-path-rec "Recursive" :bool t "(search in sub-folders)") ;;;=================================== ;;; GENERATE PATHNAMES ;;;=================================== (defmethod* infile ((name string) &key (subdirs nil) (type nil)) :icon :folder :indoc '("file name" "directories" "type extension") :initvals '("" nil nil) :doc "Returns a file pathname corresponding to <name> in the default IN-FILES directory. The IN FILES directory can be set in the Preferences. It is used as a default location to read files. <subdirs> is a list of strings corresponding to IN-FILES subdirectories. <type> is a type extension to append to the filename. If not specified, the type of <name> is used. Ex. (infile \"myfile.midi\") ==> #P\"/Users/bresson/om-infiles/myfile.midi\" Ex. (infile \"myfile.midi\" :subdirs '(\"folder1\" \"folder2\") ==> #P\"/Users/bresson/om-infiles/folder1/folder2/myfile.midi\" " (om-make-pathname :directory (append (pathname-directory (get-pref-value :files :in-file)) (list! subdirs)) :host (and (get-pref-value :files :in-file) (pathname-host (get-pref-value :files :in-file))) :name (pathname-name name) :type (or type (pathname-type name)))) (defmethod* infile ((name null) &key (subdirs nil) (type nil)) (declare (ignore type)) (om-make-pathname :directory (append (pathname-directory (get-pref-value :files :in-file)) (list! subdirs)) :host (pathname-host (get-pref-value :files :in-file)))) ;;;=================================== (defmethod* outfile ((name string) &key (subdirs nil) (type nil)) :icon :folder :indoc '("file name" "directories" "type extension") :initvals '("" nil nil) :doc "Returns a file pathname corresponding to <name> in the default OUT-FILES directory. The OUT FILES directory can be set in the Preferences. It is used as a default location to write files. <subdirs> is a list of strings corresponding to OUT-FILES subdirectories. <type> is a type extension to append to the filename. If not specified, the type of <name> is used. Ex. (outfile \"myfile.midi\") ==> #P\"/Users/bresson/om-outfiles/myfile.midi\" Ex. (outfile \"myfile.midi\" :subdirs '(\"folder1\" \"folder2\") ==> #P\"/Users/bresson/om-outfiles/folder1/folder2/myfile.midi\" " (om-make-pathname :directory (append (pathname-directory (get-pref-value :files :out-file)) (list! subdirs)) :host (pathname-host (get-pref-value :files :out-file)) :name (pathname-name name) :type (or type (pathname-type name)))) (defmethod* outfile ((name null) &key (subdirs nil) (type nil)) (declare (ignore type)) (om-make-pathname :directory (append (pathname-directory (get-pref-value :files :out-file)) (list! subdirs)) :host (pathname-host (get-pref-value :files :out-file)))) ;;;=================================== (defmethod* tmpfile ((name string) &key (subdirs nil) (type nil)) :icon :folder :indoc '("file name" "directories" "type extension") :initvals '("" nil nil) :doc "Returns a file pathname corresponding to <name> in the default TMP-FILES directory. The TMP FILES directory can be set in the Preferences. It is used as a default location to write temporary files. <subdirs> is a list of strings corresponding to TMP-FILES subdirectories. <type> is a type extension to append to the filename. If not specified, the type of <name> is used. Ex. (tmpfile \"myfile.midi\") ==> #P\"/Users/bresson/om-tmpfiles/myfile.midi\" Ex. (tmpfile \"myfile.midi\" :subdirs '(\"folder1\" \"folder2\") ==> #P\"/Users/bresson/om-tmpfiles/folder1/folder2/myfile.midi\" " (om-make-pathname :directory (append (pathname-directory (get-pref-value :files :tmp-file)) (list! subdirs)) :host (pathname-host (get-pref-value :files :tmp-file)) :name (pathname-name name) :type (or type (pathname-type name)))) (defmethod* tmpfile ((path null) &key (subdirs nil) (type nil)) (declare (ignore type)) (om-make-pathname :directory (append (pathname-directory (get-pref-value :files :tmp-file)) (list! subdirs)) :host (pathname-host (get-pref-value :files :tmp-file)))) ;;;=================================== ;;; HANDLE TEMP FILE CLEANUP ;;;=================================== (defvar *tmpparfiles* nil) (defun add-tmp-file (file) (push file *tmpparfiles*) file) (defun clean-tmp-files () (when *tmpparfiles* (om-print "Removing files:") (loop for file in *tmpparfiles* do (when (and file (probe-file file)) (om-print (format nil " ~s" file)) (om-delete-file file))) (setf *tmpparfiles* nil))) (defun maybe-clean-tmp-files () (when (get-pref-value :files :delete-tmp-files) (clean-tmp-files))) ;;;=================================== ;;; SEARCH PATH ;;;=================================== (defun search-in-search-path (path folder) (and folder (find-file-in-folder (pathname-name path) folder :type (pathname-type path) :recursive (get-pref-value :files :search-path-rec) :return-all t))) (defun check-path-using-search-path (path) (or (probe-file path) (let ((found-matches (append (search-in-search-path path (get-pref-value :files :search-path)) (search-in-search-path path (get-pref-value :files :search-path-2)) (search-in-search-path path (get-pref-value :files :search-path-3)) (search-in-search-path path (get-pref-value :files :search-path-4)) ))) (when (> (length found-matches) 1) (om-beep-msg "Warning: several candidates were found in the search path folder for file ~A.~A !!" (pathname-name path) (pathname-type path))) (car found-matches) )) ) ;;;=================================== ;;; HANDLE FILE EXIST ;;;=================================== ;;; FINDS A GOOD (UNIQUE) PATH FOR NAME IN DIR (defun unique-pathname (dir name &optional (ext "")) (let ((pathname (om-make-pathname :directory dir :name name :type ext))) (loop while (probe-file pathname) for i = 1 then (+ i 1) do (setf pathname (make-pathname :device (pathname-device dir) :directory (pathname-directory dir) :name (string+ name (format nil "~D" i)) :type ext))) pathname)) (defun auto-rename (path) (unique-pathname path (pathname-name path) (pathname-type path))) ;;; IF AUTOMATIC-RENAME OPTION IS ON AND FILE EXISTS, FINDS A NEW NAME (defun handle-new-file-exists (newpath) (when (and newpath (probe-file newpath)) (if (equal 'auto-rename (get-pref-value :files :file-exists-ation)) (setf newpath (unique-pathname (make-pathname :directory (pathname-directory newpath) :host (pathname-host newpath) :device (pathname-device newpath)) (pathname-name newpath) (pathname-type newpath))) (delete-file newpath) )) newpath) ;;;=================================== ;;; FILE SAVER/LOADER MEMORY ;;;=================================== (defvar *last-saved-dir* nil) (defun def-save-directory () (or (and *last-saved-dir* (probe-file *last-saved-dir*)) (and (get-pref-value :files :out-file) (probe-file (get-pref-value :files :out-file))) (om-user-home))) (defvar *last-loaded-dir* nil) (defun def-load-directory () (or (and *last-loaded-dir* (probe-file *last-loaded-dir*)) (and (get-pref-value :files :in-file) (probe-file (get-pref-value :files :in-file))) (om-user-home))) ;;; FILE CHOOSE TOOLS (defmethod* file-chooser (&key (type 'file) (mode 'existing) (initial-folder nil) (message nil)) :icon :folder :initvals '(file existing desktop nil) :indoc '("file or directory" "new or existing" "pathname" "prompt for the dialog") :menuins '((0 (("file" file) ("directory" directory))) (1 (("new" new) ("existing" existing))) (2 (("home" home) ("desktop" desktop) ("other" nil)))) :doc "Pops up a file or directory chooser dialog. <type> chooses between a file or directory. <mode> determines whether this should be an existing file or directory or a new one to be created. <initial-folder> determines a strating directory for browsing the file system. <message> sets a specific message on the dialog. Returns the selected pathname or NIL if cancelled." (let ((initfolder (cond ((equal initial-folder 'home) (om-user-home)) ((equal initial-folder 'desktop) (om-make-pathname :directory (append (pathname-directory (om-user-home)) '("Desktop")))) (t (if (equal mode 'new) *last-saved-dir* *last-loaded-dir*)))) (rep nil)) (setf rep (cond ((and (equal type 'file) (equal mode 'existing)) (om-choose-file-dialog :prompt message :directory initfolder)) ((and (equal type 'directory) (equal mode 'existing)) (om-choose-directory-dialog :prompt message :directory initfolder)) ((and (equal type 'file) (equal mode 'new)) (om-choose-new-file-dialog :prompt message :directory initfolder)) ((and (equal type 'directory) (equal mode 'new)) (om-choose-new-directory-dialog :prompt message :directory initfolder))) ) (if rep (setf *last-loaded-dir* (om-make-pathname :directory rep)) (abort-eval)) rep)) ;;;=================================== ;;; OTHER PATHNAME UTILITIES ;;;=================================== (defmethod* home-directory () :icon :folder :doc "Path to the home user directory." (om-user-home)) (defmethod* create-pathname (directory &optional name type) :icon :folder :doc "Generates a pathname. <directory> can be a list of directory/folder names or another pathname. <name> can be a string or NIL (and the pathname is a directory) <type> is a file extension string (or NIL if no extension). " (om-make-pathname :directory directory :name name :type type)) (defmethod* folder-contents (path &key (type nil) (folders nil) (files t) (hidden-files nil) (recursive nil)) :icon :folder :initvals '(nil nil nil t nil nil) :indoc '("path to the folder" "file type(s)" "show sub-folders" "show files" "show hidden files" "recursive") :doc "Lists the contents of <path>. <type> can be a string or list of strings. Fiters files of specific type(s). <folders> shows/hide sub-folders. <files> shows/hide files. <hidden-files> include hidden syste,m files (typically starting with '.' <recursive> search recursively in sub-folders." (om-directory path :type type :directories folders :files files :hidden-files hidden-files :recursive recursive))
13,714
Common Lisp
.lisp
239
50.627615
192
0.620862
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8d59014a650b9345f18dd3eb4187242d2d08e688c110b6fdbc8a15e50ad1a2d6
661
[ -1 ]
662
collections.lisp
cac-t-u-s_om-sharp/src/visual-language/tools/collections.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;=========================== ;;; COLLECTION = A SET OF OBJECTS OF A SAME TYPE ;;;=========================== (defclass* collection (named-object) ((obj-type :accessor obj-type :initform nil) (obj-list :initarg :obj-list :accessor obj-list :initform nil)) (:documentation "Container holding a set of several objects of the same type. Displays/enable editing the list of objects in a single 'collection editor'. The desired type can be specified as the first input (e.g. typing 'collection BPF'). If this is done, this type is used to initialize or convert the input list of objects (if possible)." )) (defmethod get-properties-list ((self collection)) '(("COLLECTION attibutes" (:name "Name" :text name)))) ;;; the collection box has same additional attributes as the object it contains (if any) (defmethod additional-box-attributes ((self collection)) (additional-box-attributes (car (obj-list self)))) (defmethod homogenize-collection (model list) nil) (defmethod om-init-instance ((self collection) &optional initargs) (let ((initial-list (loop for item in (list! (obj-list self)) collect (om-init-instance item)))) (setf (obj-list self) (if (obj-type self) ;;; coerce all object to the specified type (remove nil (mapcar #'(lambda (obj) (om-init-instance (objfromobjs obj (make-instance (obj-type self))))) initial-list)) (om-copy initial-list)))) (when (obj-list self) ;;; check if all items are of the same type (if (list-typep (obj-list self) (type-of (car (obj-list self)))) (progn (setf (obj-type self) (type-of (car (obj-list self)))) (homogenize-collection (car (obj-list self)) (obj-list self))) (progn (om-beep-msg "WARNING: ELEMENTS IN COLLECTION ARE NOT OF THE SAME TYPE!!") (setf (obj-type self) nil)))) self) ;;;=========================== ;;; BOX ;;;=========================== (defmethod object-default-edition-params ((self collection)) (append '((:show-all t)) (object-default-edition-params (car (obj-list self))))) (defmethod special-box-p ((name (eql 'collection))) t) (defmethod special-box-type ((class-name (eql 'collection))) 'CollectionBox) (defclass MultiCacheBoxEditCall (OMBoxEditCall) ((multi-cache-display :accessor multi-cache-display :initform nil))) (defclass CollectionBox (MultiCacheBoxEditCall) ()) (defmethod omNG-make-special-box ((reference (eql 'collection)) pos &optional init-args) (let ((type (and init-args (find-class (car init-args) nil))) (val (make-instance 'collection))) (when type (setf (obj-type val) (class-name type))) (let ((box (omNG-make-new-boxcall (find-class 'collection) pos val))) (setf (name box) "...") (setf (value (car (inputs box))) (obj-type val)) box))) (defmethod objfromobjs ((model symbol) (target collection)) (if (find-class model nil) (setf (obj-type target) model) (om-beep-msg "WARNING: class not found for collection: ~S" model)) target) (defmethod draw-type-of-object ((object collection)) (string+ (string-upcase (type-of object)) " OF " (string-upcase (obj-type object)))) (defmethod get-object-type-name ((object collection)) (and (obj-type object) (string+ "COLLECTION OF " (string-upcase (obj-type object)) "s (" (number-to-string (length (obj-list object))) ")"))) (defmethod object-box-label ((object collection)) (string+ (string-upcase (type-of object)) " of " (number-to-string (length (obj-list object))) " " (if (obj-type object) (string-upcase (obj-type object)) "?") (if (> (length (obj-list object)) 1) "s" "") )) (defmethod display-modes-for-object ((self collection)) '(:mini-view :text :hidden)) (defmethod get-cache-display-for-text ((self collection) box) (declare (ignore box)) (loop for obj in (obj-list self) for i = 0 then (1+ i) collect (list (format nil "[~D]" i) obj))) ;;; CollectionBox has a little hack on cache-display to store a different cache for each object ;;; The multi-cache display is a list of list (object cache) ;;; collection boxes create "multi-cache" by calling get-collection-cache-display on internbal objects (defmethod get-cache-display-for-draw ((object collection) box) (declare (ignore box)) (unless (multi-cache-display box) (setf (multi-cache-display box) (get-collection-cache-display (car (obj-list object)) (obj-list object) box))) nil) ;;; CAN BE REDEFINED FOR SPECIFIC OBJECTS: ;;; type is an object used for specialization (defmethod get-collection-cache-display ((type t) list box) (loop for o in list collect (list o (get-cache-display-for-draw o box)))) (defmethod reset-cache-display ((self CollectionBox)) (setf (multi-cache-display self) nil) (call-next-method)) (defmethod ensure-cache-display-draw ((box CollectionBox) object) (if (typep object 'collection) (call-next-method) ;;; will eventually store some cache ;;; called on elements of the collection: (progn (unless (cache-display box) (setf (cache-display box) (make-cache-display))) (unless (cache-display-draw (cache-display box)) ;;; this is just an access in memory: no need to redo the cache ;;; set the general cache to the item in the multi-cache (setf (cache-display-draw (cache-display box)) (cadr (find object (multi-cache-display box) :key #'car)))) (cache-display-draw (cache-display box))))) ;;; type is an object used for specialization ;;; otherwise, calls draw-mini-view for every object (defmethod collection-draw-mini-view ((type t) list box x y w h time) (when list (let ((ho (/ h (length list)))) (loop for o in list for yo = y then (+ yo ho) do (setf (cache-display box) nil) (draw-mini-view o box x yo w ho time)) ))) (defmethod draw-mini-view ((self collection) (box t) x y w h &optional time) (ensure-cache-display-draw box self) (collection-draw-mini-view (car (obj-list self)) (obj-list self) box x y w h time)) ;;; used for display etc. (defmethod get-obj-dur ((self collection)) (apply #'max (or (remove nil (mapcar #'get-obj-dur (obj-list self))) '(0)))) (defmethod miniview-time-to-pixel ((object collection) box (view omboxframe) time) ;;; take the longer object as reference (miniview-time-to-pixel (reduce #'(lambda (o1 o2) (if (>= (get-obj-dur o1) (get-obj-dur o2)) o1 o2)) (obj-list object)) box view time)) ;;;=========================== ;;; EDITOR ;;;=========================== (defclass collection-editor (OMEditor undoable-editor-mixin) ((internal-editor :accessor internal-editor :initform nil) (current :accessor current :initform 0))) (defmethod object-has-editor ((self collection)) t) (defmethod get-editor-class ((self collection)) 'collection-editor) (defmethod object-value ((self collection-editor)) (nth (current self) (obj-list (get-value-for-editor (object self))))) (defmethod undoable-object ((self collection-editor)) (get-value-for-editor (object self))) (defmethod get-obj-to-play ((self collection-editor)) (object-value self)) (defmethod editor-play-state ((self collection-editor)) (editor-play-state (internal-editor self))) (defmethod editor-close ((self collection-editor)) (editor-close (internal-editor self)) (call-next-method)) ;;;================================== ;multidisplay API (defclass multi-display-editor-mixin () ((multi-display-p :accessor multi-display-p :initarg :multi-display-p :initform nil) (multi-obj-list :accessor multi-obj-list :initform nil))) (defmethod handle-multi-display ((self t)) nil) (defmethod handle-multi-display ((self multi-display-editor-mixin)) t) (defmethod enable-multi-display ((self t) obj-list) nil) (defmethod enable-multi-display ((self multi-display-editor-mixin) obj-list) (setf (multi-display-p self) t (multi-obj-list self) obj-list)) (defmethod disable-multi-display ((self t)) nil) (defmethod disable-multi-display ((self multi-display-editor-mixin)) (setf (multi-display-p self) nil) (setf (multi-obj-list self) nil)) (defmethod update-multi-display ((editor collection-editor) t-or-nil) (if t-or-nil (enable-multi-display (internal-editor editor) (obj-list (get-value-for-editor (object editor)))) (disable-multi-display (internal-editor editor))) (update-to-editor (internal-editor editor) editor) (editor-invalidate-views (internal-editor editor)) ) ;;;================================== (defmethod init-editor ((editor collection-editor)) (let* ((collection (get-value-for-editor (object editor))) (current-object (and (obj-type collection) (nth (current editor) (obj-list collection)))) (abs-container (make-instance 'OMAbstractContainer :contents current-object))) (setf (internal-editor editor) (make-instance (get-editor-class current-object) :container-editor editor :object abs-container)) (setf (edition-params abs-container) (edition-params (object editor))) ;;; will share the same list in principle (init-editor (internal-editor editor)) )) (defmethod init-editor-window ((editor collection-editor)) (call-next-method) (init-editor-window (internal-editor editor)) (when (editor-get-edit-param editor :show-all) (update-multi-display editor t))) (defmethod make-editor-window-contents ((editor collection-editor)) (let* ((collection (get-value-for-editor (object editor))) (text (format-current-text editor)) (current-text (let ((font (om-def-font :large-b))) (om-make-graphic-object 'om-item-text :size (omp (om-string-size text font) 16) :text text :font font))) (prev-button (om-make-graphic-object 'om-icon-button :size (omp 16 16) :position (omp 0 0) :icon :l-arrow :icon-pushed :l-arrow-pushed :icon-disabled :l-arrow-disabled :lock-push nil :enabled (> (length (obj-list collection)) 1) :action #'(lambda (b) (declare (ignore b)) (set-current-previous editor) ))) (next-button (om-make-graphic-object 'om-icon-button :size (omp 16 16) :position (omp 0 0) :icon :r-arrow :icon-pushed :r-arrow-pushed :icon-disabled :r-arrow-disabled :lock-push nil :enabled (> (length (obj-list collection)) 1) :action #'(lambda (b) (declare (ignore b)) (set-current-next editor) ))) (-button (om-make-graphic-object 'om-icon-button :size (omp 16 16) :position (omp 0 0) :icon :- :icon-pushed :--pushed :icon-disabled :--disabled :lock-push nil :enabled (obj-list collection) :action #'(lambda (b) (remove-current-object editor) (let ((coll (get-value-for-editor (object editor)))) (if (obj-list coll) (update-multi-display editor (editor-get-edit-param editor :show-all)) (button-disable b)) (when (<= (length (obj-list coll)) 1) (button-disable prev-button) (button-disable next-button)) )) )) (+button (om-make-graphic-object 'om-icon-button :size (omp 16 16) :position (omp 0 0) :icon :+ :icon-pushed :+-pushed :icon-disabled :+-disabled :lock-push nil :enabled (and (obj-type (get-value-for-editor (object editor))) (subtypep (obj-type (get-value-for-editor (object editor))) 'standard-object)) :action #'(lambda (b) (declare (ignore b)) (add-new-object editor) (let ((coll (get-value-for-editor (object editor)))) (button-enable -button) ;; in case it was disabled.. (when (> (length (obj-list coll)) 1) (button-enable prev-button) (button-enable next-button))) (update-multi-display editor (editor-get-edit-param editor :show-all)) ))) (showall-check (when (handle-multi-display (internal-editor editor)) (om-make-di 'om-check-box :text " Show All" :size (omp 80 16) :font (om-def-font :gui) :checked-p (editor-get-edit-param editor :show-all) :focus nil :default nil :di-action #'(lambda (item) (editor-set-edit-param editor :show-all (om-checked-p item)) (update-multi-display editor (om-checked-p item))) ))) ) (set-g-component editor :current-text current-text) (om-make-layout 'om-column-layout :ratios '(1 99) :subviews (list (om-make-layout 'om-row-layout :delta 0 :ratios '(1 1 1 10 1 10 1) :align :top :subviews (list (om-make-layout 'om-row-layout :delta 0 :subviews (list (om-make-view 'om-view :size (omp 16 16) :subviews (list prev-button)) (om-make-view 'om-view :size (omp 16 16) :subviews (list next-button))) ) (om-make-graphic-object 'om-item-view :size (omp 20 20)) showall-check nil current-text nil (om-make-layout 'om-row-layout :delta 0 :subviews (list (om-make-view 'om-view :size (omp 16 16) :subviews (list +button)) (om-make-view 'om-view :size (omp 16 16) :subviews (list -button)) )) )) (if (object-value (internal-editor editor)) (setf (main-view (internal-editor editor)) (make-editor-window-contents (internal-editor editor)))) )) )) (defmethod set-window-contents ((editor collection-editor)) (when (window editor) (om-remove-subviews (window editor) (main-view editor)) (om-add-subviews (window editor) (setf (main-view editor) (make-editor-window-contents editor))) )) ;;; when updated from the box (eval) (defmethod update-to-editor ((editor collection-editor) (from OMBox)) (let ((collection (get-value-for-editor (object editor)))) (when (not (equal (type-of (internal-editor editor)) ;;; the new object has not the same editor (get-editor-class (nth (current editor) (obj-list collection))))) ;;; need to close/reset the internal editor (editor-close (internal-editor editor)) (init-editor editor) (setf (current editor) 0) (set-window-contents editor) )) ;;; with reset the virtual object for internal-editor (update-collection-editor editor) (set-current-text editor) (update-to-editor (internal-editor editor) from) (update-multi-display editor (editor-get-edit-param editor :show-all)) (call-next-method) ) (defmethod format-current-text ((editor collection-editor)) (let ((collection (get-value-for-editor (object editor)))) (if (obj-list collection) (format nil "Current ~A: ~D/~D" ;; [~A] (string-upcase (obj-type collection)) (1+ (current editor)) (length (obj-list collection)) ;(name (nth (current editor) (obj-list collection))) ) "[empty collection]"))) (defmethod editor-invalidate-views ((editor collection-editor)) (when (internal-editor editor) (om-invalidate-view (internal-editor editor)))) (defmethod set-current-text ((editor collection-editor)) (let ((text-component (get-g-component editor :current-text))) (when text-component (let ((text (format-current-text editor))) (om-set-view-size text-component (omp (+ 20 (om-string-size text (om-get-font text-component))) 16)) (om-set-text text-component text))))) (defmethod update-collection-editor ((editor collection-editor)) (declare (special *general-player*)) (set-current-text editor) (let ((internal-editor (internal-editor editor))) (when (and (boundp '*general-player*) *general-player*) (editor-stop internal-editor)) (setf (selection internal-editor) nil) (let ((abs-container (object internal-editor))) ;; in principle this is an OMAbstractContainer (setf (contents abs-container) (nth (current editor) (obj-list (get-value-for-editor (object editor)))))) (update-default-view internal-editor) (update-to-editor internal-editor editor) (editor-invalidate-views internal-editor))) (defmethod set-current-nth ((editor collection-editor) n) (let ((collection (get-value-for-editor (object editor)))) (when (obj-list collection) (setf (current editor) n)) (update-collection-editor editor))) (defmethod set-current-next ((editor collection-editor)) (let ((collection (get-value-for-editor (object editor)))) (when (obj-list collection) (set-current-nth editor (mod (1+ (current editor)) (length (obj-list collection)))) ))) (defmethod set-current-previous ((editor collection-editor)) (let ((collection (get-value-for-editor (object editor)))) (when (obj-list collection) (set-current-nth editor (mod (1- (current editor)) (length (obj-list collection)))) ))) (defmethod remove-current-object ((editor collection-editor)) (let ((collection (get-value-for-editor (object editor)))) ;;; update the obj-list (when (obj-list collection) (setf (obj-list collection) (remove (nth (current editor) (obj-list collection)) (obj-list collection))) (setf (current editor) (max 0 (min (current editor) (1- (length (obj-list collection))))))) ;;; if no more objects... (if (null (obj-list collection)) (progn ;;; close the internal editor (editor-close (internal-editor editor)) (setf (contents (object (internal-editor editor))) nil) (init-editor editor) ;; need to init the editor (reset to an empty omeditor) ;;; rest the (empty) window (set-window-contents editor)) ;;; othewise just update the editor (update-collection-editor editor)) (report-modifications editor) )) (defmethod add-new-object ((editor collection-editor)) (let* ((collection (get-value-for-editor (object editor))) (new? (null (obj-list collection)))) (setf (obj-list collection) (append (obj-list collection) (list (om-init-instance (make-instance (obj-type collection)))))) (setf (current editor) (1- (length (obj-list collection)))) (when new? ;;; need to (re)initialize an editor (init-editor editor) (set-window-contents editor) (init-editor-window (internal-editor editor))) (update-collection-editor editor) (update-multi-display editor (editor-get-edit-param editor :show-all)) ;; will add the new object to te multi-display list (report-modifications editor) )) ;;;========================= ;;; DISPATCH ACTIONS... ;;;========================= (defmethod editor-key-action ((editor collection-editor) key) (cond ((and (om-command-key-p) (equal key :om-key-left)) (set-current-previous editor) (update-collection-editor editor)) ((and (om-command-key-p) (equal key :om-key-right)) (set-current-next editor) (update-collection-editor editor)) (t (editor-key-action (internal-editor editor) key)) )) (defmethod select-all-command ((self collection-editor)) #'(lambda () (when (and (internal-editor self) (select-all-command (internal-editor self))) (funcall (select-all-command (internal-editor self))))))
21,451
Common Lisp
.lisp
435
40.574713
126
0.607964
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
04888115149b46ef023097600b4cbe30bc101e2f4117e822642224d212eb13bd
662
[ -1 ]
663
write-to-disk.lisp
cac-t-u-s_om-sharp/src/visual-language/tools/write-to-disk.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;========================================================================= ; ; UTILS TO EXPORT DATA AS TEXT ; ;========================================================================= (in-package :om) (defmethod write-data ((self list) out) (loop for elt in self do (loop for p in (list! elt) do (if (floatp p) (format out "~f " p) (format out "~d " p))) (format out "~%"))) (defmethod write-data ((self t) out) (format out "~A~%" self)) ;;; COMPAT ;;; DEPRECATED (defmethod save-params ((self t) file) (save-as-text self file)) (defmethod* save-as-text ((self t) &optional (path "data") (type "txt")) :icon :write :initvals '(nil "data") :indoc '("data (list, BPF, or TextBuffer)" "a file location") :doc "Saves the data from <self> as a text file in <path>." (let ((file (cond ((null path) (om-choose-new-file-dialog :directory (def-save-directory) :types '("Text files" "*.txt" "All files" "*.*"))) ((pathnamep path) path) ((stringp path) (if (pathname-directory path) (pathname (string+ path type)) (outfile path :type type)))))) (if file (progn (with-open-file (out file :direction :output :if-does-not-exist :create :if-exists :supersede) ;(print self) (write-data self out)) file) (abort-eval))))
2,109
Common Lisp
.lisp
47
40.382979
137
0.498294
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e20471f0e0bcb81b6e53396f8c858f8c6008ac8f98a510020e18c05d4103e281
663
[ -1 ]
664
documentation.lisp
cac-t-u-s_om-sharp/src/visual-language/utils/documentation.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;==================================== ;;; Documentation for Lisp functions ;;;==================================== (in-package :om) (setf (documentation 'first 'function) "Returns the 1st element in <list>. (Equivalent to Lisp CAR) Ex. (first '(1 2 3 4 5 6)) => 1") (setf (documentation 'second 'function) "Returns the 2nd element in <list>. Ex. (second '(1 2 3 4 5 6)) => 2") (setf (documentation 'third 'function) "Returns the 3rd element in <list>. Ex. (third '(1 2 3 4 5 6)) => 3") (setf (documentation 'nth 'function) "Returns the <n>th element in <list>. The count starts from 0, i.e. (nth 0 list) is the first element of the list. Ex. (nth 0 '(1 2 3 4 5 6)) => 1 Ex. (nth 2 '(1 2 3 4 5 6)) => 3") (setf (documentation 'rest 'function) "Returns the tail of <list>, i.e. the same list without irts first element. (Equivalent to Lisp CDR) Ex. (rest '(1 2 3 4 5 6)) => (2 3 4 5 6)") (setf (documentation 'nthcdr 'function) "Returns the tail of <list> that would be obtained by calling REST <n> times in succession, i.e. without its <n> first elements. Ex. (nthcdr 2 '(1 2 3 4 5 6)) => (3 4 5 6)") (setf (documentation 'butlast 'function) "Returns a copy of <list> without its last element or without its last <n> elements if <n> is supplied. Ex. (butlast '(1 2 3 4 5 6)) => (1 2 3 4 5) Ex. (butlast '(1 2 3 4 5 6)) => (1 2 3)") (setf (documentation 'reverse 'function) "Returns a new sequence or list of the same kind as <sequence>, containing the same elements but in reverse order. Ex. (reverse '(1 2 3 4 5 6)) => (6 5 4 3 2 1)") (setf (documentation 'length 'function) "Returns the number of elements in <sequence> (a list, a string, ...) Ex. (length '(1 2 3 4 5 6)) => 6 Ex. (length \"hello\") => 5") (setf (documentation 'list 'function) "Returns a list containing the supplied objects (<args>). Ex. (list 1 2 'a 7) => (1 2 a 7) LIST also exists as a type specifier (or class). The type specifier is mainly used to set types in other class slots or method arguments. ") (setf (documentation 'remove 'function) "Returns a new sequence that has the same elements as <sequence> except those that satisfy the test <test> with <item>. By default the test is 'eql so the items that are equal to <item> are removed. <test> can be a function or a function name. <start> and <end> determine bounding indices in the original sequence for removing elements. <count> specifies a maximal number of items to remove. <from-end> if T, starts removing items from end of the sequence <key> is a function applyed to each item before to be tested <test-not> is used to remove elemet that do not satistfy the test (deprecated use) Ex. (remove 5 '(2 5 6 7 5 3)) => (2 6 7 3) Ex. (remove 5 '(2 5 6 7 5 3) :test '>) => (2 3) Ex. (remove 5 '((b 2) (c 5) (d 6) (e 7) (f 5) (g 3))) :key 'second) => ((b 2) (d 6) (e 7) (g 3)) ") (setf (documentation 'cons 'function) "Creates a new CONS with <car> and <cdr>. A CONS is a basic compound data object having two components called the CAR and the CDR A LIST is recursively defined as a CONS which CDR is a list. Ex. (cons 'a 'b) => (a . b) Ex. (cons 'a nil) => (a) Ex. (cons 'a '(b c)) => (a b c) Ex. (cons 'a (cons 'b nil)) => (a b)") (setf (documentation 'append 'function) "Returns a new list that is the concatenation of the <lists>. Ex. (append '(1 2 3) '(4 5)) => (1 2 3 4 5)") (setf (documentation 'apply 'function) "Applies <function> to the arguments in <arg>. <function> is a function or function name. <arg> is a list of arguments. Ex. (apply '+ '(3 4)) => 7 ") (setf (documentation 'funcall 'function) "Applies <function> to <args>. <function> is a function or function name. <args> are the arguments. Ex. (funcall '+ 3 5) => 8") (setf (documentation 'mapcar 'function) "Operates on successive elements of <list> (and of the other lists of <more-lists>). <function> can be a function or function name. It is applied to the first element of each list, then to the second element of each list, and so on. The iteration terminates when the list runs out, or when the shorter list runs out if various lists are supplied. Excess elements in other lists are ignored. The value returned is a list of the results of successive calls to <function>.") (setf (documentation 'mapcan 'function) "Operates on successive elements of <list> (and of the other lists of <more-lists>). <function> can be a function or function name. It is applied to the first element of each list, then to the second element of each list, and so on. The iteration terminates when the list runs out, or when the shorter list runs out if various lists are supplied. Excess elements in other lists are ignored. The value returned is a the concatenation of the results of successive calls to <function>. <function> should therefore return lists.") (setf (system::class-documentation (find-class 't)) "Special constant in Lisp, meaning 'TRUE'. T can be used as a type specifier in class slots or method arguments in order to describe any object type (all objects inherit from the Lisp class 'T').") (setf (system::class-documentation (find-class 'integer)) "Integer number. This class is mainly used to set types in other class slots or method arguments.") (setf (system::class-documentation (find-class 'number)) "Any type of number. This class is mainly used to set types in other class slots or method arguments.") (setf (documentation 'float 'function) "Float number (decimal). FLOAT exists in Lisp as a functions, which converts its input (a real number) to a float number. Ex. (float 4) => 4.0 Ex. (flat 1/2) => 0.5 FLOAT also exists as a type specifier (or class). The type specifier is mainly used to set types in other class slots or method arguments.") (setf (documentation 'rational 'function) "Rational number (P/Q). RATIONAL exists in Lisp as a functions, which converts its input (a real number) to a rational number. It also exists as a type specifier (or class). The type specifier is mainly used to set types in other class slots or method arguments.") (setf (documentation 'string 'function) "Vector of characters. STRING exists in Lisp as a functions, which converts its input (another string, a symbol or a character) into a string. Ex. (string 'hello) => \"hello\" It also exists as a type specifier (or class). The type specifier is mainly used to set types in other class slots or method arguments. Strings are represented as characters between double-quotes (\"\"). ") (setf (documentation 'null 'function) "In Common Lisp, NIL, also notated '(), represents the empty list. The function NULL tests if something is equal to NIL or not. This function returns T if the argument is NIL, and NIL if not. Ex. (null 4) => NIL Ex. (null NIL) => T Ex. (null '()) => T Ex. (null '(5 6 7)) => NIL NULL is also the name of a class (the 'class of NIL'), and can be used to specialize method arguments.")
7,790
Common Lisp
.lisp
138
53.768116
305
0.674775
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
dd685412f03e7807e8a0b438792a4029d3a26ffc8cd2677c0d64b54c110698fa
664
[ -1 ]
665
strings.lisp
cac-t-u-s_om-sharp/src/visual-language/utils/strings.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;======================= ;;; STRING UTILITIES FOR OM ;;;======================= (in-package :om) (defun string+ (&rest strings) (eval `(concatenate 'string ,.strings))) (defun om-read-list-from-string (string &optional (pos 0) (ignore-errors nil)) (let ((str2 (delete-lisp-comments string))) (block nil (handler-bind ((error #'(lambda (e) (unless ignore-errors (om-beep-msg "read error: ~A in ~s" (type-of e) str2)) (return nil)))) (multiple-value-bind (val pos) (read-from-string str2 nil :eof :start pos) (if (eql val :eof) nil (cons val (om-read-list-from-string str2 pos ignore-errors)))) )))) (defun om-text-to-lines (text) (let ((p2 (position #\Newline text)) (rep nil)) (loop while p2 do (push (subseq text 0 p2) rep) (setf text (subseq text (+ p2 1))) (setf p2 (position #\Newline text))) (push text rep) (reverse rep))) (defun string-until-char (string char) (let ((index (search char string))) (if index (values (subseq string 0 index) (subseq string (+ index 1))) (values string nil)))) (defun string-to-list (string &optional (separator " ")) (when string (multiple-value-bind (token rest) (string-until-char string separator) (cons token (string-to-list rest separator))))) (defun string-lines-to-list (string) (string-to-list string (string #\Newline))) (defun number-to-string (num &optional decimals) (if decimals (format nil (format nil "~~,~DF" decimals) num) (format nil "~D" num))) (defun read-number (str) (if (equal str "") nil (let ((rep (read-from-string str))) (if (numberp rep) rep nil)))) (defun string-to-number (string) (and (stringp string) (read-from-string string))) (defun string-until-space (string) (let ((index (search " " string))) (if index (subseq string 0 index) string))) (defun delete-lisp-comments (string) (string-until-char string ";")) (defun delete-spaces (string) (let ((pos (position-if #'(lambda (x) (and (not (equal x #\Linefeed)) (not (equal x #\Space)) (not (equal x #\Tab)))) string))) (if pos (subseq string pos) ""))) ;======================= ; FILE READER ;======================= (defun list-from-file (pathname) (let ((path (probe-file pathname))) (when (and path (valid-file-pathname-p path)) (let ((rep-list nil)) (with-safe-open-file (in path :direction :input) (let ((line (read in nil :eof))) (loop while (and line (not (equal line :eof))) do (setf rep-list (append rep-list (list line)) line (read in nil :eof))))) rep-list)))) (defun lines-from-file (pathname) (let ((path (probe-file pathname))) (when (and path (valid-file-pathname-p path)) (with-safe-open-file (in pathname :direction :input) (let ((line (read-line in nil :eof))) (loop while (and line (not (equal line :eof))) collect line do (setf line (read-line in nil :eof)))) ) ))) ;======================= ; STRING TO SYMBOLS ;======================= (defun intern-om (string) (intern (string-upcase string) :om)) (defun intern-pack (string pck) (intern (string-upcase string) pck)) (defun intern-k (string) (intern (string-upcase string) :keyword)) ;======================= ; cross-platform / encoding tools ;======================= ;; multiple tabs ;(setf string (remove-duplicates string :test #'(lambda (x y) (equal x #\Tab)))) (defun get-switch-chars () #+win32 '((381 233) ;; é (136 224) ;; à (144 234) ;; ê (143 232) ;; è (157 249) ;; ù (153 244) ;; ô (148 238) ;; î (0 231) ;; ç (8217 39) ;; ' ) #-win32 '((142 233) ;; é (136 224) ;; à (144 243) ;; ê (143 232) (768 232) ;; è ;; #\U+0300 (157 249) ;; ù (153 244) ;; ô (148 238) ;; î (139 227) ;; ã ;; #\U+008B (141 231) ;; ç (135 225) ;; á ;; #\U+0087 (146 237) ;; í ;; #\U+0092 (8217 39) ;; ' )) (defvar *unknown-chars* '(#\U+0080 #\U+0081 #\U+0082 #\U+0083 #\U+0084 #\U+0085 #\U+0086 #\U+0088 #\U+0089 #\U+008A #\U+008C #\U+008D #\U+008E #\U+008F #\U+0090 #\U+0091 #\U+0093 #\U+0094 #\U+0095 #\U+0096 #\U+0097 #\U+0098 #\U+0099 #\U+009A #\U+009B #\U+009C #\U+009D #\U+009E #\U+009F)) (defun str-check (string) (let ((pos nil)) (loop for char-switch in (get-switch-chars) do (loop while (setf pos (position (code-char (car char-switch)) string)) do (replace string (string (code-char (cadr char-switch))) :start1 pos))) ;; unknown chars... a chercher (loop for ch in *unknown-chars* do (loop while (setf pos (position ch string)) do (replace string "?" :start1 pos))) string)) ; (string #\U+0097) ; (code-char 135) ; (print (remove-duplicates (mapcar 'code-char (om::arithm-ser 0 10000 1)) :test 'equal)) ; (char-code (elt "bamos" 1)) ; (char-code #\U+008B) ; (char-code #\U+0087) ; (char-code #\) (char-code #\') ; (str-check "Laghj « dqkjdqmlj »")
6,190
Common Lisp
.lisp
156
32.942308
126
0.527945
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
2046952f35dc5ad593cf9fef0da181ebdd633371e60159dc39580ade879a95ae
665
[ -1 ]
666
compatibility.lisp
cac-t-u-s_om-sharp/src/visual-language/utils/compatibility.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) (defvar *om-current-persistent* nil) (defvar *current-loading-document* nil) (pushr '(:old ("omp" "omm" "oml") "OM6 Files [compatibility mode]") *doctypes*) (defun load-om6-file (path) (declare (special *om-current-persistent* *current-loading-document*)) (om-print-format "Opening document : ~A" (list path) "Import/Compatibility") (clos::set-clos-initarg-checking nil) ;; in case some class initargs do not exist anymore... (let* ((previous-loading-document *current-loading-document*) (obj-type (cond ((string-equal (pathname-type path) "omp") 'OMPatchFile) ((string-equal (pathname-type path) "oml") 'OMLispFunctionFile) ((string-equal (pathname-type path) "omm") 'OMSequencerFile) (t nil))) (object (when obj-type (make-instance obj-type :name (pathname-name path))))) (when object (setf *current-loading-document* path) (register-document object) (unwind-protect (with-relative-ref-path path (with-open-file (in path :direction :input :if-does-not-exist nil) (unless (equal (read-line in nil :eof) :eof) ;; not empty ;; line #2 contains meta-data about the patch (let ((metadata (read-from-string (subseq (om-read-line in) 1)))) (if metadata (om-print-format "Converting from OM ~D (type '~A')" (list (car metadata) (cadr metadata)) "Import/Compatibility") (om-print-format "No header found in document..." nil "Import/Compatibility")) (load path) (if *om-current-persistent* ;;; filled in the patch-loading process (unwind-protect (progn (copy-contents *om-current-persistent* object) (setf (create-info object) (list (om-get-date) (om-get-date) *app-name* *version*) (window-size object) (eval (nth 4 metadata)) (saved? object) nil) object) ;;; need to close *om-current-persistent* to remove references etc. ? ) (unregister-document object)) )))) (unless previous-loading-document (clos::set-clos-initarg-checking t)) (setf *current-loading-document* previous-loading-document) )))) ;============================================================================ ; CONVERT ALL OM6-SAVE FUNCTIONS... ;============================================================================ ;====================================== ; REQUIRED LIBS ;====================================== ;;; called to lod libs prior to the patch (defun load-lib-for (list) (loop for libname in list do (require-library libname))) ;====================================== ; PATCH (MAIN SECTION) ;====================================== ;;; idea: consider an auto-alignment option for patches, ;;; => set a global variable "on" when an old patch is being loaded... ;;; Patch file ;;; macro allows us not to load any argument in &rest (defmacro om-load-patch1 (name boxes connections &rest ignore) ;;; among the ignored arguments are also the patch-pictures (declare (ignore ignore)) ;(let ((patch (make-instance 'OMPatchFile :name name))) ; (loop for box-code in boxes do ; (let ((box (eval box-code))) ; (when box (omng-add-element patch box)))) ; patch) `(let ((name-loaded ,name) (boxes-loaded ,boxes) (connections-loaded ,connections)) ;;; only top-level patch acually load their contents: (omng-load `(:patch (:name ,name-loaded) (:boxes .,(loop for box-code in boxes-loaded collect (eval box-code))) (:connections .,(loop for c in connections-loaded collect (format-imported-connection c))) ) ) )) ;;; internal sub-patch (defun om-load-patch-abs1 (name boxes connections &rest ignore) (declare (ignore ignore)) ;(let ((patch (make-instance 'OMPatchInternal :name name))) ; (loop for box-code in boxes do ; (let ((box (eval box-code))) ; (when box ; (omng-add-element patch box)))) ; patch) `(:patch (:name ,name) (:boxes .,(loop for box-code in boxes collect (eval box-code))) (:connections .,(loop for c in connections collect (format-imported-connection c))) ) ) ;====================================== ; LISP FUNCTIONS ;====================================== ;; Lisp-patch will return an "interned" version of the the form: ;; `(:textfun (:name ,name) (:text (:list "(lambda (x) (+ x 1))"))) ;;; Lisp-fun file (defun om-load-lisp-patch (name version expression) (omng-load (om-load-lisp-abspatch name version expression))) ;;; internal Lisp fun (defun om-load-lisp-abspatch (name version expression) `(:textfun (:info (:by "OM") (:version ,version)) (:name ,name) (:text (:list .,(string-to-list expression "$"))) )) ;====================================== ; ABSTRACTION BOX (PATCH/LISP FUN) ;====================================== ;;; textfun will also call this one. ;;; they load ok anyway. (defmethod om-load-boxcall ((self (eql 'abstraction)) name reference inputs position size value lock &rest rest) (declare (ignore value rest)) ;; reference contains the actual patch-code ;; (let ((type (if (equal (car reference) :textfun) :textfun :patch))) `(:box (:type :abstraction) (:reference ,reference) ;; contains the actual patch-code (:name ,name) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:h ,(if size (om-point-y size) 48)) (:lock ,(if lock (cond ((string-equal lock "x") :locked) ((string-equal lock "&") :eval-once)))) (:lambda ,(if lock (cond ((string-equal lock "l") :lambda) ((string-equal lock "o") :reference)))) (:inputs .,(mapcar #'eval inputs)) (:display :mini-view) ) ) ;====================================== ; EXTERNAL PATCH (BLUE) ;====================================== (defun load-om6-patch-from-relative-path (path-list) (declare (special *om-current-persistent* *current-loading-document*)) (let* ((name (car (last path-list))) ;;; try to locate the container-patch's OM6 workspace (om-workspace-root (when (find "elements" (pathname-directory *current-loading-document*) :test 'string-equal) (om-make-pathname :directory (subseq (pathname-directory *current-loading-document*) 0 (position "elements" (pathname-directory *current-loading-document*) :test 'string-equal))))) ;;; try to determine the original abstraction folder (doc-path-folder (when om-workspace-root (om-make-pathname :directory (append (pathname-directory om-workspace-root) (butlast path-list))))) ;;; determine the actual abstraction file (doc-path (or (and doc-path-folder (find name (om-directory doc-path-folder :type (doctype-to-ext-list :old)) :key 'pathname-name :test 'string-equal)) ;;; also search in-current-path: (find name (om-directory (om-make-pathname :directory *current-loading-document*) :type (doctype-to-ext-list :old)) :key 'pathname-name :test 'string-equal) ))) ;;; => found the patch (if (and doc-path (probe-file doc-path)) ;;; if the main form is a om-load-patch1, the returned form will be a patch (let* ((expected-type (cond ((string-equal (pathname-type doc-path) "omp") "Patch") ((string-equal (pathname-type doc-path) "oml") "LispFun") ((string-equal (pathname-type doc-path) "omm") "Sequencer"))) ;;; check if there is a registered open document with same name that is _not yet saved_ ;;; this happens in recursive patches or patches with several references to the same abstraction (registered-entry (find-if #'(lambda (entry) (and (string-equal (name (doc-entry-doc entry)) name) (string-equal (get-object-type-name (doc-entry-doc entry)) expected-type) (null (doc-entry-file entry)))) *open-documents*)) (new-patch (if registered-entry ;; the doc was already loaded (or considered so!) (doc-entry-doc registered-entry) (load-om6-file doc-path)))) ;;; return this: (omng-save-relative new-patch *current-loading-document*)) ;;; => patch not found ;;; search more broadly in non-saved registered documents (if it was previously open manually) (let ((registered-entry (find-if #'(lambda (entry) (and (string-equal (name (doc-entry-doc entry)) name) (null (doc-entry-file entry)))) *open-documents*))) (if registered-entry ;; the doc was already loaded (or considered so!) (let ((new-patch (doc-entry-doc registered-entry))) ;;; return this: (omng-save-relative new-patch *current-loading-document*)) ;;; no way to find anything: ask user (let ((user-located (and (om-y-or-n-dialog (format nil "Can you locate the original OM6 abstraction ~s ?~%(Not found in ~s)" name (reduce #'(lambda (s1 s2) (concatenate 'string s1 "/" s2)) (butlast (cdr path-list))))) (om-choose-file-dialog :prompt (format nil "Please: locate OM6 abstraction ~s." name) :directory *current-loading-document* :types (doctype-info :old))))) (if user-located ;;; got a patch (let ((new-patch (load-om6-file user-located))) ;;; return this: (omng-save-relative new-patch *current-loading-document*)) ;;; not found at all (progn (om-print-format "Abstraction box: ~s was not imported." (list name) "Import/Compatibility") ;;; will appear as "not found patch box" `(:patch-from-file (:pathname (:directory ,(cons :relative (butlast path-list))) (:name ,name))) ) ) )) )) )) ;;; reference is a relative-path list pointing to a Patch or Lisp-fun file (defmethod om-load-boxcall ((self (eql 'patch-box)) name reference inputs position size value lock &rest rest) (declare (ignore value rest)) (let ((loaded-reference (load-om6-patch-from-relative-path reference))) (om-load-boxcall 'abstraction name loaded-reference inputs position size value lock) )) ;====================================== ; BOXES (GENERAL) ;====================================== ;;; a box input (defun om-load-inputfun (class doc name value) (declare (ignore class doc)) `(:input (:type :standard) (:name ,name) (:value ,(omng-save value)))) ;;; a box input "keyword" (defun om-load-inputkeyword (class doc name value defval menu) (declare (ignore class doc name menu)) `(:input (:type :key) (:name ,value) (:value ,(omng-save defval)))) ;;; a box input with menu for different values (defun om-load-inputfunmenu1 (class doc name value items) (declare (ignore class doc items)) `(:input (:type :standard) (:name ,name) (:value ,(omng-save value)))) ;;; handle dispatch to 'lispfun or handle unknown box (defmethod om-load-boxcall ((class t) name reference inputs position size value lock &rest rest) (cond ((fboundp reference) (om-load-boxcall 'lispfun name reference inputs position size value lock)) ((and (function-changed-name reference) (fboundp (function-changed-name reference))) (let ((new-reference (function-changed-name reference))) (om-print-format "Function '~A' now replaced by '~A'" (list reference new-reference) "Import/Compatibility") (om-load-boxcall 'lispfun (string new-reference) new-reference inputs position size value lock))) (t ;; (om-print-format "Unknown function for box of type ~A: '~A'" (list class reference) "Import/Compatibility") ;; => will be signaled in om-load-from-id `(:box (:type :function) (:reference ,reference) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs .,(mapcar #'eval inputs)) )) )) ;; this is the automatic name given in OM6 to added "rest" inputs (defun is-om6-rest-arg (name) (find name '("add-input") :test 'string-equal)) (defun check-arg-for-new-name (reference name) (or (cadr (find name (update-arg-names reference) :key #'car :test #'string-equal)) (when (and (is-om6-rest-arg name) (fboundp reference)) (let ((rest-arglist (member '&rest (function-arglist reference)))) ;;; the last element in lambda-list is the name of the &rest arg (when rest-arglist (string (cadr rest-arglist))))) name)) (defmethod (setf frame-position) (pos box) pos) ;====================================== ; FUNCTION BOXES ;====================================== (defmethod om-load-boxcall ((self (eql 'lispfun)) name reference inputs position size value lock &rest rest) (let ((new-inputs (loop for formatted-in in (mapcar #'eval inputs) collect ;;; correct the type and eventually the name of box inputs (let ((name (check-arg-for-new-name reference (find-value-in-kv-list (cdr formatted-in) :name)))) (cond ((not (fboundp reference)) formatted-in) ((find name (mapcar #'symbol-name (function-main-args reference)) :test #'string-equal) `(:input (:type :standard) (:name ,name) (:value ,(find-value-in-kv-list (cdr formatted-in) :value)))) ((find name (mapcar #'symbol-name (function-optional-args reference)) :test #'string-equal) `(:input (:type :optional) (:name ,name) (:value ,(find-value-in-kv-list (cdr formatted-in) :value)))) ((find name (mapcar #'symbol-name (function-keyword-args reference)) :test #'string-equal) `(:input (:type :key) (:name ,name) (:value ,(find-value-in-kv-list (cdr formatted-in) :value)))) ((and (find '&rest (function-arglist reference)) (string-equal name (string (cadr (member '&rest (function-arglist reference)))))) `(:input (:type :optional) (:name ,name) (:value ,(find-value-in-kv-list (cdr formatted-in) :value)))) (t (om-print-format "Unknown input for function '~A': ~A" (list reference name) "Import/Compatibility") formatted-in)) )))) `(:box (:type :function) (:reference ,reference) (:x ,(om-point-x position)) (:y ,(om-point-y position)) ;;; importing the size of function boxes might not be necessary... (:w ,(and size (om-point-x size))) ;(:h ,(and size (om-point-y size))) (:lock ,(if lock (cond ((string-equal lock "x") :locked) ((string-equal lock "&") :eval-once)))) (:lambda ,(if lock (cond ((string-equal lock "l") :lambda) ((string-equal lock "o") :reference)))) (:inputs .,new-inputs) ) )) ;;; super filou (defmethod (setf numouts) (n (box-data list)) (setf (cdr (last box-data)) `((:outputs ,.(loop for i from 1 to n collect '(:output (:name "out")))) )) box-data) ;====================================== ; OBJECT BOXES ;====================================== (defmethod om-load-editor-box1 (name reference inputs position size value lock &optional fname editparams spict meditor pictlist show-name) (declare (ignore fname editparams meditor pictlist)) (let* ((ref-val (or value (and (find-class reference nil) (make-instance reference)))) (inputs (loop for formatted-in in (mapcar #'eval inputs) collect ;;; correct the type and eventually the name of box inputs (let ((name (check-arg-for-new-name reference (find-value-in-kv-list (cdr formatted-in) :name)))) (cond ((and (find-class reference nil) (string-equal name "self") (box-def-self-in reference)) ;;; this box has a special defval for "self" `(:input (:type :standard) (:name ,name) (:value ,(box-def-self-in reference)))) ((and (find-class reference nil) (find name (mapcar #'symbol-name (additional-class-attributes ref-val)) :test #'string-equal)) ;;; if the input has become a keywork input `(:input (:type :key) (:name ,name) (:value ,(find-value-in-kv-list (cdr formatted-in) :value)))) (t `(:input (:type ,(find-value-in-kv-list (cdr formatted-in) :type)) (:name ,name) (:value ,(find-value-in-kv-list (cdr formatted-in) :value)))) ))))) ;;; when a class has changed into something else... (when (update-reference reference) (setf reference (update-reference reference)) (setf value (update-value value))) `(:box (:type :object) (:reference ,reference) (:name ,name) (:value ,value) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(om-point-x size)) (:h ,(om-point-y size)) (:lock ,(if lock (cond ((string-equal lock "x") :locked) ((string-equal lock "&") :eval-once)))) (:showname ,show-name) (:display ,(if spict :mini-view :hidden)) (:inputs .,inputs) ) )) ;====================================== ; 'SLOTS' BOXES ;====================================== (defmethod om-load-boxcall ((self (eql 'slot)) name reference inputs position size value lock &rest rest) (declare (ignore value rest)) `(:box (:type :slots) (:reference ,reference) (:name ,(concatenate 'string (string-upcase reference) " SLOTS")) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:h ,(and size (om-point-y size))) (:lock ,(if lock (cond ((string-equal lock "x") :locked) ((string-equal lock "&") :eval-once)))) (:inputs .,(mapcar #'eval inputs))) ) ;====================================== ; SIMPLE VALUE BOXES ;====================================== (defmethod om-load-boxcall ((self (eql 'bastype)) name reference inputs position size value lock &rest rest) `(:box (:type :value) (:reference ,reference) (:value ,(omng-save value)) (:name ,name) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(om-point-x size)) (:h ,(om-point-y size))) ) ;====================================== ; INSTANCE BOXES ;====================================== (defclass ominstance () ((instance :accessor instance :initform nil) (edition-params :accessor edition-params :initform nil) (create-info :accessor create-info :initform nil) (doc :accessor doc :initform nil))) (defclass omlistinstance (ominstance) ()) ;;; only ominstances / omclasses have this (defun icon-from-lib (icon name) (declare (ignore name)) icon) (defun get-inst-from-globals (name) (make-instance 'OMGlobalVar :name name)) (defun om-load-boxinstance (name instance inputs position &optional fname size) (declare (ignore inputs fname size)) (if (typep instance 'OMGlobalVar) ;;; global var `(:box (:type :special) (:reference global) (:value nil) (:name ,name) (:x ,(om-point-x position)) (:y ,(om-point-y position)) ) (let* ((value (instance instance)) (type (type-of value))) ;;; instance (if (listp value) ;;; lists => collection `(:box (:type :object) (:reference collection) (:value (:object (:class collection) (:slots ((:obj-list ,(omng-save value)))))) (:name ,name) (:lock :locked) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:display :text)) (let () ;;; other sort of objects => object box (when (update-reference type) (setf type (update-reference type)) (setf value (update-value value))) `(:box (:type :object) (:reference ,type) (:name ,name) (:value ,value) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:lock :locked) (:showname t) (:display :mini-view) ) ))) ) ) ;============================================================================ ; CONNECTIONS ;============================================================================ (defun n-to-color (n) (case n (1 (om-def-color :blue)) (2 (om-def-color :red)) (3 (om-def-color :green)) (4 (om-def-color :orange)) (5 (om-def-color :pink)) (6 (om-def-color :dark-red)) (7 (om-def-color :dark-blue)) (8 (om-def-color :yellow)) (9 (om-def-color :black)) (10 (om-def-color :gray)) (11 (om-def-color :purple)) (12 (om-def-color :light-blue)) (13 (om-def-color :brown)) (14 (om-def-color :green2)) (15 (om-def-color :salmon)) (16 (om-def-color :steelblue)))) (defun format-imported-connection (c) (append `(:connection (:from (:box ,(nth 0 c) :out ,(nth 1 c))) (:to (:box ,(nth 2 c) :in ,(nth 3 c)))) (when (nth 5 c) `((:attributes (:color ,(n-to-color (nth 5 c))))) ) )) ;============================================================================ ; COMMENTS ;============================================================================ (defun str-with-nl (str) (map 'string #'(lambda (x) (if (equal x #\$) #\Newline x)) str)) (defun str-without-nl (str) (map 'string #'(lambda (x) (if (equal x #\Newline) #\$ x)) str)) (defun om-load-boxcomment (name size reference value position fname color style) (declare (ignore name value fname)) `(:comment (:text ,(str-with-nl reference)) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(om-point-x size)) (:h ,(om-point-y size)) (:text-font ,style) (:fgcolor ,color) (:border 0) ) ) ;============================================================================ ; OTHER BOXES ;============================================================================ ;;; IN BOX (defun om-load-boxin (name indice position docu &optional fname val fsize) (declare (ignore fname fsize)) `(:box (:type :io) (:reference (:in (:type omin) (:index ,indice) (:name ,name) (:doc ,docu))) (:name ,name) (:value ,(omng-save val)) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:outputs (:output (:name "out"))) )) ;;; OUT BOX (defun om-load-boxout (name indice position inputs &optional fname fsize) (declare (ignore fname fsize)) `(:box (:type :io) (:reference (:out (:type omout) (:name ,name) (:index ,indice))) (:name ,name) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:inputs .,(mapcar #'eval inputs)) )) ;;; REPEAT-N BOX (defmethod om-load-boxcall ((class t) name (reference (eql 'repeat-n)) inputs position size value lock &rest rest) (declare (ignore class name size value rest)) (when (string-equal lock "l") (om-print "REPEAT-N boxes can not be use in 'lambda' mode. In order to restore the patch, encapsulate it in a lambda-patch !" "Import/Compatibility")) `(:box (:type :special) (:reference repeat-n) (:x ,(om-point-x position)) (:y ,(om-point-y position)) ,(cons :inputs (append (mapcar #'eval inputs) '((:input (:type :optional) (:name "scope") (:value :global))))) (:lock ,(when lock (cond ((string-equal lock "x") :locked) ((string-equal lock "&") :eval-once)))) )) ;;; SEQUENCE BOX (defmethod om-load-seqbox (name reference inputs position sizeload value lock numouts) (declare (ignore name reference value numouts)) `(:box (:type :special) (:reference sequence) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and sizeload (om-point-x sizeload))) (:inputs .,(cons (eval (car inputs)) (mapcar #'(lambda (i) (declare (ignore i)) '(:input (:type :optional) (:name "op+"))) (cdr inputs)))) (:lock ,(when lock (cond ((string-equal lock "x") :locked) ((string-equal lock "&") :eval-once)))) ) ) ;;; these are useless and should just disappear (defmethod om-load-boxcall ((self (eql 'undefined)) name reference inputs position size value lock &rest trest) nil) ;====================================== ; OMLOOP ;====================================== ;;; This was used to save OMLoops ;;; OMloop is now just a normal patch (defmethod om-load-boxwithed1 ((class t) name reference inputs position size value lock boxes connec numouts &optional fname pictlist) `(:box (:type :abstraction) (:name ,name) (:reference (:loop-patch ;;; special reference to make adaptations -- see just below (:name ,name) (:boxes .,boxes) (:connections .,(loop for c in connec collect (format-imported-connection c))))) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:h ,(if size (om-point-y size) 48)) (:lock ,(if lock (cond ((string-equal lock "x") :locked) ((string-equal lock "&") :eval-once)))) (:lambda ,(if lock (cond ((string-equal lock "l") :lambda) ((string-equal lock "o") :reference)))) (:inputs .,inputs) (:display :mini-view) )) (defmethod om-load-boxcall ((class (eql 'genfun)) name (reference (eql 'listloop)) inputs position size value lock &rest rest) `(:box (:type :special) (:reference loop-list) (:name "list-loop") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs .,(remove nil (list `(:input (:type :standard) (:name "list") (:value ,(find-value-in-kv-list (cdr (eval (first inputs))) :value))) (when (second inputs) `(:input (:type :optional) (:name "by") (:value ,(find-value-in-kv-list (cdr (eval (second inputs))) :value))) ))) ))) (defmethod om-load-boxcall ((class (eql 'genfun)) name (reference (eql 'onlistloop)) inputs position size value lock &rest rest) `(:box (:type :special) (:reference loop-tail) (:name "tail-loop") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs .,(remove nil (list `(:input (:type :standard) (:name "list") (:value ,(find-value-in-kv-list (cdr (eval (first inputs))) :value))) (when (second inputs) `(:input (:type :optional) (:name "by") (:value ,(find-value-in-kv-list (cdr (eval (second inputs))) :value))) )))) )) (defmethod om-load-boxcall ((class (eql 'genfun)) name (reference (eql 'forloop)) inputs position size value lock &rest rest) `(:box (:type :special) (:reference loop-for) (:name "for") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs .,(remove nil (list `(:input (:type :standard) (:name "from") (:value ,(find-value-in-kv-list (cdr (eval (first inputs))) :value))) `(:input (:type :standard) (:name "to") (:value ,(find-value-in-kv-list (cdr (eval (second inputs))) :value))) (when (third inputs) `(:input (:type :optional) (:name "by") (:value ,(find-value-in-kv-list (cdr (eval (second inputs))) :value))) )))))) (defmethod om-load-boxcall ((class (eql 'genfun)) name (reference (eql 'whileloop)) inputs position size value lock &rest rest) `(:box (:type :special) (:reference loop-while) (:name "while") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs .,inputs))) ;;; COLLECT (defmethod om-load-boxcall ((class (eql 'genfun)) name (reference (eql 'listing)) inputs position size value lock &rest rest) `(:box (:type :special) (:reference collect) (:name "collect") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs .,inputs))) ;;; ACCUM (defmethod om-load-boxcall ((class (eql 'genfun)) name (reference (eql 'accumulator)) inputs position size value lock &rest rest) (declare (ignore name reference value numouts)) `(:box (:type :special) (:reference accum) (:name "accum") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs .,inputs) (:inputs (:input (:type :standard) (:name "data-in") (:value ,(find-value-in-kv-list (cdr (eval (first inputs))) :value))) ; !!! we invert the values of 2nd and 3rd input (:input (:type :standard) (:name "accum-function") (:value ,(find-value-in-kv-list (cdr (eval (third inputs))) :value))) (:input (:type :standard) (:name "init") (:value ,(find-value-in-kv-list (cdr (eval (second inputs))) :value))) ) )) (defmethod om-load-boxcall ((class (eql 'genfun)) name (reference (eql 'minim)) inputs position size value lock &rest rest) (om-print "Warning/OMLoop: MIN converted to ACCUM" "Import/Compatibility") `(:box (:type :special) (:reference accum) (:name "accum") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs (:input (:type :standard) (:name "data-in") (:value ,(find-value-in-kv-list (cdr (eval (first inputs))) :value))) (:input (:type :standard) (:name "accum-function") (:value om-min)) (:input (:type :standard) (:name "init") (:value nil)) ) )) (defmethod om-load-boxcall ((class (eql 'genfun)) name (reference (eql 'maxi)) inputs position size value lock &rest rest) (om-print "Warning/OMLoop: MAX converted to ACCUM" "Import/Compatibility") `(:box (:type :special) (:reference accum) (:name "accum") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs (:input (:type :standard) (:name "data-in") (:value ,(find-value-in-kv-list (cdr (eval (first inputs))) :value))) (:input (:type :standard) (:name "accum-function") (:value om-max)) (:input (:type :standard) (:name "init") (:value nil)) ) )) (defmethod om-load-boxcall ((class (eql 'genfun)) name (reference (eql 'sum)) inputs position size value lock &rest rest) (om-print "Warning/OMLoop: SUM converted to ACCUM" "Import/Compatibility") `(:box (:type :special) (:reference accum) (:name "accum") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs (:input (:type :standard) (:name "data-in") (:value ,(find-value-in-kv-list (cdr (eval (first inputs))) :value))) (:input (:type :standard) (:name "accum-function") (:value om+)) (:input (:type :standard) (:name "init") (:value 0)) ) )) (defmethod om-load-boxcall ((class (eql 'genfun)) name (reference (eql 'counter)) inputs position size value lock &rest rest) (om-print "Warning/OMLoop: COUNT converted to ACCUM" "Import/Compatibility") `(:box (:type :special) (:reference accum) (:name "accum") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs (:input (:type :standard) (:name "data-in") (:value ,(find-value-in-kv-list (cdr (eval (first inputs))) :value))) (:input (:type :standard) (:name "accum-function") (:value om-1+)) (:input (:type :standard) (:name "init") (:value 0)) ) )) ;;; used for the eachtime/iterate, finally/tempfinall, initdo/init-do boxes (defun convert-loop-box-inputs (inputs) (cons ;;; one standard input... (let* ((in (eval (car inputs))) (val (find-value-in-kv-list (cdr in) :value))) `(:input (:type :standard) (:name "action") (:value ,val))) ;;; .. and the rest of optional inputs (mapcar #'(lambda (i) (let* ((in (eval i)) (val (find-value-in-kv-list (cdr in) :value))) `(:input (:type :optional) (:name "action") (:value ,val)))) (cdr inputs)))) ;;; EACH-TIME (defmethod om-load-seqbox (name (reference (eql 'loopdo)) inputs position size value lock numouts) (declare (ignore name reference value numouts)) `(:box (:type :special) (:reference iterate) (:name "iterate") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs .,(convert-loop-box-inputs inputs)) ) ) ;;; INITDO (defmethod om-load-seqbox (name (reference (eql 'initdo)) inputs position size value lock numouts) (declare (ignore name reference value numouts)) `(:box (:type :special) (:reference init-do) (:name "init-do") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs .,(convert-loop-box-inputs inputs))) ) ;;; Finally box needs to be replaced by one or several output boxe(es) ;;; but we need to "simulate" a single box during the time of loading the patch ;;; in order to restore connections correctly (defclass TempFinally (OMPatchInit) ()) (defclass TempFinallyBox (OMPatchInitBox) ()) (defmethod special-box-p ((name (eql 'temp-finally))) t) (defmethod get-box-class ((self TempFinally)) 'TempFinallyBox) (defmethod box-symbol ((self TempFinally)) 'temp-finally) (defmethod omNG-make-special-box ((reference (eql 'temp-finally)) pos &optional init-args) (omNG-make-new-boxcall (make-instance 'TempFinally :name "finally") pos init-args)) ;;; FINALLY (defmethod om-load-seqbox (name (reference (eql 'finaldo)) inputs position size value lock numouts) (declare (ignore name reference value numouts)) `(:box (:type :special) (:reference temp-finally) (:name "temp-finally") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(and size (om-point-x size))) (:inputs .,(convert-loop-box-inputs inputs))) ) (defmethod convert-temp-finally-to-outputs ((self TempFinallyBox) (patch OMPatch)) (let ((init-x (box-x self)) (init-y (box-y self))) (loop for input in (inputs self) for i from 0 do (let ((newout (omng-make-new-boxcall (make-instance 'omout :name (format nil "output ~D" (1+ i))) (om-make-point (+ init-x (* i 60)) init-y)))) (omng-add-element patch newout) (setf (value (car (inputs newout))) (value input)) (when (car (connections input)) ;;; the input was connected... (let ((new-connection (omng-make-new-connection (from (car (connections input))) ;;; same "from" output (car (inputs newout))))) (omng-add-element patch new-connection))) )) (omng-remove-element patch self))) (defmethod connect-to-iterator-box ((self OMPatchLoopBox) (patch OMPatch)) (unless (connections (car (outputs self))) (let ((iterate-box (car (get-boxes-of-type patch 'OMPatchIteratorBox)))) ;;; in principle there will be one (and only one) iterate in the patch (when iterate-box (optional-input++ iterate-box) (omng-add-element patch (omng-make-new-connection (car (outputs self)) (car (last (inputs iterate-box)))))) ))) (defmethod flip-box-incoming-connections ((self OMBox) i1 i2) (let* ((in1 (nth i1 (inputs self))) (in2 (nth i2 (inputs self))) (c1 (car (connections in1))) (c2 (car (connections in2)))) (when c1 (setf (to c1) in2)) (when c2 (setf (to c2) in1)) )) ;;; SOME MODIFICATIONS MADE: ;;; - input order in accum ;;; - auto connect forloop/while loops etc. to iterate ;;; - convert the finally to several outputs (defmethod om-load-from-id ((id (eql :loop-patch)) data) (let ((patch (om-load-from-id :patch data))) ;;; do corrections (loop for box in (boxes patch) do (setf (box-y box) (- (box-y box) 40)) (typecase box (OMValueBox (initialize-size box)) (TempFinallyBox (convert-temp-finally-to-outputs box patch)) (OMPatchLoopBox (connect-to-iterator-box box patch)) (OMAccumBox (flip-box-incoming-connections box 1 2)) (otherwise nil))) patch)) ;====================================== ; DI-BOXES ;====================================== ;;; hacks: expressions contained in the OM6 patch format: (defmethod om-make-dialog-item ((type t) pos size text &rest args) nil) ;;; TEXT BOX ;;; hacks: expressions contained in the OM6 patch format: (defmethod om-make-dialog-item ((type (eql 'text-box)) pos size text &rest args) text) (defmethod om-load-editor-box1 (name (reference (eql 'text-box)) inputs position size value lock &optional fname editparams spict meditor pictlist show-name) (declare (ignore reference fname editparams meditor pictlist)) `(:box (:type :value) (:reference string) (:value ,value) (:name ,name) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(om-point-x size)) (:lock ,(if lock :locked nil)) (:inputs (:input (:type :optional) (:name "in") (:value ,(find-value-in-kv-list (cdr (eval (first inputs))) :value)))) )) ;;; TEXT-VIEW ;;; => Convert to textbuffer ;;; hacks: expressions contained in the OM6 patch format: (defmethod om-make-dialog-item ((type (eql 'text-view)) pos size text &rest args) (list text)) (defmethod om-set-dialog-item-text ((dummy list) text) (setf (car dummy) text)) (defmethod om-load-editor-box1 (name (reference (eql 'text-view)) inputs position size value lock &optional fname editparams spict meditor pictlist show-name) `(:box (:type :object) (:reference textbuffer) (:name "text-view") (:value (:object (:class textbuffer) (:slots ((:contents ,(omng-save (string-to-list (car value) (string #\Newline)))))))) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(om-point-x size)) (:h ,(om-point-y size)) (:lock ,(if lock :locked nil)) (:showname nil) (:display :mini-view) (:edition-params (:output-mode :text)) (:inputs (:input (:type :standard) (:name "self") (:value nil)) (:input (:type :standard) (:name "contents") (:value nil)) (:input (:type :key) (:name "output-mode") (:value :text)) ) )) ;;; SINGLE-ITEM-LIST / MULTI-ITEM-LIST ;;; hacks: expressions contained in the OM6 patch format: (defmethod om-make-dialog-item ((type (eql 'single-item-list)) pos size text &rest args) (mapcar #'list (getf args :range))) (defmethod om-make-dialog-item ((type (eql 'multi-item-list)) pos size text &rest args) (mapcar #'list (getf args :range))) (defmethod om-set-selected-item-index ((self list) index) (let ((ilist (list! index))) (loop for pos in ilist do (setf (nth pos self) (list (car (nth pos self)) t))))) (defmethod (setf di-data) (data list) nil) (defmethod om-load-editor-box1 (name (reference (eql 'single-item-list)) inputs position size value lock &optional fname editparams spict meditor pictlist show-name) (declare (ignore name lock reference fname editparams meditor pictlist)) (let* ((items-list value) (items (mapcar #'car items-list)) (selection-index (list (position t items-list :key #'cadr))) (selection (car (find t items-list :key #'cadr)))) `(:box (:type :interface) (:reference list-selection) (:name "list-selection") (:multiple-selection nil) (:value ,selection) (:items ,(omng-save items)) (:selection ,(omng-save selection-index)) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(om-point-x size)) (:h ,(om-point-y size)) (:inputs (:input (:type :key) (:name "items") (:value ,(if lock (omng-save items) (find-value-in-kv-list (cdr (eval (first inputs))) :value))))) ) )) (defmethod om-load-editor-box1 (name (reference (eql 'multi-item-list)) inputs position size value lock &optional fname editparams spict meditor pictlist show-name) (declare (ignore name lock reference fname editparams meditor pictlist)) (let* ((items-list value) (items (mapcar #'car items-list)) (selection-indices (loop for i from 0 for item in items-list when (cadr item) collect i)) (selection (loop for item in items-list when (cadr item) collect (car item)))) `(:box (:type :interface) (:reference list-selection) (:multiple-selection t) (:items ,(omng-save items)) (:selection ,(omng-save selection-indices)) (:value ,(omng-save selection)) (:name "list-selection") (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(om-point-x size)) (:h ,(om-point-y size)) (:inputs (:input (:type :key) (:name "items") (:value (if lock (omng-save items) (find-value-in-kv-list (cdr (eval (first inputs))) :value))))) ) )) ;;; MENU ;;; hacks: expressions contained in the OM6 patch format: (defmethod om-make-dialog-item ((type (eql 'pop-up-menu)) pos size text &rest args) (mapcar #'list (getf args :range))) (defmethod om-load-editor-box1 (name (reference (eql 'pop-up-menu)) inputs position size value lock &optional fname editparams spict meditor pictlist show-name) (declare (ignore name lock reference fname editparams meditor pictlist)) (let* ((items-list value) (items (mapcar #'(lambda (item) (if (stringp (car item)) (let ((read-item (ignore-errors (read-from-string (car item))))) (if (symbolp read-item) (car item) ;;; keep it as it was read-item)) ;;; we read numbers, lists, etc... (car item))) items-list)) (selection (position t items-list :key #'cadr))) `(:box (:type :interface) (:reference list-menu) (:name "list-menu") (:value ,(nth selection items)) (:items ,(omng-save items)) (:selection ,selection) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(om-point-x size)) (:inputs (:input (:type :key) (:name "items") (:value ,(if lock (omng-save items) (find-value-in-kv-list (cdr (eval (first inputs))) :value))))) ) )) ;;; CHECK-BOX ;;; hacks: expressions contained in the OM6 patch format: (defmethod om-make-dialog-item ((type (eql 'check-box)) pos size text &rest args) (list nil)) (defmethod om-set-check-box ((self list) val) (setf (car self) val)) (defmethod om-load-editor-box1 (name (reference (eql 'check-box)) inputs position size value lock &optional fname editparams spict meditor pictlist show-name) (declare (ignore name size lock reference fname editparams meditor pictlist)) `(:box (:type :interface) (:reference check-box) (:name "check-box") (:value ,(car value)) (:x ,(om-point-x position)) (:y ,(om-point-y position)) ) ) ;;; BUTTON (defmethod om-make-dialog-item ((type (eql 'button)) pos size text &rest args) text) (defmethod om-load-editor-box1 (name (reference (eql 'button)) inputs position size value lock &optional fname editparams spict meditor pictlist show-name) (declare (ignore name lock reference fname editparams meditor pictlist)) `(:box (:type :interface) (:reference button) (:name "button") (:text ,value) (:x ,(om-point-x position)) (:y ,(om-point-y position)) (:w ,(om-point-x size)) )) ;============================================================================ ; DATA: specific conversions for object types ;============================================================================ ;;;============================================================================ ;;; FROM EXTERNAL RESOURCES ;;;============================================================================ ;;; REdefinition of some OM6 load-utilities ;;; If the resource is not found we give a try in the in-file folder (defun search-for-resource (pathname) (let ((in-file-folder (get-pref-value :files :in-file))) (or (probe-file (om-make-pathname :name (pathname-name pathname) :type (pathname-type pathname) :directory in-file-folder)) pathname))) (defun om-load-if (pathname fun) (funcall fun pathname)) ;;; SDIFFILE (defmethod load-sdif-file ((path pathname)) (let ((sdiff (make-instance 'SDIFFILE)) (filepath (or (file-exists-p path) (search-for-resource path)))) (setf (file-pathname sdiff) filepath) (om-init-instance sdiff))) ;;; SOUND (defun load-sound (path &optional track vol pan) (declare (ignore track vol pan)) (let ((filepath (or (file-exists-p path) (search-for-resource path)))) (get-sound filepath))) ;;;============================================================================ ;;; PICTURES ;;;============================================================================ ;;; TODO: not supported yet (defclass picture () ()) (defclass patch-picture () ((pict-pos :accessor pict-pos :initarg :pict-pos) (pict-size :accessor pict-size :initarg :pict-size))) (defun restore-pict-path (path) path) (defun om-get-picture (name location) nil) (defun corrige (lis) lis) #| ;(let ((newpict (make-instance (quote patch-picture) :name "arrow_down_1" :source (quote user) :pict-pathname (restore-pict-path (restore-path nil)) :thepict (om-get-picture "arrow_down_1" (quote user)) :storemode :external :draw-params (quote (p 0 0 100 100)) :extraobjs nil))) (setf (pict-pos newpict) (om-make-point 619 173)) (setf (pict-size newpict) (om-make-point 50 112)) newpict) |# ;============================================================================ ;;; THE "COMPATIBILITY API": ;============================================================================ ;;; Also useful, from OM-LOAD-FROM-ID: ;;; The function FUNCTION-CHANGED-NAME allows converting a box to a new one. ;;; (e.g. (defmethod function-changed-name ((reference (eql 'old-name))) 'new-name)) ;;; When a reference has changed: ;;; e.g.: (defmethod update-reference ((ref (eql 'old-class))) 'new-class) (defmethod update-reference ((ref t)) nil) ;;; When the class exists (might have been redefined just for enabling import) ;;; and needs to be converted to something else ;;; e.g.: (defmethod update-value ((self 'old-class)) (make-instance 'new-class)) (defmethod update-value ((self t)) self) ;;; This compatibility system favors name-semantics over order: inputs will be correctly imported ;;; (in particular, if they have a default value) and connected if they have the same name in OM6. ;;; This permits same arguments to have a different position on the box. If they don't the following ;; function allows covering specific cases: ;;; When some box inputs have changed name ;;; redefine with eql-specializers for specific functions of class name ;;; e.g. (defmethod update-arg-names ((reference (eql 'function-or-class))) '(("old-arg-name" "new-arg-name"))) (defmethod update-arg-names ((ref t)) nil) ;====================================== ; compat earlier versions (OM4.x !) ;====================================== (defun om-load-patch (name boxes connections &rest ignore) (om-load-patch1 name boxes connections)) (defmethod om-point-x ((point number)) (- point (ash (ash point -16) 16))) (defmethod om-point-y ((point number)) (ash point -16)) ;====================================== ; old forms not supported: ;====================================== ; old-old: not exported by OM6 ;(defun om-load-ominstance1 (class name icon instance edparams &optional pictlist doc &rest rest) ) ;(defmethod om-load-boxcall ((self (eql 'editor)) name reference inputs position size value lock &rest rest) ) ;(defmethod om-load-boxcall ((self (eql 'slot)) name reference inputs position size value lock &rest rest) ) ;(defmethod om-load-boxcall ((self (eql 'comment)) name reference inputs position size value lock &rest rest) ) ;(defmethod om-load-boxcall ((self (eql 'mk-ins)) name reference inputs position size value lock &rest rest) ) ; Visual-OOP specifics: not supported ;(defun om-load-boxtypein (name type indice position docu keys defval &optional fname fsize) ) ;(defun om-load-initin (name type indice posi self? class &optional fsize) )
53,694
Common Lisp
.lisp
1,185
36.12827
387
0.546623
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e8a10d4669ffbd47e35de2cdb1639c5a9b36c124ab4b4c57b48f1b0e2b229be1
666
[ -1 ]
667
traduction.lisp
cac-t-u-s_om-sharp/src/visual-language/utils/traduction.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;========================================================================= ; Language translations for GUI components ;========================================================================= (in-package :om) ;;;(defpackage omstring) ;;; Mettre dans les prefs (defvar *languages* '(:en :fr)) (defvar *language* 0) (defun set-language (lang) (let ((pos (position lang *languages*))) (if pos (setf *language* (position lang *languages*)) (error "Language: ~A not found!" :lang)))) (defvar *om-strings* nil) (setf *om-strings* '((:a ("A" "La")) (:about ("About..." "A propos...")) (:absolute ("Absolute" "Absolue")) (:accepted-formats ("Accepted formats" "Format accept�s")) (:all-files ("All Files" "Tous les fichiers")) (:all-tracks ("All tracks" "Tous les tracks")) (:appearance ("Appearance" "Apparence")) (:apply ("Apply" "Appliquer")) (:apply-all ("Apply for all" "Appliquer pour tous")) (:apply-all-lost ("Apply for all lost files" "Appliquer pour tous les fichiers perdus")) (:as ("as" "sous")) (:audio-ctrl ("Audio Control" "Contr�les Audio")) (:b ("B" "Si")) (:bg-pict ("Background Picture" "Image de fond")) (:c ("C" "Do")) (:cadencies ("Cadencies" "Cadences")) (:cancel ("Cancel" "Annuler")) (:cannot-load ("Cannot load the file ~s" "Impossible de charger le fichier ~s")) (:channel ("Channel" "Canal")) (:channel-type ("~A Channel" "Canal ~A")) (:check-file-format ("Please check the file format and extension.")) (:choose-bgpict ("Choose Background Picture" "Choisir une image de fond")) (:choose-file ("Choose a file" "Choisissez un fichier")) (:choose-midi ("Choose a MIDI File" "Choisissez un fichier MIDI")) (:choose-snd ("Choose a sound file" "Choisissez un fichier audio")) (:chord ("Chord" "Accord")) (:click ("Click" "Cliquez")) (:close ("Close" "Fermer")) (:color ("Color" "Couleur")) (:commands ("Commands" "Commandes")) (:control-type ("~A Control" "Contr�les ~A")) (:copy ("Copy" "Copier")) (:cut ("Cut" "Couper")) (:d ("D" "R�")) (:degrees ("Degrees" "Degr�s")) (:delete ("Delete" "Supprimer")) (:done ("Done" "Termin�")) (:duration ("Duration" "Dur�e")) (:e ("E" "Mi")) (:edit ("Edit" "Editer")) (:editmenu ("Edit" "Edition")) (:envelope ("Envelope" "Enveloppe")) (:error ("Error" "Erreur")) (:error-msg ("An error of type ~A occurred" "Une erreur de type ~A s'est produite")) (:export ("Export" "Exportation")) (:export-format ("~A Export" "Exportation ~A")) (:exportmenu ("Export" "Exporter")) (:extract ("Extract" "Extrait")) (:f ("F" "Fa")) (:figuring ("Figuring" "Chiffrage")) (:file ("File" "Fichier")) (:file-error ("File Error" "Erreur")) (:file-format ("~A Files" "Fichiers ~A")) (:file-not-found ("File ~s not found" "Fichier ~s introuvable")) (:file-not-saved-msg ("The file ~s could not be saved" "Le fichier ~s n'a pas pu �tre enregistr�")) (:file-not-exists ("The document could not be open. This file does not exist anymore: ~s" "Le fichier n'a pas pu �tre ouvert. Le chemin sp�cifi� n'existe plus: ~s")) (:folder ("Folder" "Dossier")) (:fontsize ("Font Size" "Taille de police")) (:foreign-tones ("Foreign Tones" "Accidents")) (:from ("From" "De")) (:fromrulers ("From ruler units" "Unit�s des r�gles")) (:full-file ("Complete File" "Fichier entier")) (:g ("G" "Sol")) (:grid ("Grid" "Grille")) (:h-ruler ("Horizontal ruler (time)" "R�gle horizontale (temps)")) (:hand-mode ("Hand selection tool (move view)" "Mode \"Main\" (d�placer la vue)")) (:help ("Help" "Aide")) (:hide ("Hide" "Cacher")) (:image-import-error ("Error importing picture!" "Erreur d'importation de l'image!")) (:import ("Import" "Importation")) (:import-file ("Importing ~s" "Importation de ~s")) (:import-format ("~A Import" "Importation ~A")) (:import-error ("Importation error." "Erreur lors de l'importation.")) (:import-file-error ("Error importing ~s." "Erreur lors de l'importation de ~s.")) (:importmenu ("Import" "Importer")) (:interval-mode ("Interval selection tool" "Mode \"S�lection intervalle\"")) (:last-saved ("Last Saved" "Revenir � la version enregistr�e")) (:layout ("Layout" "Disposition")) (:lib-error ("~A Library Error." "Erreur de chargement de la biblioth�que ~A.")) (:lock ("Lock" "Bloquer")) (:look? ("Do you want to look for it?" "Voulez-vous le rechercher?")) (:lookingfor ("Looking for..." "Rechercher...")) (:major ("Major" "Majeur")) (:measure ("Measure" "Mesure")) (:measures ("Measures" "Mesures")) (:metric ("Metric" "M�trique")) (:metrics ("Metrics" "Mesures")) (:midi-ctrl ("MIDI Control" "Contr�les MIDI")) (:midifile ("MIDI File" "Fichier MIDI")) (:minor ("Minor" "Mineur")) (:modulations ("Modulations" "Modulations")) (:mosaic ("Mosaic" "Mosa�que")) (:name ("Name" "Nom")) (:new ("New" "Nouveau")) (:new-doc ("New Document" "Nouveau Document")) (:new-name ("New name" "Nouveau nom")) (:no ("No" "Non")) (:note ("Note" "Note")) (:offset ("Offset" "Offset")) (:offset-error ("Error: offset must be a positive integer!" "Erreur: les offset doivent �tre entiers et positifs!")) (:ok ("OK" "OK")) (:open ("Open" "Ouvrir")) (:param ("Parameter" "Param�tre")) (:params ("Parameters" "Param�tres")) (:partials ("Partials" "Partiels")) (:paste ("Paste" "Coller")) (:pict-unavailable ("Pict unavailable" "Image non disponible")) (:picture ("Picture" "Image")) (:picture-size ("Picture size" "Taille de l'image")) (:position ("Position" "Position")) (:preferences ("Preferences" "Pr�f�rences")) (:quit ("Quit" "Quitter")) (:reinitscales ("Reinit. views" "R�initialiser les �chelles")) (:remove-bg ("Remove Background" "Supprimer le fond")) (:rename ("Rename" "Renommer")) (:rhytmicseq ("Rhythmic Sequence" "S�quence Rythmique")) (:rulers ("Rulers" "R�gles")) (:rulers-settings ("Rulers Settings" "Param�tres des r�gles lat�rales")) (:save ("Save" "Enregistrer")) (:save-as ("Save As..." "Enregistrer sous...")) (:save-changes-in ("Save changes in ~s ?" "Enregistrer les modifications sur ~s ?")) (:sdiffile ("SDIF File" "Fichier SDIF")) (:selec-mode ("Mode \"S�lection objets\"" "Objects selection tool")) (:select-all ("Select All" "S�lectionner tout")) (:selection ("Selection" "S�lection")) (:sequence ("Sequence" "S�quence")) (:settings ("Settings" "Param�tres")) (:show ("Show" "Afficher")) (:size ("Size" "Taille")) (:snap ("Snap" "Magn�tisme")) (:sound ("Sound" "Audio")) (:tempo ("Tempo" "Tempo")) (:textcolor ("Text Color" "Couleur de texte")) (:textfont ("Text Font" "Police de texte")) (:timesign ("Time Signature" "M�trique")) (:to ("To" "�")) (:tonality ("Tonality" "Tonalit�")) (:track ("Track" "Track")) (:undo ("Undo" "Annuler")) (:unlock ("Unlock" "D�bloquer")) (:untitled ("Untitled" "Sans titre")) (:om-docversion-msg ("This document was saved in a higher version" "Ce document a �t� cr�� ou enregistr� dans une version plus r�cente")) (:upgrade-msg ("Please try to upgrade to this version or newer." "Veuillez mettre � jour le logiciel avant d'ouvrir ce document.")) (:v-ruler ("Vertical ruler" "R�gle verticale")) (:volume ("Volume" "Volume")) (:window ("Window" "Fen�tre")) (:window-size ("Window size" "Taille de la fen�tre")) (:yes ("Yes" "Oui")) (:ystep ("Y step" "Pas Y")) (:zoom-mode ("Zoom tool" "Mode \"Loupe\"")))) (defun add-om-strings (str-list) (loop for item in str-list do (when (find (car item) *om-strings* :test 'equal :key 'car) (print (format nil "WARNING: OM-STRING ~A REDEFINED" (car item))))) (setf *om-strings* (append str-list *om-strings*)) t) (defun om-str (strkey) (str-check (or (nth *language* (cadr (find strkey *om-strings* :test 'equal :key 'car))) (string-downcase strkey))))
11,776
Common Lisp
.lisp
188
42.68617
159
0.443911
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3d53ce71d661c3f359e3120ee36ac12340a563453a6882bc26e73df8d56b8b0d
667
[ -1 ]
668
help.lisp
cac-t-u-s_om-sharp/src/visual-language/utils/help.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ; Help patches (in-package :om) (defun menus-from-folder (folder) (append (loop for sub in (sort (om-directory folder :directories t :files nil) #'string< :key #'(lambda (path) (car (last (pathname-directory path))))) when (menus-from-folder sub) collect (om-make-menu (car (last (pathname-directory sub))) (menus-from-folder sub))) (loop for item in (sort (om-directory folder :type '("opat" "oseq")) #'string< :key #'pathname-name) collect (let ((path item)) (om-make-menu-item (pathname-name path) #'(lambda () (open-help-patch path))))) )) (defun get-base-help-patches-folder () (let* ((folder-name "help-patches/") (help-folder #+macosx(if (oa::om-standalone-p) (merge-pathnames folder-name (om-resources-folder)) (merge-pathnames folder-name (om-root-folder))) #-macosx(merge-pathnames folder-name (om-root-folder)) )) help-folder)) (defun make-base-help-menu-items () (menus-from-folder (get-base-help-patches-folder))) (defun get-lib-help-patches-foler (lib) (let ((thelib (if (stringp lib) (find-library lib) lib))) (when thelib (let ((help-folder (find-if #'(lambda (path) (and (member (car (last (pathname-directory path))) '("patches" "tutorials" "examples") :test #'string-equal) (menus-from-folder path))) (om-directory (mypathname thelib) :directories t :files nil)))) help-folder )))) (defun make-lib-help-menu (lib) (om-make-menu lib (menus-from-folder (get-lib-help-patches-foler lib)))) ;;; can be redefined for specific symbols (defmethod symbol-reference-patch-name ((self symbol)) (string self)) (defun get-symbol-help-patch (symb) (let* ((from-lib (or (and (omclass-p symb) (library (find-class symb))) (and (omgenericfunction-p symb) (library (fdefinition symb))))) (file-list (om-directory (if from-lib (get-lib-help-patches-foler from-lib) (get-base-help-patches-folder)) :recursive t :type '("opat") ))) (find (symbol-reference-patch-name symb) file-list :key 'pathname-name :test 'string-equal))) (defun open-help-patch (path) (declare (special *main-window*)) (om-print-format "Opening help-patch : ~A" (list (pathname-name path)) "HELP") (case (extension-to-doctype (pathname-type path)) (:old (import-doc-from-previous-om path)) (otherwise ;;; need to perform specific actions to abvoid opening it as a normal patch... (let ((doc (open-om-document path nil))) (setf (mypathname doc) nil) (setf (saved? doc) t) (update-document-path doc) ;; for the document manager (update-window-name (editor doc)) (when *main-window* (update-elements-tab *main-window*)) doc)) ))
3,953
Common Lisp
.lisp
81
38.975309
136
0.54477
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
934dd0eb032171e5fa4391a6e190d99547f38752a85eb7f968f8727d75af88e6
668
[ -1 ]
669
save.lisp
cac-t-u-s_om-sharp/src/visual-language/utils/save.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;============================ ;;; BASIC PERSISTANT FEATURES ;;;============================ (in-package :om) ;;;=================================== ;;; GENERAL SAVE FORMAT: ;;; ;(:IDENTIFIER ; (:ATTRIBUTE1 VALUE1 ; :ATTRIBUTE2 VALUE2 ; ...)) ;;;=================================== ;;; OMNG-SAVE is the general methods for saving something on disk ;;; OMNG-LOAD reloads and build Lisp/OM data from the saved list (defmethod omng-save ((self t)) 'NIL) (defmethod omng-load ((self t)) self) (defmethod omng-save ((self list)) (if (listp (cdr self)) (cons :list (mapcar 'omng-save self)) (list :cons (cons (omng-save (car self)) (omng-save (cdr self)))))) (defmethod omng-save ((self null)) 'NIL) (defmethod omng-save ((self number)) self) (defmethod omng-save ((self character)) self) ; (defmethod omng-save ((self symbol)) self) (defmethod omng-save ((self symbol)) (if (or (null (symbol-package self)) (find (symbol-package self) (append (list (find-package :om) (find-package :keyword) (find-package :common-lisp)) ;(package-use-list :om) ))) self `(:symbol ,(symbol-name self) ,(package-name (symbol-package self))) )) (defmethod om-load-from-id ((id (eql :symbol)) data) (let ((p (find-package (cadr data)))) (when p (intern (car data) p)))) ;;; CAR = IDENTIFIER, CDR = DATA ;;; OM-LOAD IS A SUB-PROCESS OF OMNG-LOAD ;;; THE FIRST ELEMENT IS PROCESSED CLOS BINDING TO OM-LOAD (defmethod omng-load ((self cons)) ;(let ((*package* (find-package :om))) (om-load-from-id (car self) (cdr self))) ;;; If ID is not recognized, the full list is loaded (defmethod om-load-from-id (id data) data) (defmethod om-load-from-id ((id (eql :list)) data) (mapcar 'omng-load data)) (defmethod om-load-from-id ((id (eql :cons)) data) (cons (omng-load (caar data)) (omng-load (cdar data)))) ;;;=================================== ;;; SAVE/LOAD METHODS FOR OBJECTS ;;;=================================== #| (defmethod omng-save ((self standard-object)) `(:object (:class ,(type-of self)) (:slots ,(loop for slot in (class-slots (class-of self)) when (slot-definition-initargs slot) collect (list (car (slot-definition-initargs slot)) (omng-save (slot-value self (slot-definition-name slot)) )))) )) (defmethod om-load-from-id ((id (eql :object)) data) (let ((class (find-value-in-kv-list data :class)) (slots (mapcar #'(lambda (slot) (list (car slot) (omng-load (cadr slot)))) (find-value-in-kv-list data :slots)))) (apply 'make-instance (cons class (reduce 'append slots))))) |# (defmethod additional-slots-to-save ((self t)) (additional-class-attributes self)) (defmethod excluded-slots-from-save ((self t)) nil) (defmethod condition-for-save-slot ((from t) slot) (and (or (slot-definition-initargs slot) (member (slot-definition-name slot) (additional-slots-to-copy from))) (not (member (slot-definition-name slot) (excluded-slots-from-copy from))) )) (defmethod save-slot-value ((self standard-object) slot-name val) (omng-save val)) ;;; objects copy/save only the slot with initargs and additional class attributes (defmethod omng-save ((self standard-object)) ; OMObject ;;; all slots with :initarg are saved (even indirect) (let* ((main-slots (loop for slot in (class-slots (class-of self)) when (and (slot-definition-initargs slot) (not (member (slot-definition-name slot) (excluded-slots-from-save self)))) collect (list (car (slot-definition-initargs slot)) (let ((slot-name (slot-definition-name slot))) (save-slot-value self slot-name (if (fboundp slot-name) (funcall slot-name self) (slot-value self slot-name)) )) ))) (add-slots (loop for add-slot in (additional-slots-to-save self) unless (find (intern-k add-slot) main-slots :key #'car) collect (list (intern-k add-slot) (omng-save ;(slot-value self add-slot) ;;; in _some cases_ the accessor is defined and not the slot... (funcall add-slot self) ))))) (append `(:object (:class ,(omng-save (type-of self))) (:slots ,main-slots)) (when add-slots `((:add-slots ,add-slots)) )))) (defmethod om-load-from-id ((id (eql :object)) data) (let* ((class-name (omng-load (find-value-in-kv-list data :class))) (ref-class (or (update-reference class-name) class-name)) (class (find-class ref-class nil))) (if class (let ((slots (remove nil (mapcar #'(lambda (slot) (if (find (car slot) (class-slots class) :key #'(lambda (slotdef) (car (slot-definition-initargs slotdef)))) (list (car slot) (omng-load (cadr slot))) (om-beep-msg "LOAD: Slot '~A' not found in class ~A !!" (car slot) (string-upcase ref-class)))) (find-value-in-kv-list data :slots)))) (more-slots (mapcar #'(lambda (slot) (car slot) (list (car slot) (omng-load (cadr slot)))) (find-value-in-kv-list data :add-slots)))) (let ((object (apply 'make-instance (cons ref-class (reduce 'append slots))))) (loop for slot in more-slots ;; when (slot-exists-p object (car slot)) ;; do (setf (slot-value object (car slot)) (cadr slot)) do (set-slot-val object (symbol-name (car slot)) (cadr slot)) ) (om-init-instance object nil) )) (om-beep-msg "LOAD: Class ~A not found !!" ref-class) ))) ; (omng-save (make-instance 'bpf)) ; (om-load-from-id :om-object '((:class bpf) (:slots ((:x-points (0 100 200)) (:y-points (0 700 200)) (:decimals 0))) (:add-slots ((color nil) (name "BPF"))))) ;;;=================================== ;;; SAVE/LOAD METHODS FOR ;;; BASIC TYPES ;;;=================================== (defmethod omng-save ((self pathname)) `(:pathname (:directory ,(pathname-directory self)) (:device ,(pathname-device self)) (:host ,(pathname-host self)) (:name ,(pathname-name self)) (:type ,(pathname-type self)))) (defmethod om-load-from-id ((id (eql :pathname)) data) (let* ((dir (find-value-in-kv-list data :directory)) (path (om-make-pathname :directory dir :device (find-value-in-kv-list data :device) :host (find-value-in-kv-list data :host) :name (find-value-in-kv-list data :name) :type (find-value-in-kv-list data :type)))) (if (equal (car dir) :relative) (restore-path path *relative-path-reference*) ;(merge-pathnames path *relative-path-reference*) path))) ; (restore-path #P"../a/b/f.wav" #P"/Users/me/Desktop/patch.opat") ; (merge-pathnames #P"../a/b/f.wav" #P"/Users/me/Desktop/patch.opat") ; => restore-path works better... (defmethod omng-save ((self gp::font-description)) `(:font (:face ,(om-font-face self)) (:size ,(om-font-size self)) (:style ,.(om-font-style self)) )) (defmethod om-load-from-id ((id (eql :font)) data) (om-make-font (find-value-in-kv-list data :face) (find-value-in-kv-list data :size) :style (find-values-in-prop-list data :style) )) (defmethod omng-save ((self font-or-nil)) `(:font-or-nil (:font ,(omng-save (font-or-nil-font self))) (:t-or-nil ,(font-or-nil-t-or-nil self)))) (defmethod om-load-from-id ((id (eql :font-or-nil)) data) (make-font-or-nil :font (omng-load (find-value-in-kv-list data :font)) :t-or-nil (find-value-in-kv-list data :t-or-nil))) (defmethod omng-save ((self oa::ompoint)) `(:point ,(om-point-x self) ,(om-point-y self))) (defmethod om-load-from-id ((id (eql :point)) data) (apply 'om-make-point data)) (defmethod omng-save ((self oa::omcolor)) `(:color ,(om-color-r self) ,(om-color-g self) ,(om-color-b self) ,(om-color-a self))) (defmethod om-load-from-id ((id (eql :color)) data) (apply 'om-make-color data)) (defmethod omng-save ((self color-or-nil)) `(:color-or-nil (:color ,(omng-save (color-or-nil-color self))) (:t-or-nil ,(color-or-nil-t-or-nil self)))) (defmethod om-load-from-id ((id (eql :color-or-nil)) data) (make-color-or-nil :color (omng-load (find-value-in-kv-list data :color)) :t-or-nil (find-value-in-kv-list data :t-or-nil))) (defmethod sethash ((self hash-table) (entry t) (value t)) (setf (gethash entry self) value)) (defmethod omNG-save ((self hash-table)) (let (keylist vallist) (maphash #'(lambda (key val) (push key keylist) (push val vallist)) self) (setf keylist (reverse keylist) vallist (reverse vallist)) `(:hash-table (:keys ,(omng-save keylist)) (:vals ,(omng-save vallist)) (:test ,(hash-table-test self))))) (defmethod om-load-from-id ((id (eql :hash-table)) data) (let ((res (make-hash-table :test (find-value-in-kv-list data :test)))) (loop for key in (omng-load (find-value-in-kv-list data :keys)) for val in (omng-load (find-value-in-kv-list data :vals)) do (setf (gethash key res) val)) res)) (defmethod omng-save ((self array)) ;;faire les types etc aussi (let* ((dimensions (array-dimensions self)) (vals (loop for i from 0 to (1- (reduce '+ dimensions)) collect (row-major-aref self i)))) `(:array (:dimensions ,(omng-save dimensions)) (:content-as-list ,(omng-save vals))))) (defmethod om-load-from-id ((id (eql :array)) data) (let ((res (make-array (omng-load (find-value-in-kv-list data :dimensions))))) (loop for val in (omng-load (find-value-in-kv-list data :content-as-list)) for i from 0 do (setf (row-major-aref res i) val)) res)) (defmethod omng-save ((self string)) self) (defmethod omng-save ((self function)) nil) (defmethod omng-save ((self number-or-nil)) `(:number-or-nil (:number ,(number-or-nil-number self)) (:t-or-nil ,(number-or-nil-t-or-nil self)))) (defmethod om-load-from-id ((id (eql :number-or-nil)) data) (make-number-or-nil :number (find-value-in-kv-list data :number) :t-or-nil (find-value-in-kv-list data :t-or-nil))) ;;;=================================== ;;; SAVE/LOAD METHODS FOR ;;; SPECIAL OBJECTS ;;;=================================== (defmethod save-patch-contents ((self OMProgrammingObject) &optional (box-values nil)) `(,(object-doctype self) (:name ,(name self)) (:doc ,(doc self)) (:info (:created ,(nth 0 (create-info self))) (:modified ,(nth 1 (create-info self))) (:by ,(nth 2 (create-info self))) (:version ,(nth 3 (create-info self)))) (:window (:size ,(when (window-size self) (list (om-point-x (window-size self)) (om-point-y (window-size self))))) (:position ,(when (window-pos self) (list (om-point-x (window-pos self)) (om-point-y (window-pos self)))))) )) ;;;============= ; PATCH / SEQUENCER ;;;============= (defmethod save-patch-contents ((self OMPatch) &optional (box-values nil)) (append (call-next-method self t) `((:grid ,(grid self)) (:lock ,(lock self)) (:boxes ,.(loop for box in (boxes self) for i = 0 then (+ i 1) collect (append (if box-values (omng-save-with-value box) (omng-save box)) (list (list :id i))))) (:connections ,.(save-connections-from-boxes (boxes self)))))) (defmethod omng-save ((self OMPatch)) (save-patch-contents self)) ;;; when we save an abstraction box.. ;;; I think this is never called anymore since OMBoxAbstraction handles its own omng-save ;(defmethod omng-save ((self OMPatchFile)) ; `(:patch-from-file ,(namestring (mypathname self)))) (defmethod omng-save-relative ((self OMPatchFile) ref-path) `(:patch-from-file ,(if (mypathname self) (omng-save (relative-pathname (mypathname self) ref-path)) (omng-save (pathname (name self)))))) (defmethod load-patch-contents ((patch OMPatch) data) (let ((*required-libs-in-current-patch* nil)) (let ((name (find-value-in-kv-list data :name)) (info (find-values-in-prop-list data :info)) (win (find-values-in-prop-list data :window))) ; in principle the name is determined by the pathname (unless (name patch) (setf (name patch) name)) (setf (create-info patch) (list (find-value-in-kv-list info :created) (find-value-in-kv-list info :modified) (find-value-in-kv-list info :by) (find-value-in-kv-list info :version)) (doc patch) (find-value-in-kv-list data :doc) ) (when win (let ((pos (find-value-in-kv-list win :position)) (size (find-value-in-kv-list win :size))) (when pos (setf (window-pos patch) (omp (car pos) (cadr pos)))) (when size (setf (window-size patch) (omp (car size) (cadr size)))))) ;;; set loaded? now in case of recursive (self-included) patched (setf (loaded? patch) t) (let* ((saved-boxes (find-values-in-prop-list data :boxes)) (saved-connections (find-values-in-prop-list data :connections))) ;;; we load the i/o boxes first (so they are taken into account, e.g. on self-embedded patch boxes ;;; but we must not change the order of boxes in the list because of the connections ;;; => double loop (let ((boxes (loop for saved-box in saved-boxes collect (if (equal :io (find-value-in-kv-list (cdr saved-box) :type)) (let ((box (omng-load saved-box))) (omng-add-element patch box) box) nil) ;; do it in the next round ))) ;;; load other boxes (loop for box in boxes for i = 0 then (+ i 1) when (null box) do (let ((box (omng-load (nth i saved-boxes)))) (setf (nth i boxes) box) (omng-add-element patch box) )) (mapc #'(lambda (c) (omng-add-element patch c)) (restore-connections-to-boxes saved-connections boxes)) )) (setf (lock patch) (find-value-in-kv-list data :lock)) (setf (grid patch) (find-value-in-kv-list data :grid)) patch))) (defmethod om-load-from-id ((id (eql :patch)) data) (let ((patch (make-instance 'OMPatchInternal))) (when data (load-patch-contents patch data)) patch)) (defmethod om-load-from-id ((id (eql :patch-from-file)) data) (let* ((path (omng-load (car data))) (checked-path (and (pathname-directory path) ;; normal case (check-path-using-search-path path))) (patch (if checked-path (load-doc-from-file checked-path :patch) ;;; no pathname-directory can occur while loading old patch abstractions from OM6 ;;; in this case we look for a not-yet-save file with same name in registered documents (let ((registered-entry (find (pathname-name path) *open-documents* :test 'string-equal :key #'(lambda (entry) (name (doc-entry-doc entry)))))) (when registered-entry (doc-entry-doc registered-entry))) ))) (unless patch (om-beep-msg "PATCH NOT FOUND: ~S !" path) (setf patch (make-instance'OMPatchFile :name (pathname-name path))) (setf (mypathname patch) path)) patch)) ;;;================================= ;;; LISP FUNCTION ;;;================================= (defmethod save-patch-contents ((self OMLispFunction) &optional (box-values nil)) (append (call-next-method self t) `((:text ,(omng-save (text self)))))) (defmethod omng-save ((self OMLispFunction)) (save-patch-contents self)) (defmethod om-load-from-id ((id (eql :textfun)) data) (let ((fun (make-instance 'OMLispFunctionInternal))) (when data (load-patch-contents fun data)) fun)) (defmethod load-patch-contents ((fun OMLispFunction) data) (let ((name (find-value-in-kv-list data :name)) (info (find-values-in-prop-list data :info)) (win (find-values-in-prop-list data :window))) (unless (name fun) (setf (name fun) name)) (setf (text fun) (omng-load (find-value-in-kv-list data :text)) (create-info fun) (list (find-value-in-kv-list info :created) (find-value-in-kv-list info :modified) (find-value-in-kv-list info :by) (find-value-in-kv-list info :version) ) (doc fun) (find-value-in-kv-list data :doc) ) (when win (let ((pos (find-value-in-kv-list win :position)) (size (find-value-in-kv-list win :size))) (when pos (setf (window-pos fun) (omp (car pos) (cadr pos)))) (when size (setf (window-size fun) (omp (car size) (cadr size)))))) (setf (loaded? fun) t) fun)) ;;;================================= ;;; INs and OUTs ... ;;;================================= (defmethod omng-save ((self OMIn)) `(:in (:type ,(type-of self)) (:index ,(index self)) (:name ,(name self)) (:doc ,(doc self)))) (defmethod omng-save ((self OMOut)) `(:out (:type ,(type-of self)) (:name ,(name self)) (:index ,(index self)) (:doc ,(doc self)))) (defmethod om-load-from-id ((id (eql :in)) data) (let* ((type (find-value-in-kv-list data :type)) (index (find-value-in-kv-list data :index)) (name (find-value-in-kv-list data :name)) (defval (find-value-in-kv-list data :defval)) (doc (find-value-in-kv-list data :doc))) (if (find-class type nil) (let ((in (make-instance type :name name :defval (omng-load defval) :doc doc))) (setf (index in) index) in) (om-beep-msg "Warning: Input of type ~A could not be loaded (unknown type)." type)) )) (defmethod om-load-from-id ((id (eql :out)) data) (let* ((type (find-value-in-kv-list data :type)) (index (find-value-in-kv-list data :index)) (name (find-value-in-kv-list data :name)) (doc (find-value-in-kv-list data :doc))) (if (find-class type nil) (let ((out (make-instance type :name name :doc doc))) (setf (index out) index) out) (om-beep-msg "Warning: Input of type ~A could not be loaded (unknown type)." type)) )) ;;;============= ; BOXES ;;;============= (defmethod box-type ((self OMBox)) :unknown) (defmethod box-type ((self OMValueBox)) :value) (defmethod box-type ((self OMFunBoxCall)) :function) (defmethod box-type ((self OMBoxEditCall)) :object) (defmethod box-type ((self OMSlotsBox)) :slots) (defmethod box-type ((self OMInOutBox)) :io) (defmethod box-type ((self OMBoxAbstraction)) :abstraction) (defmethod box-type ((self OMInterfaceBox)) :interface) (defmethod box-type ((self OMPatchComponentBox)) :special) (defmethod save-box-reference ((self OMBox)) (omng-save (reference self))) (defmethod save-box-reference ((self OMBoxAbstraction)) (let ((patch (reference self)) (container (find-persistant-container self))) (if (and (is-persistant patch) container) (let ((curr-path (mypathname patch))) (unless curr-path ;;; probably a not-saved loaded/converted abstraction (om-print-format "The abstraction ~s was saved on disk in ~s." (list (name patch) (namestring (om-make-pathname :directory (mypathname container)))) "Import/Compatibility") (setf (mypathname patch) (om-make-pathname :name (name patch) :directory (mypathname container) :type (doctype-to-extension (object-doctype patch)))) (save-document patch) (when (frame self) (om-invalidate-view (frame self))) ) ;;; save the :patch-from-file relatively to the next persistent container (omng-save-relative patch (mypathname container))) (call-next-method) ))) ;;; THE CASE WHERE THE REFERENCE OBJECT IS FROM A LIBRARY (defmethod save-box-library ((self t)) nil) (defmethod save-box-library ((self OMGFBoxcall)) (get-ref-library (fdefinition (reference self)))) (defmethod save-box-library ((self OMBoxEditCall)) (get-ref-library (find-class (reference self)))) (defmethod get-ref-library ((self t)) nil) (defmethod get-ref-library ((self OMGenericFunction)) (library self)) (defmethod get-ref-library ((self OMClass)) (library self)) ;;; save the outputs only if some are reactive, ;;; otherwise it is not useful in the general case ;;; update : now it is useful if the reference is lost (defmethod save-outputs? ((self OMBox)) ;(find t (outputs self) :key 'reactive) t) (defmethod save-state ((i box-input)) (cond ((subtypep (type-of i) 'box-optional-input) `(:input (:type :optional) (:name ,(name i)) (:value ,(omng-save (value i))) (:reactive ,(reactive i)))) ((subtypep (type-of i) 'box-keyword-input) `(:input (:type :key) (:name ,(name i)) (:value ,(omng-save (value i))) (:reactive ,(reactive i)))) (t `(:input (:type :standard) (:name ,(name i)) (:value ,(omng-save (value i))) (:reactive ,(reactive i)))) )) (defmethod save-state ((o box-output)) `(:output (:name ,(name o)) (:reactive ,(reactive o)))) (defmethod excluded-properties-from-save ((self OMBox)) nil) (defmethod omng-save ((self OMBox)) (cons :box (append (and (save-box-library self) `((:library ,(save-box-library self)))) `((:type ,(box-type self)) (:reference ,(save-box-reference self)) (:group-id ,(group-id self)) (:name ,(name self)) (:x ,(box-x self)) (:y ,(box-y self)) (:w ,(box-w self)) (:h ,(box-h self))) (remove nil (mapcar #'(lambda (prop) (when (and ;;; the slot/accessor exists (or (slot-exists-p self (nth 3 prop)) (fboundp (nth 3 prop))) ;;; e.g. when specific a accessor is defined ; avoid redundant storage if these attribuets are also declared as (editable) properties (not (find (car prop) '(:group-id :name ::x :y :w :h))) (not (find (car prop) (excluded-properties-from-save self))) ) (list (car prop) (omng-save (if (slot-exists-p self (nth 3 prop)) (slot-value self (nth 3 prop)) (funcall (nth 3 prop) self) ))))) (get-flat-properties-list self))) `((:inputs ,.(mapcar #'(lambda (i) (save-state i)) (inputs self)))) (when (save-outputs? self) `((:outputs ,.(mapcar #'(lambda (o) (save-state o)) (outputs self))))) ))) (defmethod restore-inputs ((self OMBox) inputs) (ignore-errors (loop for input-desc in inputs for i from 0 do (let ((type (find-value-in-kv-list (cdr input-desc) :type)) (name (find-value-in-kv-list (cdr input-desc) :name)) (val (find-value-in-kv-list (cdr input-desc) :value)) (reac (find-value-in-kv-list (cdr input-desc) :reactive))) (case type (:standard (let ((in (or (find name (inputs self) :test 'string-equal :key 'name) (nth i (inputs self))))) ;;; the name was not found, but it may have changed... ? (if in (setf (value in) (omng-load val) (reactive in) reac) (progn (om-print-dbg "input ~s not found on box ~A" (list name (name self)) "restore-inputs") ;;; beta: at impoprting old patches it is possible that an optional be unrecognized ;;; (because the name has changed) ;;; in this case it is passed as a :standard input : we can try to pop-it out (more-optional-input self :name name :value (omng-load val) :reactive reac) ) ))) (:optional (more-optional-input self :name name :value (omng-load val) :reactive reac)) (:key (more-keyword-input self :key name :value (omng-load val) :reactive reac)) ))))) (defmethod restore-outputs ((self OMBox) outputs) (loop for output-desc in outputs do (let* ((name (find-value-in-kv-list (cdr output-desc) :name)) (reac (find-value-in-kv-list (cdr output-desc) :reactive)) (out (find name (outputs self) :test 'string-equal :key 'name))) (if out (setf (reactive out) reac) (om-print-dbg "output ~s not found on box ~A" (list name (name self)) "restore-outputs")) ))) (defmethod save-value ((self OMBox)) `(:value ,(omng-save (car (value self))))) ;;; called for instance in the sequencer (defmethod omng-save-with-value ((self OMBox)) (append (omng-save self) (unless (lambda-state self) (list (save-value self))))) ;;; OMBoxEditCall always save the value ;;; + it is a subclass of ObjectWithEditor (save the editor size and pos) (defmethod omng-save ((self OMBoxEditCall)) (append (call-next-method) (append `((:window (:size ,(when (window-size self) (list (om-point-x (window-size self)) (om-point-y (window-size self))))) (:position ,(when (window-pos self) (list (om-point-x (window-pos self)) (om-point-y (window-pos self))))) ) (:edition-params ,.(mapcar #'(lambda (p) `(,(car p) ,(omng-save (cadr p)))) (edition-params self)))) (unless (lambda-state self) (list (save-value self)))))) ;;; OMValueBox always save the value (defmethod omng-save ((self OMValueBox)) (append (call-next-method) (list (save-value self)))) ;;; for compatibility, in case some functions have changed name (defmethod function-changed-name ((reference t)) nil) (defmethod omNG-make-special-box ((symbol t) pos &optional args) nil) (defmethod om-load-from-id ((id (eql :box)) data) ; (print (list "load BOX" (find-value-in-kv-list data :type))) (let* ((type (find-value-in-kv-list data :type)) (loaded-reference (omng-load (find-value-in-kv-list data :reference))) (reference (or (update-reference loaded-reference) loaded-reference)) (x (find-value-in-kv-list data :x)) (y (find-value-in-kv-list data :y)) (w (find-value-in-kv-list data :w)) (h (find-value-in-kv-list data :h)) (name (find-value-in-kv-list data :name)) (pos (omp x y)) (size (and (or w h) (omp w h))) (group-id (find-value-in-kv-list data :group-id)) (val (omng-load (find-value-in-kv-list data :value))) (inputs (find-values-in-prop-list data :inputs)) (outputs (find-values-in-prop-list data :outputs)) (box (case type (:value (omng-make-new-boxcall 'value pos val)) (:function (if (fboundp reference) (omng-make-new-boxcall reference pos) (let ((new-name (function-changed-name reference))) (if (and new-name (fboundp new-name)) (progn (setf name (string new-name)) (omng-make-new-boxcall new-name pos)) (progn (om-beep-msg "unknown function: ~A" reference) (omng-make-lost-fun-box reference pos)) )) )) ((or :abstraction :patch :textfun) ;;; :patch and :textfun are for compatibility: in principle all boxes are now saved with type :abstraction (let ((box (omng-make-new-boxcall (omng-load reference) pos))) ;; sometimes (e.g. in sequencers) the patches save their value (when box (setf (value box) (list val)) (setf name (name (reference box))) ;;; we forget about the saved box name... ) box)) (:io (omng-make-new-boxcall (omng-load reference) pos)) (:special (let ((box (if (symbolp reference) (omNG-make-special-box reference pos) (omng-make-new-boxcall (omng-load reference) pos)))) (when box (set-value box (list val))) box)) (:interface (let ((box (omNG-make-special-box reference pos))) (set-value box (list val)) (restore-state box (omng-load (find-value-in-kv-list data :state))) box)) (:object (if (find-class reference nil) (omng-make-new-boxcall (find-class reference nil) pos val) (progn (om-beep-msg "unknown class: ~A" reference) (omng-make-lost-class-box reference pos)))) (:slots (if (find-class reference nil) (omng-make-new-boxcall 'slots pos (find-class reference nil)) (progn (om-beep-msg "unknown class: ~A" reference) (omng-make-lost-slots-box reference pos)))) (otherwise (om-beep-msg "unknown box type: ~A" type))))) ;;; DO SOMETHING FOR UNKNOWN BOX ID (kind of 'dead boxes') (when box (load-box-attributes box data) (when inputs (restore-inputs box inputs)) (when outputs (restore-outputs box outputs)) (when group-id (setf (group-id box) group-id)) (loop for property in (get-flat-properties-list box) do (let ((prop (find-value-in-kv-list data (car property)))) (when prop (set-property box (car property) (omng-load prop))))) ;;; overwrites the one in properties (when name (set-name box name)) ;;; some properties (e.g. icon-pos) can modify the size of the box: better do it at the end (when size (let ((corrected-size (om-max-point (minimum-size box) size))) (setf (box-w box) (om-point-x corrected-size) (box-h box) (om-point-y corrected-size)))) ) box)) (defmethod load-box-attributes ((box t) data) nil) (defmethod load-box-attributes ((box OMBoxEditCall) data) (let ((edwin-info (find-values-in-prop-list data :window)) (ed-params (find-values-in-prop-list data :edition-params))) (when edwin-info (let ((wsize (find-value-in-kv-list edwin-info :size)) (wpos (find-value-in-kv-list edwin-info :position))) (when wpos (setf (window-pos box) (omp (car wpos) (cadr wpos)))) (when wsize (setf (window-size box) (omp (car wsize) (cadr wsize)))) )) (when ed-params (setf (edition-params box) (mapcar #'(lambda (p) (list (car p) (omng-load (cadr p)))) ed-params))) box)) ;;;============= ; COMMENTS ;;;============= (defmethod omng-save ((self OMComment)) (cons :comment (append `((:x ,(box-x self)) (:y ,(box-y self)) (:w ,(box-w self)) (:h ,(box-h self))) (mapcar #'(lambda (prop) (list (car prop) (omng-save (slot-value self (nth 3 prop))))) (get-flat-properties-list self)) `((:text ,(value self)))))) (defmethod om-load-from-id ((id (eql :comment)) data) (let* ((x (find-value-in-kv-list data :x)) (y (find-value-in-kv-list data :y)) (w (find-value-in-kv-list data :w)) (h (find-value-in-kv-list data :h)) (pos (omp x y)) (size (and (or w h) (omp w h))) (text (omng-load (find-value-in-kv-list data :text))) (comment (omng-make-new-comment text pos))) (when comment (when size (setf (box-w comment) (om-point-x size) (box-h comment) (om-point-y size))) (loop for property in (get-flat-properties-list comment) do (let ((prop (find-value-in-kv-list data (car property)))) (when prop (set-property comment (car property) (omng-load prop))))) (let ((fit-size (fit-comment-size comment (omp (box-w comment) (box-w comment)) t))) (setf (box-w comment) (om-point-x fit-size) (box-h comment) (om-point-y fit-size))) ) comment)) ;;;============= ; PACKAGE ;;;============= (defmethod om-load-from-id ((id (eql :package)) data) (let* ((name (find-value-in-kv-list data :name)) (pack (make-instance 'OMPackage :name (or name "Untitled Package")))) (mapc #'(lambda (class) (addclass2pack class pack)) (find-values-in-prop-list data :classes)) (mapc #'(lambda (fun) (addFun2Pack fun pack)) (find-values-in-prop-list data :functions)) (mapc #'(lambda (item) (addspecialitem2pack item pack)) (find-values-in-prop-list data :special-items)) (mapc #'(lambda (spk) (let ((sub-pack (omng-load spk))) (addpackage2pack sub-pack pack))) (find-values-in-prop-list data :packages)) pack))
36,376
Common Lisp
.lisp
739
38.014885
159
0.54449
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
6371d1b17e05a71ea993c35ed350f1abeddb0ac92be1fafe6734bdb68fe1f2e1
669
[ -1 ]
670
undo.lisp
cac-t-u-s_om-sharp/src/visual-language/utils/undo.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;============================================================================ ; UNDO/REDO MANAGEMENT ;============================================================================ (in-package :om) ;;; => each undo-able object should be a subclass of this (defclass undoable-editor-mixin () ((level :initarg :level :initform 10 :accessor level) (undo-stack :initform nil :accessor undo-stack) (redo-stack :initform nil :accessor redo-stack) (last-action :initform nil :accessor last-action) (last-item :initform nil :accessor last-item) )) ;;; object-value will be the object (BPF, etc.) for an object-box ;;; ... or the "object" slot for a patch (defmethod undoable-object ((self undoable-editor-mixin)) (object-value self)) (defmethod undo-command ((self undoable-editor-mixin)) (when (undo-stack self) #'(lambda () (do-undo self)))) (defmethod redo-command ((self undoable-editor-mixin)) (when (redo-stack self) #'(lambda () (do-redo self)))) (defmethod get-undoable-editor-state ((self undoable-editor-mixin)) (get-undoable-object-state (undoable-object self))) (defmethod restore-undoable-editor-state ((self undoable-editor-mixin) (state list)) (restore-undoable-object-state (undoable-object self) state) (update-after-state-change self)) (defmethod reset-undoable-editor-action ((self undoable-editor-mixin)) (setf (last-action self) nil (last-item self) nil)) (defmethod cleanup-undoable-editor-stack-elements ((self undoable-editor-mixin) deleted-states) (cleanup-undoable-object-elements (undoable-object self) deleted-states (append (undo-stack self) (redo-stack self)))) (defmethod cleanup-undoable-object-elements ((self t) deleted-states stacked-states) nil) (defmethod update-after-state-change ((self t)) nil) (defmethod update-after-state-change ((self OMEditor)) (om-invalidate-view (main-view self)) (report-modifications self)) (defmethod push-undo-state ((self undoable-editor-mixin)) (let ((state (get-undoable-editor-state self))) (push state (undo-stack self)) (when (> (length (undo-stack self)) (level self)) (let ((deleted-states (last (undo-stack self)))) (setf (undo-stack self) (butlast (undo-stack self))) (cleanup-undoable-editor-stack-elements self deleted-states)) ) ) ;(om-print-dbg "UNDO STACK:") ;(write (undo-stack self) :stream om-lisp::*om-stream* :pretty t) ;(terpri om-lisp::*om-stream*) ) (defmethod push-redo-state ((self undoable-editor-mixin)) (let ((state (get-undoable-editor-state self))) (push state (redo-stack self))) ; in principle this is not necessary: ; the redo-stack size will never be longer than the undo stack ;(when (> (length (redo-stack self)) (level self)) ; (setf (redo-stack self) (butlast (redo-stack self)))) ;(om-print-dbg "REDO STACK:") ;(write (redo-stack self) :stream om-lisp::*om-stream* :pretty t) ;(terpri om-lisp::*om-stream*) ) (defmethod undoable-container-editor ((self undoable-editor-mixin)) self) (defmethod undoable-container-editor ((self OMEditor)) (or (and (container-editor self) (not (equal self (container-editor self))) ;; sequencer-editor can be its own container-editor :( (undoable-container-editor (container-editor self))) (call-next-method) ;; multiple inheritance with undoable-editor-mixin ? )) (defmethod undoable-container-editor ((self t)) nil) ;;; => call this before any action which might require undo ;;; => action and item allow preventing multiple-undo storage for sequences of similar actions (to do: add also a timer?) (defmethod store-current-state-for-undo ((self undoable-editor-mixin) &key action item) (let ((editor (undoable-container-editor self))) (unless (and action (equal action (last-action editor)) (equal item (last-item editor))) ;;; this is a new 'key state' we want to store (push-undo-state editor) ;;; when we push a new undo state, the redo is reinitialized (let ((deleted-states (copy-list (redo-stack editor)))) (setf (redo-stack editor) nil) (cleanup-undoable-editor-stack-elements editor deleted-states) )) (setf (last-action editor) action (last-item editor) item))) (defmethod store-current-state-for-undo ((self t) &key action item) nil) ;;; called from properties editor (defmethod maybe-store-undo-state ((self OMEditorView) prop-id object) (store-current-state-for-undo (editor self) :action prop-id :item object)) ;;; => call this to undo (defmethod do-undo ((self undoable-editor-mixin)) (let ((editor (undoable-container-editor self))) (setf (last-action editor) nil (last-item editor) nil) (if (undo-stack editor) (progn ;;; push state in redo-stack (push-redo-state editor) ;;; restore state from undo-stack (let ((restored-state (pop (undo-stack editor)))) ;(print restored-state) (restore-undoable-editor-state editor restored-state) ) ) (om-beep)))) ;;; call this to redo (defmethod do-redo ((self undoable-editor-mixin)) (let ((editor (undoable-container-editor self))) (setf (last-action editor) nil (last-item editor) nil) (if (redo-stack editor) (progn ;;; push state in undo-stack (push-undo-state editor) ;;; restore state from redo-stack (let ((restored-state (pop (redo-stack editor)))) (restore-undoable-editor-state editor restored-state)) ) (om-beep)))) ;;;===================================== ;;; COLLECT/RESTORE STATES FOR UNDO/REDO ;;;===================================== ;;; GENERAL CASE: two methods to get/restore the state of an object (defmethod get-undoable-object-state ((self t)) (om-copy self)) (defmethod restore-undoable-object-state ((self t) state) (setf self state)) ;;; POINTS (defmethod get-undoable-object-state ((self ompoint)) (om-copy self)) (defmethod restore-undoable-object-state ((self ompoint) state) (om-point-set-values-from-point self state) self) ;;; STANDARD-OBJECTS ;;; all objects can implement this method (not only undoable-editor-mixin) ;;; e.g. slots or deep-contained objects (defmethod get-object-slots-for-undo ((self t)) nil) (defmethod get-object-slots-for-undo ((self standard-object)) (loop for slot in (class-instance-slots (class-of self)) when (slot-definition-initargs slot) collect (slot-definition-name slot))) ; check classes here :) ; (get-object-slots-for-undo (make-instance 'omboxabstraction)) (defmethod get-undoable-object-state ((self standard-object)) ; (om-print-dbg "collecting state of ~A" (list self) "UNDO") (loop for slot in (get-object-slots-for-undo self) collect (list slot (get-undoable-object-state (slot-value self slot))))) (defmethod restore-undoable-object-state ((self standard-object) (state list)) ;(om-print-dbg "---> restoring state of ~A" (list self) "UNDO") (loop for slot in (get-object-slots-for-undo self) do (setf (slot-value self slot) (restore-undoable-object-state (slot-value self slot) (cadr (find slot state :key 'car))))) ;(om-print-dbg "<--- ~A" (list self) "UNDO") self) ;;; LISTS / CONS (defmethod get-undoable-object-state ((self list)) (if (typep (car self) '(or symbol string number)) ;;; copies "simple" value lists (om-copy self) ;;; handles list of standard objects (cons (list (car self) (get-undoable-object-state (car self))) (get-undoable-object-state (cdr self))) )) ;;; restore a new list, restore each object in it (defmethod restore-undoable-object-state ((self list) (state list)) (if (typep (car state) '(or symbol string number)) ;;; "simple" value lists (om-copy state) ;;; handles list of standard objects (cons (progn (restore-undoable-object-state (car (car state)) (cadr (car state))) (car (car state))) (restore-undoable-object-state (cdr self) (cdr state))) )) ;;; BOX (defmethod get-undoable-object-state ((self OMBox)) (list (call-next-method) (mapcar 'save-state (inputs self)) (mapcar 'save-state (outputs self)) )) (defmethod get-undoable-object-state ((self OMComment)) (list (call-next-method) (value self))) ;;; the reference is shared by the different states of a soem undo-ed box (defmethod get-object-slots-for-undo ((self OMBox)) (remove 'reference (call-next-method))) (defmethod get-object-slots-for-undo ((self OMValueBox)) (append (call-next-method) '(value))) ;;; need to keep track of in/out index (defmethod get-object-slots-for-undo ((self OMInOutBox)) (append (call-next-method) '(reference))) (defmethod get-object-slots-for-undo ((self OMPatchIO)) (append (call-next-method) '(index))) (defmethod get-object-slots-for-undo ((self OMInterfaceBox)) (append (call-next-method) '(value))) ;;; restore a new list, restore each object in it (defmethod restore-undoable-object-state ((self OMBox) (state list)) (call-next-method self (car state)) (setf (inputs self) (create-box-inputs self)) (setf (outputs self) (create-box-outputs self)) (restore-inputs self (nth 1 state)) (restore-outputs self (nth 2 state)) self) (defmethod restore-undoable-object-state ((self OMComment) (state list)) (call-next-method self (car state)) (setf (value self) (cadr state)) self) (defmethod restore-undoable-object-state ((self OMBoxAbstraction) (state list)) (let ((patch (reference self))) (register-document patch) ;;; if needed.. (pushnew self (references-to patch))) (let ((rep (call-next-method))) (set-name (reference rep) (name rep)) rep)) ;;; PATCHES ;;; need special care because connections are restored from the box list (defmethod get-undoable-object-state ((self OMPatch)) `((boxes ,(get-undoable-object-state (boxes self))) (connections ,(save-connections-from-boxes (boxes self))))) (defmethod restore-undoable-object-state ((self OMPatch) (state list)) ;;; need to save/restore the connections of referencing boxes... (let* ((reference-boxes (remove-duplicates (remove-if-not #'(lambda (ref) (subtypep (type-of ref) 'OMBox)) (references-to self)) :key #'container)) (reference-containers-connections (loop for ref-b in reference-boxes when (container ref-b) collect (save-connections-from-boxes (boxes (container ref-b)))))) (loop for element in (append (boxes self) (connections self)) do (omng-remove-element self element)) ;;; => must be properly removed !!! (let* ((boxes-in-state (cadr (find 'boxes state :key 'car))) (connections-in-state (cadr (find 'connections state :key 'car)))) (loop for b-state in boxes-in-state do (let ((b (car b-state))) (when b (restore-undoable-object-state b (cadr b-state)) (loop for box-io in (append (inputs b) (outputs b)) do (setf (connections box-io) nil)) (omng-add-element self b) ))) (loop for c in (restore-connections-to-boxes connections-in-state (boxes self)) do (omng-add-element self c)) ) ;;; restore the connections of referencing boxes (loop for ref-b in reference-boxes for c-list in reference-containers-connections do (let ((pat (container ref-b))) (when pat (loop for c in (restore-connections-to-boxes c-list (boxes pat)) when (or (equal ref-b (box (to c))) (equal ref-b (box (from c)))) do (omng-add-element pat c)) (when (editor pat) (update-after-state-change (editor pat))) ))) self)) (defmethod update-after-state-change ((self patch-editor)) (let* ((patch (object self)) (view (main-view self))) (om-remove-all-subviews view) (put-patch-boxes-in-editor-view patch view) (add-lock-item self view) (report-modifications self) (om-invalidate-view view))) (defmethod cleanup-undoable-object-elements ((self OMPatch) deleted-states stacked-states) (let ((removed-boxes (remove-duplicates (loop for state in deleted-states append (mapcar 'car (cadr (find 'boxes state :key 'car)))))) (stacked-boxes (remove-duplicates (loop for state in stacked-states append (mapcar 'car (cadr (find 'boxes state :key 'car))))))) ;(om-print-dbg "Delete from undo stacks: ~A" (list removed-boxes) "UNDO") (loop for box in removed-boxes do (unless (find box stacked-boxes) ;(om-print-dbg "CLEANUP: ~A" (list box) "UNDO") (omng-delete box))) )) #| ;;; Test/debug: BPF (defmethod get-undoable-object-state ((self bpf)) (let ((rep (call-next-method))) (om-print-dbg "COLLECT: ~A" (list (point-pairs self))) rep)) (defmethod restore-undoable-object-state ((self bpf) (state list)) (let ((rep (call-next-method))) (om-print-dbg "RESTORE: ~A" (list (point-pairs self))) rep)) |#
14,273
Common Lisp
.lisp
302
40.913907
121
0.635283
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e05c63e0f3fac98dacd137f10a3f0d0d80b4d70fd31abde8fb9417711456282a
670
[ -1 ]
671
copy.lisp
cac-t-u-s_om-sharp/src/visual-language/utils/copy.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) (defmethod om-copy ((self list)) (mapcar 'om-copy self)) (defmethod om-copy ((self cons)) (cons (om-copy (car self)) (om-copy (cdr self)))) (defmethod om-copy ((self hash-table)) (let ((hashtable (make-hash-table)) keylist vallist) (maphash #'(lambda (key val) (push key keylist) (push val vallist)) self) (loop for key in (om-copy (reverse keylist)) for val in (om-copy (reverse vallist)) do (setf (gethash key hashtable) val)) hashtable)) (defmethod om-copy ((self oa::ompoint)) (om-make-point (om-point-x self) (om-point-y self))) (defmethod om-copy ((self oa::omcolor)) (om-make-color (om-color-r self) (om-color-g self) (om-color-b self) (om-color-a self) )) (defmethod om-copy ((self oa::om-pointer)) (oa::om-retain self) self) (defmethod om-copy ((self t)) self) ;;; clone-object doesn't om-init the object ;;; om-copy does (defmethod om-copy ((self standard-object)) (om-init-instance (clone-object self))) (defmethod excluded-slots-from-copy ((from t)) nil) (defmethod additional-slots-to-copy ((from t)) (additional-class-attributes from)) ;;; the slot must exit in the target object ;;; .. and not be excluded! (defmethod condition-for-copy-slot ((from t) (to t) slot) (and (slot-exists-p to (slot-definition-name slot)) (or (slot-definition-initargs slot) (member (slot-definition-name slot) (additional-slots-to-copy from))) (not (member (slot-definition-name slot) (excluded-slots-from-copy from))) )) ;;; OMObject copy/save only the slot with initargs ;;; whey ? => the previous method ensures this except if the slot is in additional-slots-to-copy ;;(defmethod condition-for-copy-slot ((from OMObject) (to t) slot) ;; (and (call-next-method) (slot-definition-initargs slot))) ;; reads using the accessor if defined, or with the slot value otherwise (defun read-slot-value (object slot) (if (fboundp (slot-definition-name slot)) (funcall (slot-definition-name slot) object) (slot-value object (slot-definition-name slot)))) ;;; clone-object doesn't om-init-instance the object ;;; om-copy does (defmethod clone-object ((object standard-object) &optional clone) ; (om-print-format "=================== OBJECT ~A" (list object)) (let ((new-object (or clone (clos::allocate-instance (class-of object))))) (loop for slot in (class-instance-slots (class-of object)) when (condition-for-copy-slot object new-object slot) do ; (om-print-format "SLOT ~A" (list (slot-definition-name slot))) (setf (slot-value new-object (slot-definition-name slot)) (om-copy (read-slot-value object slot)))) (initialize-instance new-object) new-object)) #| (defmethod clone-object ((object omobject) &optional clone) (let (initargs new-obj) (setf initargs (loop for slot in (class-slots (class-of object)) when (and (slot-definition-initargs slot) (or (not clone) (slot-exists-p clone (slot-definition-name slot)))) append (list (car (slot-definition-initargs slot)) (om-copy (slot-value object (slot-definition-name slot))) ))) (setf new-obj (apply 'make-instance (cons (if clone (type-of clone) (type-of object)) initargs))) (mapcar #'(lambda (att) (when (and (slot-exists-p object att) (slot-exists-p new-obj att)) (setf (slot-value new-obj att) (slot-value object att)))) (additional-class-attributes object)) (om-init-instance new-obj nil))) (defmethod clone-object ((self t) &optional clone) (om-beep-msg "Can not clone objects of type ~A !" (type-of self))) |# ;;============================================================================ ;; VERY BASIC CLIPBOARD (INTERNAL FOR OBJECTS) ;;============================================================================ (defparameter *om-clipboard* nil) (defparameter *om-clip-pos* nil) (defun set-om-clipboard (value) (setf *om-clipboard* value)) (defun get-om-clipboard () *om-clipboard*) (defun set-paste-position (position &optional panel) (setf *om-clip-pos* (if position (list panel position) nil))) (defun get-paste-position (panel) (when (equal panel (car *om-clip-pos*)) (cadr *om-clip-pos*)))
5,198
Common Lisp
.lisp
108
42.555556
101
0.601303
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
a7e258651be334bbc278f6db17c40b2434b934e0cebe19dff9542ebf7c86e084
671
[ -1 ]
672
pathnames.lisp
cac-t-u-s_om-sharp/src/visual-language/utils/pathnames.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;======================= ;;; Pathname utils for OM ;;;======================= (in-package :om) ;;; check file exist + path = non-nil (defun file-exists-p (path) (and path (probe-file path))) (defun valid-pathname-p (path) (or (pathnamep path) (stringp path))) (defun valid-file-pathname-p (path) (and (valid-pathname-p path) (not (om-directory-pathname-p (pathname path))))) ;;; test if pathname is has extension <type> (defun file-type-p (path type) (and (file-exists-p path) (pathname-type path) (stringp (pathname-type path)) (string-equal (pathname-type path) type))) ;;; returns the name of the directory (defun name-of-directory (path) (car (last (pathname-directory path)))) ;;; creates a pathname relative to the current file (defun om-relative-path (dirs file &optional (reference-path :current)) (let ((ref (cond ((pathnamep reference-path) reference-path) ((symbolp reference-path) (case reference-path (:om (om-root-folder)) (:current *load-pathname*) (otherwise (make-pathname :directory '(:absolute))))) (t *load-pathname*) ))) (if ref (make-pathname :host (pathname-host ref) :device (pathname-device ref) :directory (append (pathname-directory ref) dirs) :name file)))) ;;; Check if a folder exist and create it if it does not (defun check-folder (path) (unless (probe-file path) (om-create-directory path)) path) ; (find-file-in-folder "Untitled" "/Users/bresson/Desktop/" :recursive t :return-all t) (defun find-file-in-folder (name folder &key type recursive return-all) (let ((search-folder (if (equal folder :local) (om-make-pathname :directory *load-pathname*) folder))) (if return-all (loop for elt in (om-directory search-folder :files t :directories recursive) append (if (om-directory-pathname-p elt) (find-file-in-folder name elt :type type :recursive recursive :return-all t) (when (and (pathname-name elt) (string-equal name (pathname-name elt)) (or (null type) (and (pathname-type elt) (string-equal type (pathname-type elt))))) (list elt)))) (let ((result nil)) ;;; we search files first (lower-level) (loop for elt in (om-directory search-folder :files t :directories nil) while (not result) do (when (and (pathname-name elt) (string-equal name (pathname-name elt)) (or (null type) (and (pathname-type elt) (string-equal type (pathname-type elt))))) (setf result elt))) ;;; then we search subfolders (if recursive) (when (and (not result) recursive) (loop for subfolder in (om-directory search-folder :files nil :directories t) while (not result) do (setf result (find-file-in-folder name subfolder :type type :recursive t :return-all nil)))) result) ))) ;;;========================= ;;; RELATIVE PATHNAMES ;;;========================= ;(setf p1 #P"/Users/aaaa/elements/mk-examples.opat") ;(setf p2 #P"/Users/aaaa/elements/NewFolder/bouches/piece1.opat") ;(setf p3 #P"/Users/infiles/test.aif") ;(relative-pathname p3 p1) (defvar *relative-path-reference* nil) (defmacro with-relative-ref-path (path &body body) `(let ((current-relative-path *relative-path-reference*)) (setq *relative-path-reference* ,path) (let ((rep (progn ,@body))) (setq *relative-path-reference* current-relative-path) rep))) ;(setf relative-path-reference "/Users/aaaa/mk-examples.omp") ;(restore-path "../test/ist/ooo.omp" relative-path-reference) (defun relative-pathname (path &optional refpath) (let ((dirlist '(:relative)) (dirrest (cdr (pathname-directory path)))) (when refpath (let ((refrest (cdr (pathname-directory refpath)))) (loop for path-dir in (cdr (pathname-directory path)) for ref-dir in (cdr (pathname-directory refpath)) while (string-equal path-dir ref-dir) do (setf refrest (cdr refrest) dirrest (cdr dirrest))) (dotimes (i (length refrest)) (setf dirlist (append dirlist (list ".."))))) ) (loop for item in dirrest do (setf dirlist (append dirlist (list item)))) (make-pathname :device (pathname-device (or refpath path)) :host (pathname-host (or refpath path)) :directory dirlist :name (pathname-name path) :type (pathname-type path)) )) ;;; seems like 'merge-pathnames' does pretty much the same job (defmethod restore-path ((self pathname) &optional refpath) (let ((dir (pathname-directory self))) (if refpath (cond ((and (equal :relative (car dir)) (cdr dir)) (let ((updirs (or (position-if-not #'(lambda (item) (equal item :up)) (cdr dir)) 0))) (make-pathname :device (pathname-device refpath) :host (pathname-host refpath) :directory (append (list (car (pathname-directory refpath))) (butlast (cdr (pathname-directory refpath)) updirs) (nthcdr updirs (cdr dir))) :name (pathname-name self) :type (pathname-type self)))) ((equal :absolute (car dir)) self) ((or (null dir) (null (cdr dir))) ;; could not restore pathname (make-pathname :device (pathname-device refpath) :host (pathname-host refpath) :directory (pathname-directory refpath) :name (pathname-name self) :type (pathname-type self)))) self))) (defmethod restore-path ((self string) &optional refpath) (restore-path (pathname self) refpath)) (defmethod restore-path ((self t) &optional refpath) nil) ;;;========================= ;;; EXTERNAL EXECs ;;;========================= ;;; utility function to get the executable path from a .app on Mac (defun real-exec-pathname (path) (let* ((path-path (pathname path)) (name (car (last (pathname-directory path-path))))) (if (and (om-directory-pathname-p path-path) (string-equal "app" (subseq name (- (length name) 3)))) ;;; path is an application bundle (make-pathname :directory (append (pathname-directory path-path) (list "Contents" "MacOS")) :name (subseq name 0 (- (length name) 4))) ;;; otherwise... path-path))) ;;;========================= ;;; ENCODING ;;;========================= (defmacro with-safe-open-file (args &body body) (let ((default-format :utf-8) (backup-format :latin-1)) `(handler-bind ((error #'(lambda (err) (om-message-dialog (format nil "#'with-safe-open-file: an error of type ~a occurred: ~%\"~a\"" (type-of err) err)) (abort err)))) (let ((rep (catch 'format-failed (handler-bind ((sys::external-format-error #'(lambda (err) (declare (ignore err)) (throw 'format-failed ,default-format) ))) ;;; main body (with-open-file ,(append args (list :external-format default-format)) ,@body) )))) (if (equal rep ,default-format) (progn (print (format nil "External format error: could not load file as ~a. Now trying with ~a." ,default-format ,backup-format)) (with-open-file ,(append args (list :external-format backup-format)) ,@body)) rep) )) ))
8,890
Common Lisp
.lisp
185
37.648649
139
0.550329
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3d8ecdcbb9eb5a36013cf801669e67b0ec42945e3bc5a26bf38fc2e05eb3b747
672
[ -1 ]
673
lisptools.lisp
cac-t-u-s_om-sharp/src/visual-language/utils/lisptools.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;========================== ;;; Misc. Lisp Tools for OM ;;;========================== (in-package :om) (defconstant *positive-infinity* most-positive-fixnum) (defconstant *negative-infinity* most-negative-fixnum) ;;;=========================== ;;; LISTS ;;;=========================== (defun list! (thing) (if (listp thing) thing (list thing))) (defun list+ (&rest lists) (apply 'concatenate (append (list 'list) lists))) (defun first? (thing) (if (listp thing) (first thing) thing)) (defun max? (a b) (if a (if b (max a b) a) b)) (defun min? (a b) (if a (if b (min a b) a) b)) (defun firstn (list n ) (cond ((< (length list) n) list ) (t (butlast list (- (length list) n))))) (defun replace-in-list (list elem pos) (let* ((first-list (subseq list 0 pos)) (second-list (subseq list (+ pos 1)))) (append first-list (list elem) second-list))) (defun insert-in-list (list elem pos) (if (> pos (- (length list) 1)) (append list (list elem)) (append (subseq list 0 pos) (list elem) (subseq list pos)))) (defun erase-n (list pos) (loop for item in list for i = 0 then (+ i 1) when (not (= i pos)) collect item)) ;; pos = a list of indices (defun erase-nn (list pos) (loop for item in list for i = 0 then (+ i 1) when (not (member i pos)) collect item)) (defun list-typep (list typeList) "Checks if every elt in 'list' belongs to one of the types in 'typelist'" (every #'(lambda (elt) (some #'(lambda (type) (equal (type-of elt) type)) (list! typelist))) list)) (defun list-subtypep (list typeList) "Checks if every elt in 'list' belongs to one of the subtypes in 'typelist'" (every #'(lambda (elt) (some #'(lambda (type) (subtypep (type-of elt) type)) (list! typelist))) list)) (defun next-in-list (list item &optional (circular t)) (let* ((pos (position item list))) (if circular (let ((newpos (if pos (mod (1+ pos) (length list)) 0))) (nth newpos list)) (when pos (nth (1+ pos) list)) ))) (defun previous-in-list (list item &optional (circular t)) (let* ((pos (position item list))) (if circular (let ((newpos (if pos (mod (1- pos) (length list)) 0))) (nth newpos list)) (when (and pos (> pos 0)) (nth (1- pos) list)) ))) (defmacro %car (x) `(car (the cons ,x))) (defmacro %cdr (x) `(cdr (the cons ,x))) (defmacro %cadr (x) `(cadr (the cons ,x))) (defun quoted-form-p (form) (and (consp form) (eq (%car form) 'quote) (consp (%cdr form)) (null (%cdr (%cdr form))))) (defun lambda-expression-p (form) (and (consp form) (eq (%car form) 'lambda) (consp (%cdr form)) (listp (%cadr form)))) ;push item in place but in the last position (defmacro pushr (item place) `(if ,place (setf (cdr (last ,place)) (cons ,item nil)) (setf ,place (list ,item)))) (defmacro insert-in-order (object list &key (key #'identity) (test '<)) `(let ((p (position (funcall ,key ,object) ,list :test ',test :key ,key))) (if (not p) (nconc ,list (list ,object)) (if (= p 0) (push ,object ,list) (push ,object (nthcdr p ,list)))) ,list)) (defmacro filter-list (list from to &key (key #'identity)) `(remove-if #'(lambda (element) (or (< (funcall ,key element) ,from) (>= (funcall ,key element) ,to))) ,list)) (defun in-interval (n interval &key exclude-low-bound exclude-high-bound) (and (funcall (if exclude-low-bound '> '>=) n (car interval)) (funcall (if exclude-high-bound '< '<=) n (cadr interval)))) (defun closest-match (value list &key (key #'identity)) (let ((rep (car list)) (min (abs (- value (funcall key (car list)))))) (loop for elt in (cdr list) do (let ((diff (abs (- value (funcall key elt))))) (when (< diff min) (setf min diff rep elt)))) rep)) ;================= ;safe random (defun om-random-value (num) (if (= num 0) 0 (if (< num 0) (- (random (- num))) (random num)))) ;;;============================== ;;; HASH-TABLES ;;;============================== (defmethod hash-keys ((h hash-table)) (loop for key being the hash-keys of h collect key)) (defmethod hash-items ((h hash-table)) (loop for key in (hash-keys h) collect (gethash key h))) ;;;============================== ;;; PROPERTIES / KEY-VALUE LISTS ;;;============================== ;; '(:key1 :val1 :key2 :val2 ...) (defun find-value-in-arg-list (list key) (let ((pos (position key list :test 'equal))) (and pos (nth (1+ pos) list)))) ;;; => GETF (defun set-value-in-arg-list (list key value) (let ((pos (position key list :test 'equal))) (if pos (setf (nth (1+ pos) list) value) (setf list (append list (list key value)))) )) ;; '((:key1 :val1) (:key2 :val2) ...) (defun find-value-in-kv-list (list key) (cadr (find key list :test 'equal :key 'car))) (defun set-value-in-kv-list (list key value) (if list (let ((kv (find key list :test 'equal :key 'car))) (if kv (setf (cadr kv) value) (push (list key value) list)) list) (list (list key value)))) ;; '((:key1 prop1 prop2 prop3...) (:key2 prop1 prop2 prop3...) ...) (defun find-values-in-prop-list (list key) (remove nil ;;; ? (cdr (find key list :test 'equal :key 'car)) )) ;======================= ; types ;======================= (defun ensure-type (object type) (and (subtypep (type-of object) type) object)) ;======================= ; FUNCTIONS / LAMBDA LIST PARSING ;======================= (defun function-arg-list (fun) (remove-if #'(lambda (item) (member item lambda-list-keywords :test 'equal)) (function-arglist fun))) (defun function-main-args (fun) (loop for item in (function-arglist fun) while (not (member item lambda-list-keywords :test 'equal)) collect item)) (defun function-n-args (fun) (length (function-main-args fun))) (defun function-optional-args (fun) (let ((al (function-arglist fun))) (when (find '&optional al) (subseq al (1+ (position '&optional al)) (position (remove '&optional lambda-list-keywords) al :test #'(lambda (a b) (find b a))))))) (defun function-keyword-args (fun) (let ((al (function-arglist fun))) (when (find '&key al) (subseq al (1+ (position '&key al)) (position (remove '&key lambda-list-keywords) al :test #'(lambda (a b) (find b a))))))) (defun get-keywords-fun (fun) (let ((args (function-arglist fun)) rep) (loop while (and args (not rep)) do (when (equal (pop args) '&key) (setf rep t))) (setf rep nil) (loop for item in args while (not (member item lambda-list-keywords :test 'equal)) do (push (if (listp item) (car item) item) rep)) (reverse rep))) (defun get-optional-fun (fun) (let ((args (function-arglist fun)) rep) (loop while (and args (not rep)) do (when (equal (pop args) '&optional) (setf rep t))) (setf rep nil) (loop for item in args while (not (member item lambda-list-keywords :test 'equal)) do (push (if (listp item) (car item) item) rep)) (reverse rep))) (defun valued-val (val) (if (or (symbolp val) (and (consp val) (or (not (symbolp (car val))) (not (fboundp (car val)))))) val (eval val))) ;======================= ; POSITION ;======================= (defun interval-intersec (int1 int2) (when (and int2 int1) (let ((x1 (max (car int1) (car int2))) (x2 (min (cadr int1) (cadr int2)))) (if (<= x1 x2) (list x1 x2))))) ;; each rect = (left top right bottom) (defun rect-intersec (rect1 rect2) (let* ((tx (max (first rect1) (first rect2))) (ty (max (second rect1) (second rect2))) (t2x (min (third rect1) (third rect2))) (t2y (min (fourth rect1) (fourth rect2)))) (if (or (< t2x tx) (< t2y ty)) nil (list tx ty t2x t2y)))) (defun point-in-interval-p (point interval) (and (<= point (second interval)) (>= point (first interval)))) (defun point-in-rectangle-p (point left top right bottom) (let ((x (om-point-x point)) (y (om-point-y point))) (and (>= x left) (<= x right) (>= y top) (<= y bottom)))) ;======================= ; MATH ;======================= (defun 2+ (x) (+ x 2)) (defun 2- (x) (- x 2)) (defun space-ranges (range &optional (factor 0.05) (min 1)) (list (- (first range) (max min (abs (* (- (second range) (first range)) factor)))) (+ (second range) (max min (abs (* (- (second range) (first range)) factor)))) (- (third range) (max min (abs (* (- (fourth range) (third range)) factor)))) (+ (fourth range) (max min (abs (* (- (fourth range) (third range)) factor)))))) (defun average (xs weights?) (let ((num 0) (den 0) ampl) (loop while xs do (setq ampl (or (if (consp weights?) (pop weights?) 1) 1)) (incf num (* ampl (pop xs))) (incf den ampl)) (/ num den))) ;;; finds the closest multiple of n and 2 that is greater than val (defun next-double-of-n (val n) (let ((rep n)) (loop while (> val rep) do (setf rep (* rep 2))) rep)) (defun power-of-two-p (n) (or (= n 1) (= n 2) (and (zerop (mod n 2)) (power-of-two-p (/ n 2)))))
10,281
Common Lisp
.lisp
271
32.808118
106
0.548617
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
81bc5792605b086add553b3f41d3f610da57fa53503d6fa0b75c36104723db15
673
[ -1 ]
674
objects.lisp
cac-t-u-s_om-sharp/src/visual-language/core/objects.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;; for the objects with name (defclass named-object () ((name :initform nil :accessor name :type string)) (:documentation "Superclass for all objects")) (defmethod set-name ((self named-object) (text string)) (setf (name self) text)) (defmethod set-name ((self named-object) text) (setf (name self) (format nil "~A" text))) (defmethod get-name ((self named-object)) (name self)) (defmethod set-name ((self t) newname) nil) (defmethod get-name ((self t)) nil) ;;; allows using :name (defmacro om-make-instance (class &rest initargs) "Special make-instance - class must be an OMObject." (if (getf initargs :name) (let* ((pos (position :name initargs)) (name (nth (1+ pos) initargs)) (other-args (append (subseq initargs 0 pos) (subseq initargs (+ pos 2))))) `(let ((obj (make-instance ,class ,.other-args))) (set-name obj ,name) obj)) `(make-instance ,class ,.initargs))) ;;; THE SUPERCLASS FOR EVERYTHING IN THE VPL ;;; name is with initarg (defclass OMObject (named-object) ((name :initform nil :initarg :name :accessor name)) (:documentation "Superclass for all OpenMusic Objects")) ;; SPECIALIZED FOR FUNCALLABLE OBJECTS ;; WHICH DO NOT ALLOW OMOBJECT INHERITANCE (defclass OMFuncallableObject (standard-generic-function) ((name :initform nil :initarg :name :accessor name)) (:metaclass clos::funcallable-standard-class)) ;;; careful: some objects shall better not be renamed (functions, classes...) (defmethod set-name ((self OMFuncallableObject) text) (setf (name self) text)) (defmethod get-name ((self OMFuncallableObject)) (string-downcase (name self))) ;;; SUPECLASS FOR BOX, CONNECTIONS ETC. (defclass OMVPObject (OMObject) ()) ;;; AN OBJECT WITH AN EDITOR (defclass ObjectWithEditor () ((editor :initform nil :accessor editor) (window-pos :initform nil :accessor window-pos) (window-size :initform nil :accessor window-size))) ;=========================== ; OMBASICOBJECTS = OBJECTS FROM THE VISUAL LANGUAGE ;=========================== (defclass OMBasicObject (OMObject ObjectWithEditor) ((name :initform nil :accessor name :initarg :name :type string) ;; name is redefined with :initarg (protected-p :initform nil :initarg :protected-p :accessor protected-p :documentation "determines if the object is protected (i.e. modifyable by the user) or not") (icon :initform nil :initarg :icon :accessor icon) (references-to :initform nil :accessor references-to :documentation "mutable list containing the existing objects containing or referring to this object") ;(infowin :initform nil :accessor infowin :documentation "reference to the info window currently open for the object (if any)") ) (:documentation "Superclass for metaobjects, like patches, classes, generic functions...")) (defmethod release-reference ((self t) pointer) nil) (defmethod release-reference ((self OMBasicObject) pointer) (setf (references-to self) (remove pointer (references-to self)))) (defmethod retain-reference ((self OMBasicObject) pointer) (setf (references-to self) (cons pointer (references-to self)))) ;=========================== ; FUNCTIONS, METHODS ARE FUNCALLABLE BASIC OBJECTS ;=========================== (defclass OMFuncallableBasicObject (OMFuncallableObject) ((name :initform nil :accessor name :initarg :name :type string) ;; name is redefined with :initarg (protected-p :initform nil :initarg :protected-p :accessor protected-p) (icon :initform nil :initarg :icon :accessor icon) (frames :initform nil :accessor frames) (references-to :initform nil :accessor references-to)) (:metaclass clos::funcallable-standard-class)) ;(defmethod omNG-rename ((self OMfuncallableObject) name) ; "This method changes the name of the object self with the new name NAME" ; (setf (name self) name)) ;=========================== ; BASIC PROTOCOL FUNCTIONS ;=========================== ;;; add something somewhere (defgeneric omng-add-element (container element)) ;;; remove something from somewhere ;;; element might still exist after (defgeneric omng-remove-element (container element)) ;;; called when an object is deleted (cleanup, etc.) (defmethod omng-delete ((obj t)) t) (defmethod omng-delete ((obj OMBasicObject)) (close-editor obj)) (defmethod omng-delete ((obj OMFuncallableBasicObject)) (close-editor obj)) ;------------------------------------------------------------------------------ ; SPECIFIC SUBCLASSES ;------------------------------------------------------------------------------ (defclass OMProgrammingObject (OMBasicObject) ((compiled-fun-name :initform nil :accessor compiled-fun-name) (compiled? :initform nil :accessor compiled?) (doc :initform "" :accessor doc :documentation "documentation") (create-info :initform '(nil nil *app-name* 0) :accessor create-info :documentation "information about creation and last modification of the document (text)") (loaded? :initform t :accessor loaded? :documentation "is this object loaded?") (dependencies :initform nil :accessor dependencies)) (:documentation "Superclass for programming objects")) (defmethod initialize-instance :after ((self OMProgrammingObject) &rest initargs) (setf (compiled-fun-name self) (default-compiled-gensym self))) (defmethod default-compiled-gensym ((self OMProgrammingObject)) (gensym "om-")) (defmethod box-symbol ((self OMProgrammingObject)) nil) (defmethod set-name ((self OMProgrammingObject) name) (call-next-method) (when (editor self) (update-window-name (editor self))) (loop for box in (box-references-to self) ;; in principle there is only one at this stage do (set-name box (name self)) (when (frame box) (om-invalidate-view (frame box))))) (defmethod compile-if-needed ((self OMProgrammingObject)) ; (print (list "COMPILE" (name self) (compiled? self))) (unless (compiled? self) (compile-patch self))) (defmethod touch ((self t)) nil) (defmethod touch ((self OMProgrammingObject)) (setf (compiled? self) nil) (call-next-method)) ;;;======================================= ;;; PERSISTANT ;;;======================================= (defclass OMPersistantObject () ((mypathname :initform nil :initarg :mypathname :accessor mypathname :documentation "associated file pathname") (saved? :initform nil :accessor saved? :documentation "as the object been modified without saving?")) (:documentation "Mixin class for perstistant objects. Persistants object are the subset of the metaobjects which are stored as files or folders.")) (defmethod touch ((self OMPersistantObject)) (setf (saved? self) nil) (call-next-method)) (defmethod update-from-editor ((self OMProgrammingObject) &key (value-changed t) (reactive t)) (when value-changed (loop for ref in (box-references-to self) do (update-from-editor ref :value-changed value-changed :reactive reactive)) (touch self)) (call-next-method)) ;(defmethod update-from-editor ((self OMPersistantObject)) ; (touch self) ; (call-next-method)) (defmethod window-name-from-object ((self OMPersistantObject)) (if (mypathname self) (if (probe-file (mypathname self)) ;;; normal case (format nil "~A~A [~A]" (if (saved? self) "" "*") (name self) (namestring (om-make-pathname :directory (mypathname self)))) ;;; problem : the patch is open but the file is missing (format nil "MISSING FILE ! [Will be saved as ~A]" (namestring (mypathname self))) ) ;;; no pathname yet : newly created window (format nil "~A~A [...]" (if (saved? self) "" "*") (name self)))) ;;; DOES NOT COPY !! (e.G. if I copy a box refereing to a persistant object, the copy will refer to the same object) (defmethod om-copy ((self OMPersistantObject)) self) ;;;======================================= ;;; FOLDERS (not used for the moment...) ;;;======================================= (defclass OMFolder (OMBasicObject) ((elements :initform nil :accessor elements :documentation "folders contained in the workspace")) ;(presentation :initform 1 :initarg :presentation :accessor presentation :documentation "presentation mode: 1=list, 0=icons")) (:documentation "The class of the folders")) (defclass OMPersistantFolder (OMFolder OMPersistantObject) () (:documentation "Superclass of persistant objects that are saved as folders.")) ;;;======================================= ;;; DEPENDENCY MANAGEMENT ;;;======================================= (defmethod is-persistant ((self OMPersistantObject)) self) (defmethod is-persistant ((self t)) nil) (defmethod find-persistant-container ((self OMPersistantObject)) self) ;;; go check with the container of the reference box ;;; in principle all references have the same container ;;; This method is also specialized for OMBox (defmethod find-persistant-container ((self OMProgrammingObject)) (let ((one-box-ref (find-if #'(lambda (b) (subtypep (type-of b) 'OMBox)) (references-to self)))) (when one-box-ref (find-persistant-container one-box-ref)))) ;; returns references that are from outside the same patch (= non-recursive) (defmethod get-outside-references ((self OMProgrammingObject)) (loop for b in (box-references-to self) unless (or (null (find-persistant-container b)) (equal self (find-persistant-container b))) collect b)) (defmethod box-references-to ((self OMProgrammingObject)) (remove-if #'(lambda (ref) (not (subtypep (type-of ref) 'OMBox))) (references-to self))) (defmethod release-reference :around ((self OMPersistantObject) from) (call-next-method) (unless (or (get-outside-references self) (editor self)) (unregister-document self))) ;;; this is called: ;;; - by the editor-close callback ;;; - when the document is closed from the main session window (defmethod close-document ((patch OMProgrammingObject) &optional (force nil)) (let* ((outside-references (get-outside-references patch)));;; => references to the same patch outside this patch (when (or (null outside-references) (and force (om-y-or-n-dialog (format nil "The document ~A still has ~A external references. Delete anyway ?" (name patch) (length outside-references))))) ;;; release all box references (they are all inside this patch anyway) (loop for refb in (box-references-to patch) do (release-reference patch refb)) (delete-internal-elements patch) ;; (setf (loaded? patch) nil) (when force (unregister-document patch)) ) ))
11,759
Common Lisp
.lisp
216
49.12037
167
0.652616
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8028489796815b0e9e17d443033731dc7d9275675fee08abf47f558d0e3a09ec
674
[ -1 ]
675
defclass.lisp
cac-t-u-s_om-sharp/src/visual-language/core/defclass.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;========================================================================= ; Class definition ;========================================================================= (in-package :om) (defvar *def-metaclass-class* 'omstandardclass "the meta-class for om classes") (defvar *def-metaclass-slot* 'omslot "the meta-class for om slots") ;;-------------------------------------------------- ;; Class definition : DEFCLASS* ;;-------------------------------------------------- ; defclass* uses standard defclass, but set automatically the metaclass to the OMClass meta-class. ; this macro fills the omslot of the class object i.e. icon, name. ; if the option :update is set to T the macro update all objects (classes, frames, etc.) attached to the class." ;;-------------------------------------------------- (defun parse-defclass-options (options) (let* (icon metaclass doc other-options) (loop while options do (cond ((equal (caar options) :icon) (setf icon (second (pop options)))) ((equal (caar options) :documentation) (setf doc (second (pop options)))) ((equal (caar options) :metaclass) (setf metaclass (second (pop options)))) (t (push (pop options) other-options)))) (values other-options icon metaclass doc))) (defmethod update-from-reference ((self t)) nil) (defmethod update-from-reference ((self OMClass)) "This method is called when you redifine <self> to update the attached objects." (mapc #'update-from-reference (class-direct-subclasses self)) (mapc #'update-from-reference (references-to self))) ;;; supported options are ;;; :icon :documentation :metaclass :update (defmacro defclass* (name superclasses slots &rest class-options) (multiple-value-bind (other-options icon metaclass doc update?) (parse-defclass-options class-options) `(let ((new-class (defclass ,name ,superclasses ,slots (:metaclass ,(or metaclass *def-metaclass-class*)) (:documentation ,(or doc "")) ,.other-options))) (setf (name new-class) (string ',name)) (setf (icon new-class) (or ,icon 'icon-class)) (update-from-reference new-class) new-class) ))
3,001
Common Lisp
.lisp
55
49.963636
112
0.547376
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
36d6a349edc24b2c77a01db5bfb9d1e095199e74d655e5a5e72583e16414502e
675
[ -1 ]
676
defmethod.lisp
cac-t-u-s_om-sharp/src/visual-language/core/defmethod.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;========================================================================= ; Generic Function / Method definition ; most of this part is taken from OM6 ;========================================================================= (in-package :om) (defvar *def-metaclass-genfun* 'omgenericfunction "the meta-class for om generic functions") (defvar *def-metaclass-method* 'ommethod "the meta-class for om methods") (defvar *genfun-att-list* '(name icon documentation numouts inputs-default inputs-doc inputs-menus)) (defmethod get-menu-list ((self t)) self) (defmethod get-menu-list ((self symbol)) (eval self)) (defun get-menu-input (indice list) (let (rep i) (loop for item in list while (not rep) do (setf i (if (integerp (car item)) (car item) (read-from-string (format nil "~d" (car (eval item)))))) (when (= i indice) (setf rep item))) rep)) (defun parse-defgeneric* (args) (let* (icon numouts initvals doc menuins indoc) (loop for theargs in args do (cond ((equal (car theargs) :numouts) (setf numouts (second theargs))) ((equal (car theargs) :initvals) (setf initvals (second theargs))) ((equal (car theargs) :indoc) (setf indoc (second theargs))) ((equal (car theargs) :doc) (setf doc (second theargs))) ((equal (car theargs) :documentation) (setf doc (second theargs))) ((equal (car theargs) :icon) (setf icon (second theargs))) ((equal (car theargs) :menuins) (setf menuins (second theargs))))) (unless numouts (setf numouts 1)) (unless doc (setf doc "no documentation for this function")) (unless icon (setf icon 150)) ;an icon by default (values numouts initvals icon indoc doc menuins))) (defun remove-om-options (list) (loop for item in list when (not (or (member (string (car item)) *genfun-att-list* :test 'string-equal :key 'string) (equal (car item) :doc) (equal (car item) :generic-function-class) (equal (car item) :method-class))) collect item)) (defmacro defgeneric* (function-name lambda-list &rest options-and-methods &environment env) (declare (ignore env)) (multiple-value-bind (numouts initvals icon indoc doc menuins) (parse-defgeneric* options-and-methods) (unless initvals (setf initvals `',(make-list (length lambda-list) :initial-element nil))) (unless indoc (setf indoc `',(make-list (length lambda-list) :initial-element "no documentation"))) `(let* ((gen-fun (defgeneric ,function-name ,lambda-list (:documentation ,doc) (:generic-function-class ,*def-metaclass-genfun*) (:method-class ,*def-metaclass-method*) ,.(remove-om-options options-and-methods)))) (setf (numouts gen-fun) (or ,numouts 1)) (setf (inputs-default gen-fun) ,initvals) (setf (inputs-doc gen-fun) ,indoc) (setf (inputs-menus gen-fun) (decode-menuins ,menuins)) (setf (icon gen-fun) ,icon) (setf (name gen-fun) ,(string function-name)) gen-fun))) ;----------------- ;Method Definition ;----------------- ;--------------------------------------------------- ;select the optional keys in the function definition (defun parse-defmethod* (name args) (declare (ignore name)) (let* ((theargs args) (body? nil) qualy lambda-list icon numouts initvals doc menuins body indoc outdoc) (when (or (equal (car theargs) :after) (equal (car theargs) :before) (equal (car theargs) :around)) (setf qualy (list (pop theargs)))) (setf lambda-list (pop theargs)) (loop while (and theargs (not body?)) do (cond ((equal (car theargs) :numouts) (pop theargs) (setf numouts (pop theargs))) ((equal (car theargs) :initvals) (pop theargs) (setf initvals (pop theargs))) ((equal (car theargs) :indoc) (pop theargs) (setf indoc (pop theargs))) ((equal (car theargs) :outdoc) (pop theargs) (setf outdoc (pop theargs))) ((equal (car theargs) :doc) (pop theargs) (setf doc (pop theargs))) ((equal (car theargs) :icon) (pop theargs) (setf icon (pop theargs))) ((equal (car theargs) :menuins) (pop theargs) (setf menuins (pop theargs))) ((stringp (car theargs)) (setf doc (pop theargs))) (t (setf body theargs) (setf body? t)))) (values qualy lambda-list numouts initvals icon indoc outdoc doc menuins body))) ;--------------------------------------------- ;Take only the name parameter without the type (defun get-lambda-var (list) (mapcar #'(lambda (nom) (first? nom)) list)) ;------------------------------------------------------------------------- ;Define an OM method and an OM Generic function if this last doesn't exist ;(defun def-method-icon () 'default) (defun def-method-icon () nil) (defun decode-menuins (list) (when list (loop for in from 0 to (apply 'max (mapcar 'car list)) collect (cadr (find in list :test '= :key 'car))))) (defmacro defmethod* (name &rest args) (multiple-value-bind (qualy lambda-list numouts initvals icon indoc outdoc doc menuins body) (parse-defmethod* name args) (let ((lambda-var (get-lambda-var lambda-list)) iv id od) (setf iv (or initvals `',(make-list (length lambda-var) :initial-element nil))) (setf id (or indoc `',(make-list (length lambda-var) :initial-element ""))) (setf od (or outdoc `',(make-list (length lambda-var) :initial-element nil))) `(let (genfun method) (unless (fboundp ',name) (progn (setf genfun (defgeneric ,name ,lambda-var (:documentation ,doc) (:generic-function-class ,*def-metaclass-genfun*) (:method-class ,*def-metaclass-method*))) (setf (numouts genfun) (or ,numouts 1)) (setf (inputs-default genfun) ,iv) (setf (inputs-doc genfun) ,id) (setf (outputs-doc genfun) ,od) (setf (icon genfun) (or ,icon (def-method-icon))) (setf (name genfun) ,(string name)))) (unless genfun (setf genfun (fdefinition ',name)) (when ,doc (setf (documentation genfun 'function) ,doc))) (when ,icon (setf (icon genfun) ,icon)) (when ,numouts (setf (numouts genfun) ,numouts)) (when ,initvals (setf (inputs-default genfun) ,initvals)) (when ,indoc (setf (inputs-doc genfun) ,indoc)) (when ,outdoc (setf (outputs-doc genfun) ,outdoc)) (when ,menuins (setf (inputs-menus genfun) (decode-menuins ,menuins))) (setf method (defmethod ,name ,.qualy ,lambda-list ,.body)) (setf (name method) ,(string name)) method))))
7,966
Common Lisp
.lisp
146
45.246575
104
0.556014
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
a906ea4b3230e1ee81fd9865d7e9bea31528e3d2508ef552eb3df0b9553e206e
676
[ -1 ]
677
metaclasses.lisp
cac-t-u-s_om-sharp/src/visual-language/core/metaclasses.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;=========================== ;METAOBJECTS ;=========================== ;; OMPersistantObject (defclass OMClass (standard-class OMBasicObject) ((library :initform nil :accessor library)) (:documentation "Metaclass for classes.")) (defmethod omclass-p ((self t)) nil) (defmethod omclass-p ((self OMClass)) t) (defmethod omclass-p ((self symbol)) (and (find-class self nil) (omclass-p (find-class self)))) (defmethod slot-missing ((class OMClass) instance slot-name operation &optional new-value) (om-beep-msg "!!! Attempt to access non existing slot ~A in class ~A !!!" slot-name (class-name class))) (eval-when (:compile-toplevel :load-toplevel :execute) (defmethod validate-superclass ((class omclass) (super standard-class)) t) ) (defclass OMStandardClass (OMClass) () (:documentation "This is the current main metaclass, you can sub-class it and use the new class as current metaclass. This class is an OMClass (unlike OMClass itself!).") (:metaclass OMClass)) (eval-when (:compile-toplevel :load-toplevel :execute) (defmethod validate-superclass ((class omstandardclass) (super standard-class)) t) (defmethod validate-superclass ((class standard-class) (super omstandardclass)) t) (defmethod validate-superclass ((class standard-class) (super omclass)) t) ) (defclass OMGenericFunction (OMFuncallableBasicObject) ((numouts :initform nil :accessor numouts) (protected-p :initform nil :accessor protected-p :initarg :protected-p) (inputs-default :initform nil :accessor inputs-default) (library :initform nil :accessor library) (inputs-doc :initform nil :accessor inputs-doc) (outputs-doc :initform nil :accessor outputs-doc) (inputs-menus :initform nil :accessor inputs-menus)) (:default-initargs :protected-p t) (:documentation "The generic function meta-object.") (:metaclass funcallable-standard-class) ) (defmethod omgenericfunction-p ((self t)) nil) (defmethod omgenericfunction-p ((self OMGenericFunction)) t) (defmethod omgenericfunction-p ((self symbol)) (and (fboundp self) (omgenericfunction-p (fdefinition self)))) ; OMPersistantObject (defclass OMMethod (OMBasicObject standard-method) ((saved-connections :initform nil :accessor saved-connections) (graph-fun :initform nil :accessor graph-fun) (compiled? :initform t :accessor compiled?) (class-method-p :initform nil :accessor class-method-p)) (:documentation "The class of the method metaobject.") (:default-initargs :protected-p t) (:metaclass omstandardclass)) (defclass OMSlot (OMBasicObject) ((classname :initarg :classname :accessor classname) (thetype :initform t :initarg :thetype :accessor thetype) (theinitform :initarg :theinitform :accessor theinitform) (alloc :initarg :alloc :accessor alloc) (slot-package :initarg :slot-package :accessor slot-package) (io-p :initarg :io-p :accessor io-p) (doc :initarg :doc :accessor doc)) (:documentation "Instance of this class allow define graphicly slot of omClasses.") (:metaclass omstandardclass)) ; There are not all basic classes from lisp, ; you can add easy new basic types if they have a building class correspondant, ; for this see the function initbasic-lisp-types. (defclass OMBasictype (OMBasicObject) ((defval :initform nil :initarg :defval :accessor defval)) (:documentation "This class implements building class in Common Lisp because we can not inherit for building class we use delegation."))
4,310
Common Lisp
.lisp
81
49.518519
139
0.683131
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
5170372d45a0a6786bf3103fd7ccf5581d97ce7e759361936c6319b26e17d184
677
[ -1 ]
678
rulers.lisp
cac-t-u-s_om-sharp/src/visual-language/graphics/rulers.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;============================================ ;;; GRADUATED VIEWS ;;;============================================ (in-package :om) (defclass x-graduated-view () ((x1 :accessor x1 :initarg :x1 :initform 0) (x2 :accessor x2 :initarg :x2 :initform 100) (x-factor :accessor x-factor :initform 1) (x-shift :accessor x-shift :initform 0))) (defclass y-graduated-view () ((y1 :accessor y1 :initarg :y1 :initform 0) (y2 :accessor y2 :initarg :y2 :initform 100) (y-factor :accessor y-factor :initform 1) (y-shift :accessor y-shift :initform 0))) (defvar *min-ruler-extent* 10) (defmethod set-shift-and-factor ((self t)) nil) ;(defmethod x1 ((self x-graduated-view)) ; (or (slot-value self 'x1) 0)) ;(defmethod x2 ((self x-graduated-view)) ; (or (slot-value self 'x2) 0)) (defmethod set-shift-and-factor ((self x-graduated-view)) (let ((range (- (x2 self) (x1 self)))) (unless (zerop range) (let ((factor (/ (w self) range))) (setf (x-factor self) factor (x-shift self) (- (* (x1 self) factor))))) (call-next-method))) (defmethod set-shift-and-factor ((self y-graduated-view)) (let* ((range (- (y1 self) (y2 self))) (factor (/ (h self) range))) (setf (y-factor self) factor (y-shift self) (- (* (y2 self) factor)))) (call-next-method)) (defmethod om-view-resized :before ((self x-graduated-view) new-size) (set-shift-and-factor self)) (defmethod om-view-resized :before ((self y-graduated-view) new-size) (set-shift-and-factor self)) (defmethod pix-to-x ((self x-graduated-view) x) (+ (x1 self) (float (/ x (x-factor self))))) (defmethod dpix-to-dx ((self x-graduated-view) dpix) (float (/ dpix (x-factor self)))) (defmethod x-to-pix ((self x-graduated-view) x) (+ (x-shift self) (float (* (x-factor self) x)))) (defmethod dx-to-dpix ((self x-graduated-view) dx) (float (* (x-factor self) dx))) (defmethod pix-to-y ((self y-graduated-view) y) (+ (y2 self) (float (/ y (y-factor self))))) (defmethod dpix-to-dy ((self y-graduated-view) dpix) (float (/ (- dpix) (y-factor self)))) (defmethod y-to-pix ((self y-graduated-view) y) (+ (y-shift self) (float (* (y-factor self) y)))) (defmethod dy-to-dpix ((self y-graduated-view) dy) (float (* (y-factor self) dy))) ;;;============================================ ;;; INTERACTIVE CONTROLLER FOR GRADUATED VIEWS ;;;============================================ (defclass ruler-view (om-view) ((vmin :accessor vmin :initarg :vmin :initform nil) (vmax :accessor vmax :initarg :vmax :initform nil) (decimals :accessor decimals :initarg :decimals :initform 0) ;; just for display (related-views :accessor related-views :initarg :related-views :initform nil))) (defclass x-ruler-view (ruler-view x-graduated-view) ()) (defclass y-ruler-view (ruler-view y-graduated-view) ()) (defmethod v1 ((self x-ruler-view)) (x1 self)) (defmethod v1 ((self y-ruler-view)) (y1 self)) (defmethod v2 ((self x-ruler-view)) (x2 self)) (defmethod v2 ((self y-ruler-view)) (y2 self)) (defmethod (setf v1) (val (self x-ruler-view)) (setf (x1 self) val)) (defmethod (setf v1) (val (self y-ruler-view)) (setf (y1 self) val)) (defmethod (setf v2) (val (self x-ruler-view)) (setf (x2 self) val)) (defmethod (setf v2) (val (self y-ruler-view)) (setf (y2 self) val)) (defmethod ruler-value-to-pix ((self x-ruler-view) v) (x-to-pix self v) ) (defmethod ruler-value-to-pix ((self y-ruler-view) v) (y-to-pix self v)) (defmethod ruler-value-at-pos ((self x-ruler-view) pix-pos) (pix-to-x self (om-point-x pix-pos))) (defmethod ruler-value-at-pos ((self y-ruler-view) pix-pos) (pix-to-y self (om-point-y pix-pos))) ;;; DIFFERENT UTILS FOR X vs. Y (defmethod ruler-size ((self x-ruler-view)) (w self)) (defmethod ruler-size ((self y-ruler-view)) (h self)) (defmethod ruler-width ((self x-ruler-view)) (h self)) (defmethod ruler-width ((self y-ruler-view)) (w self)) (defmethod draw-line-at ((self x-ruler-view) x size) (om-draw-line x 0 x size)) (defmethod draw-line-at ((self y-ruler-view) y size) (om-draw-line (- (w self) size) y (w self) y)) (defmethod draw-string-at ((self x-ruler-view) x str) (om-draw-string (- x 6) 18 str)) ; (round (h self) 1.5) (defmethod draw-string-at ((self y-ruler-view) y str) (om-draw-string 4 (- y 2) str)) (defmethod shift-value ((self x-ruler-view) point) (om-point-x point)) (defmethod shift-value ((self y-ruler-view) point) (om-point-y point)) (defmethod zoom-value ((self x-ruler-view) point) (om-point-y point)) (defmethod zoom-value ((self y-ruler-view) point) (om-point-x point)) (defmethod pix-diff-to-value ((self x-ruler-view) diff) diff) (defmethod pix-diff-to-value ((self y-ruler-view) diff) (- diff)) (defmethod update-view-from-ruler ((self ruler-view) (view om-view)) (om-invalidate-view view)) ;;; redraw upon resize #-macosx (defmethod om-view-resized :after ((self ruler-view) size) (om-invalidate-view self)) (defmethod update-view-from-ruler ((self x-ruler-view) (view x-graduated-view)) (setf (x1 view) (v1 self) (x2 view) (v2 self)) (set-shift-and-factor view) (call-next-method)) (defmethod update-view-from-ruler ((self y-ruler-view) (view y-graduated-view)) (setf (y1 view) (v1 self) (y2 view) (v2 self)) (set-shift-and-factor view) (call-next-method)) (defmethod update-views-from-ruler ((self ruler-view)) (loop for v in (related-views self) do (update-view-from-ruler self v))) (defmethod attach-view-to-ruler ((ruler ruler-view) view) (setf (related-views ruler) (append (related-views ruler) (list view))) (update-view-from-ruler ruler view)) (defmethod scale-ruler ((ruler ruler-view) val) (when (vmin ruler) (setf (vmin ruler) (round (* (vmin ruler) val)))) (when (vmax ruler) (setf (vmax ruler) (round (* (vmax ruler) val)))) (setf (v1 ruler) (round (* (v1 ruler) val)) (v2 ruler) (round (* (v2 ruler) val))) (when (< (abs (- (v1 ruler) (v2 ruler))) *min-ruler-extent*) (let ((half-diff (ceiling (- *min-ruler-extent* (abs (- (v1 ruler) (v2 ruler)))) 2)) (reversed (> (v1 ruler) (v2 ruler)))) (if reversed (setf (v1 ruler) (+ (v1 ruler) half-diff) (v2 ruler) (- (v2 ruler) half-diff)) (setf (v1 ruler) (- (v1 ruler) half-diff) (v2 ruler) (+ (v2 ruler) half-diff)) ))) (set-shift-and-factor ruler) (om-with-delayed-redraw (om-invalidate-view ruler) (update-views-from-ruler ruler))) (defmethod unit-value-str ((self ruler-view) value &optional (unit-dur 0)) (declare (ignore unit-dur)) (if (zerop (decimals self)) (format nil "~D" value) (format nil (format nil "~~,~DF" (decimals self)) (/ value (expt 10 (decimals self)))))) (defmethod set-ruler-range ((self ruler-view) v1 v2) (let* ((v11 (min v1 v2)) (v22 (max v1 v2))) (when (>= (- v22 v11) *min-ruler-extent*) (setf (v1 self) (max? (vmin self) v11)) (setf (v2 self) (min? (vmax self) v22)))) (set-shift-and-factor self) (om-with-delayed-redraw self (om-invalidate-view self) (update-views-from-ruler self)) ) (defmethod om-view-cursor ((self x-ruler-view)) (om-get-cursor :h-size)) (defmethod om-view-cursor ((self y-ruler-view)) (om-get-cursor :v-size)) ;; GET THE 'DUR' AND SIZE (pixels) of a unit ;; so that both maxsize and maxdur are not reached (defmethod get-units ((self ruler-view) &optional (maxsize 100)) (let* ((rsize (ruler-size self)) (dur (max 1 (abs (- (v2 self) (v1 self))))) (unit-dur (expt 10 (round (log dur 10)))) (unit-size (/ (* rsize unit-dur) dur))) (when (and (equal maxsize 100) (< rsize 100)) (setf maxsize 20)) (loop while (and (> unit-size maxsize)) do (setf unit-dur (/ unit-dur 10) unit-size (/ rsize (/ dur unit-dur)))) (values unit-dur unit-size))) (defmethod om-draw-contents ((self ruler-view)) (ruler-draw self)) (defparameter *ruler-font* (om-def-font :tiny)) (defmethod ruler-draw ((self ruler-view)) (let ((min-unit-size 40)) (multiple-value-bind (unit-dur unit-size) (get-units self) ;(print (list unit-dur unit-size)) ;(when (> unit-size 200) (setf unit-dur (/ unit-dur 10))) (om-with-focused-view self (om-with-fg-color (om-def-color :black) (let ((big-unit (* unit-dur 10))) (loop for vi from (* (floor (v1 self) big-unit) big-unit) to (v2 self) by big-unit do (let ((pixi (ruler-value-to-pix self vi))) (draw-line-at self pixi 6) ; (round rwidth 2.5) (om-with-font *ruler-font* (draw-string-at self pixi (unit-value-str self vi unit-dur))) ;draw detailed graduation (when (> unit-size 4) ; (>= big-unit 10)) (loop for vii from (+ vi unit-dur) to (- (+ vi big-unit) unit-dur) by unit-dur do (let ((pixii (ruler-value-to-pix self vii))) (draw-line-at self pixii 3) (if (> unit-size min-unit-size) (om-with-font *ruler-font* (draw-string-at self pixii (unit-value-str self vii unit-dur))) (when (eql (mod vii (/ big-unit 4)) 0) (om-with-font *ruler-font* (draw-string-at self pixii (unit-value-str self vii unit-dur))) )) ))) ))))) ))) (defun draw-h-grid-line (view y) (om-draw-line 0 y (w view) y)) (defun draw-v-grid-line (view x) (om-draw-line x 0 x (h view))) (defmethod draw-grid-line-from-ruler ((self om-view) (ruler x-ruler-view) x) (draw-v-grid-line self x)) (defmethod draw-grid-line-from-ruler ((self om-view) (ruler y-ruler-view) y) (draw-h-grid-line self y)) ;;; no draw without ruler (defmethod draw-grid-from-ruler ((self om-view) (ruler null)) nil) (defmethod draw-grid-from-ruler ((self om-view) (ruler ruler-view)) (let ((unit-dur (get-units ruler))) (loop for line from (* (ceiling (v1 ruler) unit-dur) unit-dur) to (* (floor (v2 ruler) unit-dur) unit-dur) by unit-dur do (let ((v (ruler-value-to-pix ruler line))) (draw-grid-line-from-ruler self ruler v) )) )) (defmethod ruler-zoom-? ((self ruler-view)) t) (defmethod om-view-click-handler ((self ruler-view) pos) (let ((curr-pos pos) (vmin (or (vmin self) nil)) ; -1000000 (vmax (or (vmax self) nil)) ; 1000000 (r-size (ruler-size self))) (om-init-temp-graphics-motion self pos NIL :motion #'(lambda (view position) (declare (ignore view)) (let* ((curr-v (ruler-value-at-pos self position)) (dur (- (v2 self) (v1 self))) (zoom (pix-diff-to-value self (- (zoom-value self position) (zoom-value self curr-pos)))) (shift (pix-diff-to-value self (- (shift-value self position) (shift-value self curr-pos))))) (if (and (ruler-zoom-? self) (> (abs zoom) (abs shift))) ;;; ZOOM (let* ((newdur (+ dur (* zoom 0.01 dur))) (v1 (max? vmin (- curr-v (/ (* (- curr-v (v1 self)) newdur) dur)))) (v2 (min? vmax (+ v1 newdur)))) (set-ruler-range self v1 v2)) ;;; TRANSLATE (let ((dt (* (/ shift r-size) dur))) (unless (or (and (plusp shift) vmin (= vmin (v1 self))) (and (minusp shift) vmax (= vmax (v2 self)))) (set-ruler-range self (max? vmin (- (v1 self) dt)) (min? vmax (- (v2 self) dt)))))) (setf curr-pos position))) :release #'(lambda (view position) (declare (ignore view position)) (update-views-from-ruler self)) ) )) ;;; !! reinit ranges apply on the editor attached to the first related-view ;;; to define a more specific behaviour, better sub-class the ruler (defmethod reinit-x-ranges-from-ruler ((editor t) ruler) nil) (defmethod reinit-y-ranges-from-ruler ((editor t) ruler) nil) (defmethod om-view-doubleclick-handler ((self x-ruler-view) pos) (let ((ed (and (related-views self) (editor (car (related-views self)))))) (when ed (reinit-x-ranges-from-ruler ed self)))) (defmethod om-view-doubleclick-handler ((self y-ruler-view) pos) (let ((ed (and (related-views self) (editor (car (related-views self)))))) (when ed (reinit-y-ranges-from-ruler ed self))))
13,657
Common Lisp
.lisp
257
45.44358
117
0.581428
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
9143bcf66ac6fcac70c641c3711fd140daf0cc85b57a4e4d6b13c5e30d2e5272
678
[ -1 ]
679
graphic-components.lisp
cac-t-u-s_om-sharp/src/visual-language/graphics/graphic-components.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;===================== ;;; 3D-border view ;;;===================== (defclass 3Dborder-view (om-view) ((c+ :accessor c+ :initform (om-make-color 0.835 0.835 0.843) :initarg :c+) (c++ :accessor c++ :initform (om-make-color 0.87 0.87 0.88) :initarg :c++) (c- :accessor c- :initform (om-make-color 0.604 0.604 0.604) :initarg :c-) (c-- :accessor c-- :initform (om-make-color 0.514 0.514 0.514) :initarg :c--))) (defmethod om-draw-contents ((self 3Dborder-view)) (call-next-method) (let ((x (om-h-scroll-position self)) (y (om-v-scroll-position self)) (w (om-point-x (om-view-size self))) (h (om-point-y (om-view-size self)))) (draw-3D-border self x y (+ x w) (+ y h)))) (defun draw-3D-border (self x y xx yy) (om-with-fg-color self (c++ self) (om-draw-line (+ x 1) y (- xx 1) y) (om-draw-line x (+ y 1) x (- yy 1))) (om-with-fg-color self (c+ self) (om-draw-line (+ x 2) (+ y 1) (- xx 2) (+ y 1)) (om-draw-line (+ x 1) (+ y 2) (+ x 1) (- yy 2))) (om-with-fg-color self (c-- self) (om-draw-line (+ x 1) (- yy 1) (- xx 1) (- yy 1)) (om-draw-line (- xx 1) (+ y 1) (- xx 1) (- yy 1))) (om-with-fg-color self (c- self) (om-draw-line (+ x 2) (- yy 2) (- xx 2) (- yy 2)) (om-draw-line (- xx 2) (+ y 2) (- xx 2) (- yy 2)))) ;========================================================== ; custom button with pict in "resources/di/" ;========================================================== ;(let ((win (om-make-window 'om-window)) ; (v (om-make-view 'om-view :size (om-make-point 500 500))) ; (but (om-make-graphic-object 'om-icon-button :icon :but :icon-pushed :but-pushed :lock-push t))) ; (om-add-subviews win v) ; (om-add-subviews v but) ; win) (defclass om-icon-button (om-item-view) ((icon :initform nil :accessor icon :initarg :icon) (icon-pushed :initform nil :accessor icon-pushed :initarg :icon-pushed) (icon-disabled :initform nil :accessor icon-disabled :initarg :icon-disabled) (pict :initform nil :accessor pict) (pict-pushed :initform nil :accessor pict-pushed) (pict-disabled :initform nil :accessor pict-disabled) (id :initform nil :accessor id :initarg :id) (action :initform nil :accessor action :initarg :action) (lock-push :initform nil :accessor lock-push :initarg :lock-push) (pushed :initform nil :accessor pushed :initarg :pushed) (enabled :initform t :accessor enabled :initarg :enabled) (text :initform nil :accessor text :initarg :text) (fg-color :initform nil :accessor fg-color :initarg :fg-color) (font :initform nil :accessor font :initarg :font))) (defmethod om-set-fg-color ((self om-icon-button) color) (setf (fg-color self) color) (om-invalidate-view self)) (defmethod button-select ((self om-icon-button)) (setf (pushed self) t) (om-invalidate-view self)) (defmethod button-unselect ((self om-icon-button)) (setf (pushed self) nil) (om-invalidate-view self)) (defmethod button-enable ((self om-icon-button)) (setf (enabled self) t) (om-invalidate-view self)) (defmethod button-disable ((self om-icon-button)) (setf (enabled self) nil) (om-invalidate-view self)) (defmethod om-view-doubleclick-handler ((self om-icon-button) where) (om-view-click-handler self where)) (defmethod om-view-click-handler ((self om-icon-button) where) (declare (ignore where)) (when (enabled self) (if (lock-push self) (setf (pushed self) (not (pushed self))) (setf (pushed self) t)) (om-invalidate-view self))) (defmethod om-click-release-handler ((self om-icon-button) where) (when (and (enabled self) (action self)) (om-with-error-handle (apply (action self) (list self)))) (unless (lock-push self) (setf (pushed self) nil)) (om-invalidate-view self)) (defmethod om-draw-contents ((self om-icon-button)) (call-next-method) (when (and (icon self) (not (pict self))) (setf (pict self) (om-load-picture-for-view (icon self) self))) (when (and (icon-pushed self) (not (pict-pushed self))) (setf (pict-pushed self) (om-load-picture-for-view (icon-pushed self) self))) (when (and (icon-disabled self) (not (pict-disabled self))) (setf (pict-disabled self) (om-load-picture-for-view (icon-disabled self) self))) (let* ((icn (or (and (pushed self) (icon-pushed self) (pict-pushed self)) (and (not (enabled self)) (icon-disabled self) (pict-disabled self)) (and (icon self) (pict self))))) (om-draw-picture icn :w (w self) :h (h self))) (when (text self) (let* ((ff (or (font self) (om-def-font :normal))) (cc (or (fg-color self) (om-def-color :black))) (wh (values-list (om-string-size (text self) ff))) (yy (round (+ (- (cadr wh) (if (pushed self) 5 6)) (h self)) 2)) (xx (max 0 (- (round (w self) 2) (ceiling (car wh) 2))))) (om-with-fg-color self cc (om-with-font ff (om-draw-string xx yy (text self)))))) (when (and (lock-push self) (pushed self) (not (icon-pushed self))) (om-draw-rect 0 0 (w self) (h self) :fill t :color (om-make-color-alpha (om-def-color :black) 0.5)))) ;========================================================== ; custom view to pick a color ;========================================================== (defclass color-view (om-view) ((color :accessor color :initarg :color :initform (om-make-color 0 0 0)) (after-fun :accessor after-fun :initform nil :initarg :after-fun) (with-alpha :accessor with-alpha :initform t :initarg :with-alpha) (border :accessor border :initform t :initarg :border))) (defmethod om-draw-contents ((self color-view)) (let ((c (or (color self) (om-def-color :gray)))) (unless (or (= (om-color-a c) 1) (= (om-color-a c) 0)) (om-draw-rect 0 0 (om-width self) (om-height self) :color (om-make-color 1 1 1) :fill t)) (om-draw-rect 0 0 (om-width self) (om-height self) :color (or (color self) (om-def-color :gray)) :fill (color self)) (when (not (om-view-enabled self)) (om-draw-rect 0 0 (om-width self) (om-height self) :color (om-make-color-alpha (om-def-color :white) 0.5) :fill t)) (when (= (om-color-a c) 0) (om-draw-line 0 0 (om-width self) (om-height self) :color (om-def-color :gray)) (om-draw-line 0 (om-height self) (om-width self) 0 :color (om-def-color :gray))) (when (border self) (om-draw-rect 0 0 (om-width self) (om-height self) :color (om-def-color :gray) :fill nil)) )) (defmethod om-view-click-handler ((self color-view) pos) (declare (ignore pos)) (when (om-view-enabled self) (let ((color (om-choose-color-dialog :color (color self) :alpha (with-alpha self) :owner self))) (when color (setf (color self) color) (om-invalidate-view self) (when (after-fun self) (funcall (after-fun self) self)))))) ;========================================================== ; custom view to pick a font ;========================================================== (defclass font-chooser-view (om-view) ((font :accessor font :initarg :font :initform nil) (after-fun :accessor after-fun :initarg :after-fun :initform nil) (face-chooser :accessor face-chooser) (size-chooser :accessor size-chooser) (style-chooser :accessor style-chooser))) (defmethod initialize-instance :after ((self font-chooser-view) &rest args) (om-add-subviews self (om-make-layout 'om-column-layout :delta 0 :subviews (list (setf (face-chooser self) (om-make-di 'om-popup-list :enabled (om-view-enabled self) :size (omp 116 22) :font (om-def-font :gui) :items (om-list-all-fonts) :selected-item (and (font self) (om-font-face (font self))) :di-action #'(lambda (list) (setf (font self) (om-make-font (om-get-selected-item list) (om-font-size (font self)) :style (om-font-style (font self)))) (when (after-fun self) (funcall (after-fun self) (font self)))) )) (om-make-layout 'om-row-layout :delta 2 :subviews (list (setf (size-chooser self) (om-make-di 'om-popup-list :enabled (om-view-enabled self) :size (omp 50 22) :font (om-def-font :gui) :items '(8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 24 28 32 36 40 52 64) :selected-item (and (font self) (om-font-size (font self))) :di-action #'(lambda (list) (setf (font self) (om-make-font (om-font-face (font self)) (om-get-selected-item list) :style (om-font-style (font self)))) (when (after-fun self) (funcall (after-fun self) (font self)))) )) (setf (style-chooser self) (om-make-di 'om-popup-list :enabled (om-view-enabled self) :size (omp 64 22) :font (om-def-font :gui) :items '("plain" "bold" "italic" "bold-italic") :selected-item (cond ((and (font self) (find :bold (om-font-style (font self))) (find :italic (om-font-style (font self)))) "bold-italic") ((and (font self) (find :bold (om-font-style (font self)))) "bold") ((and (font self) (find :italic (om-font-style (font self)))) "italic") (t "plain")) :di-action #'(lambda (list) (setf (font self) (om-make-font (om-font-face (font self)) (om-font-size (font self)) :style (case (om-get-selected-item-index list) (1 '(:bold)) (2 '(:italic)) (3 '(:bold :italic)) (otherwise '(:plain))))) (when (after-fun self) (funcall (after-fun self) (font self)))) )) )) )) )) (defmethod set-enabled ((self font-chooser-view) enabled) (om-set-view-enabled self enabled) (om-enable-dialog-item (face-chooser self) enabled) (om-enable-dialog-item (size-chooser self) enabled) (om-enable-dialog-item (style-chooser self) enabled)) (defmethod set-font ((self font-chooser-view) font) (setf (font self) font) (om-set-selected-item (face-chooser self) (om-font-face font)) (om-set-selected-item (size-chooser self) (om-font-size font)) (om-set-selected-item (style-chooser self) (cond ((and (font self) (find :bold (om-font-style (font self))) (find :italic (om-font-style (font self)))) "bold-italic") ((and (font self) (find :bold (om-font-style (font self)))) "bold") ((and (font self) (find :italic (om-font-style (font self)))) "italic") (t "plain")))) ;========================================================== ; custom view to change a text ;========================================================== (defclass click-and-edit-text (om-view) ((text :accessor text :initform "" :initarg :text) (after-fun :accessor after-fun :initform nil :initarg :after-fun) (border :accessor border :initform t :initarg :border) (wrap-lines :accessor wrap-lines :initform nil :initarg :wrap-lines)) (:default-initargs :resize-callback nil)) (defmethod om-draw-contents ((self click-and-edit-text)) (when (border self) (om-with-fg-color (border self) (om-draw-rect 0 0 (om-width self) (om-height self)))) (om-with-fg-color (if (om-view-enabled self) (om-get-fg-color self) (om-def-color :gray)) (om-draw-string 0 (cadr (multiple-value-list (om-string-size (text self) (om-get-font self)))) (text self) :wrap (if (wrap-lines self) (om-width self) nil)))) (defmethod om-view-click-handler ((self click-and-edit-text) pos) (declare (ignore pos)) (when (om-view-enabled self) (let ((txt (om-get-user-string "" :initial-string (text self)))) (when txt (setf (text self) txt) (om-invalidate-view self) (when (after-fun self) (funcall (after-fun self) self)))))) ;============== ; NUMBOX ;============== ;;; !! except set/get-value eveything is hanled as intergers (expt 10 decimals) (defclass numbox (om-item-text) ((value :initform 0 :initarg :value :accessor value) (min-val :initform 0 :initarg :min-val :accessor min-val) (max-val :initform nil :initarg :max-val :accessor max-val) (decimals :initform 0 :initarg :decimals :accessor decimals) (enabled :initform t :initarg :enabled :accessor enabled) (db-click :initform nil :initarg :db-click :accessor db-click) (allow-nil :initform nil :initarg :allow-nil :accessor allow-nil) (change-fun :initform nil :initarg :change-fun :accessor change-fun) (after-fun :initform nil :initarg :after-fun :accessor after-fun)) (:default-initargs :border t)) (defmethod om-view-cursor ((self numbox)) (om-get-cursor :v-size)) (defmethod initialize-instance :after ((self numbox) &rest args) (let ((v (getf args :value))) (when v (set-value self v))) (set-min-max self :min (getf args :min-val) :max (getf args :max-val)) (om-set-fg-color self (if (enabled self) (om-def-color :black) (om-def-color :gray)))) ;; the value internally is always an integer (defmethod set-value ((self numbox) value) (setf (value self) (if (zerop (decimals self)) (round value) (round (* value (expt 10 (decimals self)))))) (om-set-text self (if (zerop (decimals self)) (format () " ~D" (round value)) (format () " ~v$" (decimals self) value) )) (om-invalidate-view self)) (defmethod set-min-max ((self numbox) &key min max) (when min (setf (min-val self) (round (* min (expt 10 (decimals self)))))) (when max (setf (max-val self) (round (* max (expt 10 (decimals self))))))) (defmethod get-value ((self numbox)) (if (zerop (decimals self)) (value self) (float (/ (value self) (expt 10 (decimals self)))))) (defmethod enable-numbox ((self numbox) t-or-nil) (setf (enabled self) t-or-nil) (om-set-fg-color self (if (enabled self) (om-def-color :black) (om-def-color :gray)))) (defmethod map-mouse-increment ((self numbox)) (cond ((om-shift-key-p) 10) ((om-command-key-p) 100) (t 1))) (defmethod om-view-click-handler ((self numbox) where) (when (enabled self) (let ((start-y (om-point-y where)) (start-v (or (value self) (and (numberp (allow-nil self)) (allow-nil self))))) (when start-v (om-init-temp-graphics-motion self where NIL :motion #'(lambda (view position) (declare (ignore view)) (let* ((inc (- start-y (om-point-y position))) (new-val (+ start-v (* (map-mouse-increment self) inc)))) ;(print (list (min-val self) (max-val self))) (when (and (min-val self) (< new-val (min-val self))) (setf new-val (min-val self))) (when (and (max-val self) (> new-val (max-val self))) (setf new-val (max-val self))) ;;; in principle that's ok now... (when (and (or (null (min-val self)) (>= new-val (min-val self))) (or (null (max-val self)) (<= new-val (max-val self)))) (when (and (numberp (allow-nil self)) (= new-val (allow-nil self))) (setf new-val nil)) (setf (value self) new-val) (om-set-text self (format () " ~D" (get-value self))) (om-invalidate-view self) (when (and (change-fun self) (not (= (round new-val) start-v))) (funcall (change-fun self) self))))) :release #'(lambda (view position) (declare (ignore view position)) (when (after-fun self) (funcall (after-fun self) self))) ) )))) (defun mouse-screen-coordinates () (om-subtract-points (om-mouse-position nil) (omp 20 20))) (defmethod om-view-doubleclick-handler ((self numbox) where) (when (and (enabled self) (db-click self)) (let ((pos (mouse-screen-coordinates))) (open-mini-edit pos (get-value self) #'(lambda (tf) (let ((val (read-from-string (om-dialog-item-text tf) nil))) (if (or (and (numberp val) (or (null (max-val self)) (<= val (/ (max-val self) (expt 10 (decimals self))))) (or (null (min-val self)) (>= val (/ (min-val self) (expt 10 (decimals self)))))) (and (allow-nil self) (null val))) (progn (set-value self val) (when (after-fun self) (funcall (after-fun self) self))) (om-beep))))) ))) ;============== ; MINI EDIT ;============== (defclass mini-edit-window (om-no-border-win) ((textfield :accessor textfield :initform nil) (action :accessor action :initform nil))) (defmethod om-window-activate ((self mini-edit-window) &optional activatep) (unless activatep ;; = loose focus (when (action self) (funcall (action self) (textfield self))) (om-close-window self))) (defun open-mini-edit (position value action) (let ((text (format nil "~A" value)) (font (om-def-font :normal))) (multiple-value-bind (w h) (om-string-size text font) (let* ((tf (om-make-di 'om-editable-text :text text :font font :bg-color (om-def-color :white) :size (omp (+ w 20) (+ h 20)) :border t :di-action #'(lambda (item) (let ((window (om-view-window item))) (om-window-activate window nil) )) )) (win (om-make-window 'mini-edit-window :position position :win-layout (om-make-layout 'om-simple-layout :subviews (list tf))))) (setf (textfield win) tf) (setf (action win) action) win))))
21,971
Common Lisp
.lisp
415
38.373494
119
0.490971
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
96aa48067d87fe77c45732b2aa43aabc000b33144219ec243eef84ef304d980d
679
[ -1 ]
680
icon-picts.lisp
cac-t-u-s_om-sharp/src/visual-language/graphics/icon-picts.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;=================== ;;; ICONS ;;;=================== (in-package :om) ;;; Registers all images in the folder resources/icon ;;; ALL IDENTIFIERS ARE KEYWORD SYMBOLS (defun register-images (folder) (mapc #'(lambda (file) (let* ((ic (read-from-string (pathname-name file))) (id (if (numberp ic) ic (intern-k (format nil "~A" ic))))) (om-register-picture id file))) (om-directory folder :type (om-get-know-pict-types) :directories nil :recursive t)) T) ;;; called at startup (defun register-om-icons () (let ((resources-folder (om-resources-folder))) (register-images (om-relative-path '("icons") nil resources-folder)) (register-images (om-relative-path '("di") nil resources-folder))))
1,565
Common Lisp
.lisp
35
39.771429
77
0.51082
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
2b7cdac23e9986bc7f0c7a413a6b754cef9e032d76f3eae3fafdb551a6816e96
680
[ -1 ]
681
graphic-tools.lisp
cac-t-u-s_om-sharp/src/visual-language/graphics/graphic-tools.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;======================= ;;; GUI / GRAPHIC API UTILS FOR OM ;;;======================= (in-package :om) ;;;;====================================== ;;;; Graphic components utilities ;;;; muste be called on graphic objects only (window, view,dialog-item,...) ;;;;====================================== (defmethod x ((self t)) (om-point-x (om-view-position self))) (defmethod y ((self t)) (om-point-y (om-view-position self))) (defmethod w ((self t)) (om-width self)) (defmethod h ((self t)) (om-height self)) (defmethod x+w ((self t)) (+ (x self) (w self))) (defmethod y+h ((self t)) (+ (y self) (h self))) ;;;=================== ;;; POINTS/POSITIONS MANAGEMENT ;;;=================== (defparameter *box-label-font* (om-make-font "Arial" 18 :style '(:bold))) ;;;=================== ;;; POINTS/POSITIONS MANAGEMENT ;;;=================== (defmethod print-point (point) (if (om-point-p point) (let ((str (format nil "ompoint >>> x:~A y:~A" (om-point-x point) (om-point-y point)))) (print str) point) (print point))) (defun dot-prod-2D (p1 p2) (+ (* (om-point-x p1) (om-point-x p2)) (* (om-point-y p1) (om-point-y p2)))) (defun norm-2D (p) (sqrt (dot-prod-2D p p))) (defun dist2D (p1 p2) (norm-2D (om-subtract-points p1 p2))) (defun dist-to-line (pt lp1 lp2) (let ((v (om-subtract-points lp2 lp1)) (w (om-subtract-points pt lp1))) (let ((c1 (dot-prod-2D w v))) (if (<= c1 0 ) (dist2D pt lp1) (let ((c2 (dot-prod-2D v v))) (if (<= c2 c1) (dist2D pt lp2) (let* ((b (/ c1 c2)) (pb (om-add-points lp1 (om-make-point (round (* b (om-point-x v))) (round (* b (om-point-y v))))))) (dist2D pt pb)))))))) (defun om-point-in-line-p (pt lp1 lp2 delta) (<= (dist-to-line pt lp1 lp2) delta)) (defun om-point-in-rect-p (point rx ry rw rh) (let ((x1 (if (plusp rw) rx (+ rx rw))) (x2 (if (plusp rw) (+ rx rw) rx)) (y1 (if (plusp rh) ry (+ ry rh))) (y2 (if (plusp rh) (+ ry rh) ry))) (and (>= (om-point-x point) x1) (<= (om-point-x point) x2) (>= (om-point-y point) y1) (<= (om-point-y point) y2)))) (defun rect-intersection (r1x1 r1y1 r1x2 r1y2 r2x1 r2y1 r2x2 r2y2) (let ((r1x1 (min r1x1 r1x2)) (r1x2 (max r1x1 r1x2)) (r1y1 (min r1y1 r1y2)) (r1y2 (max r1y1 r1y2)) (r2x1 (min r2x1 r2x2)) (r2x2 (max r2x1 r2x2)) (r2y1 (min r2y1 r2y2)) (r2y2 (max r2y1 r2y2))) (let ((tx (max r1x1 r2x1)) (ty (max r1y1 r2y1)) (t2x (min r1x2 r2x2)) (t2y (min r1y2 r2y2))) (if (or (< t2x tx) (< t2y ty)) NIL (list tx ty (- t2x tx) (- t2y ty)))))) ;;;=================== ;;; COLORS ;;;=================== (defconstant *golden_ratio_conjugate* 0.618033988749895) (defun make-color (spec) (cond ((consp spec) (apply 'om-make-color spec)) ((null spec) (om-random-color)) ((symbolp spec) (om-def-color spec)) (t (om-random-color)))) (defun om-make-color-255 (r g b) (om-make-color (/ r 255.0) (/ g 255.0) (/ b 255.0))) (defun rgb2hsv (col) "convert RGB values into HSV values (list in float format (0.0 to 1.0))" (let* ( ;be sure we have a correct range for input (r (min (nth 0 col) 1.0)) (r (max r 0.0)) (g (min (nth 1 col) 1.0)) (g (max g 0.0)) (b (min (nth 2 col) 1.0)) (b (max b 0.0)) (min_rgb (min r g b)) (max_rgb (max r g b)) ) (if (= min_rgb max_rgb) (list 0.0 0.0 min_rgb) (progn (let* ( (tmp_d (if (= r min_rgb) (- g b) ( if (= b min_rgb) (- r g) (- b r)))) (tmp_h (if (= r min_rgb) 3 (if (= b min_rgb) 1 5))) (h (/ (* 60 (- tmp_h (/ tmp_d (- max_rgb min_rgb)))) 360)) (v max_rgb) (s (/ (- max_rgb min_rgb) max_rgb))) (list h s v)))))) (defun hsv2rgb (h s v) "Convert HSV into RGB (values in float format [0.0-1.0])" (let* ((hh (min 1.0 h)) (ss (min 1.0 s)) (vv (min 1.0 v)) (i (floor (* hh 6))) (f (- (* hh 6) i)) (p (* vv (- 1 ss))) (q (* vv (- 1 (* f ss)))) (tt (* vv (- 1 (* (- 1 f) ss))))) (case (mod i 6) (0 (values vv tt p)) (1 (values q vv p)) (2 (values p vv tt)) (3 (values p q vv)) (4 (values tt p vv)) (5 (values vv p q))))) (defmethod om-make-color-hsv (h s v &optional (alpha 1.0)) "create a omcolor with h s v float input" ;(oa::make-omcolor :c (color:make-hsv h s v alpha)) (multiple-value-bind (r g b) (hsv2rgb h s v) (om-make-color r g b alpha))) (defun om-interpole-colors (begin end steps) (if (< steps 2) (list begin end) (let* ((difR (/ (- (om-color-r end) (om-color-r begin)) steps)) (difG (/ (- (om-color-g end) (om-color-g begin)) steps)) (difB (/ (- (om-color-b end) (om-color-b begin)) steps))) (loop for i from 0 to (- steps 1) collect (om-make-color (float (+ (* i difR) (om-color-r begin))) (float (+ (* i difG) (om-color-g begin))) (float (+ (* i difB) (om-color-b begin)))))))) (defun om-random-color (&optional (alpha 1.0)) (om-make-color (random 1.0) (random 1.0) (random 1.0) alpha)) (defmethod om-random-color-hsv (s v &optional (alpha 1.0)) (om-make-color-hsv (random 1.0) s v alpha)) (defmethod om-create-palette-from-color (col size) "Creates a palette of colors spaced with golden ratio for readability. It use a first color as source and and number of colors to generate" (let* ((r (om-color-r col)) (g (om-color-g col)) (b (om-color-b col)) (hsv (rgb2hsv (list r g b)))) (loop for i from 0 to (1- size) collect (om-make-color-hsv (mod (+ (nth 0 hsv) (* i *golden_ratio_conjugate* )) 1.0) (nth 1 hsv) (nth 2 hsv)) ))) (defmethod find-next-color-in-golden-palette (col) "compute the next color spaced by the golden ratio from the previous one in hue" (let* ((r (om-color-r col)) (g (om-color-g col)) (b (om-color-b col)) (hsv (rgb2hsv (list r g b)))) (om-make-color-hsv (mod (+ (nth 0 hsv) *golden_ratio_conjugate*) 1.0) (nth 1 hsv) (nth 2 hsv)))) (defun om-get-dark-offset-color (col factor) (let ((r (max 0.0 (- (om-color-r col) factor))) (g (max 0.0 (- (om-color-g col) factor))) (b (max 0.0 (- (om-color-b col) factor)))) (om-make-color r g b))) (defun om-get-light-offset-color (col factor) (let ((r (min 0.9 (+ (om-color-r col) factor))) (g (min 0.9 (+ (om-color-g col) factor))) (b (min 0.9 (+ (om-color-b col) factor)))) (om-make-color r g b))) (defun om-get-saturated-color (col) (let* ((r (om-color-r col)) (g (om-color-g col)) (b (om-color-b col)) (hsv (rgb2hsv (list r g b)))) (om-make-color-hsv (nth 0 hsv) 1.0 1.0))) (defun om-get-darker-color (col factor) (let* ((r (om-color-r col)) (g (om-color-g col)) (b (om-color-b col)) (hsv (rgb2hsv (list r g b))) (new_v (max 0.0 (- (nth 2 hsv) factor)))) (om-make-color-hsv (nth 0 hsv) (nth 1 hsv) new_v))) (defun om-get-lighter-color (col factor) (let* ((r (om-color-r col)) (g (om-color-g col)) (b (om-color-b col)) (hsv (rgb2hsv (list r g b))) (new_v (min 1.0 (+ (nth 2 hsv) factor)))) (om-make-color-hsv (nth 0 hsv) (nth 1 hsv) new_v))) ;;;=================== ;;; Cursors ;;;=================== (defun init-om-cursors () (let ((cursor-folder (om-relative-path '("curs") nil (om-resources-folder)))) (flet ((cursor-file (name) (merge-pathnames name cursor-folder))) (om-add-cursor :wait #+cocoa (cursor-file "wait-cursor") #-cocoa :busy (om-make-point 8 8)) (om-add-cursor :arrow nil) (om-add-cursor :h-size #+cocoa (cursor-file "h-resize-cursor") #-cocoa :h-double-arrow (om-make-point 8 8)) (om-add-cursor :v-size #+cocoa (cursor-file "v-resize-cursor") #-cocoa :v-double-arrow (om-make-point 8 8)) (om-add-cursor :resize #+cocoa (cursor-file "resize-cursor") #-cocoa :bottom-right-corner (om-make-point 8 8)) (om-add-cursor :i-beam :i-beam) (om-add-cursor :cross #+cocoa (cursor-file "croix") #-cocoa :fleur (om-make-point 8 8)) (om-add-cursor :hand #+cocoa :open-hand #-cocoa (cursor-file "hand-cursor")) (om-add-cursor :context-menu (cursor-file "contex-cursor")) (om-add-cursor :add (cursor-file "+-cursor")) (om-add-cursor :loupe (cursor-file "loupe-cursor") (om-make-point 6 6)) (om-add-cursor :pen (cursor-file "pen-cursor") (om-make-point 2 10)) (om-add-cursor :point (cursor-file "point-cursor") (om-make-point 4 4)) ))) (add-om-init-fun 'init-om-cursors) ;;;============================================ ;;; TEMP-GRAPHICS ;;;============================================ (defclass selection-rectangle (om-item-view) ()) ;;; selection rectangle can have negative sizes (defmethod om-draw-contents ((self selection-rectangle)) (let ((x (if (plusp (w self)) 0 -2)) (y (if (plusp (h self)) 0 -2)) (w (- (w self) (if (plusp (w self)) 1 -4))) (h (- (h self) (if (plusp (h self)) 1 -4)))) (om-draw-rect x y w h :line 1 :color (om-def-color :selection-a) :fill t) (om-draw-rect x y w h :line 1 :color (om-def-color :selection-inv) :angles :round) )) (defmethod oa::default-motion-action ((self selection-rectangle) position) (om-set-view-size self (om-subtract-points position (oa::init-pos oa::*global-motion-handler*)))) (defclass drag-line (om-item-view) ()) ;;; selection rectangle can have negative sizes (defmethod om-draw-contents ((self drag-line)) (let ((x1 (if (plusp (w self)) 0 -2)) (y1 (if (plusp (h self)) 0 -2)) (x2 (- (w self) (if (plusp (w self)) 1 -4))) (y2 (- (h self) (if (plusp (h self)) 1 -4))) (linesize 2)) (om-with-line-size linesize (om-with-fg-color (om-def-color :gray) (om-with-line '(1 3) (om-draw-line x1 y1 x2 y2) ;(if (> y2 y1) ; (let ((y-mid (+ y1 (round (- y2 y1) 2)))) ; (om-draw-line x1 y1 x1 y-mid) ; (om-draw-line x1 y-mid x2 y-mid) ; (om-draw-line x2 y-mid x2 y2) ; ) ; (let ((x-mid (+ x1 (round (- x2 x1) 2)))) ;(om-draw-line x1 y1 x1 (+ y1 10)) ;(om-draw-line x1 (+ y1 10) x-mid (+ y1 10)) ;(om-draw-line x-mid (+ y1 10) x-mid (- y2 10)) ;(om-draw-line x-mid (- y2 10) x2 (- y2 10)) ;(om-draw-line x2 (- y2 10) x2 y2) ;)) ))))) ;;;================================================ ;;; SPLINE CURVES ;;;================================================ ;;; SPLINE CURVES - JB ;;; algo adapted from P. Bourke ;;; http://astronomy.swin.edu.au/~pbourke/curves/spline/ (defun spline (points degree resolution) (let* ((N (- (length points) 1)) (knots (SplineKnots N degree))) (SplineCurve2D points N knots degree resolution))) ;; This returns the point "output" on the spline curve. ;; The parameter "v" indicates the position, it ranges from 0 to n-t+2 ;; u = int*, n = int, tt = int, v = double, control = XYZ*, output = XYZ* (defun SplinePoint (u n tt v control) (let ((b 0) (outp (list 0 0 0))) (loop for k = 0 then (+ k 1) while (<= k n) do (setf b (SplineBlend k tt u v)) (setf (nth 0 outp) (+ (nth 0 outp) (* (nth 0 (nth k control)) b))) (setf (nth 1 outp) (+ (nth 1 outp) (* (nth 1 (nth k control)) b))) (setf (nth 2 outp) (+ (nth 2 outp) (* (nth 2 (nth k control)) b))) ) outp)) (defun SplinePoint2D (u n tt v control) (let ((b 0) (outp (list 0 0))) (loop for k = 0 then (+ k 1) while (<= k n) do (setf b (SplineBlend k tt u v)) (setf (nth 0 outp) (+ (nth 0 outp) (* (nth 0 (nth k control)) b))) (setf (nth 1 outp) (+ (nth 1 outp) (* (nth 1 (nth k control)) b))) ) outp)) ;; Calculate the blending value, this is done recursively. ;; If the numerator and denominator are 0 the expression is 0. ;; If the deonimator is 0 the expression is 0 ;; k = int, tt = int, u = int*, v = double (defun SplineBlend (k tt u v) (let ((value 0)) (setf value (if (= tt 1) (if (and (<= (nth k u) v) (< v (nth (+ k 1) u))) 1 0) (if (and (= (nth (+ k tt -1) u) (nth k u)) (= (nth (+ k tt) u) (nth (+ k 1) u))) 0 (if (= (nth (+ k tt -1) u) (nth k u)) (* (/ (- (nth (+ tt k) u) v) (- (nth (+ tt k) u) (nth (+ k 1) u))) (SplineBlend (+ k 1) (- tt 1) u v)) (if (= (nth (+ tt k) u) (nth (+ k 1) u)) (* (/ (- v (nth k u)) (- (nth (+ k tt -1) u) (nth k u))) (SplineBlend k (- tt 1) u v)) (+ (* (/ (- v (nth k u)) (- (nth (+ tt k -1) u) (nth k u))) (SplineBlend k (- tt 1) u v)) (* (/ (- (nth (+ k tt) u) v) (- (nth (+ k tt) u) (nth (+ k 1) u))) (SplineBlend (+ k 1) (- tt 1) u v))) ))))) value)) ;; The positions of the subintervals of v and breakpoints, the position ;; on the curve are called knots. Breakpoints can be uniformly defined ;; by setting u[j] = j, a more useful series of breakpoints are defined ;; by the function below. This set of breakpoints localises changes to ;; the vicinity of the control point being modified. ;; u = int*, n = int, tt = int (defun SplineKnots (n tt) (let ((u (make-sequence 'list (+ n tt 1)))) (loop for j = 0 then (+ j 1) while (<= j (+ n tt)) do (if (< j tt) (setf (nth j u) 0) (if (<= j n) (setf (nth j u) (+ j (- tt) 1)) (if (> j n) (setf (nth j u) (+ n (- tt) 2))))) ) u)) ;; Create all the points along a spline curve ;; Control points "inp", "n" of them. ;; Knots "knots", degree "t". ;; Ouput curve "outp", "res" of them. ;; inp = XYZ*, n = int, knots = int*, tt = int, outp = XYZ*, res = int (defun SplineCurve (inp n knots tt res) (let ((outp (make-sequence 'list res)) (interval 0) (increment (/ (+ n (- tt) 2) (float (- res 1))))) (loop for i = 0 then (+ i 1) while (< i (- res 1)) do (setf (nth i outp) (SplinePoint knots n tt interval inp)) (incf interval increment)) (setf (nth (- res 1) outp) (nth n inp)) outp)) (defun SplineCurve2D (inp n knots tt res) (let ((outp (make-sequence 'list res)) (interval 0) (increment (/ (+ n (- tt) 2) (float (- res 1))))) (loop for i = 0 then (+ i 1) while (< i (- res 1)) do (setf (nth i outp) (SplinePoint2D knots n tt interval inp)) (incf interval increment)) (setf (nth (- res 1) outp) (nth n inp)) outp)) ;; Example of how to call the spline functions ;;Basically one needs to create the control points, then compute ;; the knot positions, then calculate points along the curve. ;define N 3 ;XYZ inp[N+1] = {0.0,0.0,0.0, 1.0,0.0,3.0, 2.0,0.0,1.0, 4.0,0.0,4.0}; ;define T 3 ;int knots[N+T+1]; ;define RESOLUTION 200 ;XYZ outp[RESOLUTION];
16,226
Common Lisp
.lisp
373
36.820375
141
0.516464
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
f2184f7b1dfb8ad2f186be9b44acfa94ea945c855a5e7ce2db54cd70c8747b1d
681
[ -1 ]
682
frames.lisp
cac-t-u-s_om-sharp/src/visual-language/graphics/frames.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;=========================== ;FRAMES ;=========================== (defclass OMFrame (OMObject) ((object :initform nil :initarg :object :accessor object) (state :initform nil :accessor state) (areas :initform nil :initarg :areas :accessor areas) (active-area :initform nil :initarg :active-area :accessor active-area) ) (:documentation "This is the class of frames which visualize the OMBasicObjects. Frames can be simple frames (icons, boxes, etc.) or container frames (patch editor, folder editor, etc.)" )) (defmethod get-help ((self OMFrame)) nil) ;;;================================= ;;; OMFrame implements a system of virtual subviews (or 'picking views') ;;;================================= (defclass frame-area () ((active :initform nil :initarg :active :accessor active) (object :initform nil :initarg :object :accessor object) (frame :initform nil :initarg :frame :accessor frame) (pos :initform nil :initarg :pos :accessor pos) (pick :initform '(0 0 0 0) :initarg :pick :accessor pick))) (defmethod get-position ((self frame-area)) (if (functionp (pos self)) (funcall (pos self) (frame self)) (pos self))) (defmethod get-pick ((self frame-area)) (if (functionp (pick self)) (funcall (pick self) (frame self)) (pick self))) (defmethod disabled-area ((area frame-area)) nil) (defmethod apply-in-area ((self OMFrame) function position) (let ((aa (active-area-at-pos self position))) (when aa (unless (disabled-area aa) (funcall function aa self)) ;;; the funcall must return T or the click will be reported to the frame ))) (defmethod active-area-at-pos ((self OMFrame) pos) (let ((aa nil)) (loop for area in (areas self) while (not aa) do (setf aa (and (enabled-area area) (area-at-pos? area (om-point-x pos) (om-point-y pos))))) aa)) (defmethod enabled-area ((self frame-area)) self) (defmethod area-at-pos? ((self frame-area) x y) (let ((p (get-position self)) (pick (get-pick self))) (and (>= x (+ (om-point-x p) (car pick))) (<= x (+ (om-point-x p) (caddr pick))) (>= y (+ (om-point-y p) (cadr pick))) (<= y (+ (om-point-y p) (cadddr pick))) self))) ;;; by default frame areas are invisible (defmethod om-draw-area ((area frame-area)) nil) (defmethod area-tt-text ((self frame-area)) nil) (defmethod area-tt-pos ((self frame-area)) (om-add-points (om-convert-coordinates (get-position self) (frame self) (om-view-container (frame self))) (om-make-point -20 (* -12 (1+ (length (list! (area-tt-text self)))))))) (defmethod om-enter-area ((area frame-area)) (unless (disabled-area area) (setf (active area) t) (when (area-tt-text area) (om-show-tooltip (om-view-container (frame area)) (area-tt-text area) (area-tt-pos area) 0.04)) (om-invalidate-view (frame area)))) (defmethod om-leave-area ((area frame-area)) (setf (active area) nil) (when (area-tt-text area) (om-hide-tooltip (om-view-container (frame area)))) (om-invalidate-view (frame area))) (defmethod om-view-cursor ((area frame-area)) nil) (defmethod om-view-mouse-motion-handler ((self OMFrame) position) (let ((aa (active-area-at-pos self position))) (when (and (active-area self) (not (equal aa (active-area self)))) (om-leave-area (active-area self)) (om-set-view-cursor self (om-view-cursor self))) (if (and aa (not (equal aa (active-area self)))) (om-enter-area aa) (om-set-view-cursor self (om-view-cursor self))) (setf (active-area self) aa))) (defmethod om-view-mouse-enter-handler ((self OMFrame)) ;(om-print-dbg "ENTER ~A" (list self)) (let ((helptext (get-help self))) (when (and helptext (om-command-key-p)) (om-show-tooltip (om-view-container self) helptext nil)))) (defmethod om-view-mouse-leave-handler ((self OMFrame)) ;(om-print-dbg "LEAVE ~A" (list self)) (when (active-area self) (om-leave-area (active-area self)) (setf (active-area self) nil)) (om-hide-tooltip (om-view-container self))) ;;;================================= ;;; OMFrame subclasses ;;;================================= ;;; OMSimpleFrame and OMCompoundFrame are identical ;;; but they are implemented differently in the underlying API (defclass OMSimpleFrame (OMFrame om-item-view om-drag-view) ()) (defclass OMCompoundFrame (OMFrame om-internal-view) ()) (defclass OMContainerFrame (om-view OMFrame) () (:documentation "Container frames are frames which can containt OMSimpleFrames within. In general EditorFrames are instances of the class metaobj-panel, this class inherites from the 'View' class and the 'OMcontainerFrame' class.#enddoc# #seealso# (metaobj-panel) #seealso#"))
5,560
Common Lisp
.lisp
120
42.308333
108
0.621072
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
a52bc112bccc0023cc0f08cdf1d53d372bdef9cce332242d2ee726e099c1d5ce
682
[ -1 ]
683
editor.lisp
cac-t-u-s_om-sharp/src/visual-language/windows/editor.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;==================== ;;; EDITOR GENERAL CLASSES ;;;==================== (defclass OMEditor () ((object :initarg :object :initform nil :accessor object) (container-editor :initarg :container-editor :initform nil :accessor container-editor) (related-editors :initarg :related-editors :initform nil :accessor related-editors) (window :initarg :window :initform nil :accessor window) (main-view :initarg :main-view :initform nil :accessor main-view) (g-components :initarg :g-components :initform nil :accessor g-components) (with-default-components :initarg :with-default-components :accessor with-default-components :initform t) (selection :accessor selection :initform nil))) ;;; redefinition of the window slot accessor (defmethod window ((self OMEditor)) (or (slot-value self 'window) (and (container-editor self) (not (equal self (container-editor self))) ;;; in the sequencer editor, the editor is its own container.. (window (container-editor self))))) ;;;============================= ;;; EDIT-PARAMS ;;;============================= (defclass object-with-edit-params () ((edition-params :initform nil :accessor edition-params :initarg :edition-params))) (defmethod get-edit-param ((self object-with-edit-params) param) (if (find param (edition-params self) :key 'car) (find-value-in-kv-list (edition-params self) param) (get-default-edit-param self param))) (defmethod get-default-edit-param ((self object-with-edit-params) param) nil) (defmethod set-edit-param ((self object-with-edit-params) param value) (setf (edition-params self) (set-value-in-kv-list (edition-params self) param value))) ;;; this is useful to open the editor of something that is not necessarily in a box ;;; serves as the 'object' of the editor (defclass OMAbstractContainer (ObjectWithEditor object-with-edit-params) ((contents :initarg :contents :initform nil :accessor contents))) (defmethod get-default-edit-param ((self OMAbstractContainer) param) (find-value-in-kv-list (object-default-edition-params (contents self)) param)) (defmethod get-value-for-editor ((self t)) self) (defmethod get-value-for-editor ((self OMAbstractContainer)) (contents self)) (defmethod object-value ((self OMEditor)) (cond ((object self) (get-value-for-editor (object self))) ((container-editor self) (object-value (container-editor self))) (t nil) )) ;;;============================= ;;; Superclass for main editors (patch, sequencer, Lispfile, etc.) (defclass OMDocumentEditor (OMEditor) ()) (defmethod save-command ((self OMDocumentEditor)) #'(lambda () (let ((doc-to-save (if (is-persistant (object self)) (object self) (find-persistant-container (object self))))) (if doc-to-save (progn (save-document doc-to-save) (update-window-name (editor doc-to-save))) (om-beep-msg "No container document to save !!!")) ))) (defmethod save-as-menu-name ((self OMDocumentEditor)) (if (is-persistant (object self)) "Save as..." "Externalize...")) (defmethod externalized-type ((self t)) nil) (defmethod save-as-command ((self OMDocumentEditor)) (let ((doc (object self))) (if (is-persistant doc) ;;; rename/resave the doc #'(lambda () (let ((sg-pathname (mypathname doc))) (setf (mypathname doc) nil) (if (save-document doc) ;; set name is done here in save-document (update-window-name self) (setf (mypathname doc) sg-pathname))) ) ;;; create a persistant patch if the type exists (when (externalized-type doc) #'(lambda () (change-class doc (externalized-type doc) :icon (externalized-icon doc)) (setf (create-info doc) (list (om-get-date) (om-get-date) *app-name* *version*)) (register-document doc) (save-document doc) ;; set name is done here in save-document (funcall (revert-command self)) ;; to update menus etc. )) ))) (defmethod revert-command ((self OMDocumentEditor)) (and (is-persistant (object self)) (mypathname (object self)) #'(lambda () (with-no-check (om-close-window (window self))) (open-doc-from-file (object-doctype (object self)) (mypathname (object self))) ))) ;;; Externalize an internal abstraction ;;;============================= (defclass OMEditorWindow (om-window) ((editor :initarg :editor :initform nil :accessor editor) (side-panel :initarg :side-panel :initform nil :accessor side-panel))) ;;; CLASS LINKS (defmethod editor-window-class ((self OMEditor)) 'OMEditorWindow) ;;; GET DEFAULT EDITOR VIEW USING THESE METHODS (defmethod editor-view-class ((window OMEditor)) 'OMDefaultEditorView) (defmethod editor-view-bg-color ((self OMEditor)) nil) (defmethod editor-view-scroll-params ((self OMEditor)) nil) (defmethod editor-view-drawable ((self OMEditor)) nil) ;;; ACCESSORS (defmethod editor-window ((self ObjectWithEditor)) (and (editor self) (window (editor self)))) (defmethod editor-view ((self ObjectWithEditor)) (main-view (editor self))) (defmethod editor ((self om-graphic-object)) (editor (om-view-window self))) (defmethod editor ((self t)) nil) ;;;==================== ;;; OBJECT WITH EDITOR ;;;==================== ;;; Create and open the editor for an object (defmethod open-editor ((self t)) nil) (defmethod open-editor ((self ObjectWithEditor)) (unless (editor self) (setf (editor self) (make-instance (get-editor-class self) :object self)) (init-editor (editor self))) (open-editor-window (editor self))) ;;; Close the editor for the object (defmethod close-editor ((self ObjectWithEditor)) (when (editor-window self) (om-close-window (editor-window self))) ;;; will call "close-editor" from the callback t) (defmethod close-editor ((self t)) t) ;;; called by the editor to notify a change ;;; to be redefined by the ObjectWithEditor subclasses ;;; <value-changed> specifies if the object value has changed, typically to decide wether or not to invalidate display, lock the box, etc. ;;; you don't wan to set it true, for instance, if this is just a graphical update (e.g. window size) ;;; <reactive> specifies if this change should be a candidate for triggering reactive updates ;;; you don't want to set it true, e.g. with changes that happen too frequently (e.g. results of move-drag actions). (defmethod update-from-editor ((self ObjectWithEditor) &key (value-changed t) (reactive t)) (declare (ignore value-changed reactive)) nil) (defmethod update-from-editor ((self t) &key (value-changed t) (reactive t)) (declare (ignore value-changed reactive)) nil) (defmethod window-name-from-object ((self ObjectWithEditor)) (name self)) (defmethod editor-set-edit-param ((self OMEditor) param value) (set-edit-param (object self) param value) (editor-invalidate-views self)) (defmethod editor-get-edit-param ((self OMEditor) param) (get-edit-param (object self) param)) ;;;==================== ;;; EDITOR ;;;==================== (defmethod get-editor-class ((self t)) 'OMEditor) (defmethod init-editor ((ed OMEditor)) nil) (defmethod editor-window-init-size ((self OMEditor)) (om-make-point 500 500)) (defmethod editor-window-init-pos ((self OMEditor)) (om-make-point 500 500)) (defmethod get-object-type-name ((object t)) (string-downcase (type-of object))) (defmethod editor-name-for-window-title ((object t)) (get-object-type-name object)) (defmethod update-window-name ((self OMEditor)) (when (window self) ;;; the main window editor is not necessary the one calling (om-set-window-title (window self) (editor-window-title (editor (window self)))))) (defmethod editor-window-title ((editor OMEditor)) (if (container-editor editor) (editor-window-title (container-editor editor)) (let ((editor-name (editor-name-for-window-title (object editor))) (extra-info (extra-window-title-info (object editor)))) (string+ (get-name (object editor)) (if editor-name (string+ " [" editor-name " Editor]") "") (if extra-info (string+ " " extra-info) "") )))) (defmethod editor-window-title ((editor OMDocumentEditor)) (window-name-from-object (object editor))) (defmethod extra-window-title-info ((object t)) "") ;;; Opens the window for an editor (defmethod open-editor-window ((self OMEditor)) (if (and (window self) (om-window-open-p (window self))) (om-select-window (window self)) (let* ((size (or (window-size (object self)) (editor-window-init-size self))) (win (om-make-window (editor-window-class self) :editor self :size size :position (window-pos (object self)) :title (editor-window-title self) :win-layout 'om-simple-layout :border 0 :menu-items (om-menu-items self)))) ;;; something strange going on during window creation, resize happening ;;; so we need to reset window-size here (setf (window-size (object self)) (om-view-size win)) (setf (window self) win) (build-editor-window self) (init-editor-window self) (om-show-window win) (when (get-g-component self :main-panel) (om-set-focus (get-g-component self :main-panel))) ))) ;;; the g-component p-list stores and accesses ;;; views and dialog items related to the editor (defmethod set-g-component ((self OMEditor) name comp) (setf (getf (g-components self) name) comp)) (defmethod get-g-component ((self OMEditor) name) (getf (g-components self) name)) ;;; callback called when anything closes the window ;;; called by the close-window event (defmethod editor-close ((self t)) nil) (defmethod editor-close ((self OMEditor)) (call-next-method) (setf (editor (object self)) nil)) ;;; callback called when the window is brought to front or back (defmethod editor-activate ((self OMEditor) t-or-nil) (if t-or-nil (update-inspector-for-editor self) ;;; (release-inspector self) ;; can remove this )) (defmethod update-inspector-for-editor ((self OMEditor) &optional obj (force-update nil)) (update-inspector-for-object (or obj (object self)))) ;;; called by the window/view to notify a change in the model (defmethod report-modifications ((self null)) t) (defmethod report-modifications ((self OMEditor)) ;;; update the object (update-from-editor (object self)) ;;; update the context (in case of embedded editors) (when (and (container-editor self) (not (equal self (container-editor self)))) ;;; the sequencer-editor is its own container... :( (update-to-editor (container-editor self) self) (report-modifications (container-editor self))) (when (related-editors self) (loop for ed in (related-editors self) do (update-to-editor ed self))) ;;; window title (update-window-name self)) ;;; called by the object to notify a change to the editor (defmethod update-to-editor ((self OMEditor) (from t)) ;(print (list "update" self "from" from)) (update-window-name self)) (defmethod update-default-view ((self OMEditor)) (when (get-g-component self :default-view) (update-view-contents (get-g-component self :default-view)))) ;;; called by a sub-editor when modified ;(defmethod update-container ((self OMEditor)) nil) (defmethod editor-invalidate-views ((self OMEditor)) nil) ;;;=============================== ;;; EDITORS HANDLE USER ACTIONS (defmethod allowed-element ((self OMObject) elem) nil) (defmethod allow-remove ((self OMObject) elem) t) (defmethod omNG-add-element ((self OMEditor) elem) (if (allowed-element (object self) elem) (progn (omNG-add-element (object self) elem) (report-modifications self) t) (om-beep-msg (format nil "Elements of type ~A not allowed in ~A" (type-of elem) (type-of (object self)))) )) (defmethod omNG-remove-element ((self OMEditor) elem) (if (allow-remove (object self) elem) (progn (omNG-remove-element (object self) elem) (report-modifications self) t) (om-beep-msg (format nil "Elements of type ~A can not be removed from ~A" (type-of elem) (type-of (object self)))) )) ;;; GENERAL COMMANDS FOR ALL WINDOWS (defmethod close-command ((self OMEditor)) #'(lambda () (om-close-window (window self)))) (defmethod editor-key-action ((self OMEditor) key) nil) (defmethod dispatch-key-action ((self OMEditor) key) (editor-key-action self key)) (defun om-add-key-down () (om-command-key-p)) (defun om-action-key-down () #+macosx(om-command-key-p) #-macosx(and (om-shift-key-p) (om-command-key-p))) ;;;==================== ;;; EDITOR VIEW ;;; the main-view of the editor should be an editor view (?) ;;;==================== (defclass OMEditorView (om-view) ((editor :accessor editor :initform nil :initarg :editor))) #+(or windows linux) (defmethod om-view-resized :after ((self OMEditorView) size) (om-invalidate-view self)) ;;;==================== ;;; EDITOR WINDOW ;;;==================== (defmethod build-editor-window ((editor OMEditor)) (let ((win (window editor))) (when win (om-remove-all-subviews win) (multiple-value-bind (contents main) (make-editor-window-contents editor) (setf (main-view editor) (or main contents)) (om-add-subviews win contents) )))) (defmethod init-editor-window ((ed OMEditor)) nil) ;;; called by build-editor-window ;;; this function is given the opportunity to provide what's the main-view of the editor thanks as a second value (defmethod make-editor-window-contents ((editor OMEditor)) (make-default-editor-view editor)) ;;; can be called in redefinitions of make-editor-window-contents (defmethod make-default-editor-view ((editor OMEditor)) (when (with-default-components editor) (apply 'om-make-view (append (list (editor-view-class editor) :direct-draw (editor-view-drawable editor) :editor editor :scrollbars (editor-view-scroll-params editor)) (and (editor-view-bg-color editor) (list :bg-color (editor-view-bg-color editor)))) ))) ;;; not very clean... ;(defmethod build-editor-window :after (editor) ; (when (main-view editor) ; (om-view-resized (main-view editor) (om-view-size (main-view editor))))) (defmethod om-window-activate ((self OMEditorWindow) &optional (activatep t)) (editor-activate (editor self) activatep)) (defmethod om-window-close-event ((self OMEditorWindow)) (editor-close (editor self)) (setf (window-size (object (editor self))) (om-view-size self)) (setf (window (editor self)) nil) (setf (g-components (editor self)) nil)) (defmethod om-window-check-before-close ((self OMEditorWindow)) ;(print (list "close" self)) (and (ask-save-before-close (object (editor self))) (call-next-method))) (defmethod om-view-key-handler ((self OMEditorWindow) key) ;(print (list "omeditorwindow" self key)) (dispatch-key-action (editor self) key)) (defmethod om-window-resized ((self OMEditorWindow) size) (let ((ed (editor self))) (when ed ;;; sometimes the editor is not yet set (e.g. textbuffer editor) (let ((obj (object ed))) (setf (window-size obj) size) (when (om-initialized-p self) ;;; avoids to do this during init calls (update-from-editor obj :value-changed nil :reactive nil)) ) (editor-resized ed) ))) ;;; editors can use this to refresh subviews etc. (?) (defmethod editor-resized ((self omeditor)) nil) (defmethod om-window-moved ((self OMEditorWindow) pos) (let ((ed (editor self))) (when ed ;;; sometimes the editor is not yet set (e.g. textbuffer editor) (let ((obj (object ed))) (setf (window-pos obj) pos) (when (om-initialized-p self) ;;; avoids to do this during init calls (update-from-editor obj :value-changed nil :reactive nil)) )))) ;;;==================== ;;; SELECTION TOOLS ;;;==================== (defmethod set-selection ((editor OMEditor) new-selection) (cond ((and (om-shift-key-p) new-selection) (if (find new-selection (selection editor)) (setf (selection editor) (remove new-selection (selection editor))) (progn (setf (selection editor) (cons new-selection (selection editor))) ))) (t (unless (find new-selection (selection editor)) (setf (selection editor) (and new-selection (list new-selection)))))) (when (container-editor editor) (update-to-editor (container-editor editor) editor) )) (defmethod set-selection ((editor OMEditor) (new-selection list)) (cond ((and (om-shift-key-p) new-selection) (setf (selection editor) (append new-selection (selection editor)))) (t (setf (selection editor) new-selection))) ;(print (list editor (selection editor) "=>" (container-editor editor))) (when (container-editor editor) (update-to-editor (container-editor editor) editor) )) ;;;==================== ;;; DEFAULT INSPECTOR/EDITOR ;;;==================== ;;; for an object that is just a simple value... (defmethod get-properties-list ((self number)) `(("" (:value "Value" :text read-only)))) (defmethod get-properties-list ((self symbol)) `(("" (:value "Value" :text read-only)))) (defmethod get-properties-list ((self string)) `(("" (:value "Value" :text read-only)))) (defmethod get-properties-list ((self list)) (list (cons "list elements" (loop for i from 0 to (min 100 (1- (length self))) collect (list (intern-k (format nil "elt~D" i)) (format nil "#~D" i) :text i))))) (defclass OMDefaultEditorView (OMEditorView) ()) (defmethod set-contents ((self OMDefaultEditorView)) (let* ((ed (editor self)) (object (object-value ed))) (om-add-subviews self (om-make-layout 'om-column-layout :delta 0 :subviews (loop for category in (get-properties-list object) append (append (list (let ((font (om-def-font :gui-title))) (om-make-di 'om-simple-text :text (car category) :font font :size (apply #'om-make-point (multiple-value-list (om-string-size (car category) font))) :position (om-make-point 0 6))) ) (loop for prop in (cdr category) append (list (om-make-di 'om-simple-text :text (nth 1 prop) :font (om-def-font :gui-b) :size (om-make-point 120 18)) (make-prop-item (nth 2 prop) (nth 0 prop) object :default (nth 4 prop) :update self) (om-make-di 'om-simple-text :size (om-make-point 20 4) :text "" :focus t))))))))) (defmethod update-view-contents ((self OMDefaultEditorView)) (apply 'om-remove-subviews (cons self (om-subviews self))) (set-contents self)) (defmethod initialize-instance :after ((self OMDefaultEditorView) &rest args) (set-g-component (editor self) :default-view self) (set-contents self)) ;;; called from the property-item (defmethod update-after-prop-edit ((view OMDefaultEditorView) object) (let ((editor (editor view))) (update-to-editor editor editor) (editor-invalidate-views editor) (report-modifications editor))) #| (defclass test-class () ((a :initform nil :initarg :a :accessor a) (b :initform "qdfqsdf" :initarg :b :accessor b) (c :initform nil :initarg :c :accessor c))) (defmethod get-properties-list ((self test-class)) '(("class attibutes" (:a "Color" :color a) (:b "Name" :text b) (:c "Action" :action c)))) |# ;;;================================= ;;; HELP WINDOW ;;;================================= (defmethod editor-help-list ((self omeditor)) nil) (defmethod help-command ((self omeditor)) (when (editor-help-list self) #'(lambda () (om-print-format "~%~%----------------------------------") (om-print-format "HELP FOR ~S:" (list (type-of self))) (om-print-format "~a v.~a" (list *app-name* *version-string*)) (om-print-format "----------------------------------") (loop for elt in (editor-help-list self) do (om-print-format ". ~A = ~a" (list (car elt) (cadr elt)))) (om-print-format "----------------------------------~%~%") )))
21,843
Common Lisp
.lisp
454
41.777533
138
0.632015
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
4c36ef6cf35f42f61ef1f46a38b4acad4720a3dd45308ff64b24acdf4e16c13e
683
[ -1 ]
684
main-window.lisp
cac-t-u-s_om-sharp/src/visual-language/windows/main-window.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;================= ;;; MAIN WINDOW ;;;================= (defvar *main-window* nil) (defparameter *main-window-size* (om-make-point 800 300)) (defparameter *main-window-position* nil) (defclass om-main-window (om-window) ((elements-view :accessor elements-view :initform nil) (package-view :accessor package-view :initform nil) (libs-view :accessor libs-view :initform nil) (listener-view :accessor listener-view :initform nil) (main-layout :accessor main-layout :initform nil))) ; (show-main-window) (defun show-main-window (&key front-tab) (if *main-window* (om-select-window *main-window*) (let ((win (om-make-window 'om-main-window :title (format nil "~A Window" *app-name*) :size *main-window-size* :position *main-window-position* :menu-items (om-menu-items nil) ;;; will be updated right after... ))) (setf (elements-view win) (make-ws-elements-tab) (package-view win) (make-om-package-tab) (libs-view win) (make-libs-tab) (listener-view win) (make-listener-tab)) (om-set-menu-bar win (om-menu-items win)) (om-add-subviews win (setf (main-layout win) (om-make-layout 'om-tab-layout :subviews (list (elements-view win) (package-view win) (libs-view win) (listener-view win))))) (case front-tab (:listener (om-set-current-view (main-layout win) (listener-view win))) (:documents (om-set-current-view (main-layout win) (elements-view win)))) (setf *main-window* win) (om-show-window win)))) #+windows (defmethod om-window-check-before-close ((self om-main-window)) (om-y-or-n-dialog "Quit OM#?")) #+windows (defmethod om-window-close-event :after ((self om-main-window)) (om-quit)) (defmethod om-window-close-event ((self om-main-window)) (setf *main-window* nil)) (defmethod om-window-resized ((self om-main-window) size) (when size (setf *main-window-size* size))) (defmethod om-window-moved ((self om-main-window) position) (setf *main-window-position* position)) ;;; select-all works only in the documents view (defmethod select-all-command ((self om-main-window)) (cond ((equal (om-get-current-view (main-layout self)) (elements-view self)) #'(lambda () (select-all-documents self))) ((equal (om-get-current-view (main-layout self)) (listener-view self)) #'(lambda () (listener-view-select-all self))) (t nil))) ;;; copy-paste works only in the Listener view (defmethod copy-command ((self om-main-window)) (when (equal (om-get-current-view (main-layout self)) (listener-view self)) #'(lambda () (listener-view-copy self)))) (defmethod cut-command ((self om-main-window)) (when (equal (om-get-current-view (main-layout self)) (listener-view self)) #'(lambda () (listener-view-cut self)))) (defmethod paste-command ((self om-main-window)) (when (equal (om-get-current-view (main-layout self)) (listener-view self)) #'(lambda () (listener-view-paste self)))) ;;;=========================================== ;;; WS TAB ;;;=========================================== (defun filter-ws-elements (elements filter) (cond ((equal filter :all) elements) ((equal filter :patches) (loop for elt in elements when (and (mypathname elt) (string-equal (pathname-type (mypathname elt)) "opat")) collect elt)) ((equal filter :sequencers) (loop for elt in elements when (and (mypathname elt) (string-equal (pathname-type (mypathname elt)) "oseq")) collect elt)))) (defun gen-columns-list (names) (mapcar #'(lambda (name) (case name (:name '(:title "filename" :adjust :left :visible-min-width 200)) (:date '(:title "modified" :adjust :left :visible-min-width 150)) (otherwise `(:title ,(string-downcase name) :adjust :left :visible-min-width 50)) )) names)) (defun gen-column-elements (element display-params &optional editor) (mapcar #'(lambda (item) (cond ((equal item :name) (print-element-in-list element editor)) ((equal item :type) (string-downcase (get-object-type-name element))) ((equal item :date) (cadr (create-info element))))) display-params)) (defun print-element-in-list (element editor) (if editor (cond ((equal (elements-view-mode editor) :abs-path) (if (mypathname element) (namestring (mypathname element)) (string+ (name element) " (no attached file)"))) ((equal (elements-view-mode editor) :rel-path) (if (mypathname element) (namestring (relative-pathname (mypathname element) (mypathname (object editor)))) (string+ (name element) " (no attached file)"))) (t (name element)) ) (if (mypathname element) (namestring (mypathname element)) (string+ (name element) " (no attached file)")) )) (defun make-ws-elements-tab () (let ((doc-list (om-make-di 'om-multicol-item-list :columns (gen-columns-list '(:name :type :date)) :items (mapcar 'doc-entry-doc *open-documents*) :column-function #'(lambda (item) (gen-column-elements item '(:name :type :date))) :fg-color #'(lambda (item) (if (and (mypathname item) (probe-file (mypathname item))) (om-def-color :black) (om-make-color 0.8 0.2 0.2))) :font (om-def-font :mono) :scrollbars t :alternating-background t :auto-reset-column-widths t :action-callback #'dbclicked-item-in-list :size (omp nil nil) ;:sort-styles ;(list (list :name ; (list :sort #'(lambda (x y) (string-greaterp (name x) (name y))) ; :reverse #'(lambda (x y) (string-lessp (name x) (name y))))) ; (list :path ; (list :sort #'(lambda (x y) (string-greaterp (namestring (mypathname x)) (namestring (mypathname y)))) ; :reverse #'(lambda (x y) (string-lessp (namestring (mypathname x)) (namestring (mypathname y)))))) ; (list :type ; (list :sort #'(lambda (x y) (string-greaterp (pathname-type (mypathname x)) (pathname-type (mypathname y)))) ; :reverse #'(lambda (x y) (string-lessp (pathname-type (mypathname x)) (pathname-type (mypathname y)))))) ; (list :modif ; (list :sort #'(lambda (x y) (string-greaterp (cadr (create-info x)) (cadr (create-info y)))) ; :reverse #'(lambda (x y) (string-lessp (cadr (create-info x)) (cadr (create-info y)))))) ; ) ))) (om-make-layout 'om-column-layout :name "Documents" :align :center ; :ratios '(1 nil nil) :subviews (list doc-list ;(om-make-di 'om-multi-text :enabled nil :size (om-make-point 300 20) ; :font (om-def-font :gui) ; :fg-color (om-def-color :gray) ; :text "No Workspace has been created for this session") ;(om-make-di 'om-button :enabled nil :size (om-make-point nil 24) ; :font (om-def-font :gui) ; :text "Create One?") (om-make-layout 'om-row-layout :subviews (list nil (om-make-di 'om-button :text "Save selection" :size (omp 125 24) :font (om-def-font :gui) :di-action #'(lambda (b) (declare (ignore b)) (save-documents doc-list) )) (om-make-di 'om-button :text "Close selection" :size (omp 125 24) :font (om-def-font :gui) :di-action #'(lambda (b) (declare (ignore b)) (close-documents doc-list) )))) )) ) ) (defmethod select-all-documents ((window om-main-window)) (let* ((view (elements-view window)) (list (car (om-subviews view)))) (dotimes (i (length *open-documents*)) (om-select-item-index list i)))) (defmethod update-elements-tab ((window om-main-window)) (let ((current (om-get-current-view (main-layout window)))) (om-substitute-subviews (main-layout window) (elements-view window) (setf (elements-view window) (make-ws-elements-tab))) (om-set-current-view (main-layout window) current)) ) (defun dbclicked-item-in-list (list) (mapc 'open-editor (om-get-selected-item list))) (defun close-documents (list) (setf *save-apply-all* nil) (loop for doc in (om-get-selected-item list) do (if (editor-window doc) (close-editor doc) ;;; will close-document as well (close-document doc t))) (setf *save-apply-all* nil)) (defmethod close-document ((doc t) &optional force) nil) (defun save-documents (list) (let ((selected-docs (om-get-selected-item list)) (abort nil)) (when (and (> (length selected-docs) 1) (find-if #'(lambda (doc) (null (mypathname doc))) selected-docs)) (let ((action (om-y-or-n-dialog (format nil "Some documents in the list have no attached file yet ! ~%~% Select a common destination folder (Yes) or cancel (No).")))) (if action (let ((folder (om-choose-directory-dialog))) (if folder (loop for doc in selected-docs when (null (mypathname doc)) do (setf (mypathname doc) (om-make-pathname :directory folder :name (name doc) :type (doctype-to-extension (object-doctype doc))))) (setf abort t))) (setf abort t)))) (unless abort (setf *save-apply-all* :yes) (loop for doc in (om-get-selected-item list) do (save-document doc))) )) (defmethod register-document :after ((self OMPersistantObject) &optional path) (when *main-window* (update-elements-tab *main-window*))) (defmethod unregister-document :after ((self OMPersistantObject)) (when *main-window* (update-elements-tab *main-window*))) (defmethod update-document-path :after ((self OMPersistantObject)) (when *main-window* (update-elements-tab *main-window*))) (defmethod update-create-info :after ((self OMPersistantObject)) (when *main-window* (update-elements-tab *main-window*))) ;;;; A FAIRE : drag file from/to finder ;(defun import-dragged-file (pane filename pos) ; (let ((dirname (make-pathname :directory (append (pathname-directory filename) (list (pathname-name filename)))))) ; (cond ((or (string-equal "omp" (pathname-type filename)) ; (string-equal "omm" (pathname-type filename)) ; (string-equal "she" (pathname-type filename))) ; (import-file-to-ws pane filename pos)) ; ((or ; (directoryp filename) ; (and (directoryp dirname) (probe-file dirname))) ; (make-new-folder pane dirname pos)) ; (t nil)) ; )) ;(defmethod om-import-files-in-app ((self workspacepanel) files) ; (when (= 1 (length files)) ; (import-dragged-file self (pathname (car files)) (om-mouse-position self)))) ;;;=========================================== ;;; PACKAGES ;;;=========================================== (defmethod get-sub-items ((self OMAbstractPackage)) (append (subpackages self) (classes self) (functions self) (special-items self))) (defmethod get-sub-items ((self t)) nil) (defmethod get-icon ((self OMAbstractPackage)) :icon-pack) (defmethod get-icon ((self Function)) :icon-fun) (defmethod get-icon ((self OMGenericFunction)) :icon-genfun) (defmethod get-icon ((self OMClass)) :icon-class) (defmethod get-icon ((self standard-class)) :icon-class) (defmethod get-icon ((self OMLib)) (if (loaded? self) :icon-lib-loaded :icon-lib)) (defmethod get-icon ((self symbol)) :icon-special) (defparameter *packages-tab-text* " The list on the left show the packages inbuilt in the environment. Each packages contain classes (object constructors), functions, and/or special boxes. Double click on one of these items and then add it by clicking in a patch window. ") (defun make-om-package-tab () (let ((pack-tree-view (om-make-tree-view (subpackages *om-package-tree*) :size (omp 160 20) :expand-item 'get-sub-items :print-item 'get-name :font (om-def-font :gui) :bg-color (om-def-color :light-gray) :item-icon #'(lambda (item) (get-icon item)) :icons (list :icon-pack :icon-fun :icon-genfun :icon-class :icon-special) )) (side-panel (om-make-di 'om-multi-text :size (om-make-point nil nil) :font (om-def-font :normal) :fg-color (om-def-color :dark-gray) :text *packages-tab-text*))) (om-make-layout 'om-row-layout :name "Packages Library" :subviews (list pack-tree-view :divider side-panel) ))) (defmethod update-packages-tab ((window om-main-window)) (om-substitute-subviews (main-layout window) (package-view window) (setf (package-view window) (make-om-package-tab))) (om-set-current-view (main-layout window) (package-view window))) ;;; !!! This should also work on the libraries tab below (defmethod om-selected-item-from-tree-view ((self function) (window om-main-window)) (show-doc-on-main-window (function-name self) window)) (defmethod om-selected-item-from-tree-view ((self standard-class) (window om-main-window)) (show-doc-on-main-window (class-name self) window)) (defmethod om-selected-item-from-tree-view ((self symbol) (window om-main-window)) (show-doc-on-main-window self window)) (defmethod show-doc-on-main-window ((self symbol) (window om-main-window)) (let ((doc-info (get-documentation-info self)) (view (om-get-current-view (main-layout window)))) (when (or (equal view (libs-view window)) (equal view (package-view window)))) (let ((info-text (nth 2 (om-subviews view)))) (om-set-fg-color info-text (om-def-color :black)) (om-set-dialog-item-text info-text (if doc-info (format nil "~%~A (~A)~%~%~A" (string-upcase (nth 0 doc-info)) (string-downcase (nth 1 doc-info)) (or (nth 3 doc-info) "-")) (format nil "~%~A (no documentation)" (string-upcase self))) ) ))) (defmethod om-selected-item-from-tree-view ((self OMPackage) (window om-main-window)) (let ((view (om-get-current-view (main-layout window)))) (when (or (equal view (libs-view window)) (equal view (package-view window)))) (let ((info-text (nth 2 (om-subviews view)))) (om-set-fg-color info-text (om-def-color :black)) (om-set-dialog-item-text info-text (format nil "~%Package: ~A~%~%~A" (string-upcase (name self)) (or (doc self) "-")) ) ))) ;;;=========================================== ;;; LIBRARIES ;;;=========================================== (defparameter *libs-tab-text* " The list on the left show all libraries found in the libraries search paths. - Double click on a library icon to load it. - Double click on an internal item's icon (of a loaded library) and then add it by clicking in a patch window. ") (defun make-libs-tab () (let ((libs-tree-view (om-make-tree-view (subpackages *om-libs-root-package*) :size (omp 120 20) :expand-item 'get-sub-items :print-item 'get-name :font (om-def-font :gui) :bg-color (om-def-color :light-gray) :item-icon #'(lambda (item) (get-icon item)) :icons (list :icon-pack :icon-fun :icon-genfun :icon-class :icon-special :icon-lib-loaded :icon-lib) )) (side-panel (om-make-di 'om-multi-text :size (om-make-point nil nil) :font (om-def-font :normal) :fg-color (om-def-color :dark-gray) :text *libs-tab-text*))) (om-make-layout 'om-row-layout :name "External Libraries" :subviews (list (om-make-layout 'om-column-layout :align :right :subviews (list libs-tree-view (om-make-di 'om-button :size (om-make-point nil 24) :font (om-def-font :gui) :text "Refresh list" :di-action #'(lambda (b) (declare (ignore b)) (update-registered-libraries) (update-libraries-tab *main-window*))))) :divider side-panel)) )) (defmethod update-libraries-tab ((window om-main-window)) (om-substitute-subviews (main-layout window) (libs-view window) (setf (libs-view window) (make-libs-tab))) (om-set-current-view (main-layout window) (libs-view window))) (defmethod om-double-clicked-item-from-tree-view ((self OMLib) (window om-main-window)) (when (or (not (loaded? self)) (om-y-or-n-dialog (format nil "The library '~A' is already loaded. Reload it ?" (name self)))) (load-om-library self) (update-libraries-tab window) )) (defmethod om-selected-item-from-tree-view ((self OMLib) (window om-main-window)) (let* ((view (libs-view window)) (info-text (nth 2 (om-subviews view)))) (om-set-fg-color info-text (om-def-color :black)) (om-set-dialog-item-text info-text (format nil "~%~A~%Version: ~A~%~%Location: ~A~%~%Author(s):~%~A~%~%Description:~%~A" (string-upcase (name self)) (or (version self) "-") (mypathname self) (or (author self) "Unknown") (or (doc self) "-")) ) )) (defvar *add-item-on-patch* nil) (defun set-add-item-on-patch (item) (setf *add-item-on-patch* item) (om-reset-mouse-motion) (om-set-view-cursor *main-window* (om-get-cursor :add))) (defun cancel-add-item-on-patch () (when *add-item-on-patch* (setf *add-item-on-patch* nil) (om-reset-mouse-motion) (om-set-view-cursor *main-window* nil))) (defmethod om-view-cursor :around ((self t)) (if *add-item-on-patch* (om-get-cursor :add) (call-next-method))) (defmethod om-view-key-handler :around ((self om-graphic-object) key) (declare (ignore key)) (cancel-add-item-on-patch) (call-next-method)) (defmethod om-view-click-handler :around ((self om-graphic-object) pos) (declare (ignore pos)) (call-next-method) (cancel-add-item-on-patch)) (defmethod om-double-clicked-item-from-tree-view ((self function) (window om-main-window)) (set-add-item-on-patch (function-name self))) (defmethod om-double-clicked-item-from-tree-view ((self standard-class) (window om-main-window)) (set-add-item-on-patch (class-name self))) (defmethod om-double-clicked-item-from-tree-view ((self symbol) (window om-main-window)) (set-add-item-on-patch self)) ;;; UNSELECT (defmethod om-selected-item-from-tree-view ((self null) (window om-main-window)) (let ((view (om-get-current-view (main-layout window)))) (cond ((equal view (libs-view window)) (let ((info-text (nth 2 (om-subviews view)))) (om-set-fg-color info-text (om-def-color :dark-gray)) (om-set-dialog-item-text info-text *libs-tab-text*))) ((equal view (package-view window)) (let ((info-text (nth 2 (om-subviews view)))) (om-set-fg-color info-text (om-def-color :dark-gray)) (om-set-dialog-item-text info-text *packages-tab-text*))) (t nil)))) ;;;=========================================== ;;; LISTENER ;;;=========================================== (defun make-listener-tab () (let ((listener-pane (om-lisp::om-make-listener-output-pane (get-pref-value :general :listener-font)))) (om-make-layout 'om-column-layout :name "Listener" :ratios '(1 nil) :delta 0 :subviews (list ;; main pane listener-pane (om-make-layout 'om-row-layout :subviews (list (om-make-di 'om-button :text "Open as separate window" :size (omp 180 24) :font (om-def-font :gui) :di-action #'(lambda (b) (declare (ignore b)) (show-listener-win) )) nil (om-make-di 'om-button :text "x" :size (omp 40 24) :font (om-def-font :gui) :di-action #'(lambda (b) (declare (ignore b)) (om-lisp::om-clear-listener-output-pane listener-pane) )))) )))) (defmethod listener-view-copy ((window om-main-window)) (let* ((view (listener-view window)) (pane (car (om-subviews view)))) (om-lisp::om-copy-command pane))) (defmethod listener-view-cut ((window om-main-window)) (let* ((view (listener-view window)) (pane (car (om-subviews view)))) (om-lisp::om-cut-command pane))) (defmethod listener-view-paste ((window om-main-window)) (let* ((view (listener-view window)) (pane (car (om-subviews view)))) (om-lisp::om-paste-command pane))) (defmethod listener-view-select-all ((window om-main-window)) (let* ((view (listener-view window)) (pane (car (om-subviews view)))) (om-lisp::om-select-all-command pane))) (defun prompt-on-main-window-listener (message) (when (and *main-window* (equal (om-get-current-view (main-layout *main-window*)) (listener-view *main-window*))) (let ((listener-pane (car (om-subviews (listener-view *main-window*))))) (when listener-pane (om-lisp::om-prompt-on-echo-area listener-pane message)))))
25,762
Common Lisp
.lisp
500
38
172
0.520736
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e8800bd2aec41af7a4cdd06e9c15d7a31b77022c7cd7046d2a8fed2e1870ebb1
684
[ -1 ]
685
multi-editor.lisp
cac-t-u-s_om-sharp/src/visual-language/windows/multi-editor.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) (defclass multi-view-editor () ((selected-view :accessor selected-view :initform nil))) (defclass multi-view-editor-view () ((editor :accessor editor :initarg :editor :initform nil))) ;;; the container editor can be the editor itself if if has several views inside ;;; or it can be another editor in case of objects embedded in others (defmethod handle-multi-editor-click ((self om-view) (editor t)) nil) (defmethod handle-multi-editor-click ((self om-view) (editor multi-view-editor)) (setf (selected-view editor) self)) (defmethod om-view-click-handler :around ((self multi-view-editor-view) pos) (declare (ignore position)) (when (and (editor self) (container-editor (editor self))) (handle-multi-editor-click self (container-editor (editor self)))) (call-next-method)) ;;; this method is also defined for OMBoxFrame (defmethod dispatch-key-action ((self multi-view-editor) key) (if (and (selected-view self) (not (equal (editor (selected-view self)) self))) (editor-key-action (editor (selected-view self)) key) (call-next-method)))
1,856
Common Lisp
.lisp
36
48.833333
80
0.612707
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
65f0ace8bbe4997fffde48c5a9a59eca5e9afd884d8ea17088c70321cd0a23a4
685
[ -1 ]
686
windows.lisp
cac-t-u-s_om-sharp/src/visual-language/windows/windows.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ; General windows management (in-package :om) ;;;=============================== ;;; GENERAL MENU AND COMMANDS ;;;=============================== (defmethod save-as-menu-name ((self t)) "Save as...") ;;; SELF = editor (in general...) (defun default-file-menu-items (self) (list (om-make-menu "New..." (list (om-make-menu-comp (list (om-make-menu-item "New Patch" #'(lambda () (open-new-document :patch)) :key "n") (om-make-menu-item "New Sequencer" #'(lambda () (open-new-document :sequencer))) (om-make-menu-item "New Lisp function" #'(lambda () (open-new-document :lispfun))))) (om-make-menu-item "New Text/Lisp Buffer" #'(lambda () (om-lisp::om-open-text-editor :lisp t)) :key "N") )) (om-make-menu-item "Open..." #'(lambda () (funcall (open-command self))) :key "o" :enabled (and (open-command self) t)) (om-make-menu "Open Recent..." #'(lambda (item) (declare (ignore item)) (mapcar #'(lambda (file) (om-make-menu-item (namestring file) #'(lambda () (open-om-document file)))) *om-recent-files*))) (om-make-menu-item "Open Folder..." #'(lambda () (funcall (open-folder-command self))) :key "O" :enabled (and (open-command self) t)) (om-make-menu-comp (list (om-make-menu-item "Save" #'(lambda () (funcall (save-command self))) :key "s" :enabled (and (save-command self) t)) (om-make-menu-item (save-as-menu-name self) #'(lambda () (funcall (save-as-command self))) :key "S" :enabled (and (save-as-command self) t)) (om-make-menu-item "Revert (Last Saved)" #'(lambda () (funcall (revert-command self))) :enabled #'(lambda () (and (revert-command self) t))) (om-make-menu-item "Close" #'(lambda () (funcall (close-command self))) :key "w" :enabled (and (close-command self) t)))) (om-make-menu-comp (list (om-make-menu-item "Print" #'(lambda () (funcall (print-command self))) :key "p" :enabled (and (print-command self) t)))))) (defun default-edit-menu-items (self) (list (om-make-menu-comp (list (om-make-menu-item "Undo" #'(lambda () (when (undo-command self) (funcall (undo-command self)))) :key "z" :enabled #'(lambda () (and (undo-command self) t))) (om-make-menu-item "Redo" #'(lambda () (when (redo-command self) (funcall (redo-command self)))) :key "Z" :enabled #'(lambda () (and (redo-command self) t))))) (om-make-menu-comp (list (om-make-menu-item "Copy" #'(lambda () (funcall (copy-command self))) :key "c" :enabled #'(lambda () (and (copy-command self) t))) (om-make-menu-item "Cut" #'(lambda () (funcall (cut-command self))) :key "x" :enabled #'(lambda () (and (cut-command self) t))) (om-make-menu-item "Paste"#'(lambda () (funcall (paste-command self))) :key "v" :enabled #'(lambda () (and (paste-command self) t))) (om-make-menu-item "Delete" #'(lambda () (funcall (clear-command self))) :enabled (and (clear-command self) t)))) (om-make-menu-comp (list (om-make-menu-item "Select All" #'(lambda () (funcall (select-all-command self))) :key "a" :enabled #'(lambda () (and (select-all-command self) t))))) (om-make-menu-comp (list (om-make-menu "Font" (list (om-make-menu-comp (list (om-make-menu-item "Bold" #'(lambda () (funcall (font-bold-command self))) :key "B" :enabled (and (font-bold-command self) t)) (om-make-menu-item "Italics" #'(lambda () (funcall (font-italics-command self))) :key "I" :enabled (and (font-italics-command self) t)))) (om-make-menu-item "Open Fonts..." #'(lambda () (funcall (font-command self))) :key "T" :enabled (and (font-command self) t))) :enabled (and (or (font-bold-command self) (font-italics-command self) (font-command self)) t)))) )) (defun default-windows-menu-items (self) (declare (ignore self)) (append (unless (om-standalone-p) (list (om-make-menu-item "Preferences" 'show-preferences-win :key ",") ;(om-make-menu-item "MIDI Setup" 'show-midi-setup) )) (list (om-make-menu-comp (list (om-make-menu-item "Session Window" 'show-main-window :key "W") (om-make-menu-item "Lisp Listener" 'show-listener-win :key "L") (om-make-menu-item "Shell" 'show-shell) )) (om-make-menu-comp #'(lambda (win) (declare (ignore win)) (mapcar #'(lambda (w) (om-make-menu-item (om-window-title w) #'(lambda () (om-select-window w)) :enabled #'(lambda () (not (equal w (om-front-window)))))) (remove 'om-main-window (append (om-get-all-windows 'om-window) (om-get-all-windows 'om-lisp::om-text-editor-window)) :key 'type-of)) )))) ) (defmethod get-selection-for-menu ((self t)) nil) (defun default-help-menu-items (self) (list (om-make-menu-item "Online Documentation" #'(lambda () (om-open-in-browser "https://cac-t-u-s.github.io/pages/index")) :enabled t) (om-make-menu-item "Print Editor Help [H]" #'(lambda () (funcall (help-command self))) :enabled (and (help-command self) t)) (om-make-menu-item "Print Documentation [D]" #'(lambda () (funcall (help-command self))) :enabled #'(lambda () (get-selection-for-menu self)) ) (om-make-menu-item "Function / Class Reference" #'(lambda () (let ((symbols (get-selection-for-menu self))) (if symbols (loop for ref in symbols do (show-reference-page ref)) (om-open-in-browser (namestring (get-reference-pages-index)))))) :key "d") (om-make-menu-item "Find Source..." #'(lambda () (let ((symbols (get-selection-for-menu self))) (if symbols (loop for ref in symbols do (om-lisp::om-edit-definition ref)) (let ((str (om-get-user-string "Enter a Lisp function or class name to search."))) (when str (let ((symbol (read-from-string str))) (om-lisp::om-edit-definition symbol)))) ) )) :key "E") (om-make-menu-item "Box Help Patch..." #'(lambda () (let ((help-patches (remove nil (mapcar #'get-symbol-help-patch (get-selection-for-menu self))))) (if help-patches (loop for patch in help-patches do (open-help-patch patch)) (om-beep)) )) :enabled #'(lambda () (get-selection-for-menu self)) :key "H") (om-make-menu-comp #'(lambda (win) (declare (ignore win)) (list (om-make-menu "Help Patches..." (append (make-base-help-menu-items) (list (om-make-menu-comp #'(lambda (win) (declare (ignore win)) (cons (om-make-menu-item "Libraries:" nil :enabled nil) (loop for lib in (all-om-libraries) when (get-lib-help-patches-foler lib) collect (make-lib-help-menu lib)) )) )) ))))) )) (defun main-app-menu-item () #-cocoa(when (om-standalone-p) (om-make-menu (string+ *app-name* " " *version-string*) (list (om-make-menu-comp (list (om-make-menu-item (string+ "About " *app-name* "...") 'show-about-win) (om-make-menu-item "Preferences" 'show-preferences-win :key ","))) (om-make-menu-item "Quit" 'om-quit))))) ;;; self = the OMEditor or anything (e.g. om-listener, etc.) (defmethod om-menu-items ((self t)) (remove nil (list (main-app-menu-item) (om-make-menu "File" (default-file-menu-items self)) (om-make-menu "Edit" (default-edit-menu-items self)) (om-make-menu "Windows" (default-windows-menu-items self)) (om-make-menu "Help" (default-help-menu-items self)) ))) ;;; General commands (to be implemented by the different editors) ;;; must return a function to call ;;; I they are not implemented (or return NIL) the menu items are disabled (defmethod help-command (self) nil) (defmethod font-command (self) nil) (defmethod font-bold-command (self) nil) (defmethod font-italics-command (self) nil) (defmethod select-all-command (self) nil) (defmethod undo-command (self) nil) (defmethod redo-command (self) nil) (defmethod print-command (self) nil) (defmethod save-command (self) nil) (defmethod save-as-command (self) nil) (defmethod revert-command (self) nil) (defmethod copy-command (self) nil) (defmethod cut-command (self) nil) (defmethod paste-command (self) nil) (defmethod clear-command (self) nil) ;;; always work (defmethod close-command (self) #'(lambda () (om-close-window (om-front-window)))) (defmethod open-command (self) #'(lambda () (open-om-document))) (defmethod open-folder-command (self) #'(lambda () (let ((folder (om-choose-directory-dialog :directory (or *last-open-dir* (om-user-home))))) (when folder (setf *last-open-dir* folder) (let ((files (om-directory folder :type (append (mapcar #'doctype-to-extension *om-doctypes*) (doctype-to-ext-list :old)) :recursive t))) (loop for file in files do (catch :load-error (handler-bind ((error #'(lambda (e) (om-message-dialog (format nil "An error occured at loading ~S: ~%~%~A" file e)) (throw :load-error nil) ))) (open-om-document file nil))) )))))) ;;;=============================== ;;; TEXT WINDOWS ;;; Exist for ;;; - Lisp functions ;;; - TEXTBUFFER objects ;;; - Free Text / Lisp editing ;;; uses om-text-editor-window from the OM-LISP package ;;;=============================== ;;; will also respond to the 'standard' OM-API window title method calls (defmethod om-set-window-title ((self om-lisp::om-text-editor-window) (title string)) (om-lisp::om-text-editor-window-set-title self title)) (defmethod om-window-title ((self om-lisp::om-text-editor-window)) (om-lisp::om-text-editor-window-title self)) ;;;=============================== ;;; LISTENER ;;;=============================== ; (show-listener-win) ;;; redefine the menu-bar of the listener (defmethod om-lisp::om-listener-window-menus ((self om-lisp::om-listener)) (om-menu-items self)) (add-preference :general :listener-on-top "Keep Listener in Front" :bool nil nil 'restart-listener) (add-preference :general :listener-input "Enable Listener Input" :bool nil "Allows you to type Lisp commands in the Listener window" 'restart-listener) (defun restart-listener () (let ((listenerwin (get-listener))) (when listenerwin (let ((ig (capi::interface-geometry listenerwin))) (om-close-window listenerwin) (om-lisp::om-make-listener :x (car ig) :y (cadr ig) :width (caddr ig) :height (cadddr ig) :input (get-pref-value :general :listener-input) :on-top (get-pref-value :general :listener-on-top) :font (get-pref-value :general :listener-font) :initial-lambda #'(lambda () (in-package :om)) ))))) (defun get-listener () (car (om-get-all-windows 'om-lisp::om-listener))) (defparameter *listener-window-size* (omp nil 200)) (defparameter *listener-window-position* (omp nil nil)) (defun show-listener-win () (let ((listenerwin (get-listener))) (om-lisp::om-set-text-editor-font (get-pref-value :general :textedit-font)) (if listenerwin (om-select-window listenerwin) (om-lisp::om-make-listener :initial-lambda #'(lambda () (in-package :om)) :x (om-point-x *listener-window-position*) :y (om-point-y *listener-window-position*) :width (om-point-x *listener-window-size*) :height (om-point-y *listener-window-size*) :font (get-pref-value :general :listener-font) :input (get-pref-value :general :listener-input) :on-top (get-pref-value :general :listener-on-top) :geometry-change-callback 'listener-geometry-change-callback )))) (defun listener-geometry-change-callback (listener-win x y w h) (declare (ignore listener-win)) (setf *listener-window-size* (omp w h) *listener-window-position* (omp x y))) (add-preference :general :listener-font "Listener font" :font om-lisp::*default-listener-font* nil 'set-listener-font) (defun set-listener-font () (om-lisp::om-set-listener-font (get-pref-value :general :listener-font))) (defun set-text-editor-font () (om-lisp::om-set-text-editor-font (get-pref-value :general :textedit-font))) (defmethod copy-command ((window om-lisp::om-listener)) #'(lambda () (om-lisp::listener-copy window))) (defmethod cut-command ((window om-lisp::om-listener)) #'(lambda () (om-lisp::listener-cut window))) (defmethod paste-command ((window om-lisp::om-listener)) #'(lambda () (om-lisp::listener-paste window))) (defmethod select-all-command ((window om-lisp::om-listener)) #'(lambda () (om-lisp::listener-select-all window))) (defmethod font-command ((window om-lisp::om-listener)) #'(lambda () (om-lisp::change-listener-font window))) #| (defmethod close-command ((window om-lisp::om-listener)) #'(lambda () (om-lisp::listener-close window))) |# (defun show-shell () (om-lisp::om-open-shell)) (add-preference :general :textedit-font "Text editors font" :font om-lisp::*text-editor-font* nil 'set-text-editor-font) (add-preference :general :user-code "User code folder" :folder nil '("A folder containing Lisp files loaded at startup." "Restart OM# to reload full contents.")) ;======================= ; Print messages ;======================= (defun om-beep-msg (format-string &rest args) (om-beep) (om-print (apply 'format (append (list nil format-string) args)) "[!!]") NIL) (add-preference :general :debug "Debug mode" :bool nil) (defun om-print-dbg (str &optional args prompt) (when (get-pref-value :general :debug) (om-print-format str args (or prompt "DEBUG")))) ;;;=============================== ;;; ABOUT ;;;=============================== (defclass om-about-window (om-windoid) ()) (defun show-about-win () (let ((about-win (car (om-get-all-windows 'om-about-window)))) (if about-win (om-show-window about-win) (om-make-window 'om-about-window :subviews (list (om-make-di 'om-multi-text :text (format nil "~A v~D~%r. ~A" *app-name* *version-string* *release-date*) :size (omp 200 40) )) :close-callback #'(lambda (win) (declare (ignore win)) nil) )) )) ; (show-about-win) ;;;=============================== ;;; PREFERENCES ;;;=============================== ;;; defined in om-preferences-window.lisp ;;; (defun show-preferences-win () nil)
16,921
Common Lisp
.lisp
341
39.548387
165
0.55218
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
5b0f9039151c71b5aa6f0f1970ba3310f81a2321eb3f213c56283e3810f40d0a
686
[ -1 ]
687
mach-lib.lisp
cac-t-u-s_om-sharp/src/lisp-externals/mach-lib/mach-lib.lisp
;;; Binding TIME functions from MacOSX System framework ;;; D. bouche (2014) (in-package :cl-user) (defpackage "Mach" (:nicknames "MACH") (:use common-lisp fli)) (in-package :mach) (define-c-typedef Sint32 (:signed :long)) (define-c-typedef Uint32 (:unsigned :long)) (define-c-typedef Uint64 (:unsigned :long :long)) (define-c-struct mach_timebase_info (num UInt32) (den UInt32)) (define-foreign-function (mach_timebase_info "mach_timebase_info") ((info (:ptr mach_timebase_info))) :module :system :result-type Sint32) (define-foreign-function (mach_absolute_time "mach_absolute_time") () :module :system :result-type Uint64) (define-foreign-function (mach_wait_until "mach_wait_until") ((deadline UInt64)) :module :system :result-type Sint32) (defvar *mach2nanosFactor* 1) (defun init-nanofactor () (setf *mach2nanosFactor* (fli:with-dynamic-foreign-objects ((timeBase mach::mach_timebase_info)) (let ((result (mach::mach_timebase_info timeBase))) (if (zerop result) (/ (fli::foreign-slot-value timeBase 'mach::num) (fli::foreign-slot-value timeBase 'mach::den)) (error (format nil "mach_timebase_info error ~d" result))))))) ;; internal (defun mach2ms (mach) (round mach 1000000)) (defun ms2mach (ms) (truncate (* ms 1000000))) ;; used in API/multiprocess (defun mach-time () (mach2ms (mach::mach_absolute_time))) (defun mach-wait-delay (delay-ms) (mach::mach_wait_until (+ (mach::mach_absolute_time) (ms2mach delay-ms)))) (defun mach-wait-until (absolute-time-ms) (mach::mach_wait_until (max (ms2mach absolute-time-ms) 0))) (push :mach *features*) (defun load-mach-lib () (print "Loading System framework") (fli::register-module :system :connection-style :immediate :real-name "/System/Library/Frameworks/System.framework/System" ) (mach::init-nanofactor)) ;;; CALL THIS BEFORE ! ;;;(mach::load-mach-lib)
1,945
Common Lisp
.lisp
53
33.113208
111
0.699573
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
261a3a6a0aab7ab61c3ca0c45fbb803a91ba8934e47c94a6b14184b218bcb50d
687
[ -1 ]
688
parse.lisp
cac-t-u-s_om-sharp/src/lisp-externals/Yason/parse.lisp
;; This file is part of yason, a Common Lisp JSON parser/encoder ;; ;; Copyright (c) 2008-2012 Hans Huebner and contributors ;; All rights reserved. ;; ;; Please see the file LICENSE in the distribution. (in-package :yason) (defconstant +default-string-length+ 20 "Default length of strings that are created while reading json input.") (defvar *parse-object-key-fn* #'identity "Function to call to convert a key string in a JSON array to a key in the CL hash produced.") (defvar *parse-json-arrays-as-vectors* nil "If set to a true value, JSON arrays will be parsed as vectors, not as lists.") (defvar *parse-json-booleans-as-symbols* nil "If set to a true value, JSON booleans will be read as the symbols TRUE and FALSE, not as T and NIL, respectively.") (defvar *parse-json-null-as-keyword* nil "If set to a true value, JSON nulls will be read as the keyword :NULL, not as NIL.") (defvar *parse-object-as* :hash-table "Set to either :hash-table, :plist or :alist to determine the data structure that objects are parsed to.") (defvar *parse-object-as-alist* nil "DEPRECATED, provided for backward compatibility") (defun make-adjustable-string () "Return an adjustable empty string, usable as a buffer for parsing strings and numbers." (make-array +default-string-length+ :adjustable t :fill-pointer 0 :element-type 'character)) (defun parse-number (input) ;; would be ;; (cl-ppcre:scan-to-strings "^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+|)(?:[eE][-+]?[0-9]+|)" buffer) ;; but we want to operate on streams (let ((buffer (make-adjustable-string))) (loop while (position (peek-char nil input nil) ".0123456789+-Ee") do (vector-push-extend (read-char input) buffer)) (values (read-from-string buffer)))) (defun parse-string (input) (let ((output (make-adjustable-string))) (labels ((outc (c) (vector-push-extend c output)) (next () (read-char input)) (peek () (peek-char nil input))) (let* ( (starting-symbol (next)) (string-quoted (equal starting-symbol #\")) ) (unless string-quoted (outc starting-symbol)) (loop (cond ((eql (peek) #\") (next) (return-from parse-string output)) ((eql (peek) #\\) (next) (ecase (next) (#\" (outc #\")) (#\\ (outc #\\)) (#\/ (outc #\/)) (#\b (outc #\Backspace)) (#\f (outc #\Page)) (#\n (outc #\Newline)) (#\r (outc #\Return)) (#\t (outc #\Tab)) (#\u (outc (code-char (let ((buffer (make-string 4))) (read-sequence buffer input) (parse-integer buffer :radix 16))))))) ((and (or (whitespace-p (peek)) (eql (peek) #\:)) (not string-quoted)) (return-from parse-string output)) (t (outc (next))))))))) (defun whitespace-p (char) (member char '(#\Space #\Newline #\Tab #\Linefeed #\Return))) (defun skip-whitespace (input) (loop while (and (listen input) (whitespace-p (peek-char nil input))) do (read-char input))) (defun peek-char-skipping-whitespace (input &optional (eof-error-p t)) (skip-whitespace input) (peek-char nil input eof-error-p)) (defun parse-constant (input) (destructuring-bind (expected-string return-value) (find (peek-char nil input nil) `(("true" ,(if *parse-json-booleans-as-symbols* 'true t)) ("false" ,(if *parse-json-booleans-as-symbols* 'false nil)) ("null" ,(if *parse-json-null-as-keyword* :null nil))) :key (lambda (entry) (aref (car entry) 0)) :test #'eql) (loop for char across expected-string unless (eql (read-char input nil) char) do (error "invalid constant")) return-value)) (define-condition cannot-convert-key (error) ((key-string :initarg :key-string :reader key-string)) (:report (lambda (c stream) (format stream "cannot convert key ~S used in JSON object to hash table key" (key-string c))))) (defun create-container () (ecase *parse-object-as* ((:plist :alist) nil) (:hash-table (make-hash-table :test #'equal)))) (defun add-attribute (to key value) (ecase *parse-object-as* (:plist (append to (list key value))) (:alist (acons key value to)) (:hash-table (setf (gethash key to) value) to))) (defun parse-object (input) (let ((return-value (create-container))) (read-char input) (loop (when (eql (peek-char-skipping-whitespace input) #\}) (return)) (skip-whitespace input) (setf return-value (add-attribute return-value (prog1 (let ((key-string (parse-string input))) (or (funcall *parse-object-key-fn* key-string) (error 'cannot-convert-key :key-string key-string))) (skip-whitespace input) (unless (eql #\: (read-char input)) (error 'expected-colon)) (skip-whitespace input)) (parse input))) (ecase (peek-char-skipping-whitespace input) (#\, (read-char input)) (#\} nil))) (read-char input) return-value)) (defconstant +initial-array-size+ 20 "Initial size of JSON arrays read, they will grow as needed.") (defun %parse-array (input add-element-function) "Parse JSON array from input, calling ADD-ELEMENT-FUNCTION for each array element parsed." (read-char input) (loop (when (eql (peek-char-skipping-whitespace input) #\]) (return)) (funcall add-element-function (parse input)) (ecase (peek-char-skipping-whitespace input) (#\, (read-char input)) (#\] nil))) (read-char input)) (defun parse-array (input) (if *parse-json-arrays-as-vectors* (let ((return-value (make-array +initial-array-size+ :adjustable t :fill-pointer 0))) (%parse-array input (lambda (element) (vector-push-extend element return-value))) return-value) (let (return-value) (%parse-array input (lambda (element) (push element return-value))) (nreverse return-value)))) (defgeneric parse% (input) (:method ((input stream)) ;; backward compatibility code (assert (or (not *parse-object-as-alist*) (eq *parse-object-as* :hash-table)) () "unexpected combination of *parse-object-as* and *parse-object-as-alist*, please use *parse-object-as* exclusively") (let ((*parse-object-as* (if *parse-object-as-alist* :alist *parse-object-as*))) ;; end of backward compatibility code (check-type *parse-object-as* (member :hash-table :alist :plist)) (ecase (peek-char-skipping-whitespace input) (#\" (parse-string input)) ((#\- #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (parse-number input)) (#\{ (parse-object input)) (#\[ (parse-array input)) ((#\t #\f #\n) (parse-constant input))))) (:method ((input pathname)) (with-open-file (stream input) (parse stream))) (:method ((input string)) (parse (make-string-input-stream input)))) (defun parse (input &key (object-key-fn *parse-object-key-fn*) (object-as *parse-object-as*) (json-arrays-as-vectors *parse-json-arrays-as-vectors*) (json-booleans-as-symbols *parse-json-booleans-as-symbols*) (json-nulls-as-keyword *parse-json-null-as-keyword*)) "Parse INPUT, which needs to be a string or a stream, as JSON. Returns the lisp representation of the JSON structure parsed. The keyword arguments can be used to override the parser settings as defined by the respective special variables." (let ((*parse-object-key-fn* object-key-fn) (*parse-object-as* object-as) (*parse-json-arrays-as-vectors* json-arrays-as-vectors) (*parse-json-booleans-as-symbols* json-booleans-as-symbols) (*parse-json-null-as-keyword* json-nulls-as-keyword)) (parse% input)))
8,668
Common Lisp
.lisp
215
31.176744
131
0.578192
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
693c6d451551eccc3cee46fe3820b858c051daaa0c8dfefcc84e0a653fc35875
688
[ -1 ]
689
package.lisp
cac-t-u-s_om-sharp/src/lisp-externals/Yason/package.lisp
;; This file is part of yason, a Common Lisp JSON parser/encoder ;; ;; Copyright (c) 2008-2012 Hans Huebner and contributors ;; All rights reserved. ;; ;; Please see the file LICENSE in the distribution. (defpackage :yason (:use :cl) (:export ;; Parser #:parse #:*parse-object-key-fn* #:*parse-object-as* #:*parse-object-as-alist* ; deprecated #:*parse-json-arrays-as-vectors* #:*parse-json-booleans-as-symbols* #:*parse-json-null-as-keyword* #:true #:false #:null ;; Basic encoder interface #:encode #:encode-slots #:encode-object #:encode-plist #:encode-alist #:make-json-output-stream ;; Streaming encoder interface #:with-output #:with-output-to-string* #:no-json-output-context #:with-array #:encode-array-element #:encode-array-elements #:with-object #:encode-object-element #:encode-object-elements #:with-object-element))
928
Common Lisp
.lisp
38
20.842105
64
0.685164
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
4f3d6f20ad540c71a23d2520e79bf4859f73b4857f932c8b2ee253667d3f9fb5
689
[ -1 ]
690
load-xml.lisp
cac-t-u-s_om-sharp/src/lisp-externals/XML/load-xml.lisp
(in-package :cl-user) (compile&load (merge-pathnames "s-xml/package" *load-pathname*)) (compile&load (merge-pathnames "s-xml/dom" *load-pathname*)) (compile&load (merge-pathnames "s-xml/lxml-dom" *load-pathname*)) (compile&load (merge-pathnames "s-xml/xml" *load-pathname*)) (push :xml *features*)
305
Common Lisp
.lisp
6
48.666667
65
0.732877
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d72152c795f9767f30ecca6fd1f21100528d1d4b8a88e369d21d081a875809ac
690
[ -1 ]
691
package.lisp
cac-t-u-s_om-sharp/src/lisp-externals/XML/s-xml/package.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: package.lisp,v 1.6 2005/11/20 14:24:34 scaekenberghe Exp $ ;;;; ;;;; This is a Common Lisp implementation of a very basic XML parser. ;;;; The parser is non-validating. ;;;; The API into the parser is pure functional parser hook model that comes from SSAX, ;;;; see also http://pobox.com/~oleg/ftp/Scheme/xml.html or http://ssax.sourceforge.net ;;;; Different DOM models are provided, an XSML, an LXML and a xml-element struct based one. ;;;; ;;;; Copyright (C) 2002, 2003, 2004, 2005 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (defpackage s-xml (:use common-lisp) (:export ;; main parser interface #:start-parse-xml #:print-string-xml #:xml-parser-error #:xml-parser-error-message #:xml-parser-error-args #:xml-parser-error-stream #:xml-parser-state #:get-entities #:get-seed #:get-new-element-hook #:get-finish-element-hook #:get-text-hook ;; dom parser and printer #:parse-xml-dom #:parse-xml #:parse-xml-string #:parse-xml-file #:print-xml-dom #:print-xml #:print-xml-string ;; xml-element structure #:make-xml-element #:xml-element-children #:xml-element-name #:xml-element-attribute #:xml-element-attributes #:xml-element-p #:new-xml-element #:first-xml-element-child ;; namespaces #:*ignore-namespaces* #:*local-namespace* #:*namespaces* #:*require-existing-symbols* #:*auto-export-symbols* #:*auto-create-namespace-packages* #:find-namespace #:register-namespace #:get-prefix #:get-uri #:get-package #:resolve-identifier #:extend-namespaces #:print-identifier #:split-identifier) (:documentation "A simple XML parser with an efficient, purely functional, event-based interface as well as a DOM interface")) ;;;; eof
1,946
Common Lisp
.lisp
39
47.179487
113
0.713911
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
12333b00b4996eb05e72c4d1fd9236302f75480897c1b40a29776809eb9c4974
691
[ 226625 ]
692
lxml-dom.lisp
cac-t-u-s_om-sharp/src/lisp-externals/XML/s-xml/lxml-dom.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: lxml-dom.lisp,v 1.6 2005/11/20 14:34:15 scaekenberghe Exp $ ;;;; ;;;; LXML implementation of the generic DOM parser and printer. ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) ;;; the lxml hooks to generate lxml (defun lxml-new-element-hook (name attributes seed) (declare (ignore name attributes seed)) '()) (defun lxml-finish-element-hook (name attributes parent-seed seed) (let ((xml-element (cond ((and (null seed) (null attributes)) name) (attributes `((,name ,@(let (list) (dolist (attribute attributes list) (push (cdr attribute) list) (push (car attribute) list)))) ,@(nreverse seed))) (t `(,name ,@(nreverse seed)))))) (cons xml-element parent-seed))) (defun lxml-text-hook (string seed) (cons string seed)) ;;; standard DOM interfaces (defmethod parse-xml-dom (stream (output-type (eql :lxml))) (car (start-parse-xml stream (make-instance 'xml-parser-state :new-element-hook #'lxml-new-element-hook :finish-element-hook #'lxml-finish-element-hook :text-hook #'lxml-text-hook)))) (defun plist->alist (plist) (when plist (cons (cons (first plist) (second plist)) (plist->alist (rest (rest plist)))))) (defmethod print-xml-dom (dom (input-type (eql :lxml)) stream pretty level) (declare (special *namespaces*)) (cond ((symbolp dom) (print-solitary-tag dom stream)) ((stringp dom) (print-string-xml dom stream)) ((consp dom) (let (tag attributes) (cond ((symbolp (first dom)) (setf tag (first dom))) ((consp (first dom)) (setf tag (first (first dom)) attributes (plist->alist (rest (first dom))))) (t (error "Input not recognized as LXML ~s" dom))) (let ((*namespaces* (extend-namespaces attributes *namespaces*))) (write-char #\< stream) (print-identifier tag stream) (loop :for (name . value) :in attributes :do (print-attribute name value stream)) (if (rest dom) (let ((children (rest dom))) (write-char #\> stream) (if (and (= (length children) 1) (stringp (first children))) (print-string-xml (first children) stream) (progn (dolist (child children) (when pretty (print-spaces (* 2 level) stream)) (if (stringp child) (print-string-xml child stream) (print-xml-dom child input-type stream pretty (1+ level)))) (when pretty (print-spaces (* 2 (1- level)) stream)))) (print-closing-tag tag stream)) (write-string "/>" stream))))) (t (error "Input not recognized as LXML ~s" dom)))) ;;;; eof
3,173
Common Lisp
.lisp
73
34.69863
90
0.586598
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
fbc9718c7f6a7529665c5c4f93faec5d1732e3c6acde5fd6c65708696091c925
692
[ 76 ]
693
xml.lisp
cac-t-u-s_om-sharp/src/lisp-externals/XML/s-xml/xml.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: xml.lisp,v 1.14 2005/11/20 14:24:34 scaekenberghe Exp $ ;;;; ;;;; This is a Common Lisp implementation of a basic but usable XML parser. ;;;; The parser is non-validating and not complete (no CDATA). ;;;; Namespace and entities are handled. ;;;; The API into the parser is a pure functional parser hook model that comes from SSAX, ;;;; see also http://pobox.com/~oleg/ftp/Scheme/xml.html or http://ssax.sourceforge.net ;;;; Different DOM models are provided, an XSML, an LXML and a xml-element struct based one. ;;;; ;;;; Copyright (C) 2002, 2003, 2004, 2005 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) ;;; error reporting (define-condition xml-parser-error (error) ((message :initarg :message :reader xml-parser-error-message) (args :initarg :args :reader xml-parser-error-args) (stream :initarg :stream :reader xml-parser-error-stream :initform nil)) (:report (lambda (condition stream) (format stream "XML parser ~?~@[ near stream position ~d~]." (xml-parser-error-message condition) (xml-parser-error-args condition) (and (xml-parser-error-stream condition) (file-position (xml-parser-error-stream condition)))))) (:documentation "Thrown by the XML parser to indicate errorneous input")) (setf (documentation 'xml-parser-error-message 'function) "Get the message from an XML parser error" (documentation 'xml-parser-error-args 'function) "Get the error arguments from an XML parser error" (documentation 'xml-parser-error-stream 'function) "Get the stream from an XML parser error") (defun parser-error (message &optional args stream) (make-condition 'xml-parser-error :message message :args args :stream stream)) ;;; utilities (defun whitespace-char-p (char) "Is char an XML whitespace character ?" (or (char= char #\space) (char= char #\tab) (char= char #\return) (char= char #\linefeed) ;;; MODIF JB 21/01/2013 (char= char #\Zero-Width-No-Break-Space))) (defun identifier-char-p (char) "Is char an XML identifier character ?" (or (and (char<= #\A char) (char<= char #\Z)) (and (char<= #\a char) (char<= char #\z)) (and (char<= #\0 char) (char<= char #\9)) (char= char #\-) (char= char #\_) (char= char #\.) (char= char #\:))) (defun skip-whitespace (stream) "Skip over XML whitespace in stream, return first non-whitespace character which was peeked but not read, return nil on eof" (loop (let ((char (peek-char nil stream nil nil))) (if (and char (whitespace-char-p char)) (read-char stream) (return char))))) (defun make-extendable-string (&optional (size 10)) "Make an extendable string which is a one-dimensional character array which is adjustable and has a fill pointer" (make-array size :element-type 'character :adjustable t :fill-pointer 0)) (defun print-string-xml (string stream &key (start 0) end) "Write the characters of string to stream using basic XML conventions" (loop for offset upfrom start below (or end (length string)) for char = (char string offset) do (case char (#\& (write-string "&amp;" stream)) (#\< (write-string "&lt;" stream)) (#\> (write-string "&gt;" stream)) (#\" (write-string "&quot;" stream)) ((#\newline #\return #\tab) (write-char char stream)) (t (if (and (<= 32 (char-code char)) (<= (char-code char) 126)) (write-char char stream) (progn (write-string "&#x" stream) (write (char-code char) :stream stream :base 16) (write-char #\; stream))))))) (defun make-standard-entities () "A hashtable mapping XML entity names to their replacement strings, filled with the standard set" (let ((entities (make-hash-table :test #'equal))) (setf (gethash "amp" entities) (string #\&) (gethash "quot" entities) (string #\") (gethash "apos" entities) (string #\') (gethash "lt" entities) (string #\<) (gethash "gt" entities) (string #\>) (gethash "nbsp" entities) (string #\space)) entities)) (defun resolve-entity (stream extendable-string entities &optional (entity (make-extendable-string))) "Read and resolve an XML entity from stream, positioned after the '&' entity marker, accepting &name; &#DEC; and &#xHEX; formats, destructively modifying string, which is also returned, destructively modifying entity, incorrect entity formats result in errors" (loop (let ((char (read-char stream nil nil))) (cond ((null char) (error (parser-error "encountered eof before end of entity"))) ((char= #\; char) (return)) (t (vector-push-extend char entity))))) (if (char= (char entity 0) #\#) (let ((code (if (char= (char entity 1) #\x) (parse-integer entity :start 2 :radix 16 :junk-allowed t) (parse-integer entity :start 1 :radix 10 :junk-allowed t)))) (when (null code) (error (parser-error "encountered incorrect entity &~s;" (list entity) stream))) (vector-push-extend (code-char code) extendable-string)) (let ((value (gethash entity entities))) (if value (loop :for char :across value :do (vector-push-extend char extendable-string)) (error (parser-error "encountered unknown entity &~s;" (list entity) stream))))) extendable-string) ;;; namespace support (defvar *ignore-namespaces* nil "When t, namespaces are ignored like in the old version of S-XML") (defclass xml-namespace () ((uri :documentation "The URI used to identify this namespace" :accessor get-uri :initarg :uri) (prefix :documentation "The preferred prefix assigned to this namespace" :accessor get-prefix :initarg :prefix :initform nil) (package :documentation "The Common Lisp package where this namespace's symbols are interned" :accessor get-package :initarg :package :initform nil)) (:documentation "Describes an XML namespace and how it is handled")) (defmethod print-object ((object xml-namespace) stream) (print-unreadable-object (object stream :type t :identity t) (format stream "~A - ~A" (get-prefix object) (get-uri object)))) (defvar *local-namespace* (make-instance 'xml-namespace :uri "local" :prefix "" :package (find-package :keyword)) "The local (global default) XML namespace") (defvar *xml-namespace* (make-instance 'xml-namespace :uri "http://www.w3.org/XML/1998/namespace" :prefix "xml" :package (or (find-package :xml) (make-package :xml :nicknames '("XML")))) "REC-xml-names-19990114 says the prefix xml is bound to the namespace http://www.w3.org/XML/1998/namespace.") (defvar *known-namespaces* (list *local-namespace* *xml-namespace*) "The list of known/defined namespaces") (defvar *namespaces* `(("xml" . ,*xml-namespace*) ("" . ,*local-namespace*)) "Ordered list of (prefix . XML-namespace) bindings currently in effect - special variable") (defun find-namespace (uri) "Find a registered XML namespace identified by uri" (find uri *known-namespaces* :key #'get-uri :test #'string-equal)) (defun register-namespace (uri prefix package) "Register a new or redefine an existing XML namespace defined by uri with prefix and package" (let ((namespace (find-namespace uri))) (if namespace (setf (get-prefix namespace) prefix (get-package namespace) (find-package package)) (push (setf namespace (make-instance 'xml-namespace :uri uri :prefix prefix :package (find-package package))) *known-namespaces*)) namespace)) (defun find-namespace-binding (prefix namespaces) "Find the XML namespace currently bound to prefix in the namespaces bindings" (cdr (assoc prefix namespaces :test #'string-equal))) (defun split-identifier (identifier) "Split an identifier 'prefix:name' and return (values prefix name)" (when (symbolp identifier) (setf identifier (symbol-name identifier))) (let ((colon-position (position #\: identifier :test #'char=))) (if colon-position (values (subseq identifier 0 colon-position) (subseq identifier (1+ colon-position))) (values nil identifier)))) (defvar *require-existing-symbols* nil "If t, each XML identifier must exist as symbol already") (defvar *auto-export-symbols* t "If t, export newly interned symbols form their packages") (defun resolve-identifier (identifier namespaces &optional as-attribute) "Resolve the string identifier in the list of namespace bindings" (if *ignore-namespaces* (intern identifier :keyword) (flet ((intern-symbol (string package) ; intern string as a symbol in package (if *require-existing-symbols* (let ((symbol (find-symbol string package))) (or symbol (error "Symbol ~s does not exist in ~s" string package))) (let ((symbol (intern string package))) (when (and *auto-export-symbols* (not (eql package (find-package :keyword)))) (export symbol package)) symbol)))) (multiple-value-bind (prefix name) (split-identifier identifier) (if (or (null prefix) (string= prefix "xmlns")) (if as-attribute (intern (if (string= prefix "xmlns") identifier name) (get-package *local-namespace*)) (let ((default-namespace (find-namespace-binding "" namespaces))) (intern-symbol name (get-package default-namespace)))) (let ((namespace (find-namespace-binding prefix namespaces))) (if namespace (intern-symbol name (get-package namespace)) (error "namespace not found for prefix ~s" prefix)))))))) (defvar *auto-create-namespace-packages* t "If t, new packages will be created for namespaces, if needed, named by the prefix") (defun new-namespace (uri &optional prefix) "Register a new namespace for uri and prefix, creating a package if necessary" (if prefix (register-namespace uri prefix (or (find-package prefix) (if *auto-create-namespace-packages* (make-package prefix :nicknames `(,(string-upcase prefix))) (error "Cannot find or create package ~s" prefix)))) (let ((unique-name (loop :for i :upfrom 0 :do (let ((name (format nil "ns-~d" i))) (when (not (find-package name)) (return name)))))) (register-namespace uri unique-name (if *auto-create-namespace-packages* (make-package (string-upcase unique-name) :nicknames `(,unique-name)) (error "Cannot create package ~s" unique-name)))))) (defun extend-namespaces (attributes namespaces) "Given possible 'xmlns[:prefix]' attributes, extend the namespaces bindings" (unless *ignore-namespaces* (let (default-namespace-uri) (loop :for (key . value) :in attributes :do (if (string= key "xmlns") (setf default-namespace-uri value) (multiple-value-bind (prefix name) (split-identifier key) (when (string= prefix "xmlns") (let* ((uri value) (prefix name) (namespace (find-namespace uri))) (unless namespace (setf namespace (new-namespace uri prefix))) (push `(,prefix . ,namespace) namespaces)))))) (when default-namespace-uri (let ((namespace (find-namespace default-namespace-uri))) (unless namespace (setf namespace (new-namespace default-namespace-uri))) (push `("" . ,namespace) namespaces))))) namespaces) (defun print-identifier (identifier stream &optional as-attribute) "Print identifier on stream using namespace conventions" (declare (ignore as-attribute) (special *namespaces*)) (if *ignore-namespaces* (princ identifier stream) (if (symbolp identifier) (let ((package (symbol-package identifier)) (name (symbol-name identifier))) (let* ((namespace (find package *known-namespaces* :key #'get-package)) (prefix (or (car (find namespace *namespaces* :key #'cdr)) (get-prefix namespace)))) (if (string= prefix "") (princ name stream) (format stream "~a:~a" prefix name)))) (princ identifier stream)))) ;;; the parser state (defclass xml-parser-state () ((entities :documentation "A hashtable mapping XML entity names to their replacement stings" :accessor get-entities :initarg :entities :initform (make-standard-entities)) (seed :documentation "The user seed object" :accessor get-seed :initarg :seed :initform nil) (buffer :documentation "The main reusable character buffer" :accessor get-buffer :initform (make-extendable-string)) (mini-buffer :documentation "The secondary, smaller reusable character buffer" :accessor get-mini-buffer :initform (make-extendable-string)) (new-element-hook :documentation "Called when new element starts" ;; Handle the start of a new xml element with name and attributes, ;; receiving seed from previous element (sibling or parent) ;; return seed to be used for first child (content) ;; or directly to finish-element-hook :accessor get-new-element-hook :initarg :new-element-hook :initform #'(lambda (name attributes seed) (declare (ignore name attributes)) seed)) (finish-element-hook :documentation "Called when element ends" ;; Handle the end of an xml element with name and attributes, ;; receiving parent-seed, the seed passed to us when this element started, ;; i.e. passed to our corresponding new-element-hook ;; and receiving seed from last child (content) ;; or directly from new-element-hook ;; return final seed for this element to next element (sibling or parent) :accessor get-finish-element-hook :initarg :finish-element-hook :initform #'(lambda (name attributes parent-seed seed) (declare (ignore name attributes parent-seed)) seed)) (text-hook :documentation "Called when text is found" ;; Handle text in string, found as contents, ;; receiving seed from previous element (sibling or parent), ;; return final seed for this element to next element (sibling or parent) :accessor get-text-hook :initarg :text-hook :initform #'(lambda (string seed) (declare (ignore string)) seed))) (:documentation "The XML parser state passed along all code making up the parser")) (setf (documentation 'get-seed 'function) "Get the initial user seed of an XML parser state" (documentation 'get-entities 'function) "Get the entities hashtable of an XML parser state" (documentation 'get-new-element-hook 'function) "Get the new element hook of an XML parser state" (documentation 'get-finish-element-hook 'function) "Get the finish element hook of an XML parser state" (documentation 'get-text-hook 'function) "Get the text hook of an XML parser state") #-allegro (setf (documentation '(setf get-seed) 'function) "Set the initial user seed of an XML parser state" (documentation '(setf get-entities) 'function) "Set the entities hashtable of an XML parser state" (documentation '(setf get-new-element-hook) 'function) "Set the new element hook of an XML parser state" (documentation '(setf get-finish-element-hook) 'function) "Set the finish element hook of an XML parser state" (documentation '(setf get-text-hook) 'function) "Set the text hook of an XML parser state") (defmethod get-mini-buffer :after ((state xml-parser-state)) "Reset and return the reusable mini buffer" (with-slots (mini-buffer) state (setf (fill-pointer mini-buffer) 0))) (defmethod get-buffer :after ((state xml-parser-state)) "Reset and return the main reusable buffer" (with-slots (buffer) state (setf (fill-pointer buffer) 0))) ;;; parser support (defun parse-whitespace (stream extendable-string) "Read and collect XML whitespace from stream in string which is destructively modified, return first non-whitespace character which was peeked but not read, return nil on eof" (loop (let ((char (peek-char nil stream nil nil))) (if (and char (whitespace-char-p char)) (vector-push-extend (read-char stream) extendable-string) (return char))))) (defun parse-string (stream state &optional (string (make-extendable-string))) "Read and return an XML string from stream, delimited by either single or double quotes, the stream is expected to be on the opening delimiter, at the end the closing delimiter is also read, entities are resolved, eof before end of string is an error" (let ((delimiter (read-char stream nil nil)) (char)) (when (or (null delimiter) (not (or (char= delimiter #\') (char= delimiter #\")))) (error (parser-error "expected string delimiter" nil stream))) (loop (setf char (read-char stream nil nil)) (cond ((null char) (error (parser-error "encountered eof before end of string"))) ((char= char delimiter) (return)) ((char= char #\&) (resolve-entity stream string (get-entities state) (get-mini-buffer state))) (t (vector-push-extend char string)))) string)) (defun parse-text (stream state extendable-string) "Read and collect XML text from stream in string which is destructively modified, the text ends with a '<', which is peeked and returned, entities are resolved, eof is considered an error" (let (char) (loop (setf char (peek-char nil stream nil nil)) (when (null char) (error (parser-error "encountered unexpected eof in text"))) (when (char= char #\<) (return)) (read-char stream) (if (char= char #\&) (resolve-entity stream extendable-string (get-entities state) (get-mini-buffer state)) (vector-push-extend char extendable-string))) char)) (defun parse-identifier (stream &optional (identifier (make-extendable-string))) "Read and returns an XML identifier from stream, positioned at the start of the identifier, ending with the first non-identifier character, which is peeked, the identifier is written destructively into identifier which is also returned" (loop (let ((char (peek-char nil stream nil nil))) (cond ((and char (identifier-char-p char)) (read-char stream) (vector-push-extend char identifier)) (t (return identifier)))))) (defun skip-comment (stream) "Skip an XML comment in stream, positioned after the opening '<!--', consumes the closing '-->' sequence, unexpected eof or a malformed closing sequence result in a error" (let ((dashes-to-read 2)) (loop (if (zerop dashes-to-read) (return)) (let ((char (read-char stream nil nil))) (if (null char) (error (parser-error "encountered unexpected eof for comment"))) (if (char= char #\-) (decf dashes-to-read) (setf dashes-to-read 2))))) (if (char/= (read-char stream nil nil) #\>) (error (parser-error "expected > ending comment" nil stream)))) (defun read-cdata (stream state &optional (string (make-extendable-string))) "Reads in the CDATA and calls the callback for CDATA if it exists" ;; we already read the <![CDATA[ stuff ;; continue to read until we hit ]]> (let ((char #\space) (last-3-characters (list #\[ #\A #\T)) (pattern (list #\> #\] #\]))) (loop (setf char (read-char stream nil nil)) (when (null char) (error (parser-error "encountered unexpected eof in text"))) (push char last-3-characters) (setf (cdddr last-3-characters) nil) (cond ((equal last-3-characters pattern) (setf (fill-pointer string) (- (fill-pointer string) 2)) (setf (get-seed state) (funcall (get-text-hook state) (copy-seq string) (get-seed state))) (return-from read-cdata)) (t (vector-push-extend char string)))))) (defun skip-special-tag (stream state) "Skip an XML special tag (comments and processing instructions) in stream, positioned after the opening '<', unexpected eof is an error" ;; opening < has been read, consume ? or ! (read-char stream) (let ((char (read-char stream nil nil))) ;; see if we are dealing with a comment (when (char= char #\-) (setf char (read-char stream nil nil)) (when (char= char #\-) (skip-comment stream) (return-from skip-special-tag))) ;; maybe we are dealing with CDATA? (when (and (char= char #\[) (loop :for pattern :across "CDATA[" :for char = (read-char stream nil nil) :when (null char) :do (error (parser-error "encountered unexpected eof in cdata")) :always (char= char pattern))) (read-cdata stream state (get-buffer state)) (return-from skip-special-tag)) ;; loop over chars, dealing with strings (skipping their content) ;; and counting opening and closing < and > chars (let ((taglevel 1) (string-delimiter)) (loop (when (zerop taglevel) (return)) (setf char (read-char stream nil nil)) (when (null char) (error (parser-error "encountered unexpected eof for special (! or ?) tag" nil stream))) (if string-delimiter ;; inside a string we only look for a closing string delimiter (when (char= char string-delimiter) (setf string-delimiter nil)) ;; outside a string we count < and > and watch out for strings (cond ((or (char= char #\') (char= char #\")) (setf string-delimiter char)) ((char= char #\<) (incf taglevel)) ((char= char #\>) (decf taglevel)))))))) ;;; the XML parser proper (defun parse-xml-element-attributes (stream state) "Parse XML element attributes from stream positioned after the tag identifier, returning the attributes as an assoc list, ending at either a '>' or a '/' which is peeked and also returned" (declare (special *namespaces*)) (let (char attributes) (loop ;; skip whitespace separating items (setf char (skip-whitespace stream)) ;; start tag attributes ends with > or /> (when (and char (or (char= char #\>) (char= char #\/))) (return)) ;; read the attribute key (let ((key (copy-seq (parse-identifier stream (get-mini-buffer state))))) ;; skip separating whitespace (setf char (skip-whitespace stream)) ;; require = sign (and consume it if present) (if (and char (char= char #\=)) (read-char stream) (error (parser-error "expected =" nil stream))) ;; skip separating whitespace (skip-whitespace stream) ;; read the attribute value as a string (push (cons key (copy-seq (parse-string stream state (get-buffer state)))) attributes))) ;; return attributes peek char ending loop (values attributes char))) (defun parse-xml-element (stream state) "Parse and return an XML element from stream, positioned after the opening '<'" (declare (special *namespaces*)) ;; opening < has been read (when (or (char= (peek-char nil stream nil nil) #\!) ;;; MODIF JB 21/01/2013 (char= (peek-char nil stream nil nil) #\?)) (skip-special-tag stream state) (return-from parse-xml-element)) (let (char buffer open-tag parent-seed has-children) (setf parent-seed (get-seed state)) ;; read tag name (no whitespace between < and name ?) (setf open-tag (copy-seq (parse-identifier stream (get-mini-buffer state)))) ;; tag has been read, read attributes if any (multiple-value-bind (attributes peeked-char) (parse-xml-element-attributes stream state) (let ((*namespaces* (extend-namespaces attributes *namespaces*))) (setf open-tag (resolve-identifier open-tag *namespaces*) attributes (loop :for (key . value) :in attributes :collect (cons (resolve-identifier key *namespaces* t) value))) (setf (get-seed state) (funcall (get-new-element-hook state) open-tag attributes (get-seed state))) (setf char peeked-char) (when (char= char #\/) ;; handle solitary tag of the form <tag .. /> (read-char stream) (setf char (read-char stream nil nil)) (if (char= #\> char) (progn (setf (get-seed state) (funcall (get-finish-element-hook state) open-tag attributes parent-seed (get-seed state))) (return-from parse-xml-element)) (error (parser-error "expected >" nil stream)))) ;; consume > (read-char stream) (loop (setf buffer (get-buffer state)) ;; read whitespace into buffer (setf char (parse-whitespace stream buffer)) ;; see what ended the whitespace scan (cond ((null char) (error (parser-error "encountered unexpected eof handling ~a" (list open-tag)))) ((char= char #\<) ;; consume the < (read-char stream) (if (char= (peek-char nil stream nil nil) #\/) (progn ;; handle the matching closing tag </tag> and done ;; if we read whitespace as this (leaf) element's contents, it is significant (when (and (not has-children) (plusp (length buffer))) (setf (get-seed state) (funcall (get-text-hook state) (copy-seq buffer) (get-seed state)))) (read-char stream) (let ((close-tag (resolve-identifier (parse-identifier stream (get-mini-buffer state)) *namespaces*))) (unless (eq open-tag close-tag) (error (parser-error "found <~a> not matched by </~a> but by <~a>" (list open-tag open-tag close-tag) stream))) (unless (char= (read-char stream nil nil) #\>) (error (parser-error "expected >" nil stream))) (setf (get-seed state) (funcall (get-finish-element-hook state) open-tag attributes parent-seed (get-seed state)))) (return)) ;; handle child tag and loop, no hooks to call here ;; whitespace between child elements is skipped (progn (setf has-children t) (parse-xml-element stream state)))) (t ;; no child tag, concatenate text to whitespace in buffer ;; handle text content and loop (setf char (parse-text stream state buffer)) (setf (get-seed state) (funcall (get-text-hook state) (copy-seq buffer) (get-seed state)))))))))) (defun start-parse-xml (stream &optional (state (make-instance 'xml-parser-state))) "Parse and return a toplevel XML element from stream, using parser state" (loop (let ((char (skip-whitespace stream))) (when (null char) (return-from start-parse-xml)) ;; skip whitespace until start tag (unless (char= char #\<) (error (parser-error "expected <" nil stream))) (read-char stream) ; consume peeked char (setf char (peek-char nil stream nil nil)) (if (or (char= char #\!) (char= char #\?)) ;; deal with special tags (skip-special-tag stream state) (progn ;; read the main element (parse-xml-element stream state) (return-from start-parse-xml (get-seed state))))))) ;;;; eof
29,103
Common Lisp
.lisp
596
40.013423
111
0.628697
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
db3039fb0a6dee3d1c77364bf23a87864c5f303965e34905909018ee0f41c91f
693
[ -1 ]
694
dom.lisp
cac-t-u-s_om-sharp/src/lisp-externals/XML/s-xml/dom.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: dom.lisp,v 1.2 2005/08/29 15:01:47 scaekenberghe Exp $ ;;;; ;;;; This is the generic simple DOM parser and printer interface. ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) ;;; top level DOM parser interface (defgeneric parse-xml-dom (stream output-type) (:documentation "Parse a character stream as XML and generate a DOM of output-type")) (defun parse-xml (stream &key (output-type :lxml)) "Parse a character stream as XML and generate a DOM of output-type, defaulting to :lxml" (parse-xml-dom stream output-type)) (defun parse-xml-string (string &key (output-type :lxml)) "Parse a string as XML and generate a DOM of output-type, defaulting to :lxml" (with-input-from-string (stream string) (parse-xml-dom stream output-type))) (defun parse-xml-file (filename &key (output-type :lxml)) "Parse a character file as XML and generate a DOM of output-type, defaulting to :lxml" (with-open-file (in filename :direction :input) (parse-xml-dom in output-type))) ;;; top level DOM printer interface (defgeneric print-xml-dom (dom input-type stream pretty level) (:documentation "Generate XML output on a character stream from a DOM of input-type, optionally pretty printing using level")) (defun print-xml (dom &key (stream t) (pretty nil) (input-type :lxml) (header)) "Generate XML output on a character stream (t by default) from a DOM of input-type (:lxml by default), optionally pretty printing (off by default), or adding a header (none by default)" (when header (format stream header)) (when pretty (terpri stream)) (print-xml-dom dom input-type stream pretty 1)) (defun print-xml-string (dom &key (pretty nil) (input-type :lxml)) "Generate XML output to a string from a DOM of input-type (:lxml by default), optionally pretty printing (off by default)" (with-output-to-string (stream) (print-xml dom :stream stream :pretty pretty :input-type input-type))) ;;; shared/common support functions (defun print-spaces (n stream &optional (preceding-newline t)) (when preceding-newline (terpri stream)) (loop :repeat n :do (write-char #\Space stream))) (defun print-solitary-tag (tag stream) (write-char #\< stream) (print-identifier tag stream) (write-string "/>" stream)) (defun print-closing-tag (tag stream) (write-string "</" stream) (print-identifier tag stream) (write-char #\> stream)) (defun print-attribute (name value stream) (write-char #\space stream) (print-identifier name stream t) (write-string "=\"" stream) (print-string-xml value stream) (write-char #\" stream)) ;;;; eof
2,896
Common Lisp
.lisp
59
46.322034
187
0.724175
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
92f8ff490a678c963d5c51614b7e60fa9743db2a7e49255b3a5cfd3de8289e48
694
[ 235316 ]
695
class.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/class.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: class.lisp 665 2008-12-04 17:17:41Z binghe $ (in-package :comm+) (defclass socket-datagram () ((open-p :type boolean :accessor socket-open-p :initform t) (socket :type integer :reader socket-datagram-socket :initarg :socket) ;;; following slots are taken from USOCKET project (wait-list :initform nil :accessor wait-list :documentation "WAIT-LIST the object is associated with.") (state :initform nil :accessor state :documentation "Per-socket return value for the `wait-for-input' function. The value stored in this slot can be any of NIL - not ready :READ - ready to read :READ-WRITE - ready to read and write :WRITE - ready to write The last two remain unused in the current version.")) (:documentation "datagram socket class")) (defmethod initialize-instance :after ((instance socket-datagram) &rest initargs &key &allow-other-keys) (hcl:flag-special-free-action instance)) (defclass inet-datagram (socket-datagram rtt-info-mixin) ()) (defclass unix-datagram (socket-datagram) ((local-pathname :type (or null string pathname) :accessor unix-datagram-pathname :initarg :pathname))) (defun make-inet-datagram (socket-fd) (make-instance 'inet-datagram :socket socket-fd)) (defun make-unix-datagram (socket-fd &optional pathname) (make-instance 'unix-datagram :socket socket-fd :pathname pathname)) (defmethod close-datagram ((socket socket-datagram)) (close-socket (socket-datagram-socket socket))) (defmethod close-datagram :after ((socket socket-datagram)) (setf (socket-open-p socket) nil)) (defmethod close-datagram :after ((socket unix-datagram)) (ignore-errors (delete-file (unix-datagram-pathname socket)))) ;; Register a special free action for closing datagram usocket when being GCed (defun socket-special-free-action (object) (when (and (typep object 'socket-datagram) (socket-open-p object)) (close-datagram object))) (eval-when (:load-toplevel :execute) (hcl:add-special-free-action 'socket-special-free-action)) (defgeneric socket-receive-timeout (socket)) (defgeneric (setf socket-receive-timeout) (seconds socket)) (defmethod socket-receive-timeout ((socket socket-datagram)) (socket-receive-timeout (socket-datagram-socket socket))) (defmethod (setf socket-receive-timeout) (seconds (socket socket-datagram)) (setf (socket-receive-timeout (socket-datagram-socket socket)) seconds)) (defgeneric send-message (socket buffer &key)) (defgeneric receive-message (socket &key)) (defgeneric socket-reuse-address (socket)) (defgeneric (setf socket-reuse-address) (flag socket)) (defmethod socket-reuse-address ((socket-fd integer)) "Get socket option: REUSEADDR, return value is 0 or 1" (fli:with-dynamic-foreign-objects ((flag :int) (len :int)) (let ((reply (getsockopt socket-fd *sockopt_sol_socket* *sockopt_so_reuseaddr* (fli:copy-pointer flag :type '(:pointer :void)) len))) (when (zerop reply) (values (fli:dereference flag) t))))) (defmethod socket-reuse-address ((socket inet-datagram)) (socket-reuse-address (socket-datagram-socket socket))) (defmethod (setf socket-reuse-address) (flag (socket-fd integer)) "Set socket option: REUSEADDR, argument flag can be a boolean" (setf (socket-reuse-address socket-fd) (if flag 1 0))) (defmethod (setf socket-reuse-address) ((flag integer) (socket-fd integer)) "Set socket option: REUSEADDR, argument flag can be 0 or 1" (declare (type (integer 0 1) flag)) (fli:with-dynamic-foreign-objects ((%flag :int)) (setf (fli:dereference %flag) flag) (let ((reply (setsockopt socket-fd *sockopt_sol_socket* *sockopt_so_reuseaddr* (fli:copy-pointer %flag :type '(:pointer :void)) (fli:size-of :int)))) (when (zerop reply) (values flag t))))) (defmethod (setf socket-reuse-address) (flag (socket inet-datagram)) (setf (socket-reuse-address (socket-datagram-socket socket)) flag))
4,398
Common Lisp
.lisp
97
38.030928
78
0.663003
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
9b19d21752783d1c92c9209e99b7de044e02cad17ebddd4f45f0ebc7059eca38
695
[ -1 ]
696
package.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/package.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: package.lisp 666 2008-12-04 17:18:16Z binghe $ (in-package :cl-user) (defpackage comm+ (:use :common-lisp :lispworks :comm) (:import-from :comm #:*socket_af_inet* #:*socket_af_unix* #:*socket_pf_unspec* #:*socket_sock_stream* #:*sockopt_sol_socket* #:*sockopt_so_reuseaddr* #:%send #:announce-server-started #:bind #:close-socket #:connect #:getpeername #:getsockname #:getsockopt #:htonl #:htons #:in_addr #:initialize-sockaddr_in #:ntohl #:ntohs #:s_addr #:setsockopt #:sin_addr #:sin_port #:sockaddr #:sockaddr_in #-(or lispworks4 lispworks5 lispworks6.0) #:sockaddr_in6 #-(or lispworks4 lispworks5 lispworks6.0) #:lw-sockaddr #:socket #:socket-listen #+mswindows #:ensure-sockets #+mswindows #:ioctlsocket #+mswindows #:wsa-get-last-error #+mswindows #:wsa-event-select #+mswindows #:wsa-cleanup) (:import-from :system #-mswindows #:ioctl) (:export #:*client-address* #:*client-port* #:*major-version* #:*minor-version* #:*rtt-maxnrexmt* #:*rtt-rxtmax* #:*rtt-rxtmin* #:close-datagram #:connect-to-udp-server #:connect-to-unix-path #:get-socket-pathname #:get-socket-peer-pathname #:inet-datagram ; class #:mcast-interface #:mcast-join #:mcast-leave #:mcast-loop #:mcast-ttl #:open-udp-socket #:open-udp-stream #:open-unix-socket #:open-unix-stream #:receive-message #:send-message #:socket-datagram ; class #:socket-datagram-socket #:socket-header-include ; for icmp #:socket-raw ; class #:socket-raw-socket #:socket-receive-timeout #:socket-reuse-address #:start-udp-server #:stop-udp-server #:sync-message #:unix-datagram ; class #:wait-for-input #:with-connected-udp-socket #:with-connected-unix-socket #:with-udp-socket #:with-udp-stream #:with-unix-socket)) (in-package :comm+) ;;; Export all external symbols of COMM (eval-when (:load-toplevel :execute) (do-external-symbols (symbol (find-package :comm)) (export symbol))) (defparameter *major-version* 4) (defparameter *minor-version* 1)
2,261
Common Lisp
.lisp
92
20.021739
60
0.640481
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
fe2bb57c6ca1a0cbf56d636617cdc6118b77192c1168e99630b63905e7788a11
696
[ -1 ]
697
lispworks-udp.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/lispworks-udp.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: lispworks-udp.lisp 900 2011-06-30 16:30:07Z binghe $ (in-package :comm+) (defconstant +max-udp-message-size+ 65536) ;;;; Below is something we have to define (others already in COMM package) ;;;; binghe: my design goal is to use what COMM already have, and no C code. (defconstant *socket_sock_dgram* 2 "Connectionless, unreliable datagrams of fixed maximum length.") (defconstant *sockopt_ipproto_udp* 17) (defconstant *sockopt_so_rcvtimeo* #-linux #x1006 #+linux 20 "Socket receive timeout") (fli:define-c-struct timeval (tv-sec :long) (tv-usec :long)) ;;; ssize_t ;;; recvfrom(int socket, void *restrict buffer, size_t length, int flags, ;;; struct sockaddr *restrict address, socklen_t *restrict address_len); (fli:define-foreign-function (%recvfrom "recvfrom" :source) ((socket :int) (buffer (:pointer (:unsigned :byte))) (length :int) (flags :int) (address (:pointer (:struct sockaddr))) (address-len (:pointer :int))) :result-type :int) ;;; ssize_t ;;; sendto(int socket, const void *buffer, size_t length, int flags, ;;; const struct sockaddr *dest_addr, socklen_t dest_len); (fli:define-foreign-function (%sendto "sendto" :source) ((socket :int) (buffer (:pointer (:unsigned :byte))) (length :int) (flags :int) (address (:pointer (:struct sockaddr))) (address-len :int)) :result-type :int) #-mswindows (defmethod (setf socket-receive-timeout) (seconds (socket-fd integer)) "Set socket option: RCVTIMEO, argument seconds can be a float number" (declare (type number seconds)) (multiple-value-bind (sec usec) (truncate seconds) (fli:with-dynamic-foreign-objects ((timeout (:struct timeval))) (fli:with-foreign-slots (tv-sec tv-usec) timeout (setf tv-sec sec tv-usec (truncate (* 1000000 usec))) (if (zerop (setsockopt socket-fd *sockopt_sol_socket* *sockopt_so_rcvtimeo* (fli:copy-pointer timeout :type '(:pointer :void)) (fli:size-of '(:struct timeval)))) seconds))))) #+mswindows (defmethod (setf socket-receive-timeout) (seconds (socket-fd integer)) "Set socket option: RCVTIMEO, argument seconds can be a float number. On mswindows, you must bind the socket before use this function." (declare (type number seconds)) (fli:with-dynamic-foreign-objects ((timeout :int)) (setf (fli:dereference timeout) (truncate (* 1000 seconds))) (if (zerop (setsockopt socket-fd *sockopt_sol_socket* *sockopt_so_rcvtimeo* (fli:copy-pointer timeout :type '(:pointer :char)) (fli:size-of :int))) seconds))) #-mswindows (defmethod socket-receive-timeout ((socket-fd integer)) "Get socket option: RCVTIMEO, return value is a float number" (fli:with-dynamic-foreign-objects ((timeout (:struct timeval)) (len :int)) (getsockopt socket-fd *sockopt_sol_socket* *sockopt_so_rcvtimeo* (fli:copy-pointer timeout :type '(:pointer :void)) len) (fli:with-foreign-slots (tv-sec tv-usec) timeout (float (+ tv-sec (/ tv-usec 1000000)))))) #+mswindows (defmethod socket-receive-timeout ((socket-fd integer)) "Get socket option: RCVTIMEO, return value is a float number" (fli:with-dynamic-foreign-objects ((timeout :int) (len :int)) (getsockopt socket-fd *sockopt_sol_socket* *sockopt_so_rcvtimeo* (fli:copy-pointer timeout :type '(:pointer :void)) len) (float (/ (fli:dereference timeout) 1000)))) (defun get-last-error () #+mswindows (wsa-get-last-error) #-mswindows (errno-value)) (defun raise-socket-error (reason &rest args) (declare (type string reason)) (error 'socket-error :format-string (format nil "ERROR ~D: ~A" (get-last-error) reason) :format-arguments args))
4,337
Common Lisp
.lisp
104
32.644231
81
0.598862
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
a05a5bc7c1185455b3e033943209046afdfae9ba22870d0605ab80663ba263ba
697
[ -1 ]
698
rtt-client.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/rtt-client.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: rtt-client.lisp 572 2008-10-08 14:21:33Z binghe $ (in-package :comm+) (defun default-rtt-function (message) (values message 0)) (defun sync-message (socket message &key host service (max-receive-length +max-udp-message-size+) (encode-function #'default-rtt-function) (decode-function #'default-rtt-function)) (declare (type inet-datagram socket)) (let ((socket-fd (socket-datagram-socket socket))) (rtt-newpack socket) (multiple-value-bind (data send-seq) (funcall encode-function message) (let ((data-length (length data))) (loop with send-ts = (rtt-ts socket) and recv-message = nil and recv-seq = -1 and continue-p = t do (progn (send-message socket data :length data-length :host host :service service) (loop with timeout-p = nil do (progn (setf (socket-receive-timeout socket-fd) (rtt-start socket) timeout-p nil) (let ((m (receive-message socket :max-buffer-size max-receive-length))) (if m ; got a receive message (multiple-value-setq (recv-message recv-seq) (funcall decode-function m)) ;; timeout (let ((old-rto (slot-value socket 'rto))) (setf continue-p (rtt-timeout socket) timeout-p t) (warn 'rtt-timeout-warning :socket socket :old-rto old-rto :new-rto (slot-value socket 'rto)) (unless continue-p (error 'rtt-timeout-error :socket socket) (rtt-init socket)))))) until (and (not timeout-p) (or (= recv-seq send-seq) (warn 'rtt-seq-mismatch-warning :socket socket :send-seq send-seq :recv-seq recv-seq))) finally (let ((recv-ts (rtt-ts socket))) (rtt-stop socket (- recv-ts send-ts)) (return nil)))) until (or recv-message (not continue-p)) finally (return recv-message))))))
2,752
Common Lisp
.lisp
53
29.622642
89
0.432864
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d4a9b7002679337c0c2a26e0a1441530395b4c5a66d8d41d6b554f018c38d6d9
698
[ -1 ]
699
wait-for-input.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/wait-for-input.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: wait-for-input.lisp 643 2008-11-20 05:21:49Z binghe $ ;;;; WAIT-FOR-INPUT from USOCKET Project (in-package :comm+) #-mswindows (defun check-for-multiprocessing-started (&optional errorp) (unless mp:*current-process* (funcall (if errorp 'error 'warn) "You must start multiprocessing on Lispworks by calling~ ~%~3t(~s)~ ~%for ~s function properly." 'mp:initialize-multiprocessing 'wait-for-input))) #-mswindows (check-for-multiprocessing-started) (defgeneric wait-for-input (socket-or-sockets &key timeout ready-only)) (defstruct (wait-list (:constructor %make-wait-list)) %wait ;; implementation specific waiters ;; the list of all usockets map ;; maps implementation sockets to usockets ) ;; Implementation specific: ;; ;; %setup-wait-list ;; %add-waiter ;; %remove-waiter (defun make-wait-list (waiters) (let ((wl (%make-wait-list))) (setf (wait-list-map wl) (make-hash-table)) (%setup-wait-list wl) (dolist (x waiters) (add-waiter wl x)) wl)) (defun add-waiter (wait-list input) (setf (gethash (socket-datagram-socket input) (wait-list-map wait-list)) input (wait-list input) wait-list) (pushnew input (wait-list-waiters wait-list)) (%add-waiter wait-list input)) (defun remove-waiter (wait-list input) (%remove-waiter wait-list input) (setf (wait-list-waiters wait-list) (remove input (wait-list-waiters wait-list)) (wait-list input) nil) (remhash (socket-datagram-socket input) (wait-list-map wait-list))) (defun remove-all-waiters (wait-list) (dolist (waiter (wait-list-waiters wait-list)) (%remove-waiter wait-list waiter)) (setf (wait-list-waiters wait-list) nil) (clrhash (wait-list-map wait-list))) (defmethod wait-for-input ((socket inet-datagram) &key timeout ready-only) (multiple-value-bind (socks to) (wait-for-input (list socket) :timeout timeout :ready-only ready-only) (values (if ready-only (car socks) socket) to))) (defmethod wait-for-input ((sockets list) &key timeout ready-only) (let ((wl (make-wait-list sockets))) (multiple-value-bind (socks to) (wait-for-input wl :timeout timeout :ready-only ready-only) (values (if ready-only socks sockets) to)))) (defmethod wait-for-input ((sockets wait-list) &key timeout ready-only) (let* ((start (get-internal-real-time)) (sockets-ready 0)) (dolist (x (wait-list-waiters sockets)) (when (setf (state x) (if (and (typep x 'inet-datagram) (socket-listen (socket-datagram-socket x))) :read nil)) (incf sockets-ready))) ;; the internal routine is responsibe for ;; making sure the wait doesn't block on socket-streams of ;; which theready- socket isn't ready, but there's space left in the ;; buffer (wait-for-input-internal sockets :timeout (if (zerop sockets-ready) timeout 0)) (let ((to-result (when timeout (let ((elapsed (/ (- (get-internal-real-time) start) internal-time-units-per-second))) (when (< elapsed timeout) (- timeout elapsed)))))) (values (if ready-only (remove-if #'null (wait-list-waiters sockets) :key #'state) sockets) to-result)))) #-mswindows (progn (defun %setup-wait-list (wait-list) (declare (ignore wait-list))) (defun %add-waiter (wait-list waiter) (declare (ignore wait-list waiter))) (defun %remove-waiter (wait-list waiter) (declare (ignore wait-list waiter))) (defmethod wait-for-input-internal (wait-list &key timeout) (dolist (x (wait-list-waiters wait-list)) (mp:notice-fd (socket-datagram-socket x))) (labels ((wait-function (socks) (let (rv) (dolist (x socks rv) (when (socket-listen (socket-datagram-socket x)) (setf (state x) :read rv t)))))) (if timeout (mp:process-wait-with-timeout "Waiting for a socket to become active" (truncate timeout) #'wait-function (wait-list-waiters wait-list)) (mp:process-wait "Waiting for a socket to become active" #'wait-function (wait-list-waiters wait-list)))) (dolist (x (wait-list-waiters wait-list)) (mp:unnotice-fd (socket-datagram-socket x))) wait-list))
4,472
Common Lisp
.lisp
110
33.909091
80
0.641032
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
f2974ba254cde66e3a942e087de2429ae4596ddaa66a6bd859427d197a673cbd
699
[ -1 ]
700
icmp.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/icmp.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: icmp.lisp 666 2008-12-04 17:18:16Z binghe $ ;;;; ICMP support for LispWorks (in-package :comm+) (defconstant *socket_sock_raw* 3) (defconstant *sockopt_ipproto_icmp* 1 "control message protocol") (defconstant *sockopt_ipproto_raw* 255 "raw IP packet") (defconstant *sockopt_ip_hdrincl* #-linux 2 #+linux 3 "int; header is included with data") (defclass socket-raw (socket-datagram) ((socket :type integer :reader socket-raw-socket :initarg :socket))) (defgeneric socket-header-include (socket)) (defgeneric (setf socket-header-include) (flag socket)) (defmethod socket-header-include ((socket socket-raw)) (socket-header-include (socket-raw-socket socket))) (defmethod socket-header-include ((socket-fd integer)) "Get socket option: IP_HDRINCL, return value is 0 or 1" (fli:with-dynamic-foreign-objects ((flag :int) (len :int)) (let ((reply (getsockopt socket-fd *sockopt_ipproto_ip* *sockopt_ip_hdrincl* (fli:copy-pointer flag :type '(:pointer :void)) len))) (when (zerop reply) (values (fli:dereference flag) t))))) (defmethod (setf socket-header-include) (flag (socket socket-raw)) (setf (socket-header-include (socket-raw-socket socket)) flag)) (defmethod (setf socket-header-include) (flag (socket-fd integer)) (setf (socket-header-include socket-fd) (if flag 1 0))) (defmethod (setf socket-header-include) ((flag integer) (socket-fd integer)) "Set socket option: IP_HDRINCL, flag can be 0 or 1" (declare (type (integer 0 1) flag)) (fli:with-dynamic-foreign-objects ((%flag :int)) (setf (fli:dereference %flag) flag) (let ((reply (setsockopt socket-fd *sockopt_ipproto_ip* *sockopt_ip_hdrincl* (fli:copy-pointer %flag :type '(:pointer :void)) (fli:size-of :int)))) (when (zerop reply) (values flag t))))) (defun open-icmp-socket () (let ((socket-fd (socket *socket_af_inet* *socket_sock_raw* *sockopt_ipproto_icmp*))) socket-fd))
2,298
Common Lisp
.lisp
48
37.9375
88
0.605027
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
4d1ae912fe4372cebdb71b59fd393aa06826954a828ad1fa8ae5fee9f9aec6d6
700
[ -1 ]
701
udp-server.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/udp-server.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: udp-server.lisp 656 2008-11-21 17:39:14Z binghe $ ;;;; UDP Server Support for LispWorks (in-package :comm+) (defvar *client-address* 0 "client address used in udp process function") (defvar *client-port* 0 "client port used in udp process function") (defun udp-server-loop (arguments socket fn max-buffer-size) (declare (type socket-datagram socket) (type list arguments) (ftype (function (sequence) sequence) fn)) "Main loop for A iterate UDP Server, function type as we declared." (mp:ensure-process-cleanup `(udp-server-loop-cleanup ,socket)) (let ((message (make-array max-buffer-size :element-type '(unsigned-byte 8) :initial-element 0 :allocation :static)) (socket-fd (socket-datagram-socket socket))) (fli:with-dynamic-foreign-objects ((client-addr (:struct sockaddr_in)) (len :int #-(or lispworks3 lispworks4 lispworks5.0) :initial-element (fli:size-of '(:struct sockaddr_in)))) (fli:with-dynamic-lisp-array-pointer (ptr message :type '(:unsigned :byte)) (loop (let ((n (%recvfrom socket-fd ptr max-buffer-size 0 (fli:copy-pointer client-addr :type '(:struct sockaddr)) len))) (when (plusp n) (let ((*client-address* (ntohl (fli:foreign-slot-value (fli:foreign-slot-value client-addr 'sin_addr :object-type '(:struct sockaddr_in) :type '(:struct in_addr) :copy-foreign-object nil) 's_addr :object-type '(:struct in_addr)))) (*client-port* (ntohs (fli:foreign-slot-value client-addr 'sin_port :object-type '(:struct sockaddr_in) :type '(:unsigned :short) :copy-foreign-object nil)))) (let ((reply-message (apply fn (cons (subseq message 0 n) arguments)))) (when reply-message ;; or we don't make a reply message (let ((length-out (length reply-message))) (replace message reply-message) (%sendto socket-fd ptr length-out 0 (fli:copy-pointer client-addr :type '(:struct sockaddr)) (fli:dereference len))))))) (mp:process-allow-scheduling))))))) (defun udp-server-loop-cleanup (process socket) (declare (type socket-datagram socket) (type mp:process process) (ignore process)) (close-datagram socket)) (defun start-udp-server (&key (function #'identity) (arguments nil) (announce nil) address (service 0) (process-name (format nil "~S UDP server" service)) (loop-time 1) (max-buffer-size +max-udp-message-size+) (multicast nil) (mcast-interface 0) (mcast-ttl 1 mcast-ttl-p) (mcast-loop t mcast-loop-p)) "Something like START-UP-SERVER" (let* ((socket (open-udp-socket :local-address address :local-port service :read-timeout loop-time :errorp t :reuse-address multicast)) (socket-fd (socket-datagram-socket socket))) (announce-server-started announce socket-fd nil) ;; multicast support (4.1) (when multicast (mcast-join socket-fd address :interface mcast-interface :errorp t) (when mcast-ttl-p (setf (mcast-ttl socket-fd) mcast-ttl)) (when mcast-loop-p (setf (mcast-loop socket-fd) mcast-loop))) ;; start a thread (let ((process (mp:process-run-function process-name nil #'udp-server-loop arguments ; additional arguments for function socket function max-buffer-size))) (setf (getf (mp:process-plist process) 'socket) socket) process))) (defun stop-udp-server (process &key wait) (let ((socket (getf (mp:process-plist process) 'socket))) (mp:process-kill process) (prog1 (zerop (close-datagram socket)) (when wait (mp:process-wait "Wait until UDP server process be killed" #'(lambda () (not (mp:process-alive-p process))))))))
5,197
Common Lisp
.lisp
92
35.597826
92
0.483428
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e1b0e831c2b2f5ac87d6c1e3ba81e04bcecccf92a030b37e32ca43dce5230f8e
701
[ -1 ]
702
defsys.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/defsys.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: defsys.lisp 659 2008-11-22 12:45:13Z binghe $ ;;;; System Definition for LispWorks UDP (in-package :cl-user) ;;; Load COMM package (require "comm") #+(and lispworks4 win32) (pushnew :mswindows *features*) (defsystem lispworks-udp (:optimize ((safety 3) (debug 3))) :members (package rtt lispworks-udp class #-mswindows wait-for-input condition multicast udp-client udp-server rtt-client #-mswindows unix #-mswindows unix-server #-mswindows icmp) :rules ((:in-order-to :compile :all (:requires (:load :previous)))))
734
Common Lisp
.lisp
29
17.931034
55
0.554922
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
cf9f8c05b315c605f4ff30d2ec1a9a77a5c5cb7674455399b47abdfece2f184a
702
[ -1 ]
703
udp-client.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/udp-client.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: udp-client.lisp 900 2011-06-30 16:30:07Z binghe $ ;;;; UDP Client Support for LispWorks (in-package :comm+) (defun initialize-dynamic-sockaddr (hostname service protocol) #+(or lispworks4 lispworks5 lispworks6.0) (let ((server-addr (fli:allocate-dynamic-foreign-object :type '(:struct sockaddr_in)))) (values (initialize-sockaddr_in server-addr *socket_af_inet* hostname service protocol) *socket_af_inet* server-addr (fli:pointer-element-size server-addr))) #-(or lispworks4 lispworks5 lispworks6.0) (progn (when (stringp hostname) (let ((resolved-hostname (comm:get-host-entry hostname :fields '(:address)))) (unless resolved-hostname (return-from initialize-dynamic-sockaddr :unknown-host)) (setq hostname resolved-hostname))) (if (or (null hostname) (integerp hostname) (comm:ipv6-address-p hostname)) (let ((server-addr (fli:allocate-dynamic-foreign-object :type '(:struct lw-sockaddr)))) (multiple-value-bind (error family) (initialize-sockaddr_in server-addr hostname service protocol) (values error family server-addr (if (eql family *socket_af_inet*) (fli:size-of '(:struct sockaddr_in)) (fli:size-of '(:struct sockaddr_in6)))))) :bad-host))) (defun open-udp-socket (&key errorp local-address (local-port #+mswindows 0 #-mswindows nil) (address-family *socket_af_inet*) read-timeout reuse-address) "Open a unconnected UDP socket. For binding on address ANY(*), just not set LOCAL-ADDRESS (NIL), for binding on random free unused port, set LOCAL-PORT to 0." ;; Note: move (ensure-sockets) here to make sure delivered applications ;; correctly have networking support initialized. ;; ;; Following words was from Martin Simmons, forwarded by Camille Troillard: ;; Calling comm::ensure-sockets at load time looks like a bug in Lispworks-udp ;; (it is too early and also unnecessary). ;; The LispWorks comm package calls comm::ensure-sockets when it is needed, so I ;; think open-udp-socket should probably do it too. Calling it more than once is ;; safe and it will be very fast after the first time. #+mswindows (ensure-sockets) (let ((socket-fd (socket address-family *socket_sock_dgram* *socket_pf_unspec*))) (if socket-fd (progn (when read-timeout (setf (socket-receive-timeout socket-fd) read-timeout)) (when reuse-address (setf (socket-reuse-address socket-fd) reuse-address)) (if local-port (progn ;; bind to local address/port if specified. (fli:with-dynamic-foreign-objects () (multiple-value-bind (error local-address-family client-addr client-addr-length) (initialize-dynamic-sockaddr local-address local-port "udp") (if (or error (not (eql address-family local-address-family))) (error "cannot resolve hostname ~S, service ~S: ~A" local-address local-port (or error "address family mismatch")) (if (bind socket-fd (fli:copy-pointer client-addr :type '(:struct sockaddr)) client-addr-length) ;; success, return socket fd (make-inet-datagram socket-fd) (progn ;; fail, close socket and return nil (close-socket socket-fd) (when errorp (raise-socket-error "cannot bind to local")))))))) (make-inet-datagram socket-fd))) (when errorp (raise-socket-error "cannot create socket"))))) (defmacro with-udp-socket ((socket &rest options) &body body) `(let ((,socket (open-udp-socket ,@options))) (unwind-protect (progn ,@body) (close-datagram ,socket)))) (defvar *inet-message-send-buffer* (make-array +max-udp-message-size+ :element-type '(unsigned-byte 8) :allocation :static)) (defvar *inet-message-send-lock* (mp:make-lock)) (defmethod send-message ((socket inet-datagram) buffer &key (length (length buffer)) host service) "Send message to a socket, using sendto()/send()" (declare (type sequence buffer)) (flet ((send-it (client-addr client-addr-length) (mp:with-lock (*inet-message-send-lock*) (let ((socket-fd (socket-datagram-socket socket)) (message *inet-message-send-buffer*)) (replace message buffer :end2 length) (fli:with-dynamic-lisp-array-pointer (ptr message :type '(:unsigned :byte)) (if client-addr (%sendto socket-fd ptr (min length +max-udp-message-size+) 0 (fli:copy-pointer client-addr :type '(:struct sockaddr)) client-addr-length) (%send socket-fd ptr (min length +max-udp-message-size+) 0))))))) (if (and host service) (fli:with-dynamic-foreign-objects () (multiple-value-bind (error address-family client-addr client-addr-length) (initialize-dynamic-sockaddr host service "udp") (declare (ignore address-family)) (if error (error "cannot resolve hostname ~S, service ~S: ~A" host service error) (send-it client-addr client-addr-length)))) (send-it nil nil)))) (defvar *inet-message-receive-buffer* (make-array +max-udp-message-size+ :element-type '(unsigned-byte 8) :allocation :static)) (defvar *inet-message-receive-lock* (mp:make-lock)) (defmethod receive-message ((socket inet-datagram) &key buffer (length (length buffer)) read-timeout (max-buffer-size +max-udp-message-size+)) "Receive message from socket, read-timeout is a float number in seconds. This function will return 4 values: 1. receive buffer 2. number of receive bytes 3. remote address 4. remote port" (declare (type socket-datagram socket) (type sequence buffer)) (let ((message *inet-message-receive-buffer*) (socket-fd (socket-datagram-socket socket))) (fli:with-dynamic-foreign-objects ((client-addr (:struct sockaddr_in)) (len :int #-(or lispworks3 lispworks4 lispworks5.0) :initial-element (fli:size-of '(:struct sockaddr_in)))) (fli:with-dynamic-lisp-array-pointer (ptr message :type '(:unsigned :byte)) ;; setup new read timeout (when read-timeout (setf (socket-receive-timeout socket-fd) read-timeout)) (mp:with-lock (*inet-message-receive-lock*) (let ((n (%recvfrom socket-fd ptr max-buffer-size 0 (fli:copy-pointer client-addr :type '(:struct sockaddr)) len))) (if (plusp n) (values (if buffer (replace buffer message :end1 (min length max-buffer-size) :end2 (min n max-buffer-size)) (subseq message 0 (min n max-buffer-size))) (min n max-buffer-size) (ntohl (fli:foreign-slot-value (fli:foreign-slot-value client-addr 'sin_addr :object-type '(:struct sockaddr_in) :type '(:struct in_addr) :copy-foreign-object nil) 's_addr :object-type '(:struct in_addr))) (ntohs (fli:foreign-slot-value client-addr 'sin_port :object-type '(:struct sockaddr_in) :type '(:unsigned :short)))) (values nil n 0 0)))))))) (defun connect-to-udp-server (hostname service &key errorp local-address local-port read-timeout) "Something like CONNECT-TO-TCP-SERVER" (let ((socket (open-udp-socket :errorp errorp :local-address local-address :local-port local-port :read-timeout read-timeout))) (if socket (let ((socket-fd (socket-datagram-socket socket))) (fli:with-dynamic-foreign-objects () ;; connect to remote address/port (multiple-value-bind (error address-family server-addr server-addr-length) (initialize-dynamic-sockaddr hostname service "udp") (declare (ignore address-family)) (if error (error "cannot resolve hostname ~S, service ~S: ~A" hostname service error) (if (connect socket-fd (fli:copy-pointer server-addr :type '(:struct sockaddr)) server-addr-length) ;; success, return socket fd socket ;; fail, close socket and return nil (progn (close-datagram socket) (when errorp (raise-socket-error "cannot connect")))))))) (when errorp (error (raise-socket-error "cannot create socket")))))) (defmacro with-connected-udp-socket ((socket &rest options) &body body) `(let ((,socket (connect-to-udp-server ,@options))) (unwind-protect (progn ,@body) (close-datagram ,socket)))) (defun open-udp-stream (hostname service &key (direction :io) (element-type 'base-char) errorp read-timeout local-address local-port) "Something like OPEN-TCP-STREAM" (let* ((socket (connect-to-udp-server hostname service :errorp errorp :local-address local-address :local-port local-port)) (socket-fd (socket-datagram-socket socket))) (make-instance 'socket-stream :socket socket-fd :direction direction :element-type element-type :read-timeout read-timeout))) (defmacro with-udp-stream ((stream &rest options) &body body) `(let ((,stream (open-udp-stream ,@options))) (unwind-protect (progn ,@body) (close ,stream))))
11,109
Common Lisp
.lisp
219
35.675799
98
0.549719
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e9cdb97848b00befeaeda4cdc1b249705915c90fe383485b493090147847745e
703
[ -1 ]
704
unix.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/unix.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: unix.lisp 902 2011-07-29 07:14:02Z binghe $ ;;;; UNIX Domain Socket support for LispWorks ;;; NOTE: OPEN-UNIX-STREAM (and only it) is from http://www.bew.org.uk/Lisp/ ;;; Original license of UNIX Domain Socket support for LispWorks: ;;; Copyright 2001, Barry Wilkes <[email protected]> ;;; uk.org.bew.comm-ext, an extension to the network interface for LispWorks/Linux ;;; ;;; uk.org.bew.comm-ext is licensed under the terms of the Lisp Lesser GNU ;;; Public License (http://opensource.franz.com/preamble.html), known as ;;; the LLGPL. The LLGPL consists of a preamble (see above URL) and the ;;; LGPL. Where these conflict, the preamble takes precedence. ;;; uk.org.bew.comm-ext is referenced in the preamble as the "LIBRARY." (in-package :comm+) (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +max-unix-path-length+ #+darwin 104 #-darwin 108)) ;; (fli:size-of '(:struct sockaddr_un)) = #+darwin 106 #-darwin 110 (fli:define-c-struct sockaddr_un #+darwin (sun_len (:unsigned :byte)) (sun_family (:unsigned #+darwin :byte #-darwin :short)) (sun_path (:c-array (:unsigned :byte) #.+max-unix-path-length+))) (defun initialize-sockaddr_un (unaddr family pathname) (declare (type (satisfies fli:pointerp) unaddr) (type integer family) (type (or string pathname) pathname)) (let ((path (namestring (translate-logical-pathname pathname)))) (fli:fill-foreign-object unaddr :byte 0) (let* ((code (ef:encode-lisp-string path :utf-8)) (len (length code))) (fli:with-foreign-slots (#+darwin sun_len sun_family) unaddr #+darwin (setf sun_len (+ len 2)) (setf sun_family family)) (fli:replace-foreign-array (fli:foreign-slot-pointer unaddr 'sun_path) code :start1 0 :end1 (min len +max-unix-path-length+)) (setf (fli:foreign-aref (fli:foreign-slot-pointer unaddr 'sun_path) (min len (1- +max-unix-path-length+))) 0) (values)))) (defun get-socket-peer-pathname (socket-fd) "Get the connect pathname of a unix domain socket, only useful on stream socket" (declare (type integer socket-fd)) (fli:with-dynamic-foreign-objects ((sock-addr (:struct sockaddr_un)) (len :int #-(or lispworks3 lispworks4 lispworks5.0) :initial-element (fli:size-of '(:struct sockaddr_un)))) (fli:fill-foreign-object sock-addr :byte 0) (let ((return-code (getpeername socket-fd (fli:copy-pointer sock-addr :type '(:struct sockaddr)) len))) (when (zerop return-code) (fli:convert-from-foreign-string (fli:foreign-slot-pointer sock-addr 'sun_path) :external-format :utf-8 :null-terminated-p t :allow-null t))))) (defun get-socket-pathname (socket-fd) "Get the bind pathname of a unix domain socket, only useful on stream socket" (declare (type integer socket-fd)) (fli:with-dynamic-foreign-objects ((sock-addr (:struct sockaddr_un)) (len :int #-(or lispworks3 lispworks4 lispworks5.0) :initial-element (fli:size-of '(:struct sockaddr_un)))) (fli:fill-foreign-object sock-addr :byte 0) (let ((return-code (getsockname socket-fd (fli:copy-pointer sock-addr :type '(:struct sockaddr)) len))) (when (zerop return-code) (fli:convert-from-foreign-string (fli:foreign-slot-pointer sock-addr 'sun_path) :external-format :utf-8 :null-terminated-p t :allow-null t))))) (defun open-unix-socket (&key (protocol :datagram) errorp path read-timeout) (let ((socket-fd (socket *socket_af_unix* (ecase protocol (:stream *socket_sock_stream*) (:datagram *socket_sock_dgram*)) *socket_pf_unspec*))) (if socket-fd (progn (when read-timeout (setf (socket-receive-timeout socket-fd) read-timeout)) (if path (progn (fli:with-dynamic-foreign-objects ((client-addr (:struct sockaddr_un))) (initialize-sockaddr_un client-addr *socket_af_unix* path) (ignore-errors (delete-file path)) (if (bind socket-fd (fli:copy-pointer client-addr :type '(:struct sockaddr)) (fli:pointer-element-size client-addr)) ;; success, return socket fd (ecase protocol (:stream socket-fd) (:datagram (make-unix-datagram socket-fd path))) (progn ;; fail, close socket and return nil (close-socket socket-fd) (when errorp (error 'socket-error :format-string "cannot bind local pathname")))))) (ecase protocol (:stream socket-fd) (:datagram (make-unix-datagram socket-fd))))) (when errorp (error 'socket-error :format-string "cannot create socket"))))) (defmacro with-unix-socket ((socket &rest options) &body body) `(let ((,socket (open-unix-socket ,@options))) (unwind-protect (progn ,@body) (close-datagram ,socket)))) (defun connect-to-unix-path (pathname &key (protocol :datagram) errorp read-timeout) "Something like CONNECT-TO-TCP-SERVER" (declare (type (or pathname string) pathname)) (let ((socket (open-unix-socket :protocol protocol :errorp errorp :read-timeout read-timeout))) (if socket (let ((socket-fd (ecase protocol (:stream socket) (:datagram (socket-datagram-socket socket))))) (fli:with-dynamic-foreign-objects ((server-addr (:struct sockaddr_un))) (initialize-sockaddr_un server-addr *socket_af_unix* (truename pathname)) (if (connect socket-fd (fli:copy-pointer server-addr :type '(:struct sockaddr)) (fli:pointer-element-size server-addr)) ;; success (ecase protocol (:stream socket-fd) (:datagram socket)) ;; fail (progn (ecase protocol (:stream (close-socket socket-fd)) (:datagram (close-datagram socket))) (when errorp (error 'socket-error :format-string "Cannot connect: ~S." (lw:get-unix-error (lw:errno-value)))))))) (when errorp (error 'socket-error :format-string "Cannot create socket: ~S." (lw:get-unix-error (lw:errno-value))))))) (defmacro with-connected-unix-socket ((socket &rest options) &body body) `(let ((,socket (connect-to-unix-path ,@options))) (unwind-protect (progn ,@body) (close-datagram ,socket)))) (defun open-unix-stream (pathname &key (direction :io) (element-type 'base-char) errorp read-timeout) "Open a UNIX domain socket stream" (declare (type (or pathname string) pathname)) (let ((socket-fd (connect-to-unix-path pathname :protocol :stream :errorp errorp))) (if socket-fd (make-instance 'comm:socket-stream :socket socket-fd :element-type element-type :direction direction :read-timeout read-timeout)))) (defmacro with-unix-stream ((stream &rest options) &body body) `(let ((,stream (open-unix-stream ,@options))) (unwind-protect (progn ,@body) (close ,stream)))) (defvar *unix-message-send-buffer* (make-array +max-udp-message-size+ :element-type '(unsigned-byte 8) :allocation :static)) (defvar *unix-message-send-lock* (mp:make-lock)) (defmethod send-message ((socket unix-datagram) buffer &key (length (length buffer)) path) "Send message to a socket, using send()/sendto()" (declare (type sequence buffer)) (let ((message *unix-message-send-buffer*) (socket-fd (socket-datagram-socket socket))) (fli:with-dynamic-foreign-objects ((client-addr (:struct sockaddr_un)) (len :int #-(or lispworks3 lispworks4 lispworks5.0) :initial-element (fli:size-of '(:struct sockaddr_un)))) (fli:with-dynamic-lisp-array-pointer (ptr message :type '(:unsigned :byte)) (mp:with-lock (*unix-message-send-lock*) (replace message buffer :end2 length) (if path (progn (initialize-sockaddr_un client-addr *socket_af_unix* path) (%sendto socket-fd ptr (min length +max-udp-message-size+) 0 (fli:copy-pointer client-addr :type '(:struct sockaddr)) (fli:dereference len))) (%send socket-fd ptr (min length +max-udp-message-size+) 0))))))) (defvar *unix-message-receive-buffer* (make-array +max-udp-message-size+ :element-type '(unsigned-byte 8) :allocation :static)) (defvar *unix-message-receive-lock* (mp:make-lock)) (defmethod receive-message ((socket unix-datagram) &key buffer (length (length buffer)) read-timeout (max-buffer-size +max-udp-message-size+)) "Receive message from socket, read-timeout is a float number in seconds. This function will return 4 values: 1. receive buffer 2. number of receive bytes 3. peer pathname" (declare (type socket-datagram socket) (type sequence buffer)) (let ((message *unix-message-receive-buffer*) (socket-fd (socket-datagram-socket socket))) (fli:with-dynamic-foreign-objects ((client-addr (:struct sockaddr_un)) (len :int #-(or lispworks3 lispworks4 lispworks5.0) :initial-element (fli:size-of '(:struct sockaddr_un)))) (fli:with-dynamic-lisp-array-pointer (ptr message :type '(:unsigned :byte)) ;; setup new read timeout (when read-timeout (setf (socket-receive-timeout socket-fd) read-timeout)) (mp:with-lock (*unix-message-receive-lock*) (let ((n (%recvfrom socket-fd ptr max-buffer-size 0 (fli:copy-pointer client-addr :type '(:struct sockaddr)) len))) (if (plusp n) (values (if buffer (replace buffer message :end1 (min length max-buffer-size) :end2 (min n max-buffer-size)) (subseq message 0 (min n max-buffer-size))) (min n max-buffer-size) (fli:convert-from-foreign-string (fli:foreign-slot-pointer client-addr 'sun_path) :external-format :utf-8 :null-terminated-p t :allow-null t)) (values nil n ""))))))))
12,044
Common Lisp
.lisp
236
36.139831
105
0.543819
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
993f8df9f3c7062c093f95b7bca6fc0680e222a6b7e432b557c513d25fc15db4
704
[ -1 ]
705
multicast.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/multicast.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: multicast.lisp 654 2008-11-21 16:36:01Z binghe $ ;;; UDP Multicat support for LispWorks (in-package :comm+) (defconstant *sockopt_ipproto_ip* 0 "Dummy protocol") (defconstant *sockopt_ip_multicast_if* #-linux 9 #+linux 32 "specify default interface for outgoing multicasts") (defconstant *sockopt_ip_multicast_ttl* #-linux 10 #+linux 33 "specify TTL for outgoing multicasts") (defconstant *sockopt_ip_multicast_loop* #-linux 11 #+linux 34 "enable or disable loopback of outgoing multicasts") (defconstant *sockopt_ip_add_membership* #-linux 12 #+linux 35 "join a multicast group") (defconstant *sockopt_ip_drop_membership* #-linux 13 #+linux 36 "leave a multicast group") ;; (fli:size-of '(:struct ip_mreq)) = 8 (fli:define-c-struct ip_mreq (imr_multiaddr (:struct in_addr)) (imr_interface (:struct in_addr))) (defgeneric mcast-join (socket address &key)) (defmethod mcast-join ((socket inet-datagram) address &key (interface 0) errorp) (mcast-join (socket-datagram-socket socket) address :interface interface :errorp errorp)) (defmethod mcast-join ((socket-fd integer) address &key (interface 0) errorp) "Join the multicast group (address) on a interface" (declare (type (or string integer) address interface)) (fli:with-dynamic-foreign-objects ((mreq (:struct ip_mreq)) (sock-addr (:struct sockaddr_in))) ;; 1. set multiaddr (initialize-sockaddr_in sock-addr *socket_af_inet* address 0 "udp") (setf (fli:foreign-slot-value (fli:foreign-slot-value mreq 'imr_multiaddr :object-type '(:struct ip_mreq) :type '(:struct in_addr) :copy-foreign-object nil) 's_addr :object-type '(:struct in_addr)) (fli:foreign-slot-value (fli:foreign-slot-value sock-addr 'sin_addr :object-type '(:struct sockaddr_in) :type '(:struct in_addr) :copy-foreign-object nil) 's_addr :object-type '(:struct in_addr))) ;; 2. set interface (initialize-sockaddr_in sock-addr *socket_af_inet* interface 0 "udp") (setf (fli:foreign-slot-value (fli:foreign-slot-value mreq 'imr_interface :object-type '(:struct ip_mreq) :type '(:struct in_addr) :copy-foreign-object nil) 's_addr :object-type '(:struct in_addr)) (fli:foreign-slot-value (fli:foreign-slot-value sock-addr 'sin_addr :object-type '(:struct sockaddr_in) :type '(:struct in_addr) :copy-foreign-object nil) 's_addr :object-type '(:struct in_addr))) ;; 3. call setsockopt() (let ((reply (setsockopt socket-fd *sockopt_ipproto_ip* *sockopt_ip_add_membership* (fli:copy-pointer mreq :type '(:pointer :char)) (fli:size-of '(:struct ip_mreq))))) (or (zerop reply) (if errorp (raise-socket-error "cannot join to multicast group: ~A" address) (values nil (get-last-error))))))) (defgeneric mcast-leave (socket address &key)) (defmethod mcast-leave ((socket inet-datagram) address &key errorp) (mcast-leave (socket-datagram-socket socket) address :errorp errorp)) (defmethod mcast-leave ((socket-fd integer) address &key errorp) "Leave the multicast group (address)" (declare (type (or string integer) address)) (fli:with-dynamic-foreign-objects ((mreq (:struct ip_mreq)) (sock-addr (:struct sockaddr_in))) ;; 1. set multiaddr (initialize-sockaddr_in sock-addr *socket_af_inet* address 0 "udp") (setf (fli:foreign-slot-value (fli:foreign-slot-value mreq 'imr_multiaddr :object-type '(:struct ip_mreq) :type '(:struct in_addr) :copy-foreign-object nil) 's_addr :object-type '(:struct in_addr)) (fli:foreign-slot-value (fli:foreign-slot-value sock-addr 'sin_addr :object-type '(:struct sockaddr_in) :type '(:struct in_addr) :copy-foreign-object nil) 's_addr :object-type '(:struct in_addr))) ;; 2. set interface to zero (INADDR_ANY) (setf (fli:foreign-slot-value (fli:foreign-slot-value mreq 'imr_interface :object-type '(:struct ip_mreq) :type '(:struct in_addr) :copy-foreign-object nil) 's_addr :object-type '(:struct in_addr)) 0) ;; 3. call setsockopt() (let ((reply (setsockopt socket-fd *sockopt_ipproto_ip* *sockopt_ip_drop_membership* (fli:copy-pointer mreq :type '(:pointer :char)) (fli:size-of '(:struct ip_mreq))))) (or (zerop reply) (if errorp (raise-socket-error "cannot leave the multicast group: ~A" address) (values nil (get-last-error))))))) (defgeneric mcast-interface (socket)) (defmethod mcast-interface ((socket inet-datagram)) (mcast-interface (socket-datagram-socket))) (defmethod mcast-interface ((socket-fd integer)) (fli:with-dynamic-foreign-objects ((in-addr (:struct in_addr)) (len :int)) (let ((reply (getsockopt socket-fd *sockopt_ipproto_ip* *sockopt_ip_multicast_if* (fli:copy-pointer in-addr :type '(:pointer :char)) len))) (when (zerop reply) (values (ntohl (fli:foreign-slot-value in-addr 's_addr :object-type '(:struct in_addr))) t))))) (defgeneric mcast-loop (socket)) (defmethod mcast-loop ((socket inet-datagram)) (mcast-loop (socket-datagram-socket socket))) (defmethod mcast-loop ((socket-fd integer)) (fli:with-dynamic-foreign-objects ((flag (:unsigned :char)) (len :int)) (let ((reply (getsockopt socket-fd *sockopt_ipproto_ip* *sockopt_ip_multicast_loop* (fli:copy-pointer flag :type '(:pointer :char)) len))) (when (zerop reply) (values (fli:dereference flag) t))))) (defgeneric mcast-ttl (socket)) (defmethod mcast-ttl ((socket inet-datagram)) (mcast-ttl (socket-datagram-socket socket))) (defmethod mcast-ttl ((socket-fd integer)) (fli:with-dynamic-foreign-objects ((ttl (:unsigned :char)) (len :int)) (let ((reply (getsockopt socket-fd *sockopt_ipproto_ip* *sockopt_ip_multicast_ttl* (fli:copy-pointer ttl :type '(:pointer :char)) len))) (when (zerop reply) (values (fli:dereference ttl) t))))) (defgeneric (setf mcast-ttl) (ttl socket)) (defmethod (setf mcast-ttl) (ttl (socket inet-datagram)) (setf (mcast-ttl (socket-datagram-socket socket)) ttl)) (defmethod (setf mcast-ttl) ((ttl integer) (socket-fd integer)) (declare (type (integer 0) ttl)) (fli:with-dynamic-foreign-objects ((%ttl (:unsigned :char))) (setf (fli:dereference %ttl) ttl) (let ((reply (setsockopt socket-fd *sockopt_ipproto_ip* *sockopt_ip_multicast_ttl* (fli:copy-pointer %ttl :type '(:pointer :char)) (fli:size-of '(:unsigned :char))))) (when (zerop reply) (values ttl t))))) (defgeneric (setf mcast-interface) (interface socket)) (defmethod (setf mcast-interface) (interface (socket inet-datagram)) (setf (mcast-interface (socket-datagram-socket socket)) interface)) (defmethod (setf mcast-interface) ((interface string) (socket-fd integer)) (setf (mcast-interface socket-fd) (get-host-entry interface :fields '(:address)))) (defmethod (setf mcast-interface) ((interface integer) (socket-fd integer)) (declare (type (or string integer) interface)) (fli:with-dynamic-foreign-objects ((in-addr (:struct in_addr))) (setf (fli:foreign-slot-value in-addr 's_addr :object-type '(:struct in_addr)) (htonl interface)) (let ((reply (setsockopt socket-fd *sockopt_ipproto_ip* *sockopt_ip_multicast_if* (fli:copy-pointer in-addr :type '(:pointer :char)) (fli:size-of '(:struct in_addr))))) (when (zerop reply) (values interface t))))) (defgeneric (setf mcast-loop) (flag socket)) (defmethod (setf mcast-loop) (flag (socket inet-datagram)) (setf (mcast-loop (socket-datagram-socket socket)) (if flag 1 0))) (defmethod (setf mcast-loop) (flag (socket-fd integer)) (setf (mcast-loop socket-fd) (if flag 1 0))) (defmethod (setf mcast-loop) ((flag integer) (socket-fd integer)) (declare (type (integer 0 1) flag)) (fli:with-dynamic-foreign-objects ((%flag (:unsigned :char))) (setf (fli:dereference %flag) flag) (let ((reply (setsockopt socket-fd *sockopt_ipproto_ip* *sockopt_ip_multicast_loop* (fli:copy-pointer %flag :type '(:pointer :char)) (fli:size-of '(:unsigned :char))))) (when (zerop reply) (values flag t)))))
10,225
Common Lisp
.lisp
210
35.085714
81
0.549549
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3fac04d8c1fc78ace27fc33aef57239156df948002a4b30bbedca53e93e8ce48
705
[ -1 ]
706
unix-server.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/unix-server.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: unix-server.lisp 570 2008-10-08 10:04:21Z binghe $ (in-package :comm+)
106
Common Lisp
.lisp
3
34
60
0.598039
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
4ca2a84fa64bf9414646850f3f7ad46450290200864323e4076fe7b61e5e50ec
706
[ -1 ]
707
condition.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/condition.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: condition.lisp 645 2008-11-20 09:15:03Z binghe $ ;;;; Condition for LispWorks-UDP (in-package :comm+) (define-condition socket-warning (warning) ((socket :type socket-datagram :reader socket-warning-socket :initarg :socket))) (define-condition rtt-timeout-warning (socket-warning) ((old-rto :type short-float :reader old-rto-of :initarg :old-rto) (new-rto :type short-float :reader new-rto-of :initarg :new-rto)) (:report (lambda (condition stream) (format stream "Receive timeout (~0,1Fs), next: ~0,1Fs.~%" (old-rto-of condition) (new-rto-of condition)))) (:documentation "RTT timeout warning")) (define-condition rtt-seq-mismatch-warning (socket-warning) ((send-seq :type integer :reader send-seq-of :initarg :send-seq) (recv-seq :type integer :reader recv-seq-of :initarg :recv-seq)) (:report (lambda (condition stream) (format stream "Sequence number mismatch (~D -> ~D), try read again.~%" (send-seq-of condition) (recv-seq-of condition)))) (:documentation "RTT sequence mismatch warning")) (define-condition datagram-socket-error (socket-error) ((socket :type socket-datagram :reader socket-error-socket :initarg :socket))) (define-condition rtt-timeout-error (datagram-socket-error) () (:report (lambda (condition stream) (declare (ignore condition)) (format stream "Max retransmit times (~D) reached, give up.~%" *rtt-maxnrexmt*))) (:documentation "RTT timeout error"))
1,747
Common Lisp
.lisp
43
31.837209
84
0.606007
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
5ca7b97fb564dfbbc209e395055121dbe0c296cc9e792c8169f4d248e5abf3ec
707
[ -1 ]
708
interface.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/interface.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: interface.lisp 573 2008-10-09 09:52:35Z binghe $ (in-package :comm+) (defconstant +IFF_UP+ #x1 "interface is up") (defconstant +IFF_BROADCAST+ #x2 "broadcast address valid") (defconstant +IFF_MULTICAST+ #x8000 "supports multicast") (defconstant +IFF_LOOPBACK+ #x8 "is a loopback net") (defconstant +IFF_POINTOPOINT+ #x10 "interface is point-to-point link") (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +IFNAMSIZ+ 16) ;; (fli:size-of '(:struct ifreq)) = 32 (fli:define-c-struct ifreq (ifr_name (:ef-mb-string :limit +IFNAMSIZ+ :external-format :ascii :null-terminated-p t)) (ifr_ifru (:union (ifru_addr (:struct sockaddr)) (ifru_dstaddr (:struct sockaddr)) (ifru_broadaddr (:struct sockaddr)) (ifru_flags :short) (ifru_metric :int) (ifru_data (:pointer :void))))) ;; (fli:size-of '(:struct ifconf)) = 8 (fli:define-c-struct ifconf (ifc_len :int) (ifc_ifcu (:union (ifcu_buf (:pointer :void)) (ifcu_req (:pointer (:struct ifreq))))))) ;;; #define SIOCGIFCONF _IOWR('i', 36, struct ifconf) /* get ifnet list */ ;;; #define _IOWR(g,n,t) _IOC(IOC_INOUT, (g), (n), sizeof(t)) ;;; #define _IOC(inout,group,num,len) \ ;;; (inout | ((len & IOCPARM_MASK) << 16) | ((group) << 8) | (num)) ;;; #define IOCPARM_MASK 0x1fff /* parameter length, at most 13 bits */ ;;; #define IOC_INOUT (IOC_IN|IOC_OUT) ;;; #define IOC_OUT (unsigned long)0x40000000 ;;; #define IOC_IN (unsigned long)0x80000000 (eval-when (:compile-toplevel) (defconstant +IOC_IN+ #x80000000) (defconstant +IOC_OUT+ #x40000000) (defconstant +IOC_INOUT+ (logior +IOC_IN+ +IOC_OUT+)) (defconstant +IOCPARM_MASK+ #x1fff) (defun _IOWR (g n type) (_IOC +IOC_INOUT+ g n (fli:size-of type))) (defun _IOC (inout group num len) (logior inout (ash (logand len +IOCPARM_MASK+) 16) (ash group 8) num))) (defconstant +SIOCGIFCONF+ #+linux #x8912 #-linux #.(_IOWR (char-code #\i) 36 '(:struct ifconf)) "_IOWR('i', 36, struct ifconf), get ifnet list") (defun list-all-interfaces () (with-udp-socket (socket :errorp t) (let ((socket-fd (socket-datagram-socket socket)) (len (* 100 (fli:size-of '(:struct ifreq))))) (fli:with-dynamic-foreign-objects ((ifc (:struct ifconf)) (ifr (:pointer (:struct ifreq))) (ifrcopy (:struct ifreq)) (sinptr (:pointer (:struct sockaddr_in))) (buf (:pointer :byte))) (setf (fli:dereference buf) (fli:allocate-dynamic-foreign-object :type :byte :nelems len) (fli:foreign-slot-value ifc 'ifc_len) len (fli:foreign-slot-value (fli:foreign-slot-pointer ifc 'ifc_ifcu) 'ifcu_buf) buf) (ioctl socket-fd +SIOCGIFCONF+ ifc) (fli:foreign-slot-value ifc 'ifc_len)))))
3,324
Common Lisp
.lisp
71
37.126761
85
0.54254
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
2e2c7b1f80717cea9af9695e2a1005dafdbd05063ad5ece123e1ddc6bb19a15e
708
[ -1 ]
709
rtt.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/rtt.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: rtt.lisp 641 2008-11-20 03:52:57Z binghe $ (in-package :comm+) ;;; UNIX Network Programming v1 - Networking APIs: Sockets and XTI ;;; Chapter 20: Advance UDP Sockets ;;; Adding Reliability to a UDP Application (defclass rtt-info-mixin () ((rtt :type short-float :documentation "most recent measured RTT, seconds") (srtt :type short-float :documentation "smoothed RTT estimator, seconds") (rttvar :type short-float :documentation "smoothed mean deviation, seconds") (rto :type short-float :documentation "current RTO to use, seconds") (nrexmt :type fixnum :documentation "#times retransmitted: 0, 1, 2, ...") (base :type integer :documentation "#sec since 1/1/1970 at start, but we use Lisp time here")) (:documentation "RTT Info Class")) (defvar *rtt-rxtmin* 2.0s0 "min retransmit timeout value, seconds") (defvar *rtt-rxtmax* 60.0s0 "max retransmit timeout value, seconds") (defvar *rtt-maxnrexmt* 3 "max #times to retransmit") (defmethod rtt-rtocalc ((instance rtt-info-mixin)) "Calculate the RTO value based on current estimators: smoothed RTT plus four times the deviation." (with-slots (srtt rttvar) instance (+ srtt (* 4.0s0 rttvar)))) (defun rtt-minmax (rto) "rtt-minmax makes certain that the RTO is between the upper and lower limits." (declare (type short-float rto)) (cond ((< rto *rtt-rxtmin*) *rtt-rxtmin*) ((> rto *rtt-rxtmax*) *rtt-rxtmax*) (t rto))) (defmethod initialize-instance :after ((instance rtt-info-mixin) &rest initargs &key &allow-other-keys) (declare (ignore initargs)) (rtt-init instance)) (defmethod rtt-init ((instance rtt-info-mixin)) (with-slots (base rtt srtt rttvar rto) instance (setf base (get-internal-real-time) rtt 0.0s0 srtt 0.0s0 rttvar 0.75s0 rto (rtt-minmax (rtt-rtocalc instance))))) (defmethod rtt-ts ((instance rtt-info-mixin)) (* (- (get-internal-real-time) (slot-value instance 'base)) #.(/ 1000 internal-time-units-per-second))) (defmethod rtt-start ((instance rtt-info-mixin)) "return value can be used as: alarm(rtt_start(&foo))" (round (slot-value instance 'rto))) (defmethod rtt-stop ((instance rtt-info-mixin) (ms number)) (with-slots (rtt srtt rttvar rto) instance (setf rtt (/ ms 1000.0s0)) (let ((delta (- rtt srtt))) (incf srtt (/ delta 8.0s0)) (incf rttvar (/ (- (abs delta) rttvar) 4.0s0))) (setf rto (rtt-minmax (rtt-rtocalc instance))))) (defmethod rtt-timeout ((instance rtt-info-mixin)) (with-slots (rto nrexmt) instance (setf rto (* rto 2.0s0)) (< (incf nrexmt) *rtt-maxnrexmt*))) (defmethod rtt-newpack ((instance rtt-info-mixin)) (setf (slot-value instance 'nrexmt) 0))
2,870
Common Lisp
.lisp
64
39.5625
85
0.66058
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
2f600f856f59b72043ab1d6df4f54859c74755c96c8efe4366ef033335341cb0
709
[ -1 ]
710
test.lisp
cac-t-u-s_om-sharp/src/lisp-externals/lispworks-udp/test.lisp
;;;; -*- Mode: Lisp -*- ;;;; $Id: test.lisp 658 2008-11-21 18:27:24Z binghe $ (in-package :cl-user) ;;; UDP Echo Test: use macros (defun udp-echo-test-3 (&optional (port 10000)) (let* ((fn #'(lambda (data) (map '(simple-array (unsigned-byte 8) (*)) #'char-code (format nil "receive from ~A:~A -> ~A" (comm+:ip-address-string comm+:*client-address*) comm+:*client-port* (map 'string #'code-char data))))) (server-process (comm+:start-udp-server :function fn :service port))) (unwind-protect (comm+:with-udp-stream (stream "localhost" port :read-timeout 1 :errorp t) (let ((data "Hello, world!")) (format stream "~A" data) (terpri stream) ;; = "~%" or #\Newline (force-output stream) (format t "STREAM: Send message: ~A~%" data) (let ((echo (read-line stream nil nil))) (format t "STREAM: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) (defun udp-echo-test-4 (&optional (port 10000)) (let* ((server-process (comm+:start-udp-server :function #'reverse :service port))) (unwind-protect (comm+:with-udp-socket (socket :read-timeout 10) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (comm+:send-message socket data :host "localhost" :service port) (format t "SOCKET: Send message: ~A~%" data) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) (defun udp-echo-test-5 (&optional (port 10000)) "Limit MAX-BUFFER-SIZE, less than send bytes." (let* ((echo-fn #'(lambda (data) data)) (server-process (comm+:start-udp-server :function echo-fn :service port))) (unwind-protect (comm+:with-connected-udp-socket (socket "localhost" port :read-timeout 1 :errorp t) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (princ (comm+:send-message socket data :host nil :service nil)) (format t "SOCKET: Send message: ~A~%" data) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) (defun loop-test (&optional (port 3500)) (labels ((echo-fn (data) data)) (loop for i from 1 to 10 do (let ((server (comm+:start-udp-server :function #'echo-fn :service port :loop-time 0.3))) (comm+:with-udp-socket (socket :read-timeout 1) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (comm+:send-message socket data (length data) "localhost" port) (format t "SOCKET: Send message: ~A~%" data) (let ((echo (multiple-value-list (comm+:receive-message socket)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (princ (comm+:stop-udp-server server :wait t)))))) (defun rtt-test-1 (&optional (port 10000)) "RTT test" (let ((server-process (comm+:start-udp-server :function #'reverse :service port))) (unwind-protect (comm+:with-connected-udp-socket (socket "localhost" port :errorp t) (comm+:sync-message socket "xxxxABCDEFGH" :max-receive-length 8 :encode-function #'(lambda (x) (values (map 'vector #'char-code x) 0)) :decode-function #'(lambda (x) (values (map 'string #'code-char x) 0)))) (comm+:stop-udp-server server-process)))) (defun rtt-test-2 (&optional (port 10000)) "RTT test, no server" (comm+:with-udp-socket (socket) (handler-case (comm+:sync-message socket "xxxxABCDEFGH" :host "localhost" :service port :max-receive-length 8 :encode-function #'(lambda (x) (values (map 'vector #'char-code x) 0)) :decode-function #'(lambda (x) (values (map 'string #'code-char x) 0))) (error (c) (format t "Got a condition (~A): ~A~%" (type-of c) c))))) #-mswindows (defun wait-test-1 (&optional (port 10000)) (let* ((server-process (comm+:start-udp-server :function #'reverse :service port))) (unwind-protect (comm+:with-udp-socket (socket) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (comm+:send-message socket data :host "localhost" :service port) (format t "SOCKET: Send message: ~A~%" data) ;;; wait the socket until it's available (comm+:wait-for-input socket) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) #-mswindows (defun mcast-test-1 (&optional (host "224.0.0.1") (port 10000)) "Send one get three" (let* ((echo-fn #'(lambda (data) data)) (server-processes (mapcar #'(lambda (x) (comm+:start-udp-server :function echo-fn :service port :announce t :address host :multicast t)) '(nil nil nil)))) (unwind-protect (comm+:with-connected-udp-socket (socket host port :read-timeout 1 :errorp t) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (format t "~A~%" (comm+:send-message socket data)) (format t "SOCKET: Send message: ~A~%" data) (dotimes (i 3) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo))))) (mapcar #'comm+:stop-udp-server server-processes))))
6,449
Common Lisp
.lisp
116
40.051724
104
0.512654
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
f0fbeb9227a64b22efa9076f6de5975bf2f485b5acd85ffd6700581b5201755f
710
[ -1 ]
711
ieee-floats.lisp
cac-t-u-s_om-sharp/src/lisp-externals/ieee-floats/ieee-floats.lisp
;;; Functions for converting floating point numbers represented in ;;; IEEE 754 style to lisp numbers. ;;; ;;; See http://common-lisp.net/project/ieee-floats/ (defpackage :ieee-floats (:use :common-lisp) (:export :make-float-converters :encode-float32 :decode-float32 :encode-float64 :decode-float64)) (in-package :ieee-floats) ;; The following macro may look a bit overcomplicated to the casual ;; reader. The main culprit is the fact that NaN and infinity can be ;; optionally included, which adds a bunch of conditional parts. ;; ;; Assuming you already know more or less how floating point numbers ;; are typically represented, I'll try to elaborate a bit on the more ;; confusing parts, as marked by letters: ;; ;; (A) Exponents in IEEE floats are offset by half their range, for ;; example with 8 exponent bits a number with exponent 2 has 129 ;; stored in its exponent field. ;; ;; (B) The maximum possible exponent is reserved for special cases ;; (NaN, infinity). ;; ;; (C) If the exponent fits in the exponent-bits, we have to adjust ;; the significand for the hidden bit. Because decode-float will ;; return a significand between 0 and 1, and we want one between 1 ;; and 2 to be able to hide the hidden bit, we double it and then ;; subtract one (the hidden bit) before converting it to integer ;; representation (to adjust for this, 1 is subtracted from the ;; exponent earlier). When the exponent is too small, we set it to ;; zero (meaning no hidden bit, exponent of 1), and adjust the ;; significand downward to compensate for this. ;; ;; (D) Here the hidden bit is added. When the exponent is 0, there is ;; no hidden bit, and the exponent is interpreted as 1. ;; ;; (E) Here the exponent offset is subtracted, but also an extra ;; factor to account for the fact that the bits stored in the ;; significand are supposed to come after the 'decimal dot'. (defmacro make-float-converters (encoder-name decoder-name exponent-bits significand-bits support-nan-and-infinity-p) "Writes an encoder and decoder function for floating point numbers with the given amount of exponent and significand bits (plus an extra sign bit). If support-nan-and-infinity-p is true, the decoders will also understand these special cases. NaN is represented as :not-a-number, and the infinities as :positive-infinity and :negative-infinity. Note that this means that the in- or output of these functions is not just floating point numbers anymore, but also keywords." (let* ((total-bits (+ 1 exponent-bits significand-bits)) (exponent-offset (1- (expt 2 (1- exponent-bits)))) ; (A) (sign-part `(ldb (byte 1 ,(1- total-bits)) bits)) (exponent-part `(ldb (byte ,exponent-bits ,significand-bits) bits)) (significand-part `(ldb (byte ,significand-bits 0) bits)) (nan support-nan-and-infinity-p) (max-exponent (1- (expt 2 exponent-bits)))) ; (B) `(progn (defun ,encoder-name (float) ,@(unless nan `((declare (type float float)))) (multiple-value-bind (sign significand exponent) (cond ,@(when nan `(((eq float :not-a-number) (values 0 1 ,max-exponent)) ((eq float :positive-infinity) (values 0 0 ,max-exponent)) ((eq float :negative-infinity) (values 1 0 ,max-exponent)))) ((zerop float) (values 0 0 0)) (t (multiple-value-bind (significand exponent sign) (decode-float float) (let ((exponent (+ (1- exponent) ,exponent-offset)) (sign (if (= sign 1.0) 0 1))) (unless (< exponent ,(expt 2 exponent-bits)) (error "Floating point overflow when encoding ~A." float)) (if (<= exponent 0) ; (C) (values sign (ash (round (* ,(expt 2 significand-bits) significand)) exponent) 0) (values sign (round (* ,(expt 2 significand-bits) (1- (* significand 2)))) exponent)))))) (let ((bits 0)) (declare (type (unsigned-byte ,total-bits) bits)) (setf ,sign-part sign ,exponent-part exponent ,significand-part significand) bits))) (defun ,decoder-name (bits) (declare (type (unsigned-byte ,total-bits) bits)) (let* ((sign ,sign-part) (exponent ,exponent-part) (significand ,significand-part)) ,@(when nan `((when (= exponent ,max-exponent) (return-from ,decoder-name (cond ((not (zerop significand)) :not-a-number) ((zerop sign) :positive-infinity) (t :negative-infinity)))))) (if (zerop exponent) ; (D) (setf exponent 1) (setf (ldb (byte 1 ,significand-bits) significand) 1)) (unless (zerop sign) (setf significand (- significand))) (scale-float (float significand ,(if (> total-bits 32) 1.0d0 1.0)) (- exponent ,(+ exponent-offset significand-bits)))))))) ; (E) ;; And instances of the above for the common forms of floats. (make-float-converters encode-float32 decode-float32 8 23 nil) (make-float-converters encode-float64 decode-float64 11 52 nil) ;;; Copyright (c) 2006 Marijn Haverbeke ;;; ;;; This software is provided 'as-is', without any express or implied ;;; warranty. In no event will the authors be held liable for any ;;; damages arising from the use of this software. ;;; ;;; Permission is granted to anyone to use this software for any ;;; purpose, including commercial applications, and to alter it and ;;; redistribute it freely, subject to the following restrictions: ;;; ;;; 1. The origin of this software must not be misrepresented; you must ;;; not claim that you wrote the original software. If you use this ;;; software in a product, an acknowledgment in the product ;;; documentation would be appreciated but is not required. ;;; ;;; 2. Altered source versions must be plainly marked as such, and must ;;; not be misrepresented as being the original software. ;;; ;;; 3. This notice may not be removed or altered from any source ;;; distribution.
6,273
Common Lisp
.lisp
130
42.153846
117
0.658898
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
4da2238a5d0e7b7e0dfaca52ffaff069c6f2210691153882d3255b514e965b12
711
[ -1 ]
712
package.lisp
cac-t-u-s_om-sharp/src/lisp-externals/cl-svg/package.lisp
;;; -*- Mode: LISP; Syntax: Common-lisp; Package: cl-svg; Lowercase: Yes -*- ;;; $Id$ ;;; ;;; Copyright (c) 2008 William S. Annis. All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE ;;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ;;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ;;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT ;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY ;;; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF ;;; SUCH DAMAGE. (defpackage :cl-svg (:nicknames :svg) (:use :common-lisp) (:export #:*indent-spacing* #:*float-format-precision* #:without-attribute-check #:missing-attributes #:stream-out #:xlink-href #:svg-toplevel #:svg-1.1-toplevel #:make-svg-toplevel #:with-svg-to-file #:add-stylesheet #:add-namespace #:add-element #:add-class #:draw #:draw* #:desc #:title #:comment #:script #:script-link #:style #:text #:tspan #:make-svg-symbol #:make-marker #:make-pattern #:make-mask #:gradient-stop #:stop #:make-linear-gradient #:make-radial-gradient #:make-group #:link #:make-foreign-object ;; transformations #:transform #:scale #:translate #:rotate #:skew-x #:skew-y #:matrix ;; the many path helpers #:make-path #:with-path #:path #:move-to #:move-to-r #:line-to #:line-to-r #:horizontal-to #:horizontal-to-r #:vertical-to #:vertical-to-r #:curve-to #:curve-to-r #:smooth-curve-to #:smooth-curve-to-r #:quadratic-curve-to #:quadratic-curve-to-r #:smooth-quadratic-curve-to #:smooth-quadratic-curve-to-r #:arc-to #:arc-to-r #:close-path)) ;;; package.lisp ends here
3,125
Common Lisp
.lisp
85
28.552941
78
0.600395
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
b945319f2fe9212dd859d33ca1c020e22688269af47a75056d9f30005ba05887
712
[ -1 ]
713
compatibility.lisp
cac-t-u-s_om-sharp/src/packages/sdif/compatibility.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;; compatibility for om6 code (e.g. in external libraries) (defmethod filepathname ((self sdiffile)) (file-pathname self)) (defmethod streamsdesc ((self sdiffile)) (file-map self)) ;;; for OM patches (defmethod function-changed-name ((reference (eql 'f0->pf))) 'sdif->bpf)
1,035
Common Lisp
.lisp
20
50.55
77
0.530168
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
09aa8b3c4f994cf4add4bfec7719a037daf5754cfc0defb396a477b7425be0da
713
[ -1 ]
714
sdif.lisp
cac-t-u-s_om-sharp/src/packages/sdif/sdif.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) (require-om-package "basic") (require-om-package "score") (load (decode-local-path "sdif-lib/load-sdif.lisp")) (compile&load (decode-local-path "sdif-om/sdif-struct")) (compile&load (decode-local-path "sdif-om/sdif-file")) (compile&load (decode-local-path "sdif-om/sdif-partials")) (compile&load (decode-local-path "sdif-om/sdif-write")) (compile&load (decode-local-path "sdif-om/sdif-tools")) (compile&load (decode-local-path "sdif-om/sdif-editor")) (compile&load (decode-local-path "compatibility")) (omNG-make-package "SDIF" :container-pack *om-package-tree* :doc "Tools for manipulating data in the Standard Description Interchange Format (SDIF)" :classes '(sdiffile) :subpackages (list (omNG-make-package "SDIF Structures" :classes '(sdifframe sdifmatrix sdiftype sdifnvt) :functions '(find-in-nvt find-in-nvtlist)) (omNG-make-package "Read and Convert" :functions '(SDIFInfo SDIFTypeDescription GetNVTList GetSDIFData GetSDIFTimes GetSDIFFrames GetSDIFPartials GetSDIFChords SDIF->chord-seq SDIF->bpf SDIF->markers SDIF->text)) (omNG-make-package "Write" :functions '(write-sdif-file bpf->sdif markers->sdif chord-seq->sdif open-sdif-stream sdif-write-frame sdif-write-header)) ))
2,239
Common Lisp
.lisp
49
38.673469
90
0.573137
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
cdd01338ce8dfb0b06e9111aa7dc63a7da13f39268bc73a7f73cd7622fd8e609
714
[ -1 ]
715
sdif-api.lisp
cac-t-u-s_om-sharp/src/packages/sdif/sdif-lib/sdif-api.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;=========================================================================== ; SDIF FUNCTIONS ;=========================================================================== (in-package :sdif) (export '(sdif-init sdif-init-cond sdif-kill sdif-check-file sdif-get-pos sdif-set-pos sdif-get-signature sdif-calculate-padding ) :sdif) ;;; INIT/CLOSE SDIF (defvar *sdif-initialized* nil) (defun sdif-init (string) (unless *sdif-initialized* (when sdif::*sdif-library* (print "Initializing SDIF...") (sdif::SdifGenInit string)) (setf *sdif-initialized* t))) (defun sdif-init-cond () (unless *sdif-initialized* (when sdif::*sdif-library* (print "Initializing SDIF...") (sdif::SdifGenInitCond "")) (setf *sdif-initialized* t))) (defun sdif-kill () (print "Killing SDIF...") (sdif::SdifGenKill) (setf *sdif-initialized* nil)) (defun sdif-check-file (filename) (sdif::sdif-init-cond) (not (zerop (sdif::SdifCheckFileFormat (namestring filename))))) (defmethod sdif-open-file ((self string) &optional (mode sdif::eReadWriteFile)) (sdif::sdif-init-cond) (let ((fileptr (sdif::SDIFFOpen self mode))) (and (not (fli:null-pointer-p fileptr)) fileptr))) (defmethod sdif-open-file ((self pathname) &optional (mode sdif::eReadWriteFile)) (sdif-open-file (namestring self) mode)) (defun sdif-get-pos (ptr) (let ((thelong (cffi::%foreign-alloc 8)) rep) (sdif::SdiffGetPos ptr thelong) (setf rep (cffi::mem-ref thelong :unsigned-long)) (cffi:foreign-free thelong) rep)) (defun sdif-set-pos (ptr thelong) (let ((longptr (cffi::%foreign-alloc 8))) (cffi::mem-set thelong longptr :unsigned-long) (sdif::SdiffSetPos ptr longptr) (cffi::foreign-free longptr) t)) (defun sdif-read-next-signature (sdiff) (let ((temp-ptr (cffi::%foreign-alloc 4))) ; (cffi::mem-set 0 sdiff :long) (unwind-protect (sdif::SdifFGetSignature sdiff temp-ptr)) (cffi::foreign-free temp-ptr))) (defun sdif-check-signature (str) (and (not (string-equal "" str)) (string>= str "0000") (string<= str "zzzz"))) (defun sdif-calculate-padding (bytes) (let ((align 8)) (cond ((zerop bytes) 0) ((< bytes align) (- align bytes)) (t (mod (- (cadr (multiple-value-list (ceiling bytes align)))) align)) ;(t (- align (mod bytes align))) ))) ; (sdif-calculate-padding 4) ;;;============================ ;;; TESTS #| (Sdif-Init "") (Sdif-Kill) (setf filepath (namestring (capi::prompt-for-file nil))) (setf filepath (namestring filepath)) (setf sdiffile (Sdif-Open-file filepath :eReadFile)) (sdif-close-file sdiffile) (sdif-check-file filepath) (sdif::sdifFreadgeneralheader sdiffile) (sdif::sdifFReadAllASCIIChunks sdiffile) (sdif::sdifFReadFrameHeader sdiffile) (sdif::SdifFSkipFrameData sdiffile) (setf sign (sdif::SdifFCurrSignature sdiffile)) (setf sign (sdif::SdifFCurrMatrixSignature sdiffile)) (setf sign (sdif::SdifFCurrFrameSignature sdiffile)) (sdif-Signature-to-string sign) (setf bytesread (ff::make-foreign-pointer :size 2 :type :int)) (setf posptr (ff::make-foreign-pointer :size 8 :type :int)) (sdif::SdifFGetSignature sdiffile bytesread) (sdif::sdiffcurrtime sdiffile) (sdif::sdiffcurrdatatype sdiffile) (sdif::sdiffcurrID sdiffile) (sdif::sdiffcurrnbmatrix sdiffile) (sdif::sdiffreadmatrixheader sdiffile) (sdif::sdiffcurrnbcol sdiffile) (sdif::sdiffcurrnbrow sdiffile) (sdif::sdiffskipmatrixdata sdiffile) (sdif::sdiffgetsignature sdiffile bytesread) (sdif::sdiffgetpos sdiffile posptr) (sys::memref-int (ff::foreign-pointer-address posptr) 0 0 :unsigned-long) (defun signature (sdiff ptr) (print (sdif::sdifSignaturetostring (sdif::SdifFCurrSignature sdiff))) (sdif::sdifFReadFrameHeader sdiff) (sdif::sdifFSkipFrameData sdiff) (sdif::SdifFGetSignature sdiffile ptr)) |#
4,819
Common Lisp
.lisp
124
34.193548
83
0.616062
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
fcbf926bf380f247a49fe46b1b9f0cb6fa77b46dd10e07afbae8bbbd851d92e6
715
[ -1 ]
716
load-sdif.lisp
cac-t-u-s_om-sharp/src/packages/sdif/sdif-lib/load-sdif.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;=========================================================================== ; loads the SDIF API ;=========================================================================== (in-package :cl-user) (defpackage "SDIF-PACKAGE" (:nicknames "SDIF") (:use :common-lisp :cffi)) (defvar sdif::*sdif-library* nil) (compile&load (merge-pathnames "sdif" *load-pathname*)) (compile&load (merge-pathnames "sdif-api" *load-pathname*)) (pushnew :sdif *features*) ;;;============================== ;;; CHARGEMENT (defun load-sdif-lib () (setf sdif::*sdif-library* (om-fi::om-load-foreign-library "SDIF" `((:macosx ,(om-fi::om-foreign-library-pathname "libSDIF.dylib")) (:windows (:or ,(om-fi::om-foreign-library-pathname "libsdif.dll") (:default "sdif"))) (:linux (:or "libsdif.so" ,(om-fi::om-foreign-library-pathname "libsdif.so"))) (t (:default "libsdif"))))) (setf sdif::*sdif-initialized* NIL)) (om-fi::add-foreign-loader 'load-sdif-lib)
1,799
Common Lisp
.lisp
37
44.054054
98
0.482699
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e24d9ce9c8bd6d03b620dc762e843b8a5a3fd60a570b9cd87f2d68fb379477ae
716
[ -1 ]
717
sdif.lisp
cac-t-u-s_om-sharp/src/packages/sdif/sdif-lib/sdif.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;=========================================================================== ; SDIF Library binding ;=========================================================================== (in-package :sdif) ;(define-foreign-type sdif-name () ':pointer) (defctype sdif-name :pointer) (defconstant eUnknownFileMode 0) (defconstant eWriteFile 1) (defconstant eReadFile 2) (defconstant eReadWriteFile 3) (defconstant ePredefinedTypes 4) ;;;============================================ ;;; SDIF GENERAL (defcfun ("SdifGenInit" SdifGenInitSTR) :void (PredefinedTypesFile sdif-name)) (defun SdifGenInit (str) (with-foreign-string (cstr str) (sdif::SdifGenInitSTR cstr))) (defcfun ("SdifGenInitCond" SdifGenInitCondSTR) :void (PredefinedTypesFile sdif-name)) (defun SdifGenInitCond (str) (with-foreign-string (cstr str) (sdif::SdifGenInitCondSTR cstr))) (defcfun ("SdifGenKill" SdifGenKill) :void) (defcfun ("SdifPrintVersion" SdifPrintVersion) :void ) (defcfun ("SdifenableErrorOutput" SdifenableErrorOutput) :void ) (defcfun ("SdifDisableErrorOutput" SdifDisableErrorOutput) :void ) (defcfun ("SdifSizeofDataType" SdifSizeofDataType) :unsigned-int (SdifDataTypeET :unsigned-int)) ;;;============================================ ;;; SDIF FILE (defcfun ("SdifFOpen" SdifFOpenSTR) :pointer (name sdif-name) (mode :unsigned-int)) (defun SdifFOpen (str mode) (with-foreign-string (cstr str) (sdif::SdifFOpenSTR cstr mode))) (defcfun ("SdifFClose" SdifFClose) :void (sdifF :pointer)) (defcfun ("SdifCheckFileFormat" SdifCheckFileFormatSTR) :int (name sdif-name)) (defun SdifCheckFileFormat (str) (with-foreign-string (cstr str) (sdif::SdifCheckFileFormatSTR cstr))) (defcfun ("SdifToText" SdifToTextSTR) :unsigned-int (sdifF :pointer) (textStreamName sdif-name)) (defun SdifToText (sdiff str) (with-foreign-string (cstr str) (sdif::SdifToTextSTR sdiff cstr))) (defcfun ("SdifFGetPos" SdifFGetPos) :int (pointer :pointer) (pos :pointer)) (defcfun ("SdifFSetPos" SdifFSetPos) :int ( pointer :pointer) (pos :pointer)) ;;;============================================ ;;; READ SDIF (defcfun ("SdifFGetSignature" SdifFGetSignature) :int (sdifF :pointer) (nbCharRead :pointer)) (defcfun ("SdifFReadGeneralHeader" SdifFReadGeneralHeader) :unsigned-int (sdifF :pointer)) (defcfun ("SdifFReadAllASCIIChunks" SdifFReadAllASCIIChunks) :unsigned-int (sdifF :pointer)) (defcfun ("SdifFReadMatrixHeader" SdifFReadMatrixHeader) :unsigned-int (sdifF :pointer)) (defcfun ("SdifFReadOneRow" SdifFReadOneRow) :unsigned-int (sdifF :pointer)) (defcfun ("SdifFSkipOneRow" SdifFSkipOneRow) :unsigned-int (sdifF :pointer)) (defcfun ("SdifFReadFrameHeader" SdifFReadFrameHeader) :unsigned-int (sdifF :pointer)) (defcfun ("SdifFSkipMatrix" SdifFSkipMatrix) :unsigned-int (sdifF :pointer)) (defcfun ("SdifFSkipMatrixData" SdifFSkipMatrixData) :unsigned-int (sdifF :pointer)) (defcfun ("SdifFSkipFrameData" SdifFSkipFrameData) :unsigned-int (sdifF :pointer)) (defcfun ("SdifFReadPadding" SdifFReadPadding) :unsigned-int (sdifF :pointer) (Padding :unsigned-int)) (defcfun ("SdifFSkip" SdifFSkip) :unsigned-int (sdifF :pointer) (bytes :unsigned-int )) (defcfun ("SdifFReadAndIgnore" SdifFReadAndIgnore) :unsigned-int (sdifF :pointer) (bytes :unsigned-int )) ;;;============================================ ;;; SDIF CURR ;;; remplace unsigned-fullword par address pour les renvois de signature.. a tester (defcfun ("SdifSignatureToString" SdifSignatureToStringSTR) :pointer (Signature :pointer)) (defun SdifSignatureToString (sdifsignature) (foreign-string-to-lisp (sdif::SdifSignatureToStringSTR sdifsignature))) (defcfun ("SdifStringToSignature" SdifStringToSignatureSTR) :pointer (str :pointer)) (defun SdifStringToSignature (str) (with-foreign-string (cstr str) (sdif::SdifStringToSignatureSTR cstr))) (defcfun ("SdifFCurrSignature" SdifFCurrSignature) :pointer (SdifF :pointer)) (defcfun ("SdifFCleanCurrSignature" SdifFCleanCurrSignature) :pointer (SdifF :pointer)) (defcfun ("SdifFCurrFrameSignature" SdifFCurrFrameSignature) :pointer (SdifF :pointer)) (defcfun ("SdifFCurrMatrixSignature" SdifFCurrMatrixSignature) :pointer (SdifF :pointer)) (defcfun ("SdifFCurrTime" SdifFCurrTime) :double (SdifF :pointer)) (defcfun ("SdifFCurrID" SdifFCurrID) :unsigned-int (SdifF :pointer)) ;;; !!! actually does not return INT but SdifDataTypeET ... (defcfun ("SdifFCurrDataType" SdifFCurrDataType) :unsigned-int (SdifF :pointer)) (defcfun ("SdifFCurrNbMatrix" SdifFCurrNbMatrix) :unsigned-int (SdifF :pointer)) (defcfun ("SdifFCurrNbCol" SdifFCurrNbCol) :unsigned-int (SdifF :pointer)) (defcfun ("SdifFCurrNbRow" SdifFCurrNbRow) :unsigned-int (SdifF :pointer)) (defcfun ("SdifFCurrOneRowCol" SdifFCurrOneRowCol) :double (SdifF :pointer) (numcol :unsigned-int)) ;;;============================================ ;;; CREATE SDIF (defcfun ("SdifFSetCurrFrameHeader" SdifFSetCurrFrameHeader) :pointer (SdifF :pointer) (Signature :pointer) (Size :unsigned-int) (NbMatrix :unsigned-int) (NumID :unsigned-int) (Time :double)) (defcfun ("SdifFSetCurrMatrixHeader" SdifFSetCurrMatrixHeader) :pointer (SdifF :pointer) (Signature :pointer) (DataType :unsigned-int) (NbRow :unsigned-int)) (defcfun ("SdifFSetCurrOneRow" SdifFSetCurrOneRow) :pointer (SdifF :pointer) (values :pointer)) (defcfun ("SdifFSetCurrOneRowCol" SdifFSetCurrOneRowCol) :pointer (SdifF :pointer) (numcol :unsigned-int) (value :double)) ;;;============================================ ;;; WRITE SDIF (defcfun ("SdifFWriteGeneralHeader" SdifFWriteGeneralHeader) :unsigned-int (sdifF :pointer)) (defcfun ("SdifFWriteAllASCIIChunks" SdifFWriteAllASCIIChunks) :unsigned-int (sdifF :pointer)) (defcfun ("SdifFWriteFrameHeader" SdifFWriteFrameHeader) :unsigned-int (sdifF :pointer)) (defcfun ("SdifUpdateChunkSize" SdifUpdateChunkSize) :void (sdifF :pointer) (chunk-size :unsigned-int)) (defcfun ("SdifUpdateFrameHeader" SdifUpdateFrameHeader) :int (sdifF :pointer) (chunksize :unsigned-int) (nummat :int)) (defcfun ("SdifFWriteMatrixHeader" SdifFWriteMatrixHeader) :unsigned-int (SdifF :pointer)) (defcfun ("SdifFWriteOneRow" SdifFWriteOneRow) :unsigned-int (SdifF :pointer)) (defcfun ("SdifFWriteMatrixData" SdifFWriteMatrixData) :unsigned-int (SdifF :pointer) (data :pointer)) (defcfun ("SdifFWriteMatrix" SdifFWriteMatrix) :unsigned-int (SdifF :pointer) (Signature :pointer) (DataType :unsigned-int) (NbRow :unsigned-int) (NbCol :unsigned-int) (data :pointer)) (defcfun ("SdifFWritePadding" SdifFWritePadding) :unsigned-int (sdifF :pointer) (padding :unsigned-int)) (defcfun ("SdifPaddingCalculate" SdifPaddingCalculate) :unsigned-int (sdifF :pointer) (nbbytes :unsigned-int)) ;;;================================= ;;; ID TABLE (defcfun ("SdifStreamIDTablePutSID" SdifStreamIDTablePutSIDSTR) :pointer (SDITable :pointer) (NumID :unsigned-int) (Source sdif-name) (TreeWay sdif-name)) (defun SdifStreamIDTablePutSID (table id name tree) (with-foreign-string (strname name) (with-foreign-string (strtree tree) (SdifStreamIDTablePutSIDSTR table id strname strtree)))) (defcfun ("SdifFStreamIDTable" SdifFStreamIDTable) :pointer (file :pointer)) (defcfun ("SdifStreamIDTableGetNbData" SdifStreamIDTableGetNbData) :unsigned-int (SdifStreamIDTableT :pointer)) (defcfun ("SdifStreamIDTableGetSID" SdifStreamIDTableGetSID) :pointer (SdifStreamIDTableT :pointer) (NumID :unsigned-int)) (defcfun ("SdifStreamIDEntryGetSID" SdifStreamIDEntryGetSID) :unsigned-int (SdifStreamIDT :pointer)) (defcfun ("SdifStreamIDEntryGetSource" SdifStreamIDEntryGetSourceSTR) :pointer (SdifStreamIDT :pointer)) (defun SdifStreamIDEntryGetSource (sid) (foreign-string-to-lisp (SdifStreamIDEntryGetSourceSTR sid))) (defcfun ("SdifStreamIDEntryGetTreeWay" SdifStreamIDEntryGetTreeWaySTR) :pointer (SdifStreamIDT :pointer)) (defun SdifStreamIDEntryGetTreeWay (sid) (foreign-string-to-lisp (SdifStreamIDEntryGetTreeWaySTR sid))) ;;;================================= ;;; NVT (defcfun ("SdifCreateNameValuesL" SdifCreateNameValuesL) :pointer (hashsize :unsigned-int)) (defcfun ("SdifKillNameValuesL" SdifKillNameValuesL) :void (NVL :pointer)) (defcfun ("SdifFNameValueList" SdifFNameValueList) :pointer (sdifF :pointer)) (defcfun ("SdifNameValuesLGet" SdifNameValuesLGetSTR) :pointer (NVL :pointer) (name :pointer)) (defun SdifNameValuesLGet (nvl name) (with-foreign-string (strname name) (sdif::SdifNameValuesLGetSTR nvl strname))) (defcfun ("SdifNameValuesLNewTable" SdifNameValuesLNewTable) :pointer (SdifNameValuesLT :pointer) (StreamID :unsigned-int)) (defcfun ("SdifNameValuesLSetCurrNVT" SdifNameValuesLSetCurrNVT) :pointer (NVL :pointer) (numNVT :unsigned-int)) (defcfun ("SdifNameValuesLPutCurrNVT" SdifNameValuesLPutCurrNVTSTR) :pointer (SdifNameValuesLT :pointer) (name sdif-name) (value sdif-name)) (defun SdifNameValuesLPutCurrNVT (table name value) (with-foreign-string (strname name) (with-foreign-string (strvalue value) (sdif::SdifNameValuesLPutCurrNVTSTR table strname strvalue)))) (defcfun ("SdifNameValueTableGetStreamID" SdifNameValueTableGetStreamID) :int (NVT :pointer)) (defcfun ("SdifNameValueTableGetNumTable" SdifNameValueTableGetNumTable) :int (NVT :pointer)) (defcfun ("SdifNameValueTableList" SdifNameValueTableList) :pointer (NVL :pointer)) (defcfun ("SdifNameValueTableGetHashTable" SdifNameValueTableGetHashTable) :pointer (NVT :pointer)) (defcfun ("SdifNameValueGetName" SdifNameValueGetNameSTR) :pointer (NV :pointer)) (defun SdifNameValueGetName (nv) (foreign-string-to-lisp (sdif::SdifNameValueGetNameSTR nv))) (defcfun ("SdifNameValueGetValue" SdifNameValueGetValueSTR) :pointer (NV :pointer)) (defun SdifNameValueGetValue (nv) (foreign-string-to-lisp (sdif::SdifNameValueGetValueSTR nv))) ;;;================================= ;;;TYPES TABLE (defcfun ("SdifFGetMatrixTypesTable" SdifFGetMatrixTypesTable) :pointer (file :pointer)) (defcfun ("SdifFGetFrameTypesTable" SdifFGetFrameTypesTable) :pointer (file :pointer)) (defcfun ("SdifCreateMatrixType" SdifCreateMatrixType) :pointer (Signature :unsigned-int) (SdifMatrixTypeT :pointer)) (defcfun ("SdifPutMatrixType" SdifPutMatrixType) :void (mtable :pointer) (SdifMatrixTypeT :pointer)) (defcfun ("SdifMatrixTypeInsertTailColumnDef" SdifMatrixTypeInsertTailColumnDefSTR) :pointer (matrix :pointer) (str sdif-name)) (defun SdifMatrixTypeInsertTailColumnDef (matrixtype name) (with-foreign-string (strname name) (sdif::SdifMatrixTypeInsertTailColumnDefSTR matrixtype strname))) (defcfun ("SdifCreateFrameType" SdifCreateFrameType) :pointer (Signature :unsigned-int) (SdifMatrixTypeT :pointer)) (defcfun ("SdifPutFrameType" SdifPutFrameType) :void (ftable :pointer) (SdifFrameTypeT :pointer)) (defcfun ("SdifFrameTypePutComponent" SdifFrameTypePutComponentSTR) :pointer (frame :pointer) (sign :unsigned-int) (str sdif-name)) (defun SdifFrameTypePutComponent (frametype sign name) (with-foreign-string (strname name) (sdif::SdifFrameTypePutComponentSTR frametype sign strname))) (defcfun ("SdifTestMatrixType" SdifTestMatrixType) :pointer (sdifF :pointer) (signature :pointer)) (defcfun ("SdifTestFrameType" SdifTestFrameType) :pointer (sdifF :pointer) (signature :pointer)) (defcfun ("SdifMatrixTypeGetColumnName" SdifMatrixTypeGetColumnNameSTR) :pointer (MatrixType :pointer) (num :int)) (defun SdifMatrixTypeGetColumnName (mtype num) (foreign-string-to-lisp (sdif::SdifMatrixTypeGetColumnNameSTR mtype num))) (defcfun ("SdifMatrixTypeGetNbColumns" SdifMatrixTypeGetNbColumns) :int (MatrixType :pointer)) (defcfun ("SdifFrameTypeGetNbComponents" SdifFrameTypeGetNbComponents) :int (FrameType :pointer)) (defcfun ("SdifFrameTypeGetNthComponent" SdifFrameTypeGetNthComponent) :pointer (FrameType :pointer) (num :int)) (defcfun ("SdifFrameTypeGetComponentSignature" SdifFrameTypeGetComponentSignature) :pointer (Component :pointer)) ;;;================================= ;;; STRING (defcfun ("SdifStringNew" SdifStringNew) :pointer) (defcfun ("SdifStringFree" SdifStringFree) :void (str :pointer)) (defcfun ("SdifStringAppend" SdifStringAppendSTR) :int (str :pointer) (str1 :pointer)) (defun SdifStringAppend (ptr str) (with-foreign-string (strp str) (sdif::SdifStringAppendSTR ptr strp))) (defcfun ("SdifStringGetC" SdifStringGetC) :int (str :pointer)) (defcfun ("SdifFGetAllTypefromSdifString" SdifFGetAllTypefromSdifString) :unsigned-int (file :pointer) (str :pointer)) ;;;================================= ;;; LIST (defcfun ("SdifListGetNbData" SdifListGetNbData) :unsigned-int (list :pointer)) (defcfun ("SdifListInitLoop" SdifListInitLoop) :int (list :pointer)) (defcfun ("SdifListIsNext" SdifListIsNext) :int (list :pointer)) (defcfun ("SdifListGetNext" SdifListGetNext) :pointer (list :pointer)) ;;;================================= ;;; HASH TABLE ITERATOR (defcfun ("SdifHashTableGetNbData" SdifHashTableGetNbData) :unsigned-int (sdifhashtable :pointer)) (defcfun ("SdifCreateHashTableIterator" SdifCreateHashTableIterator) :pointer (sdifhashtable :pointer)) (defcfun ("SdifKillHashTableIterator" SdifKillHashTableIterator) :void (htiterator :pointer)) (defcfun ("SdifHashTableIteratorInitLoop" SdifHashTableIteratorInitLoop) :pointer (htiterator :pointer) (sdifhashtable :pointer)) (defcfun ("SdifHashTableIteratorIsNext" SdifHashTableIteratorIsNext) :int (htiterator :pointer)) (defcfun ("SdifHashTableIteratorGetNext" SdifHashTableIteratorGetNext) :pointer (htiterator :pointer))
14,599
Common Lisp
.lisp
195
71.297436
133
0.730297
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
9ef62dd3db969b17eb4c0136a27a52116de068503e558b0c64a1d407b6ff71c3
717
[ -1 ]
718
sdif-file.lisp
cac-t-u-s_om-sharp/src/packages/sdif/sdif-om/sdif-file.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;================================================================================ ;;; SDIFFILE is a pointer to a file on the disk ;;; It loads a filemap for quick inspect ;;; It can be edited to the extend of this map (streams, frames etc.) ;;; Frames can be extracted to a data-track for further manipulations ;;;================================================================================ (defclass* SDIFFile (sdif-object) ((file-pathname :initform nil :accessor file-pathname) (file-map :initform nil :accessor file-map)) (:documentation " SDIFFILE represents an SDIF file stored in your hard drive. SDIF is a generic format for the storage and transfer of sound description data between applications. It is used in particular by software like SuperVP, pm2, AudioSculpt, Spear, etc. to store and export sound analyses. See http://www.ircam.fr/sdif for more inforamtion about SDIF Connect a pathname to an SDIF file, or the output of a function returning such a pathname, to initialize the SDIFFILE. If <self> = :choose-file (default when not connected), the evaluation of the SDIFFILE box will open a file chooser dialog. Lock the box ('b') to keep the current file. ")) (defmethod additional-slots-to-save ((self SDIFFile)) '(file-pathname file-map)) (defmethod additional-slots-to-copy ((self SDIFFile)) '(file-pathname file-map)) ;;; specialized to save SDIFFile pathname relative ;;; + prevent saving unnecessary slots (defmethod omng-save ((self SDIFFile)) `(:object (:class ,(type-of self)) (:add-slots ((:file-map ,(omng-save (file-map self))) (:file-pathname ,(and (file-pathname self) (omng-save (relative-pathname (file-pathname self) *relative-path-reference*)))) )) )) ;;; INIT METHODS (defmethod box-def-self-in ((self (eql 'SDIFFile))) :choose-file) (defmethod objFromObjs ((model (eql :choose-file)) (target SDIFFile)) (let ((file (om-choose-file-dialog :prompt "Choose an SDIF file..." :types '("SDIF files" "*.sdif")))) (if file (objFromObjs file target) (abort-eval)))) (defmethod objfromobjs ((model pathname) (target SDIFFile)) (when (and (or (probe-file model) (om-beep-msg "File note found: ~A" model)) (or (sdif::sdif-check-file model) (om-beep-msg "Invalid SDIF file: ~A" model))) (setf (file-pathname target) model) target)) (defmethod objfromobjs ((model string) (target SDIFFile)) (objfromobjs (pathname model) target)) ;;; Calls to the SDIF library must be all in the same thread ;;; => We do it in the patch evaluation thread (defun eval-sdif-expression (function) (om-lisp::om-eval-on-process function)) (defmethod om-init-instance ((self SDIFFile) &optional initargs) (call-next-method) (when (and initargs ;;; we want to load only in evaluations (not in copy/load-patch) (file-pathname self)) ;;; this would be in case we do it outside of evaluation context... ;; (eval-sdif-expression #'(lambda () (load-sdif-file self))) (load-sdif-file self) ) self) ;;; CONNECT SDIFFILE TO TEXTBUFFER (defmethod objfromobjs ((self SDIFFile) (target TextBuffer)) (objfromobjs (sdif->text self) target)) ;;; DISPLAY BOX (defmethod display-modes-for-object ((self sdiffile)) '(:mini-view :text :hidden)) (defmethod get-cache-display-for-text ((self sdiffile) box) (declare (ignore box)) `((:file-pathname ,(file-pathname self)) (:file-contents ,(loop for stream in (file-map self) collect (format nil "~D:~A ~A" (fstream-desc-id stream) (fstream-desc-fsig stream) (mapcar 'mstream-desc-msig (fstream-desc-matrices stream))) ) ))) (defmethod default-name ((self sdiffile)) (when (file-pathname self) (string+ (pathname-name (file-pathname self)) "." (pathname-type (file-pathname self))))) (defmethod draw-mini-view ((self sdiffile) (box t) x y w h &optional time) (let* ((n-streams (length (file-map self))) (stream-h (round h (max n-streams 1))) (max-t (list-max (mapcar 'fstream-desc-tmax (file-map self)))) (font (om-def-font :small))) (om-with-font (om-make-font "Courier" 36 :style '(:bold)) (om-with-fg-color (om-make-color 0.6 0.6 0.6 0.5) (om-draw-string (- (round w 2) 38) (+ y (max 30 (+ 14 (/ h 2)))) "SDIF"))) (om-with-font font (loop for stream in (file-map self) for ypos = y then (+ ypos stream-h) do (when (> max-t 0) (om-draw-rect (+ x (* w (/ (fstream-desc-tmin stream) max-t))) (+ ypos 2) (* w (/ (fstream-desc-tmax stream) max-t)) (- stream-h 4) :color (om-make-color-alpha (om-def-color :dark-blue) 0.5) :fill t)) (om-with-fg-color (om-def-color :white) (om-draw-string (+ x 4) (+ ypos 12) (format nil "~D:~A ~A" (fstream-desc-id stream) (fstream-desc-fsig stream) (mapcar 'mstream-desc-msig (fstream-desc-matrices stream)))))) ))) ;;; Drop an SDIF file in patch (pushr '(:sdif ("sdif") "SDIF files") *doctypes*) (defmethod omNG-make-new-box-from-file ((type (eql :sdif)) file pos) (let* ((sdiffile (objfromobjs file (make-instance 'SDIFFile))) (box (make-new-box-with-instance (om-init-instance sdiffile T) pos))) (set-lock-state box :locked) box)) ;;;======================== ;;; FILL FILE-MAP from file ;;;======================== (defstruct fstream-desc id fsig tmin tmax nf matrices) (defstruct mstream-desc msig fields rmax tmin tmax nf) ;;; COPY / SAVE / LOAD UTILS (defmethod om-copy ((self fstream-desc)) (make-fstream-desc :id (fstream-desc-id self) :fsig (fstream-desc-fsig self) :tmin (fstream-desc-tmin self) :tmax (fstream-desc-tmax self) :nf (fstream-desc-nf self) :matrices (om-copy (fstream-desc-matrices self)))) (defmethod omng-save ((self fstream-desc)) `(:fstream-desc (:id ,(fstream-desc-id self)) (:fsig ,(fstream-desc-fsig self)) (:tmin ,(fstream-desc-tmin self)) (:tmax ,(fstream-desc-tmax self)) (:nf ,(fstream-desc-nf self)) (:matrices ,(omng-save (fstream-desc-matrices self))))) (defmethod om-load-from-id ((id (eql :fstream-desc)) data) (make-fstream-desc :id (find-value-in-kv-list data :id) :fsig (find-value-in-kv-list data :fsig) :tmin (find-value-in-kv-list data :tmin) :tmax (find-value-in-kv-list data :tmax) :nf (find-value-in-kv-list data :nf) :matrices (omng-load (find-value-in-kv-list data :matrices)) )) (defmethod om-copy ((self mstream-desc)) (make-mstream-desc :msig (mstream-desc-msig self) :fields (mstream-desc-fields self) :rmax (mstream-desc-rmax self) :tmin (mstream-desc-tmin self) :tmax (mstream-desc-tmax self) :nf (mstream-desc-nf self))) (defmethod omng-save ((self mstream-desc)) `(:mstream-desc (:msig ,(mstream-desc-msig self)) (:fields ,(mstream-desc-fields self)) (:rmax ,(mstream-desc-rmax self)) (:tmin ,(mstream-desc-tmin self)) (:tmax ,(mstream-desc-tmax self)) (:nf ,(mstream-desc-nf self)))) (defmethod om-load-from-id ((id (eql :mstream-desc)) data) (make-mstream-desc :msig (find-value-in-kv-list data :msig) :fields (find-value-in-kv-list data :fields) :rmax (find-value-in-kv-list data :rmax) :tmin (find-value-in-kv-list data :tmin) :tmax (find-value-in-kv-list data :tmax) :nf (find-value-in-kv-list data :nf) )) (defun check-current-singnature (ptr) (sdif::sdif-check-signature (sdif::SdifSignatureToString (sdif::SdifFCurrSignature ptr)))) (defmethod get-frame-from-sdif (ptr &optional (with-data t)) (sdif::SdifFReadFrameHeader ptr) (let ((sig (sdif::SdifSignatureToString (sdif::SdifFCurrFrameSignature ptr))) (time (sdif::SdifFCurrTime ptr)) (sid (sdif::SdifFCurrId ptr))) (make-instance 'SDIFFrame :ftime time :frametype sig :streamid sid :lmatrix (let ((nummatrix (sdif::SdifFCurrNbMatrix ptr))) (loop for i from 1 to nummatrix collect (get-matrix-from-sdif ptr with-data)))))) (defun get-matrix-column-name-protect (mtype i) (or (ignore-errors (sdif::SdifMatrixTypeGetColumnName mtype i)) (progn (om-print-dbg "SDIF library seems damaged: impossible to read matrix column names") (format nil "??????x~D" i)) )) (defmethod get-matrix-from-sdif (ptr &optional (with-data t)) (sdif::SdifFReadMatrixHeader ptr) (let* ((sig (sdif::SdifSignatureToString (sdif::SdifFCurrMatrixSignature ptr))) (ne (sdif::SdifFCurrNbRow ptr)) (nf (sdif::SdifFCurrNbCol ptr)) (matrix (make-instance 'SDIFMatrix :matrixtype sig))) (setf (field-names matrix) (let ((mtype (sdif::SdifTestMatrixType ptr (sdif::SdifStringToSignature sig)))) (if (om-null-pointer-p mtype) (loop for i from 1 to nf collect (format nil "c~D" i)) (loop for i from 1 to nf collect (get-matrix-column-name-protect mtype i)) ))) (if with-data (let ((bytesread 0)) (setf (data matrix) (loop for f from 1 to nf collect (make-list ne))) (loop for r from 0 to (1- ne) do (progn (setf bytesread (+ bytesread (sdif::SdifFReadOneRow ptr))) (loop for n from 1 to nf do (setf (nth r (nth (1- n) (data matrix))) (sdif::SdifFCurrOneRowCol ptr n))))) (om-init-instance matrix) (sdif::SdifFReadPadding ptr (sdif::sdif-calculate-padding bytesread)) ) (progn (setf (fields matrix) nf) (setf (elts matrix) ne) (sdif::SdifFSkipMatrixData ptr)) ) matrix)) (defmethod load-sdif-file ((self SDIFFile)) (cond ((not (file-pathname self)) (om-beep-msg "Error loading SDIF file: -- no file")) ((not (probe-file (file-pathname self))) (om-beep-msg "Error loading SDIF file -- file does not exist: ~D" (file-pathname self))) ((not (sdif::sdif-check-file (file-pathname self))) (om-beep-msg "Error loading SDIF file -- wrong format: ~D" (file-pathname self))) (t (let ((sdiffileptr (sdif::sdif-open-file (file-pathname self) sdif::eReadWriteFile))) (om-print-format "Loading SDIF file : ~A" (list (file-pathname self)) "SDIF") (if sdiffileptr (unwind-protect (progn (sdif::SdifFReadGeneralHeader sdiffileptr) (sdif::SdifFReadAllASCIIChunks sdiffileptr) ;;; set the file-map (loop while (check-current-singnature sdiffileptr) do (let ((f (get-frame-from-sdif sdiffileptr NIL))) (record-in-streams self f) (sdif::sdif-read-next-signature sdiffileptr)))) (sdif::SDIFFClose sdiffileptr)) (om-beep-msg "Error loading SDIF file -- bad pointer: ~D" (file-pathname self))) ))) (setf (file-map self) (sort (file-map self) '< :key 'fstream-desc-id)) self) (defun record-in-streams (self frame) (let ((streamdesc (find frame (file-map self) :test #'(lambda (frame stream) (and (string-equal (frametype frame) (fstream-desc-fsig stream)) (= (streamid frame) (fstream-desc-id stream))))))) (if streamdesc (let ((frame-time (ftime frame))) ;;; EXISTING FRAME STREAM (setf (fstream-desc-nf streamdesc) (1+ (fstream-desc-nf streamdesc))) (when (< frame-time (fstream-desc-tmin streamdesc)) (setf (fstream-desc-tmin streamdesc) frame-time)) (when (> frame-time (fstream-desc-tmax streamdesc)) (setf (fstream-desc-tmax streamdesc) frame-time)) (loop for mat in (lmatrix frame) do (let ((mstreamdesc (find mat (fstream-desc-matrices streamdesc) :test #'(lambda (mat mstreamdesc) (string-equal (matrixtype mat) (mstream-desc-msig mstreamdesc)))))) (if mstreamdesc (let () ;;; EXISTING MATRIX STREAM (setf (mstream-desc-nf mstreamdesc) (1+ (mstream-desc-nf mstreamdesc))) (when (< frame-time (mstream-desc-tmin mstreamdesc)) (setf (mstream-desc-tmin mstreamdesc) frame-time)) (when (> frame-time (mstream-desc-tmax mstreamdesc)) (setf (mstream-desc-tmax mstreamdesc) frame-time)) (when (> (elts mat) (mstream-desc-rmax mstreamdesc)) (setf (mstream-desc-rmax mstreamdesc) (elts mat))) ;(when (> (fields mat) (mstream-desc-fields mstreamdesc)) ; (setf (mstream-desc-fields mstreamdesc) (fields mat))) ) ;;; NEW MATRIX STREAM (pushr (make-mstream-desc :msig (matrixtype mat) :fields (first-n (SDIFTypeDescription self (matrixtype mat) 'm) (fields mat)) :rmax (elts mat) :tmin frame-time :tmax frame-time :nf 1) (fstream-desc-matrices streamdesc))) )) ) ;;; NEW FRAME STREAM (pushr (make-fstream-desc :fsig (frametype frame) :id (streamid frame) :tmin (ftime frame) :tmax (ftime frame) :nf 1 :matrices (loop for mat in (lmatrix frame) collect (make-mstream-desc :msig (matrixtype mat) :fields (first-n (SDIFTypeDescription self (matrixtype mat) 'm) (fields mat)) :rmax (elts mat) :tmin (ftime frame) :tmax (ftime frame) :nf 1))) (file-map self)) ))) ;;;=================================== ;;; BASIC INFO ACCESSORS ;;;=================================== (defmethod* SDIFInfo ((self sdifFile) &optional (print t)) :doc "Returns a list with all matrix-streams in <self> (tuples StreamID-FrameType-MatrixType). When <print> (default), also prints a detailed description in the Listener. " :indoc '("SDIF file") :initvals '(nil t) :icon :sdif (let ((rep-list nil)) (when print (om-print-format "~%----------------------------------------------------------") (om-print-format "SDIF file description for:~%~D" (list (namestring (file-pathname self)))) (om-print-format "- NUMBER OF SDIF STREAMS: ~D" (list (length (file-map self))))) (loop for st in (file-map self) do (when print (om-print-format "- STREAM ID ~D - ~D Frames type = ~A" (list (fstream-desc-id st) (fstream-desc-nf st) (fstream-desc-fsig st))) (om-print-format " Tmin= ~D - Tmax= ~D" (list (fstream-desc-tmin st) (fstream-desc-tmax st))) (om-print-format " Matrices:")) (loop for ma in (fstream-desc-matrices st) do (pushr (list (fstream-desc-id st) (fstream-desc-fsig st) (mstream-desc-msig ma)) rep-list) (when print (om-print-format " ~D" (list (mstream-desc-msig ma)))) )) (when print (om-print-format "(End of file description)") (om-print-format "----------------------------------------------------------~%")) rep-list )) ;;;=================================== ;;; INFO / META DATA FROM SDIF HEADERS ;;;=================================== (defun matrixinfo-from-signature (file msig) (let* ((sig (sdif::SdifStringToSignature msig)) (mtype (sdif::SdifTestMatrixType file sig))) (if (om-null-pointer-p mtype) (progn (print (string+ "Matrix Type " msig " not found.")) NIL) (let ((mnumcol (sdif::SdifMatrixTypeGetNbColumns mtype))) (loop for i = 1 then (+ i 1) while (<= i mnumcol) collect (get-matrix-column-name-protect mtype i)) ) ))) (defun frameinfo-from-signature (file fsig) (let* ((sig (sdif::SdifStringToSignature fsig)) (ftype (sdif::SdifTestFrameType file sig))) (if (om-null-pointer-p ftype) (progn (print (string+ "Frame Type " fsig " not found.")) NIL) (let ((fnumcomp (sdif::SdifFrameTypeGetNbComponents ftype))) (loop for i = 1 then (+ i 1) while (<= i fnumcomp) collect (let ((fcomp (sdif::SdifFrameTypeGetNthComponent ftype i))) (if (om-null-pointer-p fcomp) NIL (let ((msig (sdif::SdifFrameTypeGetComponentSignature fcomp))) (list (sdif::SdifSignaturetoString msig) (matrixinfo-from-signature file (sdif::SdifSignatureToString msig)) )) )))) ))) (defmethod* SDIFTypeDescription ((self SDIFFile) (signature string) &optional (type 'm)) :indoc '("SDIF file" "SDIF type Signature" "Frame / Matrix") :initvals '(nil "1TYP" m) :menuins '((2 (("Matrix" m) ("Frame" f)))) :icon :sdif :doc "Returns a description of type <signature>. This function must be connected to an SDIF file (<self>) containing this data type. <type> (m/f) specifies if the type correspond to matrices (default) or to frames. Matrix type description is a list of the different field (columns) names. Frame type description is a list of lists containing the internal matrix signatures and their respective type descriptions. " (let ((sdifptr (sdif::sdif-open-file (file-pathname self) sdif::eReadWriteFile))) (if sdifptr (unwind-protect (progn (sdif::SdifFReadGeneralHeader sdifptr) (sdif::SdifFReadAllASCIIChunks sdifptr) (case type ('m (matrixinfo-from-signature sdifptr signature)) ('f (frameinfo-from-signature sdifptr signature)))) (sdif::SDIFFClose sdifptr))))) ;;;===================== ;;; NVT Utils ;;;===================== (defmethod get-nvt-list ((self string)) (let ((fileptr (sdif::sdif-open-file self sdif::eReadWriteFile))) (if fileptr (unwind-protect (progn (sdif::SdifFReadGeneralHeader fileptr) (sdif::SdifFReadAllASCIIChunks fileptr) (let* ((nvtlist (sdif::SdifFNameValueList fileptr)) (nvtl (sdif::SdifNameValueTableList nvtlist)) ;; (numnvt (sdif::SdifListGetNbData nvtl)) (nvtiter (sdif::SdifCreateHashTableIterator nil))) (unwind-protect (progn (sdif::SdifListInitLoop nvtl) (loop for i = 0 then (+ i 1) while (< i 2000) ;; just in case :) while (let ((next (sdif::SdifListIsNext nvtl))) (and next (> next 0))) collect (let* ((curnvt (sdif::SdifListGetNext nvtl)) (nvht (sdif::SdifNameValueTableGetHashTable curnvt)) (nvnum (sdif::SdifNameValueTableGetNumTable curnvt)) (nvstream (sdif::SdifNameValueTableGetStreamID curnvt)) (nvtdata (make-instance 'SDIFNVT :id nvstream))) (setf (tnum nvtdata) nvnum) (sdif::SdifHashTableIteratorInitLoop nvtiter nvht) (setf (nv-pairs nvtdata) (loop for i = 0 then (+ i 1) while (< i 2000) while (let ((nextit (sdif::SdifHashTableIteratorIsNext nvtiter))) (and nextit (> nextit 0))) collect (let* ((nv (sdif::SdifHashTableIteratorGetNext nvtiter)) (name (sdif::SdifNameValueGetName nv)) (value (sdif::SdifNameValueGetValue nv))) (when (string-equal name "TableName") (setf (tablename nvtdata) value)) (list name value)))) nvtdata) )) (sdif::SdifKillHashTableIterator nvtiter)) )) (sdif::SDIFFClose fileptr))))) (defmethod get-nvt-list ((self SDIFFile)) (get-nvt-list (file-pathname self))) (defmethod get-nvt-list ((self pathname)) (get-nvt-list (namestring self))) (defmethod* GetNVTList ((self t)) :icon :sdif :indoc '("SDIF file") :initvals '(nil) :doc "Returns the list of Name/Value tables in <self> (SDIFFile object or path to an SDIF file). Name/Value tables are formatted as SDIFNVT objects. " (get-nvt-list self)) (defmethod* find-in-nvtlist ((nvtlist list) (entry string) &optional table-num) :indoc '("list of SDIFNVT" "A name entry in the NameValue table" "Table Number") :initvals '(nil "" nil) :icon :sdif :doc "Finds value corresponding to name <entry> in the name/value tables <nvtlist>. <table-num> allows looking specifically in table number <table-num> as internally assigned to SDIF NVTs. " (if (and table-num (numberp table-num)) (let ((nvt (find table-num nvtlist :key 'tnum))) (if nvt (find-in-nvt nvt entry) (om-beep-msg "There is no table number ~D" table-num))) (let ((rep nil)) (loop for nvt in nvtlist while (not rep) do (setf rep (find-in-nvt nvt entry))) rep))) (defmethod* find-in-nvt ((nvt SDIFNVT) (entry string)) :indoc '("a SDIFNVT object" "A name entry in the Name/Value table") :icon :sdif :initvals '(nil "") :doc "Finds value corresponding to name <entry> in the name/value table <nvt>." (cadr (find entry (nv-pairs nvt) :test 'string-equal :key 'car))) ;;;============================= ;;; READ DATA ;;;============================= (defmethod get-sdif-data ((self pathname) streamNum frameT matT colNum rmin rmax tmin tmax &key (with-data t)) (get-sdif-data (namestring self) streamNum frameT matT colNum rmin rmax tmin tmax :with-data with-data)) (defmethod get-sdif-data ((self SDIFFIle) streamNum frameT matT colNum rmin rmax tmin tmax &key (with-data t)) (when (file-pathname self) (get-sdif-data (file-pathname self) streamNum frameT matT colNum rmin rmax tmin tmax :with-data with-data))) (defmethod get-sdif-data ((self string) streamNum frameT matT colNum rmin rmax tmin tmax &key (with-data t)) (cond ((or (and rmin rmax (> rmin rmax)) (and tmin tmax (> tmin tmax))) (om-beep-msg "GET-SDIF-DATA: Wrong parameters (tmin > tmax) or (rmin > rmax)..." )) ((not (probe-file self)) (om-beep-msg (format nil "FILE: ~A NOT FOUND..." self))) (t (let ((sdiffileptr (sdif::sdif-open-file self sdif::eReadWriteFile)) (error nil) (sdifdata nil) (sdiftimes nil)) (om-print "extracting data..." "SDIF") (if sdiffileptr (unwind-protect (let ((curr-time nil)) (sdif::SdifFReadGeneralHeader sdiffileptr) (sdif::SdifFReadAllASCIIChunks sdiffileptr) ;;; HERE (loop while (and (check-current-singnature sdiffileptr) ;;; more frames in the file (not error) ;;; so far so good (or (not curr-time) (not tmax) (not (>= curr-time tmax)))) ;;; did not ran over the tmax already do (sdif::SdifFReadFrameHeader sdiffileptr) (let ((fsig (sdif::SdifSignatureToString (sdif::SdifFCurrFrameSignature sdiffileptr))) (sid (sdif::SdifFCurrId sdiffileptr))) (setq curr-time (sdif::SdifFCurrTime sdiffileptr)) (if (and (or (not streamNum) (= streamNum sid)) (string-equal frameT fsig) (or (not tmin) (>= curr-time tmin))) ;;; we're in a candidate frame (dotimes (m (sdif::SdifFCurrNbMatrix sdiffileptr)) (sdif::SdifFReadMatrixHeader sdiffileptr) (let ((msig (sdif::SdifSignatureToString (sdif::SdifFCurrMatrixSignature sdiffileptr))) (ne (sdif::SdifFCurrNbRow sdiffileptr)) (nf (sdif::SdifFCurrNbCol sdiffileptr)) ;; (size (sdif::SdifSizeofDataType (sdif::SdifFCurrDataType sdiffileptr))) ;; don't need size ?? ) (if (or (null matT) (string-equal msig matT)) ;;; we're in a candidate matrix (if with-data (if (and (numberp colNum) (<= nf colNum)) (progn (om-beep-msg (format nil "Error the matrix ~A has only ~D fields" msig nf)) (setf error t)) (let ((r1 0) (r2 (1- ne)) (bytesread 0)) (when (and rmin (> ne rmin)) (setf r1 rmin)) (when (and rmax (> ne rmax)) (setf r1 rmax)) ;;; go to r1 (loop for k from 0 to (1- r1) do (setf bytesread (+ bytesread (sdif::SdifFSkipOneRow sdiffileptr)))) ;;; read (let ((data (loop for k from r1 to r2 do (setf bytesread (+ bytesread (sdif::SdifFReadOneRow sdiffileptr))) collect (cond ((numberp colNum) (coerce (sdif::SdifFCurrOneRowCol sdiffileptr (1+ colNum)) 'single-float)) ((consp colNum) (loop for n in colNum collect (coerce (sdif::SdifFCurrOneRowCol sdiffileptr (1+ n)) 'single-float))) ((null colNum) (loop for n from 1 to nf collect (coerce (sdif::SdifFCurrOneRowCol sdiffileptr n) 'single-float))))) )) (loop for k from (1+ r2) to (1- ne) do (setf bytesread (+ bytesread (sdif::SdifFSkipOneRow sdiffileptr)))) ;(print (list "read" bytesread "pad" (sdif::sdif-calculate-padding bytesread))) (sdif::SdifFReadPadding sdiffileptr (sdif::sdif-calculate-padding bytesread)) (when data (push data sdifdata) (push curr-time sdiftimes))) )) ;;; no data (just times) (progn (push curr-time sdiftimes) (sdif::SdifFSkipMatrixData sdiffileptr)) ) (sdif::SdifFSkipMatrixData sdiffileptr) )) ) ;;; skip the frame (sdif::sdiffskipframedata sdiffileptr) ) (sdif::sdif-read-next-signature sdiffileptr) )) (if (or sdifdata sdiftimes) (values (reverse sdifdata) (reverse sdiftimes)) (progn (om-print-format "No data found for Frame ~A / Matrix ~A in stream #~D (t1=~D t2=~D r1=~D r2=~D)" (list frameT matT streamNum tmin tmax rmin rmax) "SDIF") nil)) ) (sdif::SDIFFClose sdiffileptr)) (om-beep-msg "Error loading SDIF file -- bad pointer: ~D" self)) )))) (defmethod* GetSDIFData ((self t) sID (frameType string) (matType string) Cnum rmin rmax tmin tmax) :indoc '("SDIF file" "stream number (int)" "frame type (string)" "matrix type (string)" "field number (int or list)" "min row" "max row" "min time (s)" "max time (s)") :outdoc '("matrix values" "times") :initvals '(nil 0 "" "" 0 nil nil nil nil) :icon :sdif :doc "Extracts and returns a data array (<rmin>-<rmax>, <tmin>-<tmax>) from the <cnum> field of the <matType> matrix from the Stream <sid> of <frameType> frames from <self>. <self> can be an SDIFFile object or a pathname to a valid SDIF file. <cnum> can be a single value or a list of values (for multiple dimentional descriptions) Unspecified arguments mean all SDIF data (i.e. for instance any time, all rows, fields, etc.) will be considered and returned. <frameType> and <matType> MUST be specified (4-character SDIF signatures for frame and matrix types) Use SDIFINFO or the SDIF file editor for information about the Frame and Matrix types contained in <self>. Ex. (GETSDIFDATA <SDIFFile> 0 \"1MRK\" \"1TRC\" (0 1) nil nil 0.0 2.0) means : Get all data from Stream number 1, frames of type 1MRK, matrices of type 1TRC, columns (i.e. fields) 0 and 1, all matrox rows, between 0.0s and 2.0s. The second oulet returns all corresponding frame TIMES." :numouts 2 (get-sdif-data self sID frameType matType Cnum rmin rmax tmin tmax :with-data t)) ;;;============================= ;;; READ DATA ;;;============================= (defmethod get-sdif-times ((self pathname) streamNum frameT matT tmin tmax) (get-sdif-times (namestring self) streamNum frameT matT tmin tmax)) (defmethod get-sdif-times ((self SDIFFIle) streamNum frameT matT tmin tmax) (when (file-pathname self) (get-sdif-times (file-pathname self) streamNum frameT matT tmin tmax))) (defmethod get-sdif-times ((self string) streamNum frameT matT tmin tmax) (cond ((and tmin tmax (> tmin tmax)) (om-beep-msg "GET-SDIF-TIMES: Wrong parameters (tmin > tmax) ..." )) ((not (probe-file self)) (om-beep-msg "FILE: ~A NOT FOUND..." self)) (t (let ((sdiffileptr (sdif::sdif-open-file self sdif::eReadWriteFile)) (error nil) (sdiftimes nil)) (om-print "extracting frame times..." "SDIF") (if sdiffileptr (unwind-protect (let ((curr-time nil)) (sdif::SdifFReadGeneralHeader sdiffileptr) (sdif::SdifFReadAllASCIIChunks sdiffileptr) ;;; HERE (loop while (and (check-current-singnature sdiffileptr) ;;; more frames in the file (not error) ;;; so far so good (or (not curr-time) (not tmax) (not (>= curr-time tmax)))) ;;; did not ran over the tmax already do (sdif::SdifFReadFrameHeader sdiffileptr) (let ((fsig (sdif::SdifSignatureToString (sdif::SdifFCurrFrameSignature sdiffileptr))) (sid (sdif::SdifFCurrId sdiffileptr))) (setq curr-time (sdif::SdifFCurrTime sdiffileptr)) (if (and (or (not streamNum) (= streamNum sid)) (or (not frameT) (string-equal frameT fsig)) (or (not tmin) (>= curr-time tmin))) ;;; we're in a candidate frame.. (if (null matT) ;;; OK: keep this one (progn (push curr-time sdiftimes) (unless (= 0 (sdif::SdifFCurrNbMatrix sdiffileptr)) (sdif::sdiffskipframedata sdiffileptr)) ; no skip if there's not data ; that seemed to actually skip the next frame... ) ;;; search matrices (dotimes (m (sdif::SdifFCurrNbMatrix sdiffileptr)) (sdif::SdifFReadMatrixHeader sdiffileptr) (let ((msig (sdif::SdifSignatureToString (sdif::SdifFCurrMatrixSignature sdiffileptr)))) (when (string-equal msig matT) ;;; OK: keep this one (push curr-time sdiftimes)) ) (sdif::SdifFSkipMatrixData sdiffileptr) ) ) ;;; not a candidate frame: just skip the frame (sdif::sdiffskipframedata sdiffileptr) ) ) (sdif::sdif-read-next-signature sdiffileptr) ) (if sdiftimes (reverse sdiftimes) (progn (om-print-format "No data found for Frame ~A / Matrix ~A in stream #~D (t1=~D t2=~D)" (list frameT matT streamNum tmin tmax) "SDIF") nil)) ) (sdif::SDIFFClose sdiffileptr)) (om-beep-msg "Error loading SDIF file -- bad pointer: ~D" self)) ))) ) (defmethod* GetSDIFTimes ((self t) sID frameType matType tmin tmax) :indoc '("SDIF file" "stream number (integer)" "frame type" "matrix type" "min time (s)" "max time (s)") :initvals '(nil 0 nil nil nil nil) :icon :sdif :doc "Returns a list of times (s) between <tmin> and <tmax> for frames of type <frameType> from the stream <sID> in <self>, containing a matrix of type <matType>. Unspecified arguments mean respectively that all streamms (for <sID>), frames (<frameType>), matrices (<matType>) and no time boundaries (<tmin> and <tmax>) are considered. Use SDIFINFO for information about the Frame and Matrix types contained in <self>." (get-sdif-times self sID frameType matType tmin tmax)) (defmethod* GetSDIFFrames ((self t) &key sID frameType tmin tmax) :indoc '("SDIF file" "stream number" "frame type (string)" "min time (s)" "max time (s)") :initvals '(nil nil nil nil nil) :icon :sdif :doc "Creates and returns an SDIFStream instance from SDIF data in stream <sid> of <self>. <self> can be an SDIFFile object or a pathname to a valid SDIF file. <sid> can be a list of IDs (intergers). <tmin> and <tmax> determine a time window in the stream(s). <frameType> and <matType> select frames and/or matrices of a specific type." (get-sdif-frames self sID frameType tmin tmax)) (defmethod get-sdif-frames ((self sdifFile) streamNum frameT tmin tmax &key apply-fun) (if (file-pathname self) (get-sdif-frames (file-pathname self) streamNum frameT tmin tmax :apply-fun apply-fun) (om-beep-msg "SDIFFILE: no file loaded!" self))) (defmethod get-sdif-frames ((self pathname) streamNum frameT tmin tmax &key apply-fun) (get-sdif-frames (namestring self) streamNum frameT tmin tmax :apply-fun apply-fun)) (defmethod get-sdif-frames ((self string) streamNum frameT tmin tmax &key apply-fun) (cond ((not (probe-file self)) (om-beep-msg (format nil "FILE: ~A NOT FOUND..." self))) (t (let ((sdiffileptr (sdif::sdif-open-file self sdif::eReadWriteFile)) (frame-list nil)) (if sdiffileptr (unwind-protect (let ((curr-time nil)) (sdif::SdifFReadGeneralHeader sdiffileptr) (sdif::SdifFReadAllASCIIChunks sdiffileptr) (loop while (and (check-current-singnature sdiffileptr) ;;; more frames in the file (or (not curr-time) (not tmax) (not (>= curr-time tmax)))) do (sdif::SdifFReadFrameHeader sdiffileptr) (let ((sig (sdif::SdifSignatureToString (sdif::SdifFCurrFrameSignature sdiffileptr))) (sid (sdif::SdifFCurrId sdiffileptr))) (setq curr-time (sdif::SdifFCurrTime sdiffileptr)) (if (and (or (not streamNum) (and (numberp streamnum) (= streamNum sid)) (and (listp streamnum) (find sid streamNum :test '=))) (or (not frameT) (string-equal frameT sig)) (or (not tmin) (>= curr-time tmin)) (or (not tmax) (<= curr-time tmax))) (let ((frame (make-instance 'SDIFFrame :ftime curr-time :frametype sig :streamid sid :lmatrix (let ((nummatrix (sdif::SdifFCurrNbMatrix sdiffileptr))) (loop for i from 1 to nummatrix collect (get-matrix-from-sdif sdiffileptr t)))))) (when apply-fun (funcall apply-fun frame)) (push frame frame-list) ) (sdif::sdiffskipframedata sdiffileptr)) (sdif::sdif-read-next-signature sdiffileptr)))) (sdif::SDIFFClose sdiffileptr)) (om-beep-msg "Error loading SDIF file -- bad pointer: ~D" self)) (reverse frame-list) )))) ;;;========================== ;;; TEXT CONVERSION ;;;========================== (defmethod* SDIF->text ((self string) &optional out-filename) :indoc '("SDIF file" "text file pathname") :icon :sdif :doc "Converts <self> to text-SDIF in <out-filename>. If no pathname is given with <out-filename>, the SDIF file name will be used with the extension \".txt\"." (let ((outfile (if out-filename (or (handle-new-file-exists out-filename) (om-choose-new-file-dialog :types (list (format nil (om-str :file-format) "Text") "*.txt" ))) (outfile "tmp_sdif_to_text_convert.txt")))) (when outfile (let ((SDIFF (sdif::sdif-open-file self))) (when SDIFF (sdif::SdifToText SDIFF (namestring outfile)) (sdif::SDIFFClose SDIFF) outfile))))) (defmethod* SDIF->text ((self pathname) &optional out-filename) (SDIF->text (namestring self) out-filename)) (defmethod* SDIF->text ((self SDIFFile) &optional out-filename) (SDIF->text (file-pathname self) out-filename))
42,191
Common Lisp
.lisp
733
41.302865
175
0.523673
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
a472d05a710d98a081424c80763ae273abb270d9452c092b9b2eb26a2ab8f129
718
[ -1 ]
719
sdif-tools.lisp
cac-t-u-s_om-sharp/src/packages/sdif/sdif-om/sdif-tools.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;============================================================================ ; From OM6 SDIF Analysis / Processing Tools ; jb - 2005 ;============================================================================ (in-package :om) ;;;========================================================================== ;;; FFT TOOLS ;;;========================================================================== ;;; "re-sample" frequencies of an fft of type 1GB4 ;;; this function is not hyper-useful but can be used as a model for other SDIF file processing operation (defmethod resample-sdif-fft-freqs ((self SDIFFile) &key out-file (stream-num 0) (f-min 0) (f-max 22050) (f-step 100)) (when (or (find "1GB4" (file-map self) :key 'fstream-desc-fsig :test 'string-equal) ;;; the file contains FFT data (om-beep-msg "Sorry this SDIF file does not contain a valid SVP fft (1GB4)")) (let* ((out-path (or (and out-file (handle-new-file-exists out-file)) (om-choose-new-file-dialog))) (outptr (and out-path (sdif::sdif-open-file out-path sdif::eWriteFile)))) (when outptr (unwind-protect (flet ((find-amplitude-in-f-a-list (freq f-a-list) (let ((min-dist 44000) (val 0) dist) (loop for f-a in f-a-list do (setf dist (abs (- freq (first f-a)))) (if (<= dist min-dist) (setf min-dist dist val (second f-a)))) val))) (sdif::SdifFWriteGeneralHeader outptr) (sdif-write-nvt outptr `(("Author" ,(string+ *app-name* " " *version-string*)))) (sdif-write-types-string outptr "{1MTD 1GB4 {frequency, amplitude} 1FTD XFFT {1GB4 fftata;}}") (sdif::SdifFWriteAllASCIIChunks outptr) (get-sdif-frames self stream-num "1GB4" nil nil :apply-fun #'(lambda (frame) (let ((mat (find "1GB4" (lmatrix frame) :key 'matrixtype :test 'string-equal))) (om-print-format "Sampling SDIF frame at ~D" (list (ftime frame))) (when mat (let* ((f-a-list (mat-trans (get-array-data mat))) (sampled-f-a-list (loop for f from f-min to f-max by f-step collect (list f (find-amplitude-in-f-a-list f f-a-list))))) (setf (data mat) (mat-trans sampled-f-a-list)) (om-init-instance mat) ;; updates the elts and fields slots )) (sdif-write frame outptr) ))) (namestring out-path) ) ;;; cleanup/close (sdif::sdiffclose outptr) )) ) ) ) (defmethod fftdata->sdif ((fftdata list) &key timelist out-file) (let* ((out-path (or (and out-file (handle-new-file-exists out-file)) (om-choose-new-file-dialog))) (outptr (and out-path (sdif::sdif-open-file out-path sdif::eWriteFile)))) (when outptr (unwind-protect (let () (sdif::SdifFWriteGeneralHeader outptr) (sdif-write-nvt outptr `(("Author" ,(string+ *app-name* " " *version-string*)))) (sdif-write-types-string outptr "{1MTD 1GB1 {amplitude} 1FTD XFFT {1GB1 fftata;}}") (sdif::SdifFWriteAllASCIIChunks outptr) (loop for framedata in fftdata for i = 0 then (+ i 1) do (let* ((mat (om-init-instance (make-instance 'SDIFMatrix :matrixtype "1GB1" :data (list framedata)))) (frame (make-instance 'SDIFFrame :frametype "XFFT" :ftime (if timelist (nth i timelist) i) :streamid 0 :lmatrix (list mat)))) (sdif-write frame outptr) )) (namestring out-path)) ;;; cleanup (sdif::sdiffclose outptr)) ))) ;;;========================================================================== ;;; BPF/F0 TOOLS ;;;========================================================================== (defmethod* sdif->bpf ((self sdiffile) &key (frametype "1FQ0") (matrixtype "1FQ0") (stream 0) (field 0) (tmin nil) (tmax nil)) :icon :sdif :indoc '("SDIF file" "frame type (string)" "matrix type (string)" "stream ID (int)" "field number" "min time (s)" "max time (s)") :initvals '(nil "1FQ0" "1FQ0" 0 0 nil nil) :doc "Reads SDIF data and formats results as a BPF. Default values are suited to read and convert 1FQ0 frame and matrix types, typically resulting from fundamental frequency analysis. Other type of data can be extracted by setting the <stream>, <frame>, <matrix> and <field> arguments accordingly. <tmin> and <tmax> bound the extracted data in a time interval. " (when (and stream frametype frametype field) (multiple-value-bind (y x) (getsdifdata self stream frametype matrixtype field nil nil tmin tmax) (make-instance 'bpf :x-points x :y-points (flat y))))) (defmethod* bpf->sdif ((self bpf) ftype mtype &key (scope 'time) (typedefs nil) (out-file "mybpf.sdif")) :icon :sdif :initvals '(nil "1FQ0" "1FQ0" time nil nil "mybpf.sdif") :indoc '("a BPF" "frame type (string)" "matrix type (string)" "x = time or elements" "custom types declaration" "output file") :menuins '((3 (("Time" time) ("Elements" elts)))) :doc "Saves the contents of <self> (a BPF) as an SDIF file in <outfile>. <ftype> and <mtype> determine the SDIF type to enclose the data in (default = 1FQ0, i.e. fundamental frequency). If these types are not standard, they must be declared and given as a list of SDIFType objects in <typedefs>. If <outfile> is just a filename (not a pathname) the file is written in the default 'out-files' folder. <scope> chooses whether the x-dimension of the BPF should be considered as time (default) or as the elements in a single matrix. " (let* ((out-path (handle-new-file-exists (cond ((pathnamep out-file) out-file) ((stringp out-file) (outfile out-file)) (t (om-choose-new-file-dialog))))) (outptr (and out-path (sdif::sdif-open-file out-path sdif::eWriteFile)))) (if outptr (unwind-protect (let () (sdif::SdifFWriteGeneralHeader outptr) (sdif-write (default-om-NVT) outptr) (when typedefs (sdif-write-types outptr (list! typedefs))) (sdif::SdifFWriteAllASCIIChunks outptr) (if (equal scope 'time) ;;; write a sequence of frames (loop for time in (x-points self) for val in (y-points self) do (let* ((mat (om-init-instance (make-instance 'SDIFMatrix :matrixtype mtype :data (list (list val))))) (frame (make-instance 'SDIFFrame :frametype ftype :ftime time :streamid 0 :lmatrix (list mat)))) (sdif-write frame outptr) )) ;;; write a single big frame/matrix (let* ((mat (om-init-instance (make-instance 'SDIFMatrix :matrixtype mtype :data (list (y-points self))))) (frame (make-instance 'SDIFFrame :frametype ftype :ftime 0.0 :streamid 0 :lmatrix (list mat)))) (sdif-write frame outptr) ) ) (namestring out-path)) ; cleanup (sdif::sdiffclose outptr)) ; ... else (om-beep-msg "Error at opening SDIF-file for output") ))) ;;;========================================================================== ;;; MARKERS TOOLS ;;;========================================================================== ;;; for compat when loading old patches (defmethod function-changed-name ((reference (eql 'get-mrk-onsets))) 'sdif->markers) (defmethod* sdif->markers ((self sdiffile) &key (frame "1MRK") (matrix nil) (stream 0) (tmin nil) (tmax)) :icon :sdif :indoc '("SDIF file" "frame type (string)" "matrix type (string)" "stream ID (int)" "min time (s)" "max time (s)") :initvals '(nil "1MRK" nil 0 nil nil) :doc "Reads SDIF data and formats results as a list of time lmarkers (in s). Default values are suited to read 1MRK frames, typically resulting from markers or transient detection analysis. Other more specific type of data can be extracted by setting the <stream>, <frame>, <matrix> arguments accordingly. <tmin> and <tmax> bound the extracted data in a time interval. " (when (and stream frame) (GetSDIFTimes self stream frame matrix tmin tmax))) (defmethod* markers->sdif ((self list) &key (ftype "1MRK") (typedefs nil) (out-file "markers.sdif")) :icon :sdif :initvals '(nil "1MRK" nil "mybpf.sdif") :indoc '("onset list (s)" "SDIF frame type" "custom types declaration" "output file") :doc "Saves <self> (a list of onsets) as an SDIF file in <outfile>. <ftype> determines the SDIF frame type to use (default = 1MRK, the standard SDIF type for time markers). If this type is not standard, it must be declared and given as an SDIFType object in <typedefs>. If <outfile> is just a filename (not a pathname) the file is written in the default 'out-files' folder. " (let* ((out-path (handle-new-file-exists (cond ((pathnamep out-file) out-file) ((stringp out-file) (outfile out-file)) (t (om-choose-new-file-dialog))))) (outptr (and out-path (sdif::sdif-open-file out-path sdif::eWriteFile)))) (when outptr (unwind-protect (let () (sdif::SdifFWriteGeneralHeader outptr) (sdif-write-nvt outptr `(("Author" ,(string+ *app-name* " " *version-string*)))) (when typedefs (sdif-write-types outptr (list! typedefs))) (sdif::SdifFWriteAllASCIIChunks outptr) ;;; write a sequence of frames (loop for time in self do (let* ((frame (make-instance 'SDIFFrame :frametype ftype :ftime time :streamid 0))) (sdif-write frame outptr) )) (namestring out-path)) ;;; cleanup (sdif::sdiffclose outptr)) )))
12,184
Common Lisp
.lisp
206
44.067961
131
0.500755
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
353405f92c7612e4e10714ab1d7be39948149d56b96b0dd19541ba5aa15d2a63
719
[ -1 ]
720
sdif-write.lisp
cac-t-u-s_om-sharp/src/packages/sdif/sdif-om/sdif-write.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;============================================== ;writing sdif data ;============================================== (defmethod sdif-write ((self t) ptr) nil) (defmethod sdif-write ((self list) ptr) (mapcar #'(lambda (elt) (sdif-write elt ptr)) self)) (defun align-bytes (n align) (* align (ceiling n align))) (defmethod sdif-header-size ((self sdifmatrix)) 16) (defmethod sdif-header-size ((self sdifframe)) 16) (defmethod sdif-size ((self sdifmatrix)) (+ (sdif-header-size self) (align-bytes (* 4 (elts self) (fields self)) 8))) (defmethod sdif-size ((self sdifframe)) (reduce '+ (cons (sdif-header-size self) (mapcar 'sdif-size (lmatrix self))))) (defmethod sdif-write ((matrix sdifmatrix) file-ptr) (let* ((data-type-size 4) ;;; flat data list (data (cond ((listp (car (data matrix))) (flat (mat-trans (data matrix)))) ((array-field-p (car (data matrix))) (flat (mat-trans (mapcar 'array-field-data (data matrix))))) (t (data matrix)))) (data-ptr (om-alloc-memory (* data-type-size (fields matrix) (elts matrix))))) (loop for val in data for i from 0 do (om-write-ptr data-ptr (* i data-type-size) 'single-float (coerce val 'single-float)) ) (sdif::SdifFWriteMatrix file-ptr (sdif::SdifStringToSignature (matrixtype matrix)) data-type-size (elts matrix) (fields matrix) data-ptr) (om-free-memory data-ptr) )) (defmethod sdif-write ((self sdifframe) file-ptr) (let ((framesize (sdif-size self))) (sdif::SdifFSetCurrFrameHeader file-ptr (sdif::SdifStringToSignature (frametype self)) framesize (length (lmatrix self)) (streamID self) (coerce (ftime self) 'double-float)) (sdif::SdifFWriteFrameHeader file-ptr) (loop for item in (lmatrix self) do (sdif-write item file-ptr)) )) ;;;====================================== ;;; TYPES / NVT / IDS ;;; to do BEFORE SdifWriteAllASCIIChunks ;;;====================================== ;;; TYPES ;;;====================================== (defmethod format-type-string ((self sdiftype)) (let ((str "") (desc "")) (cond ((equal 'F (struct self)) (loop for item in (description self) do (when (listp item) (setf desc (string+ desc (car item) " " (second item) "; ")))) (setf desc (subseq desc 0 (max 0 (- (length desc) 1)))) (setf str (string+ str " 1FTD " (signature self) " {" desc "}"))) ((equal 'M (struct self)) (loop for item in (description self) do (when (stringp item) (setf desc (string+ desc item ", ")))) (setf desc (subseq desc 0 (- (length desc) 2))) (setf str (string+ str " 1MTD " (signature self) " {" desc "}"))) (t nil)) str)) (defun sdif-write-types-string (fileptr types-string) (let ((sstr (sdif::SdifStringNew))) (sdif::SdifStringAppend sstr types-string) (sdif::SdifStringGetC sstr) (sdif::SdifFGetAllTypefromSdifString fileptr sstr) )) ;;; write a list of SDIFType objects (defun sdif-write-types (fileptr typeslist) (let ((str "{") (FList nil) (MList nil)) (loop for typedef in typeslist do (if (typep typedef 'sdiftype) (cond ((equal 'F (struct typedef)) (push typedef Flist)) ((equal 'M (struct typedef)) (push typedef Mlist))) (om-beep-msg "NOT AN SDIFTYPE: ~A" typedef))) (loop for mdef in Mlist do (setf str (string+ str (format-type-string mdef)))) (loop for fdef in Flist do (setf str (string+ str (format-type-string fdef)))) (setf str (string+ str "}")) (sdif-write-types-string fileptr str))) ;;;====================================== ;;; NVT ;;;====================================== (defun sdif-write-nvt (fileptr name-values &key id tablename) (let ((nvtlist (sdif::SdifFNameValueList fileptr))) (sdif::SdifNameValuesLNewTable nvtlist (or id #xffff)) (when tablename (sdif::SdifNameValuesLPutCurrNVT nvtlist "TableName" tablename)) (loop for nv-pair in name-values do (sdif::SdifNameValuesLPutCurrNVT nvtlist (car nv-pair) (cadr nv-pair))))) (defmethod sdif-write ((self SDIFNVT) fileptr) (sdif-write-nvt fileptr (nv-pairs self) :id (ID self) :tablename (tablename self))) ;;;====================================== ;;; IDS ;;;====================================== (defun sdif-write-IDS (file id str tree) (let ((idstable (sdif::SdifFStreamIDTable file))) (sdif::SdifStreamIDTablePutSID idstable id str tree))) ;;;====================================== ;;; GENERAL / TOP-LEVEL ;;;====================================== (defmethod* write-sdif-file ((frames list) &key (outpath "out.sdif") types nvts) :indoc '("a list of SDIFFrame objects" "SDIF file pathname" "list of SDIFType obvjects" "list of SDIFNVT objects") :outdoc '("pathname of written SDIF file") :initvals '(nil "out.sdif" nil nil) :icon 'sdif :doc "Writes <frames> (list of SDIFFrame objects) as a new SDIF file (as sepecified by <outpath>). - All non-standard SDIF frame and matrix types must be declared as SDIFTYPE objects and passed in a list to <types>. - Additional meta-data can be passed as a list of SDIFNVT objects in <nvts>. If no path, or just a file name is given with <outpath> file will be written in the OM# \"output files\" folder specified in the preferences. " (let ((out-path (cond ((pathnamep outpath) outpath) ((stringp outpath) (outfile outpath)) (t (om-choose-new-file-dialog))))) (when out-path (let ((sdiffileptr (sdif::sdif-open-file out-path sdif::eWriteFile))) (if sdiffileptr (unwind-protect (progn (sdif::SdifFWriteGeneralHeader sdiffileptr) (loop for nvt in (cons (default-om-NVT) (list! nvts)) do (sdif-write nvt sdiffileptr)) (when types (sdif-write-types sdiffileptr (list! types))) (sdif::SdifFWriteAllASCIIChunks sdiffileptr) (loop for frame in frames do (sdif-write frame sdiffileptr)) ) (sdif::SDIFFClose sdiffileptr)) (om-beep-msg "Could not open file for writing: ~A" out-path)) (probe-file out-path) )))) ;;;================================== ;;; USING DYNAMIC STREAM POINTER (IN A VISUAL PROGRAM) ;;; EQUIVALENT TO OM6's FILE-BOX ;;; ================================== (defclass sdif-fstream (fstream) ()) (defmethod om-cleanup ((self sdif-fstream)) (when (open? self) (sdif::sdiffclose (fs self)) (setf (open? self) nil))) (defmethod* open-SDIF-stream (path &key (direction :io)) :initvals '(nil :io :supersede) :indoc '("a valid pathname" "stream direction (read/write)" "behaviour if the file exists") :menuins '((1 (("read" :input) ("write" :output) ("read/write" :io))) (2 (("rename" :rename) ("supersede" :supersede) ("overwrite" :overwrite) ("append" :append)))) :icon :file :doc "Opens an SDIF file stream where other functions can read and write. Open FILE-STREAMs are automatically closed by the garbage collection system when they are not used anymore, however, it is recommended to close them explicitely with CLOSE-FILE-STREAM as soon as they are not needed in order to limit the number of streams open. " (let ((SDIFF (sdif::sdif-open-file path (case direction (:input sdif::eReadFile) (:output sdif::eWriteFile) (otherwise sdif::eReadWriteFile))))) (unless SDIFF (om-beep-msg "ERROR SDIF stream could not be open in mode ~D: ~A" direction path)) (make-instance 'sdif-fstream :fs SDIFF :fpath path :open? (if SDIFF t nil)) )) (defmethod* sdif-write-header ((fstream sdif-fstream) &optional (types nil) (nvts nil) (sids nil)) :icon :write :indoc '("an SDIF file pointer" "list of SDIFType" "list of SDIFNVT" "list of stream ID list") :doc "Writes the header of the SDIF file in <fstream>. This is a mandatory operation before to start writing SDIF frames in the file. <fstream> is a file pointer created by open-SDIF-stream. <types>, <nvts> and <sids> are SDIF types, name/value tables, stream ID descriptors to declare and write in the file header. - <types> must be a list of SDIFTYPE objects. - <nvts> must be a list of SDIFNVT objects. - <sids> must be a list of stream descriptors of the form (ID name description); e.g. (0 "my-stream" "x/y/z"). " (if (fs fstream) (progn (sdif::SdifFWriteGeneralHeader (fs fstream)) (loop for NVT in (cons (default-om-NVT) (list! nvts)) do (sdif-write NVT (fs fstream))) (when types (sdif-write-types (fs fstream) (list! types))) (when sids (loop for SID in sids do (apply #'sdif-write-IDS (cons (fs fstream) SID)))) (sdif::SdifFWriteAllASCIIChunks (fs fstream))) (progn (om-beep-msg "ERROR No valid open SDIF file stream!!") (abort)) )) (defmethod* sdif-write-frame ((self sdifframe) (fstream sdif-fstream)) :icon :write :indoc '("an SDIFFrame to write" "an SDIF file pointer") :doc "Writes the SDIF frame <self> in <fstream>. <fstream> is a file pointer created by open-SDIF-stream." (sdif-write self (fs fstream))) (defmethod* sdif-write-frame ((self t) (fstream sdif-fstream)) (print "Error: only write frames in SDIF files!") nil)
10,645
Common Lisp
.lisp
212
42.514151
260
0.578157
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
dd6dd992edea725ff274e62e0612aff54be2c7ff3baf4860f4d1ec7b34595323
720
[ -1 ]
721
sdif-partials.lisp
cac-t-u-s_om-sharp/src/packages/sdif/sdif-om/sdif-partials.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;============================================ ;;; READ/WRITE CHORDS AND PARTIALS ;;;============================================ ;;; A utility structure to deal with partials (defstruct partial (t-list) (f-list) (a-list) (ph-list)) ;;; the default struct accessors can not (yet?) be instaniated as boxes in OM (defun mk-partial (&key t-list f-list a-list ph-list) (make-partial :t-list t-list :f-list f-list :a-list a-list :ph-list ph-list)) (defun partial-times (p) (partial-t-list p)) (defun partial-freqs (p) (partial-f-list p)) (defun partial-amps (p) (partial-a-list p)) ;;;============================================ ;;; READ... ;;;============================================ (defmethod* GetSDIFPartials ((self t) &optional (stream nil)) :indoc '("an SDIF file") :icon :sdif :doc "Return a list of partial structures from an SDIF file (using 1TRC or 1MRK frames) <stream> selects a specific SDIF stream (usually corresponding to a channel in audio analysis files). " (let ((frames (GetSDIFFrames self :sid stream)) (mrk-partials (make-hash-table)) (trc-partials (make-hash-table)) (trc-fields '("Index" "Frequency" "Amplitude" "Phase")) (mrk-fields '("Id")) bmat emat pmat partial-list) (flet ((get-sdif-trc-field (matrix fieldname) (nth (position fieldname trc-fields :test 'string-equal) (data matrix))) (get-sdif-mrk-field (matrix fieldname) (nth (position fieldname mrk-fields :test 'string-equal) (data matrix)))) (loop for fr in frames do (cond ((string-equal "1MRK" (frametype fr)) (loop for mat in (lmatrix fr) do (cond ((string-equal "1BEG" (matrixtype mat)) (setf bmat mat)) ((string-equal "1END" (matrixtype mat)) (setf emat mat)) ((string-equal "1TRC" (matrixtype mat)) (setf pmat mat)) (t nil)) (when bmat ;;; a begin matrix : set time info (loop for i in (get-sdif-mrk-field bmat "Id") do (sethash mrk-partials i (make-partial :t-list (list (ftime fr) (ftime fr)) :f-list nil :a-list nil)))) (when pmat ;;; a parameter matrix : add data in partials (loop for i in (get-sdif-trc-field pmat "Index") for f in (get-sdif-trc-field pmat "Frequency") for a in (get-sdif-trc-field pmat "Amplitude") do (let ((p (gethash i mrk-partials))) (when p (setf (partial-f-list p) (list f f)) (setf (partial-a-list p) (list a a)) )))) (when emat ;;; a end matrix: find the partial, set duration and put in the final list (loop for i in (get-sdif-mrk-field emat "Id") do (let ((p (gethash i mrk-partials))) (when p (setf (partial-t-list p) (list (car (partial-t-list p)) (ftime fr))))))) (setf bmat nil) (setf emat nil) (setf pmat nil))) ((or (string-equal "1TRC" (frametype fr)) (string-equal "1HRM" (frametype fr))) (loop for mat in (lmatrix fr) do (when (or (string-equal "1TRC" (matrixtype mat)) (string-equal "1TRC" (matrixtype mat))) (loop for i in (get-sdif-trc-field mat "Index") for f in (get-sdif-trc-field mat "Frequency") for a in (get-sdif-trc-field mat "Amplitude") for ph in (get-sdif-trc-field mat "Phase") do (let ((p (gethash i trc-partials))) (if p (setf (partial-t-list p) (append (partial-t-list p) (list (ftime fr))) (partial-f-list p) (append (partial-f-list p) (list f)) (partial-a-list p) (append (partial-a-list p) (list a)) (partial-ph-list p) (append (partial-ph-list p) (list ph))) (sethash trc-partials i (make-partial :t-list (list (ftime fr)) :f-list (list f) :a-list (list a) :ph-list (list ph)))) ))))) )) ) (maphash #'(lambda (key p) (declare (ignore key)) (push p partial-list)) mrk-partials) (maphash #'(lambda (key p) (declare (ignore key)) (push p partial-list)) trc-partials) (sort (reverse partial-list) '< :key #'(lambda (p) (car (partial-t-list p)))) )) ;;; GetSDIFFrames will handle the dispatch wrt. type of self (defmethod chord-seq-raw-data ((self t) &optional (stream nil)) (loop for partial in (GetSDIFPartials self stream) collect (remove nil ;;; in case there is no phase (list (partial-t-list partial) (partial-f-list partial) (partial-a-list partial) (partial-ph-list partial) )))) (defmethod* GetSDIFChords ((self t) &optional (stream nil)) :indoc '("an SDIF file") :icon :sdif :doc "Returns a list of chords data from an SDIF file (using 1MRK / 1TRC frames). Chords are formatted as (pitch [Hz] onset [s] duration [s] velocity [lin]). <stream> selects a specific SDIF stream (usually corresponding to a channel in audio analysis files). " (mapcar #'(lambda (p) (let ((t1 (list-min (partial-t-list p))) (t2 (list-max (partial-t-list p)))) (list (om-mean (partial-f-list p)) t1 (- t2 t1) (om-mean (partial-a-list p))))) (GetSDIFPartials self stream))) (defmethod* SDIF->chord-seq ((self t) &optional (stream nil)) :indoc '("an SDIF file") :icon :sdif :doc "Generates a CHORD-SEQ instance from the 1TRC or 1MRK frame data in <self> (SDIFFILE). Internally calls and formats data from GetSDIFChords. <stream> selects a specific SDIF stream (usually corresponding to a channel in audio analysis files). " (let* ((chord-data (sort (GetSDIFChords self stream) '< :key 'cadr)) (chords nil) (cseqdata nil)) (loop for note in chord-data do ;;; note = (pitch onset dur vel) ;;; (car chords) = (onset (pitches) (durs) (vels)) (if (and (car chords) (= (second note) (car (car chords)))) ;;; add note to chord (setf (car chords) (list (first (car chords)) (append (second (car chords)) (list (first note))) (append (third (car chords)) (list (third note))) (append (fourth (car chords)) (list (fourth note))))) ;;; else create new chord (push (list (second note) (list (first note)) (list (third note)) (list (fourth note))) chords))) (setf cseqdata (mat-trans (reverse chords))) (make-instance 'chord-seq :lonset (om-round (om* (first cseqdata) 1000)) :lmidic (om-round (f->mc (second cseqdata))) :ldur (om-round (om* (third cseqdata) 1000)) :lvel (om-round (om-scale (fourth cseqdata) 50 127))))) ;;;============================================ ;;; WRITE... ;;;============================================ (defun make-1TRC-frames (partials &optional separate-streams) (let ((frames (sort (loop for partial in (sort partials '< :key #'(lambda (p) (car (partial-t-list p)))) for i = 0 then (+ i 1) append (let ((1-partial-frames (loop for time in (partial-t-list partial) for n from 0 collect (let ((matrix (om-init-instance (make-instance 'SDIFMatrix :matrixtype "1TRC" :data (list (list (1+ i)) (list (nth n (partial-f-list partial))) (list (or (nth n (partial-a-list partial)) 1.0)) (list (or (nth n (partial-ph-list partial)) 0))))))) (make-instance 'SDIFFrame :ftime time :frametype "1TRC" :streamid (if separate-streams i 0) :lmatrix (list matrix)))))) (setf (nth 2 (data (car (lmatrix (car (last 1-partial-frames)))))) (list 0.0)) 1-partial-frames)) '< :key 'ftime))) (if separate-streams frames (merge-frame-data frames)) )) (defun get-partial-f-a-ph-at-time (partial time) (let ((pos (position time (partial-t-list partial) :test '=))) (if pos (list (nth pos (partial-f-list partial)) (if (partial-a-list partial) (nth pos (partial-a-list partial)) 1.0) (if (partial-ph-list partial) (nth pos (partial-ph-list partial)) 0)) (let* ((pos-before (position time (partial-t-list partial) :test '>= :from-end t)) (t1 (nth pos-before (partial-t-list partial))) (t2 (nth (1+ pos-before) (partial-t-list partial)))) (list (linear-interpol t1 t2 (nth pos-before (partial-f-list partial)) (nth (1+ pos-before) (partial-f-list partial)) time) (if (partial-a-list partial) (linear-interpol t1 t2 (nth pos-before (partial-a-list partial)) (nth (1+ pos-before) (partial-a-list partial)) time) 1.0) (if (partial-ph-list partial) (linear-interpol t1 t2 (nth pos-before (partial-ph-list partial)) (nth (1+ pos-before) (partial-ph-list partial)) time) 0))) ))) (defun make-1TRC-frames-synchronous (partials &optional sr) (flet ((make-frame-at-time (p-list time) (let* ((data (sort (loop for partial in p-list for i = 1 then (+ i 1) when (and (>= time (car (partial-t-list partial))) (<= time (car (last (partial-t-list partial))))) collect (cons i (get-partial-f-a-ph-at-time partial time))) '< :key 'car)) (matrix (om-init-instance (make-instance 'SDIFMatrix :matrixtype "1TRC" :data (mat-trans data))))) (make-instance 'SDIFFrame :ftime time :streamid 0 :frametype "1TRC" :lmatrix (list matrix))))) (if sr (let* ((t-lists (mapcar 'partial-t-list partials)) (tmin (reduce 'min (mapcar 'list-min t-lists))) (tmax (reduce 'max (mapcar 'list-max t-lists)))) (loop for ftime from tmin to (+ tmax .2) by sr collect (make-frame-at-time partials ftime))) (let ((timeslist (sort (remove-duplicates (loop for partial in partials append (partial-t-list partial)) :test '=) '<))) (loop for ftime in timeslist collect (make-frame-at-time partials ftime))) ))) (defmethod* partials->sdif ((partials list) &key (outpath "partials.sdif") (frame-rate 0.01)) :indoc '("a list of partials" "output pathname") :initvals '(nil "partials.sdif" 0.01) :icon :sdif :doc "Saves the contents of <partials> as an SDIF file in <outpath>. Data is stored as a sequence of 1TRC frames containing 1TRC matrices. SDIF partials are resampled in synchronous frames at <frame-rate>. " (let ((out-path (handle-new-file-exists (cond ((pathnamep outpath) outpath) ((stringp outpath) (outfile outpath)) (t (om-choose-new-file-dialog)))))) (when out-path (let ((sdiffileptr (sdif::sdif-open-file out-path sdif::eWriteFile))) (if sdiffileptr (unwind-protect (progn (sdif::SdifFWriteGeneralHeader sdiffileptr) (sdif-write (default-om-NVT) sdiffileptr) (sdif::SdifFWriteAllASCIIChunks sdiffileptr) (when partials (loop for frame in (make-1trc-frames-synchronous partials frame-rate) do (sdif-write frame sdiffileptr) )) (namestring out-path)) (sdif::SDIFFClose sdiffileptr)) (om-beep-msg "Could not open file for writing: ~A" out-path)) )))) ;;;========================================== ;;; CHORD-SEQ ;;;========================================== ;;; returns list of (date ((id1 freq vel 0) (....))) for begins ;;; and (date (id1 id2 ...)) for ends (defmethod! chordseq-to-datalist ((self chord-seq)) (let* ((ind -1) (chord-data nil) (enddata nil) newendlist) ;;; recup data (setf chord-data (loop for chord in (inside self) collect (list (date chord) (loop for note in (inside chord) do (pushr (list (+ (date chord) (dur note)) (incf ind)) enddata) collect (list ind (mc->f (midic note)) (/ (vel note) 1270.0) 0))))) ;;; mettre tous les end simulatnes dans une meme frame (setf enddata (sort enddata '< :key 'car)) (let* (tmptime) (setf newendlist (loop while enddata do (setf tmptime (car (car enddata))) collect (list tmptime (loop while (equal (car (car enddata)) tmptime) collect (second (pop enddata))))) )) (sort (append chord-data newendlist) '< :key 'car) )) (defun make-1MRK-frames (datalist) (let ((last-time nil) (framesdatalist nil)) ;;; group data in same frames (loop for data in datalist do (if (and last-time (= (car data) last-time)) (setf (cadr (last-elem framesdatalist)) (append (cadr (last-elem framesdatalist)) (cadr data))) (pushr data framesdatalist)) (setf last-time (car data))) (loop for framedata in framesdatalist collect (let ((date (/ (car framedata) 1000.0)) (begnotes nil) begmat (endnotes nil) endmat) (loop for elt in (second framedata) do (if (consp elt) (pushr elt begnotes) (pushr elt endnotes))) (when begnotes (setf begmat (list (om-init-instance (make-instance 'SDIFMatrix :matrixtype "1BEG" :data (list (mapcar 'car begnotes)))) (om-init-instance (make-instance 'SDIFMatrix :matrixtype "1TRC" :data (mat-trans begnotes))) ))) (when endnotes (setf endmat (list (om-init-instance (make-instance 'SDIFMatrix :matrixtype "1END" :data (list endnotes)))))) (make-instance 'SDIFFrame :ftime date :streamid 0 :frametype "1MRK" :lmatrix (append begmat endmat)) )) )) (defmethod! chord-seq->sdif ((self chord-seq) &optional (outpath "cseq.sdif")) :icon :sdif :indoc '("a CHORD-SEQ" "output pathname") :doc "Saves the contents of <self> (a CHORD-SEQ) as an SDIF file in <outpath>. Data is stored as a sequence of 1MRK frames containing 1BEG and 1END matrices for begin and end times, and 1TRC matrices for chords values. " (let ((out-path (cond ((pathnamep outpath) outpath) ((stringp outpath) (outfile outpath)) (t (om-choose-new-file-dialog))))) (when out-path (let ((sdiffileptr (sdif::sdif-open-file out-path sdif::eWriteFile))) (if sdiffileptr (unwind-protect (progn (sdif::SdifFWriteGeneralHeader sdiffileptr) (sdif-write (default-om-NVT) sdiffileptr) (sdif-write-types sdiffileptr (list (make-instance 'sdiftype :struct 'F :signature "1MRK" :description '(("1BEG" "begin markers") ("1TRC" "sinusoidal tracks") ("1END" "end markers"))))) (sdif::SdifFWriteAllASCIIChunks sdiffileptr) (let ((datalist (chordseq-to-datalist self))) (loop for frame in (make-1MRK-frames datalist) do (sdif-write frame sdiffileptr)) )) (sdif::SDIFFClose sdiffileptr)) (om-beep-msg "Could not open file for writing: ~A" out-path)) (probe-file out-path) ))))
19,487
Common Lisp
.lisp
361
36.481994
139
0.473223
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
dafb4cea90afc11394a13a685fcb19f350b1bed85dc04c115765b04072b317af
721
[ -1 ]
722
sdif-editor.lisp
cac-t-u-s_om-sharp/src/packages/sdif/sdif-om/sdif-editor.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) (defclass sdiffile-editor (OMEditor) ()) (defmethod object-has-editor ((self SDIFFile)) t) (defmethod get-editor-class ((self SDIFFile)) 'sdiffile-editor) (defmethod object-name-for-window-title ((self SDIFFile)) "SDIF File") (defmethod extra-window-title-info ((self SDIFFile)) (if (file-pathname self) (namestring (file-pathname self)) "No file attached")) (defmethod make-editor-window-contents ((editor sdiffile-editor)) (set-g-component editor :filemap-layout (om-make-layout 'om-column-layout)) (set-g-component editor :matrix-text (om-make-di 'om-simple-text :size (omp nil 22) :font (om-def-font :normal-b))) (set-g-component editor :field-plot (om-make-view 'field-plot-view :editor editor :bg-color (om-def-color :white))) (set-g-component editor :matrix-field-menu (om-make-di 'om-popup-list :size (omp nil 22) :font (om-def-font :normal) :di-action #'(lambda (item) (when (selection editor) (update-plot-data (get-g-component editor :field-plot) (f-desc (selection editor)) (m-desc (selection editor)) (om-get-selected-item-index item)) )))) (om-make-layout 'om-row-layout :ratios '(1 nil 1) :subviews (list (get-g-component editor :filemap-layout) :divider (om-make-layout 'om-column-layout :ratios '(1 100) :subviews (list (om-make-layout 'om-row-layout :subviews (list (get-g-component editor :matrix-text) (get-g-component editor :matrix-field-menu))) (get-g-component editor :field-plot)) )) ) ) (defmethod update-to-editor ((editor sdiffile-editor) (from t)) (call-next-method) (init-editor-window editor)) ;;;========================================================== ;;; DISPLAY / SELECT MATRIX STREAMS ;;;========================================================== (defclass sdifmat-stream-view (OMEditorView) ((f-desc :initform nil :initarg :f-desc :accessor f-desc) (m-desc :initform nil :initarg :m-desc :accessor m-desc))) (defmethod om-draw-contents ((self sdifmat-stream-view)) (let ((selected (equal (selection (editor self)) self))) (om-draw-rect 3 0 (- (w self) 6) (- (h self) 3) :fill t :color (if selected (om-make-color .6 .64 .64) (om-def-color :light-gray))) (om-with-fg-color (if selected (om-def-color :white) (om-def-color :dark-gray)) (om-with-font (om-def-font :normal) (om-draw-string 6 12 (format nil "Matrix: ~A" (mstream-desc-msig (m-desc self)))) (om-draw-string 6 24 (format nil " Matrix Fields: ~A" (mstream-desc-fields (m-desc self)))) (om-draw-string 6 36 (format nil " Max. Elts.: ~D" (mstream-desc-rmax (m-desc self)))) (om-draw-string 6 48 (format nil " Nb. Occurrences: ~D" (mstream-desc-nf (m-desc self))))) ))) (defmethod om-view-click-handler ((self sdifmat-stream-view) pos) (let ((ed (editor self))) (unless (equal (selection ed) self) (setf (selection ed) self) (update-selected-contents ed (f-desc self) (m-desc self)) (om-invalidate-view (get-g-component ed :filemap-layout)) ))) (defmethod update-selected-contents ((editor sdiffile-editor) f-desc m-desc) (om-set-dialog-item-text (get-g-component editor :matrix-text) (if m-desc (format nil "Matrix: ~A" (mstream-desc-msig m-desc)) "Select a matrix stream on the left panel..")) (om-set-item-list (get-g-component editor :matrix-field-menu) (if m-desc (mstream-desc-fields m-desc) nil)) (update-plot-data (get-g-component editor :field-plot) f-desc m-desc 0) ) (defmethod init-editor-window ((editor sdiffile-editor)) (let ((sdiffile (object-value editor)) (map-layout (get-g-component editor :filemap-layout))) (om-remove-all-subviews map-layout) (apply 'om-add-subviews (cons map-layout (cons (om-make-di 'om-simple-text :size (omp nil 16) :font (om-def-font :normal) :fg-color (om-def-color :dark-gray) :text (format nil "File: ~A" (file-pathname sdiffile))) (loop for stream-desc in (file-map sdiffile) collect (om-make-layout 'om-simple-layout :size (omp nil nil) :bg-color (om-def-color :gray) :delta 10 :subviews (list (om-make-layout 'om-column-layout :delta 0 :subviews (cons (om-make-di 'om-simple-text :size (omp nil 16) :font (om-def-font :normal) :fg-color (om-def-color :white) :text (format nil "Stream ~D: ~A [~D frames from ~f to ~fs]" (fstream-desc-id stream-desc) (fstream-desc-fsig stream-desc) (fstream-desc-nf stream-desc) (fstream-desc-tmin stream-desc) (fstream-desc-tmax stream-desc))) (if (fstream-desc-matrices stream-desc) (loop for mat-desc in (fstream-desc-matrices stream-desc) collect (om-make-view 'sdifmat-stream-view :editor editor :m-desc mat-desc :f-desc stream-desc :size (omp nil nil) :bg-color (om-def-color :gray)) ) (list (om-make-di 'om-simple-text :size (omp nil nil) :font (om-def-font :normal) :fg-color (om-def-color :white) :text "[no matrices inside]")) ) ))) ) )))) (update-selected-contents editor nil nil) )) ;;;========================================================== ;;; PLOTS NUMERIC DATA ;;;========================================================== (defclass field-plot-view (OMEditorView) ((data :initform nil :initarg :data :accessor data) (vmin :accessor vmin :initarg :vmin :initform nil) (vmax :accessor vmax :initarg :vmax :initform nil) (tmax :accessor tmax :initarg :tmax :initform 0)) (:default-initargs :draw-with-buffer t)) (defmethod om-draw-contents ((self field-plot-view)) ;;; data can be a list of NIL when reloading SDIF Files (when (remove nil (data self)) (let* ((mi (vmin self)) (ma (vmax self)) (lx 10) (ly 10) (lh (- (h self) 20)) (xfact (if (plusp (tmax self)) (/ (- (w self) 20) (tmax self)) 1)) (c-min .7) (c-fact (if (= 1 (length (data self))) c-min (/ c-min (length (data self)))))) (when (= mi ma) (setf mi (- mi 10) ma (+ ma 10))) (loop for row in (reverse (data self)) for i = 1 then (+ i 1) do (let ((c (- c-min (* i c-fact)))) (om-with-fg-color (om-make-color c c c) (if (= 1 (length row)) (om-draw-string 20 (+ 20 (* i 20)) (format nil "~f" (cadr (car row)))) (loop for v on row when (cdr v) do (om-draw-line (+ lx (* (first (car v)) xfact)) (+ ly (om-scale (second (car v)) lh 0 mi ma)) (+ lx (* (first (cadr v)) xfact)) (+ ly (om-scale (second (cadr v)) lh 0 mi ma)) ) ) ))) )))) (defmethod update-plot-data ((self field-plot-view) f-desc m-desc field-num) ;;; will do this in the main OM-EVAL thread where all SDIF happens (eval-sdif-expression #'(lambda () (let ((ed (editor self))) (if (and f-desc m-desc field-num) (multiple-value-bind (sdifdata sdiftimes) (getsdifdata (object-value ed) (fstream-desc-id f-desc) (fstream-desc-fsig f-desc) (mstream-desc-msig m-desc) field-num nil nil nil nil) (setf (vmin self) (list-min (flat sdifdata))) (setf (vmax self) (list-max (flat sdifdata))) (setf (tmax self) (car (last sdiftimes))) (setf (data self) ;;; TAKES ONLY the FIRST 100 ROWS (loop for r from 0 to (min 100 (1- (mstream-desc-rmax m-desc))) collect (loop for timetag in sdiftimes for data in sdifdata when (nth r data) collect (list timetag (nth r data))) )) ) (setf (data self) nil)) (om-invalidate-view self) )) ))
11,613
Common Lisp
.lisp
200
36.955
154
0.434414
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
9a8a0c14f67d179f6e58a7a52361b735ace703ed0e3a067831c7b972888a3f39
722
[ -1 ]
723
sdif-struct.lisp
cac-t-u-s_om-sharp/src/packages/sdif/sdif-om/sdif-struct.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;========================= ;;; dummy class for SDIF lib initialization ;;;========================= (defclass sdif-object () ()) ;(defmethod initialize-instance :after ((self sdif-object) &rest initargs) ; (sdif::sdif-init-cond)) ;;;========================= ;;; SDIF TYPE ;;;========================= (defclass* SDIFType () ((struct :initform 'F :initarg :struct :accessor struct :documentation "frame (= f) or matrix (= m)") (signature :initform "" :initarg :Signature :accessor signature :documentation "SDIF type signature") (description :initform nil :initarg :description :accessor description :documentation "type description")) (:documentation "An SDIF type declaration to be written in an SDIF file or buffer. SDIF types define data structures in the SDIF frameworks. They are identified by a 4 ASCII characters (e.g. 1TRC, 1FQ0, ETC..) See http://sdif.sourceforge.net/ for more inforamtion about SDIF TYPES. Matrix type description is a list with the names of the different description fields in this matrix (e.g. '(\"freq\" \"amp\" \"phase\")) Frame type description is a list with the types and names of the different matrices allowed in the frame (e.g. '((\"TYP1\" \"matrix1\") (\"TYP2\" \"matrix2\")) " )) ;;; we don't really need this as a class... (defmethod* make-sdif-m-type (sign fieldnames) (make-instance 'SDIFType :struct 'm :signature sign :description fieldnames)) (defmethod* make-sdif-f-type (sign matrixtypes &optional matrixnames) (make-instance 'SDIFType :struct 'f :signature sign :description (loop for type in (list! matrixtypes) for i = 0 then (+ i 1) collect (list type (or (nth i matrixnames) (format nil "matrix~D" (1+ i))))))) (defmethod sdif-types-from-field-names (field-names &key mat-type f-type) (let ((ft (or f-type "XFRA")) (mt (or mat-type "XMAT"))) (list (make-sdif-f-type ft mt) (make-sdif-m-type mt field-names)) )) ;;; NEEDS SUPPORT FOR MENUINS IN CLASSES !! ;; (("Frame" 'F) ("Matrix" 'M)) ;;;========================= ;;; SDIF NAME-VALUE TABLE ;;;========================= (defclass* SDIFNVT () ((NV-pairs :initform nil :initarg :NV-pairs :accessor NV-pairs :documentation "list of (name value) pairs") (TableName :initform nil :initarg :TableName :accessor TableName :documentation "name (string)") (ID :initform 0 :initarg :ID :accessor ID :documentation "table ID (integer)") (tnum :initform 0 :accessor tnum)) (:documentation "An SDIF Name/Value table to be written in an SDIF file or buffer. SDIF NVTs gibe additional info on the data in an SDIF file in the form of name/value pairs They have an ID and ususally a TableName name/value. See http://sdif.sourceforge.net/ for more inforamtion about SDIF TYPES. " )) (defun default-om-NVT () (make-instance 'SDIFNVT :tablename "FileInfo" :ID 0 :NV-pairs (list (list "Author" (string+ *app-name* " " *version-string*)) (list "Date" (om-get-date))))) ;;;========================= ;;; SDIF MATRIX ;;;========================= (defclass* SDIFMatrix (2D-array) ((matrixtype :initform nil :initarg :matrixtype :accessor matrixtype :documentation "SDIF matrix type signature") ;(elts :initform 0 :initarg :elts :accessor elts :documentation "number of elements (a.k.a lines)") ;(fields :initform nil :initarg :fields :accessor fields :documentation "Name of SDIF fields") (data :initform nil :initarg :data :accessor data :documentation "data matrix / list of lists : (field1 field2 ...)") ) (:documentation "SDIF data stored as a 2D array. SDIF Matrix define multidimensional sound description data at a given moment (no temporal dimension). The lines of the matrix define the different fields of the description data (e.g. frequencies, amplitudes, etc.) The number of fields usually depends on the SDIF type specification corresponding to <signature>. The number of elements is variable. SDIFMatrix is a virtual 2D array of <fields> x <elts>. All data is contained in <data> - as a list of lists ((freqs) (amps) (phases) ...) or - as flat list, containing the successive field values for each element (e.g. '(freq1 amp1 phase1 frezq2 amp2 phase2 ...)). This case optimizes file writing operations. See http://sdif.sourceforge.net/ for more inforamtion about SDIF ")) ; (defmethod allow-extra-controls ((self SDIFMatrix)) t) (defun merge-matrix-data (data1 data2) (loop for c1 in data1 for c2 in data2 collect (append c1 c2))) ;;; TODO: ;;; matrixtype could be a SDIFtype and do something at initialization to initialize the fields... ;;;========================= ;;; SDIF FRAME ;;;========================= ;;; Ensemble de matrices correspondant a un instant d'echantillonnage ;;; Unite minimum pour ecrire dans un fichier SDIF (defclass* SDIFFrame (sdif-object data-frame) ((frametype :initform nil :initarg :frametype :initarg :signature :accessor frametype :documentation "4-char signature of the SDIF frame type") (ftime :accessor ftime :initarg :ftime :initform 0.0 :documentation "time of the frame (s)") (streamid :initform 0 :initarg :streamid :accessor streamid :documentation "SDIF stream ID (integer)") (lmatrix :initform nil :initarg :lmatrix :accessor lmatrix :documentation "list of SDIFMatrix objects")) (:documentation "An SDIF data chunk. SDIF frames are data chunk containing one or more SDIF matrices (<lmatrix>) and precisely localized in time (<fTime>). Frames can be grouped in streams identified by an ID (<streamid>) in order to describe parallele data. The number and type of matrices allowed in a given frame depends on the SDIF frame type specification corresponding to <signature>. See http://sdif.sourceforge.net/ for more inforamtion about SDIF. " )) ;;; in case there is just 1 matrix -- avoids using list (defmethod initialize-instance :after ((self sdifframe) &rest initargs) (setf (lmatrix self) (list! (lmatrix self))) (setf (slot-value self 'onset) (sec->ms (ftime self)))) ;;; the onset from data-frame/timed-object is computed from ftime (defmethod onset ((self SDIFFrame)) (sec->ms (ftime self))) (defmethod (setf onset) (date (self SDIFFrame)) (call-next-method) (setf (ftime self) (ms->sec date))) ;;; merge frames for same kind of (single) matrices (adds data in the matrix) (defun merge-frame-data (frames) (let ((newframes nil)) (loop while frames do (let ((fr (pop frames))) (if (and newframes (= (ftime (car newframes)) (ftime fr)) (string-equal (frametype (car newframes)) (frametype fr))) (loop for matrix in (lmatrix fr) do (let ((fmat (find (matrixtype matrix) (lmatrix (car newframes)) :test 'string-equal :key 'matrixtype))) (if fmat (setf (data fmat) (merge-matrix-data (data fmat) (data matrix)) (elts fmat) (1+ (elts fmat))) (setf (lmatrix fr) (append (lmatrix fr) (list matrix)))))) (push (make-instance 'SDIFFrame :ftime (ftime fr) :frametype (frametype fr) :streamID 0 :lmatrix (lmatrix fr)) newframes)))) (reverse newframes))) ;;; merge frames for same kind of frames (appends matrices) (defun merge-frames (frames) (let ((newframes nil)) (setf frames (sort frames '< :key 'ftime)) (loop while frames do (let ((fr (pop frames))) (if (and newframes (= (ftime (car newframes)) (ftime fr)) (= (streamID (car newframes)) (streamID fr)) (string-equal (frametype (car newframes)) (frametype fr))) (setf (lmatrix (car newframes)) (append (lmatrix (car newframes)) (lmatrix fr))) (push fr newframes)))) (reverse newframes))) ;;; use in a DATA-TRACK (defmethod data-frame-text-description ((self SDIFFrame)) (cons (string+ "SDIF " (frametype self)) (flat (mapcar #'(lambda (m) (format nil "~A ~A" (matrixtype m) (data m))) (lmatrix self)))) )
9,071
Common Lisp
.lisp
167
48.413174
159
0.632506
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1080faf037d6dedb1ca86c2c7f9349563ce0dbd9b00b018fe19d634470716257
723
[ -1 ]
724
score.lisp
cac-t-u-s_om-sharp/src/packages/score/score.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) (add-preference-module :score "Score") (mapc #'(lambda (filename) (compile&load (decode-local-path filename))) '("score-objects/score-object" "score-objects/chord" "score-objects/chord-seq" "score-objects/tree" "score-objects/ratios" "score-objects/voice" "score-objects/multiseq-poly" "score-objects/extras" "functions/conversions" "functions/score-functions" "functions/trees" "functions/quantify" "functions/segmentation" "draw/draw-score-basic" "draw/draw-score-rhythm" "draw/draw-score-spacing" "editor/scales" "editor/score-editor" "editor/chord-editor" "editor/chord-seq-editor" "editor/voice-editor" "editor/multiseq-poly-editor" "editor/score-boxes" "editor/play" "editor/groups" "editor/analysis" "math/n-cercle" "math/n-cercle-editor" "import-export/midi" "import-export/musicxml-import" "compatibility" )) (omNG-make-package "Score" :container-pack *om-package-tree* :doc "Score tools and objects" :classes '(note chord chord-seq voice multi-seq poly) :functions nil :subpackages (list (omNG-make-package "Score Tools" :doc "Manipulation of score objects" :functions '(object-dur get-chords concat select insert merger align-chords split-voices true-durations) :subpackages nil) (omNG-make-package "Rhythm" :doc "Operations on rhythm trees and ratios" :functions '(mktree tree2ratio pulsemaker maketreegroups n-pulses group-pulses get-pulse-places get-rest-places get-signatures reducetree tietree filtertree reversetree rotatetree remove-rests subst-rhythm invert-rhythm omquantify) :subpackages nil) (omNG-make-package "Extras/Groups" :doc "Extra elements attached to chords in score editors." :functions '(add-extras remove-extras get-extras get-segments map-segments) :classes '(score-marker head-extra vel-extra text-extra symb-extra) :subpackages nil) (omNG-make-package "Utils" :doc "Unit conversion utilities etc." :functions '(approx-m mc->f f->mc mc->n n->mc int->symb symb->int beats->ms) :subpackages nil) (omNG-make-package "Math" :doc "Mathematical tools and Set theory" :classes '(n-cercle) :functions '(chord2c c2chord c2chord-seq chord-seq2c c2rhythm rhythm2c nc-rotate nc-complement nc-inverse) :subpackages nil) (omNG-make-package "Import/Export" :doc "Import and export utilities" :functions '(import-musicxml import-midi save-as-midi) ;; export-musicxml :subpackages nil)))
4,431
Common Lisp
.lisp
95
31.273684
112
0.49397
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
87e56da47ebe8e8d11d3ad82a9115b3d32990d83485ec8714286656c4cd9cf8b
724
[ -1 ]
725
compatibility.lisp
cac-t-u-s_om-sharp/src/packages/score/compatibility.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;; LOAD OBJECTS AND CODE FROM OM6 (in-package :om) ;;; compat API: (defmethod update-arg-names ((reference (eql 'chord-seq))) '(("legato" "llegato"))) ;;; Redefinitions of OM6 load utilities (defun load-obj-list-from-save (list) (loop for item in list collect (eval item))) ;;; SCORE OBJECTS ;;; => TODO (defmethod set-patch-pairs ((self t) list) ) (defmethod load-port-info ((self t) port) ) (defmethod init-mus-color ((self t) color) ) (defmethod set-extra-pairs ((self t) extras) ) (defmethod set-tonalite ((self t) tonalite) ) (defmethod set-object-analysis ((self t) analyse) ) ;;; SCORE EDITOR PARAMS (defun load-score-edition-params (editparams) (let ((staff-symb (cdr (find 'staff editparams :key #'car)))) (when staff-symb `((:edition-params (:staff ,(intern-k (symbol-name staff-symb))))) ))) (defmethod om-load-editor-box1 (name (reference (eql 'note)) inputs position size value lock &optional fname editparams spict meditor pictlist show-name) (declare (ignore fname meditor pictlist)) (append (call-next-method) (load-score-edition-params editparams))) (defmethod om-load-editor-box1 (name (reference (eql 'chord)) inputs position size value lock &optional fname editparams spict meditor pictlist show-name) (declare (ignore fname meditor pictlist)) (append (call-next-method) (load-score-edition-params editparams))) (defmethod om-load-editor-box1 (name (reference (eql 'chord-seq)) inputs position size value lock &optional fname editparams spict meditor pictlist show-name) (declare (ignore fname meditor pictlist)) (append (call-next-method) (load-score-edition-params editparams))) (defmethod om-load-editor-box1 (name (reference (eql 'voice)) inputs position size value lock &optional fname editparams spict meditor pictlist show-name) (declare (ignore fname meditor pictlist)) (append (call-next-method) (load-score-edition-params editparams))) ;;; => hack / to(re)do when score editors are operational (defclass edition-values () ((paper-size :accessor paper-size) (top-margin :accessor top-margin) (left-margin :accessor left-margin) (right-margin :accessor right-margin) (bottom-margin :accessor bottom-margin) (orientation :accessor orientation) (scale :accessor scale) (system-space :accessor system-space) (system-color :accessor system-color) (line-space :accessor line-space) (title :accessor title) (show-title? :accessor show-title?) (show-page? :accessor show-page?) (sheet-id :accessor sheet-id) (page-mode :accessor page-mode))) ;;; SHEET (defclass sheet-track-obj () ((end-t :accessor end-t) (obj-size :accessor obj-size) (obj-margin :accessor obj-margin) (obj-staff :accessor obj-staff) ))
3,670
Common Lisp
.lisp
80
41.0875
97
0.639597
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
470774f6c5b8958e10db575b32caec69d3b1e8445edb5cd6180181236c123d8e
725
[ -1 ]
726
musicxml-export.lisp
cac-t-u-s_om-sharp/src/packages/score/import-export/musicxml-export.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;======================= ;;; EXPORT MUSICXML ;;;======================= ;; This code is almost taken "as-is" adapted from OM 6.15 export-mxml.lisp ;; Author : Karim Haddad ;; Revision: 1.1 2008/06/23 ;; Revision: 2 2015/10/05 J. Bresson ;; Adaptation from OM6 IN PROGRESS !! 2019/10 J. Bresson (in-package :om) (defvar *xml-version* "XML 1.0") ;;; PREDICATES (defmethod group-p ((self group)) t) (defmethod group-p ((self t)) nil) (defmethod chord-p ((self chord)) t) (defmethod chord-p ((self continuation-chord)) t) (defmethod chord-p ((self t)) nil) (defmethod cont-chord-p ((self continuation-chord)) t) (defmethod cont-chord-p ((self t)) nil) (defmethod rest-p ((self r-rest)) t) (defmethod rest-p ((self t)) nil) (defmethod in-group? ((self chord)) (group-p (parent self))) (defmethod in-group? ((self continuation-chord)) (group-p (parent self))) (defmethod in-group? ((self r-rest)) (group-p (parent self))) (defmethod in-group? ((self t)) nil) (defmethod alone-in-group? ((self score-element)) (and (in-group? self) (= (length (inside (parent self))) 1))) (defmethod singelton-group? ((self group)) (let* ((inside (inside self))) (and (= (length inside) 1) (or (chord-p (car inside)) (rest-p (car inside)))))) (defmethod singelton-group? ((self t)) nil) ;;; UTILS (defun lst->ratio (liste) (/ (car liste) (cadr liste))) (defmethod getratiogroup ((self measure)) (list 1 1)) ;; modified version of om::find-denom ;; Find the rigth denom to ratio of tuplet. (defun findenom (num durtot) (if num (cond ((or (is-binaire? durtot) (power-of-two-p durtot)) (get-denom-bin num)) ;;;changed here from is-binaire? to powerof2? ((is-ternaire? durtot) (get-denom-ter num)) (t (get-denom-other durtot num))) (list 1 1) )) (defparameter *note-types* '((2 breve) (1 whole) (1/2 half) (1/4 quarter) (1/8 eighth) (1/16 16th) (1/32 32nd) (1/64 64th) (1/128 128th) (1/256 256th) (1/512 512th)(1/1024 1024th))) (defmethod getnotetype ((self group)) (let* ((tree (tree self)) (real-beat-val (/ 1 (om::fdenominator (first tree)))) (symb-beat-val (/ 1 (om::find-beat-symbol (om::fdenominator (first tree))))) (dur-obj-noire (/ (om::extent self) (om::qvalue self))) (factor (/ (* 1/4 dur-obj-noire) real-beat-val)) (dur (* symb-beat-val factor)) (durtot (if (listp dur) (car dur) dur)) (num (or (om::get-group-ratio self) (om::extent self))) (denom (om::find-denom num durtot)) (unite (/ durtot (if (listp denom) (second denom) denom)))) (format nil "~A" (cadr (find unite *note-types* :key 'car))) )) (defmethod getratiogroup ((self om::group)) (if (singelton-group? self) (list 1 1) ;;; when a group is in fact a single note (let* ((allparents (reverse (cdr (getdemall self)))) (dur (get-dur-group self)) (num (om::get-group-ratio self))) ;;; check definition of get-group-ratio (if (not allparents) (let* ((denom (findenom num dur))) (if (listp denom) denom (list num (findenom num dur)))) ;;; a voir !!!!!!! (let* ((fact (get-dur-group self)) (ratios (loop for i in allparents do (setf fact (* fact (lst->ratio (getratiogroup i)))))) ;;; donne le facteur accumule des nested tup (denom (findenom num fact))) (if (listp denom) denom (list num denom) )) )))) ;;;ici il fait la meme chose que getratiogroup averc les ratios... (defmethod getratiodur ((self group)) (let* ((allparents (reverse (cdr (getdemall self)))) (dur (get-dur-group self)) (num (om::get-group-ratio self))) (if (not allparents) dur (let* ((fact (get-dur-group self)) (ratios (loop for i in allparents do (setf fact (* fact (lst->ratio (getratiogroup i))))));;; donne le facteur accumule des nested tup (denom (findenom num fact))) fact )) )) (defun get-grp-level (self) "donne l'index des tuplet imbriques" (let* ((buf (om::parent self)) (num (car (getratiogroup buf))) (denom (second (getratiogroup buf))) (nums (list num)) (denoms (list denom)) (index 0)) (loop while (group-p buf) do (progn (incf index) (setf buf (parent buf)) (push (car (getratiogroup buf)) nums) (push (second (getratiogroup buf)) denoms) (setf num (* num (car (getratiogroup buf)))) (setf denom (* denom (second (getratiogroup buf)))))) (list index num denom (butlast (reverse nums)) (butlast (reverse denoms))))) (defun getallgroups (self) (let* ((buf (parent self)) (rep '())) (loop while (group-p buf) do (let ((ratiogroup (getratiogroup buf))) (push (list (car ratiogroup) (cadr ratiogroup) (getnotetype buf)) rep) (setf buf (parent buf)))) rep)) (defmethod getratiounite ((self group)) (/ (getratiodur self) (second (getratiogroup self)))) (defmethod getdemall ((self om::group)) "For nested tuplets. Returns all group-parents to a group including the group itself" (let* ((test self) (res (list self))) (loop while test do (progn (push (parent test) res) (if (measure-p (parent test)) (setf test nil) (setf test (parent test))))) (butlast (reverse res)))) (defmethod get-dur-group ((self measure)) "Returns the duration of measure * whole note" (let* ((ext (om::extent self)) (qval (om::qvalue self))) (/ ext (* qval 4)))) (defmethod get-dur-group ((self group)) "Returns the duration of measure * whole note. durtot etant la duree du group parent" (let* ((ext (om::extent self)) (qval (om::qvalue self))) (/ ext (* qval 4)))) (defun reduce-num-den-fig (list) "Reduces binary ratios and fig dedoubles. C-a-d si on a (14 8 1/16) il retourne (7 4 1/8)" (if (= (car list) (second list)) list (let ((res list)) (setf res (list (/ (car res) 2) (/ (second res) 2) (* (third res) 2))) (if (or (ratiop (car res)) (ratiop (second res))) (list (* 2 (car res)) (* 2 (second res)) (/ (third res) 2)) (reduce-num-den-fig res) )))) (defmethod get-group-info ((self group)) (let* ((rat (om::first-n (getratiogroup self) 2)) (unit (getratiounite self)) (reduce (reduce-num-den-fig (om::flat (list rat unit))))) (list (car reduce) (second reduce) (format nil "~A" (cadr (find (third reduce) *note-types* :key 'car)))) )) (defmethod get-group-info ((self measure)) (list 1 1)) ;;============================================ (defun first-of-this-group (self grp) (let ((frst (car (om::collect-chords grp)))) (equal self frst))) (defun last-of-this-group (self grp) (let ((lst (car (reverse (om::collect-chords grp))))) (equal self lst))) (defun tied? (self) (or (and (not (cont-chord-p self)) (cont-chord-p (om::next-container self '(chord)))) (and (cont-chord-p self) (not (cont-chord-p (om::next-container self '(chord))))) (and (cont-chord-p self) (cont-chord-p (om::next-container self '(chord)))))) (defun cons-xml-tied (self) (cond ((and (not (cont-chord-p self)) (cont-chord-p (om::next-container self '(chord)))) "<tie type=\"start\"/>") ((and (om::cont-chord-p self) (not (om::cont-chord-p (om::next-container self '(chord))))) "<tie type=\"stop\"/>") ((and (om::cont-chord-p self) (om::cont-chord-p (om::next-container self '(chord)))) "<tie type=\"stop\"/><tie type=\"start\"/>") (t nil))) ;;;;the nil thing is comin from here (defun cons-xml-tied-notation (self) (cond ((and (not (om::cont-chord-p self)) (om::cont-chord-p (om::next-container self '(om::chord)))) "<tied type=\"start\"/>") ((and (om::cont-chord-p self) (not (om::cont-chord-p (om::next-container self '(om::chord))))) "<tied type=\"stop\"/>") ((and (om::cont-chord-p self) (om::cont-chord-p (om::next-container self '(om::chord)))) "<tied type=\"stop\"/><tied type=\"start\"/>") (t NIL))) ;;;;the nil thing is comin from here (defun cons-xml-tuplet-start (num denom notetype nbr) (list (format nil "<tuplet bracket=\"yes\" number=\"~A\" placement=\"above\" type=\"start\">" nbr) (list "<tuplet-actual>" (list (format nil "<tuplet-number>~A</tuplet-number>" num) (format nil "<tuplet-type>~A</tuplet-type>" notetype)) "</tuplet-actual>" "<tuplet-normal>" (list (format nil "<tuplet-number>~A</tuplet-number>" denom) (format nil "<tuplet-type>~A</tuplet-type>" notetype)) "</tuplet-normal>") "</tuplet>")) (defun cons-xml-tuplet-end (nbr) (list (format nil "<tuplet number=\"~A\" type=\"stop\"/>" nbr))) ;; disons que tous les char sont des accents :) (defun accent? (self) (om::get-extras self "char")) (defun cons-xml-articulation (self) (list "<articulations>" (list "<accent default-x=\"-1\" default-y=\"-61\" placement=\"below\"/>") "</articulations>")) (defun cons-xml-groupnotation (self) (list "<notations>" (if (in-group? self) (let* ((lvl (get-grp-level self)) (ratio (getratiogroup (parent self))) (act-note (second lvl)) (norm-note (third lvl)) (indx (car lvl)) (numdeno (getallgroups self)) (numdenom (remove nil (loop for i in numdeno collect (if (not (= 1 (/ (car i) (second i)))) i ) ;;; PB if group (n n) !!! ))) (simpli (/ act-note norm-note))) (if (not (= (/ act-note norm-note) 1)) (cond ((and (om::last-of-group? self) (om::first-of-group? self)) (when (accent? self) (list (cons-xml-articulation self)))) ((and (om::first-of-group? self) (not (om::last-of-group? self))) (remove nil (append (let ((obj self) (indx (+ (length numdenom) 1))) (remove nil (loop for i in (reverse numdenom) append (progn (setf obj (om::parent obj)) (setf indx (- indx 1)) (when (first-of-this-group self obj) (cons-xml-tuplet-start (car i) (second i) (third i) indx)))))) (list (cons-xml-tied-notation self) (when (accent? self) (cons-xml-articulation self)))))) ((and (om::last-of-group? self) (not (om::first-of-group? self))) (remove nil (append (let ((obj self) (indx (+ (length numdenom) 1))) (remove nil (loop for i in numdenom append (progn (setf obj (om::parent obj)) (setf indx (- indx 1)) (when (last-of-this-group self obj) (cons-xml-tuplet-end indx)))))) (list (cons-xml-tied-notation self) (when (accent? self) (cons-xml-articulation self)))))) (t (when (accent? self) (list (cons-xml-articulation self)))) ) (when (or (tied? self) (accent? self)) (remove nil (list (when (tied? self) (cons-xml-tied-notation self)) (when (accent? self) (cons-xml-articulation self))))) )) (when (or (tied? self) (accent? self)) (remove nil (list (when (tied? self) (cons-xml-tied-notation self)) (when (accent? self) (cons-xml-articulation self))))) ) ;;; VEL (cons-xml-velocity self) "</notations>" )) (defun get-parent-measure (self) "Donne la mesure liee a l'obj chord par exemple" (let ((obj (om::parent self))) (loop while (not (om::measure-p obj)) do (setf obj (om::parent obj))) obj)) (defmethod donne-figure ((self om::chord)) (let* ((mesure (get-parent-measure self)) (inside (om::inside mesure)) (tree (om::tree mesure)) (real-beat-val (/ 1 (om::fdenominator (first tree)))) (symb-beat-val (/ 1 (om::find-beat-symbol (om::fdenominator (first tree))))) (dur-obj-noire (/ (om::extent self) (om::qvalue self))) (factor (/ (* 1/4 dur-obj-noire) real-beat-val)) (stem (om::extent self)) (obj self)) (loop while (not (om::measure-p obj)) do (progn (setf stem (* stem (om::extent (om::parent obj)))) (setf obj (om::parent obj)))) (let ((numbeams (om::get-number-of-beams (* symb-beat-val factor)))) (if (listp numbeams) (car numbeams) numbeams )))) (defmethod donne-figure ((self om::r-rest)) (let* ((mesure (get-parent-measure self)) (inside (om::inside mesure)) (tree (om::tree mesure)) (real-beat-val (/ 1 (om::fdenominator (first tree)))) (symb-beat-val (/ 1 (om::find-beat-symbol (om::fdenominator (first tree))))) (dur-obj-noire (/ (om::extent self) (om::qvalue self))) (factor (/ (* 1/4 dur-obj-noire) real-beat-val)) (stem (om::extent self)) (obj self)) (loop while (not (om::measure-p obj)) do (progn (setf stem (* stem (om::extent (om::parent obj)))) (setf obj (om::parent obj)))) (let ((numbeams (om::get-number-of-beams (* symb-beat-val factor)))) (if (listp numbeams) (car numbeams) numbeams )))) (defmethod donne-figure ((self t)) 0) (defun cons-xml-beam (self) (let* ((beamself (donne-figure self)) (beamprev (donne-figure (prv-cont self))) (beamnext (donne-figure (nxt-cont self)))) (remove nil (list (cond ((and (in-group? self) (not (om::first-of-group? self)) (not (om::last-of-group? self)) (> beamself 0)) (cond ((and (> beamprev 0) (> beamnext 0)) "<beam>continue</beam>") ((and (> beamprev 0) (not (> beamnext 0))) "<beam>end</beam>") ((and (not (> beamprev 0)) (> beamnext 0)) "<beam>begin</beam>"))) ((and (om::first-of-group? self) (> beamself 0)) (if (and (in-group? (prv-cont self)) (> beamprev 0) (> beamnext 0) (prv-is-samegrp? self)) "<beam>continue</beam>" "<beam>begin</beam>")) ((and (om::last-of-group? self) (> beamself 0)) (if (and (in-group? (nxt-cont self)) (> beamprev 0) (> beamnext 0) (nxt-is-samegrp? self)) "<beam>continue</beam>" "<beam>end</beam>")) (t NIL)) )) )) (defun prv-cont (self) (om::previous-container self '(chord r-rest))) (defun nxt-cont (self) (om::next-container self '(chord r-rest))) (defun prv-is-samegrp? (self) (let ((prev (prv-cont self))) (equal (parent self) (parent prev)))) (defun nxt-is-samegrp? (self) (let ((next (nxt-cont self))) (equal (parent self) (parent next)))) ;;;--------<PITCH>-------- (defparameter *kascii-note-C-scale* (mapc #'(lambda (x) (setf (car x) (string-upcase (string (car x))))) '((c . :n) (c . :h) (c . :q) (c . :hq) (c . :s) (c . :hs) (c . :qs) (c . :hqs) (d . :n) (d . :h) (d . :q) (d . :hq) (d . :s) (d . :hs) (d . :qs) (d . :hqs) (e . :n) (e . :h) (e . :q) (e . :hq) (f . :n) (f . :h) (f . :q) (f . :hq) (f . :s) (f . :hs) (f . :qs) (f . :hqs) (g . :n) (g . :h) (g . :q) (g . :hq) (g . :s) (g . :hs) (g . :qs) (g . :hqs) (a . :n) (a . :h) (a . :q) (a . :hq) (a . :s) (a . :hs) (a . :qs) (a . :hqs) (b . :n) (b . :h) (b . :q) (b . :hq)))) (defparameter *kascii-note-scales* (list *kascii-note-C-scale*)) (defparameter *kascii-note-alterations* '((:s 1 +100) (:f -1 -100) (:q 0.5 +50) (:qs 1.5 +150) (:-q -0.5 -50) (:f-q -1.5 -150) (:h 0.25 +25) (:hq 0.75 +75) (:hs 1.25 +125) (:hqs 1.75 +175) (:-h -0.25 -25) (:-hq -0.75 -75)(:-hs -1.25 -125)(:-hqs -1.75 -175) (:n 0 0))) (defparameter *note-accidentals* '((0.25 natural-up) (0.5 quarter-sharp) (0.75 sharp-down) (1 sharp) (1.25 sharp-up) (1.5 three-quarters-sharp) (1.75 sharp-three) )) ; (mc->xmlvalues 6548 4) (defun mc->xmlvalues (midic &optional (approx 2)) "Converts <midic> to a string representing a symbolic ascii note." (let* ((kascii-note-scale (car *kascii-note-scales*)) (dmidic (/ 1200 (length kascii-note-scale))) (vals (multiple-value-list (round (om::approx-m midic approx) dmidic))) (midic/50 (car vals)) (cents (cadr vals)) (vals2 (multiple-value-list (floor (* midic/50 dmidic) 1200))) (oct+2 (- (car vals2) 1)) (midic<1200 (cadr vals2)) (note (nth (/ midic<1200 dmidic) kascii-note-scale)) (alt (cdr note))) (list midic (coerce (car note) 'character) (cadr (find alt *kascii-note-alterations* :key 'car)) oct+2))) ;;;--------</PITCH>-------- ;;;--------<NOTE HEADS>-------- (defun notetype (val) (cond ((>= val 2) 2) ((>= val 1/2) 1/2) ((>= val 1/4) 1/4) ((>= val 1/8) 1/8) ((>= val 1/16) 1/16) ((>= val 1/32) 1/32) ((>= val 1/64) 1/64) ((>= val 1/128) 1/128) ((>= val 1/256) 1/256))) (defun note-strict-lp (val) (cond ((>= val 16) (car (om::before&after-bin val))) ((= val 8) 8) ((= val 4) 4) ((= val 2) 2) (t (denominator val)))) (defun get-head-and-points (val) (let* ((haut (numerator val)) (bas (denominator val)) (bef (car (om::before&after-bin haut))) (points 0) (char 1)) (cond ((= bef haut) (setf char (note-strict-lp (/ haut bas))) (setf points 0)) ((= (* bef 1.5) haut) (setf char (note-strict-lp (/ bef bas))) (setf points 1)) ((= (* bef 1.75) haut) (setf char (note-strict-lp (/ bef bas))) (setf points 2))) (if (> val 1) (list (/ char 1) points) (list (/ 1 char) points)) )) ;;;-------</NOTE HEADS>-------- ;;;-------<MISC>-------- (defun cons-xml-text-extras (self) (when (om::get-extras self "text") (list "<lyric default-y=\"-80\" justify=\"left\" number=\"1\">" (list "<syllabic>single</syllabic>" (format nil "<text>~A</text>" (om::thetext (car (om::get-extras self "text")))) "<extend type=\"start\"/>") "</lyric>"))) (defmethod cons-xml-velocity ((self om::chord)) (when (om::get-extras self "vel") (let* ((ex (car (om::get-extras self "vel"))) (schar (or (om::dynamics ex) (om::get-dyn-from-vel (om::get-object-vel (om::object ex)))))) (list (format nil "<dynamics placement=\"below\"><~A/></dynamics>" schar))))) (defmethod cons-xml-velocity ((self om::r-rest)) nil) (defun midi-vel-to-mxml-vel (vel) (round (* (/ vel 90.0) 100))) ;;;================ ;;; CHORD / NOTES ;;;================ ;;; new here in order to put the correct <duration> according to <divisions> of each measure. ;;; for compatibility ;(defmethod get-xml-duration ((self t)) ; (* (/ (om::extent self) 4) (/ 1 (om::qvalue self)))) (defmethod get-xml-duration ((self t)) (* (mesure-divisions (get-parent-measure self)) (/ (om::extent self) (om::qvalue self)))) (defun cons-xml-time-modification (self) (if (and (in-group? self) (not (alone-in-group? self))) (let ((ratio (butlast (get-group-info (parent self))))) (list "<time-modification>" (list (format nil "<actual-notes>~A</actual-notes>" (car ratio)) (format nil "<normal-notes>~A</normal-notes>" (cadr ratio))) "</time-modification>")) NIL)) (defmethod cons-xml-expr ((self om::chord) &key free key (approx 2) part) (let* (;; (dur free) (dur (if (listp free) (car free) free)) (head-and-pts (get-head-and-points dur)) (note-head (cadr (find (car head-and-pts) *note-types* :key 'car))) (nbpoints (cadr head-and-pts)) (durtot (get-xml-duration self)) ;;; !!!! (inside (om::inside self))) (loop for note in inside for i = 0 then (+ i 1) append (let* ((note-values (mc->xmlvalues (om::midic note) approx)) (step (nth 1 note-values)) (alteration (nth 2 note-values)) (octave (nth 3 note-values))) (list (format nil "<note dynamics=\"~D\">" (midi-vel-to-mxml-vel (om::vel note))) (unless (= i 0) "<chord/>") ;;; if this is not the first note in the chord (remove nil (append (list "<pitch>" (remove nil (list (format nil "<step>~A</step>" step) (when alteration (format nil "<alter>~A</alter>" alteration)) (format nil "<octave>~A</octave>" octave))) "</pitch>" (format nil "<duration>~A</duration>" durtot) (cons-xml-tied self) ;;; ties (performance) (let ((headstr (format nil "<type>~A</type>" note-head))) (loop for i from 1 to nbpoints do (setf headstr (concatenate 'string headstr "<dot/>"))) headstr) (when (find alteration *note-accidentals* :key 'car) ;;; accidental (if any) (format nil "<accidental>~A</accidental>" (cadr (find alteration *note-accidentals* :key 'car)))) (format nil "<instrument id=\"P~D-I~D\"/>" part (om::chan note)) ) (cons-xml-time-modification self) (cons-xml-beam self) (cons-xml-groupnotation self) (when (= i 0) (cons-xml-text-extras self)) )) "</note>") )))) (defmethod cons-xml-expr ((self om::r-rest) &key free key (approx 2) part) (let* ((dur (if (listp free) (car free) free)) (head-and-pts (get-head-and-points dur)) (note-head (cadr (find (car head-and-pts) *note-types* :key 'car))) (nbpoints (cadr head-and-pts)) (durtot (get-xml-duration self))) (list "<note>" "<rest/>" (remove nil (list (format nil "<duration>~A</duration>" durtot) (let ((headstr (format nil "<type>~A</type>" note-head))) (loop for i from 1 to nbpoints do (setf headstr (concatenate 'string headstr "<dot/>"))) headstr) (cons-xml-time-modification self) (cons-xml-beam self) (cons-xml-groupnotation self))) "</note>"))) ;;;=================================== ;;; RECURSIVE CONTAINERS (JB 29/09/15) ;;;=================================== (defmethod cons-xml-expr ((self group) &key free key (approx 2) part) (let* ((durtot free) (cpt (if (listp free) (cadr free) 0)) (num (or (get-group-ratio self) (om::extent self))) (denom (find-denom num durtot)) (num (if (listp denom) (car denom) num)) (denom (if (listp denom) (cadr denom) denom)) (unite (/ durtot denom))) (cond ((not (get-group-ratio self)) (loop for obj in (inside self) append (let* (; (dur-obj (/ (/ (om::extent obj) (om::qvalue obj)) (/ (om::extent self) (om::qvalue self)))) (dur-obj (symbolic-dur self))) (cons-xml-expr obj :free dur-obj ;; (* dur-obj durtot) :approx approx :part part)))) ((= (/ num denom) 1) (loop for obj in (inside self) append (let* ((operation (/ (/ (om::extent obj) (om::qvalue obj)) (/ (om::extent self) (om::qvalue self)))) (dur-obj (* num operation))) (cons-xml-expr obj :free (* dur-obj unite) :approx approx :part part))) ;;;; ACHTUNG !! ) (t (let ((depth 0) (rep nil)) (loop for obj in (inside self) do (setf rep (append rep (let* ((operation (/ (/ (om::extent obj) (om::qvalue obj)) (/ (om::extent self) (om::qvalue self)))) (dur-obj (* num operation)) (tmp (multiple-value-list (cons-xml-expr obj :free (list (* dur-obj unite) cpt) :approx approx :part part))) (exp (car tmp))) (when (and (cadr tmp) (> (cadr tmp) depth)) (setf depth (cadr tmp))) exp)))) (values rep (+ depth 1)) )) ))) ;;;; <divisions> problem.... ;;;finale's value to be tested on Sibelius.... (768) ;;;sibelius ' value is 256.... (defun list-pgcd (list) (let ((res (car list))) (loop for deb in (cdr list) do (setf res (pgcd res deb))) res)) (defmethod mesure-divisions ((self om::measure)) (let* ((ratios (tree2ratio (list '? (om-round (list (tree self)))))) (timesig (car (tree self))) (num (car timesig)) (denom (second timesig)) (comp (x-append 1/4 ratios)) ;; 1/4 for now... (1/4 = time-signature denom) (props (om* (om/ 1 (list-pgcd ratios)) comp))) (* num (car props)))) (defmethod cons-xml-expr ((self measure) &key free (key '(G 2)) (approx 2) part) (let* ((mesnum free) (inside (inside self)) (tree (tree self)) (signature (car tree)) ;; (real-beat-val (/ 1 (fdenominator signature))) (symb-beat-val (/ 1 (find-beat-symbol (fdenominator signature))))) (list (format nil "<measure number=\"~D\">" mesnum) (append (remove nil (list "<attributes>" (list (format nil "<divisions>~A</divisions>" (mesure-divisions self)) ;;; (caar (dursdivisions self))) "<key>" (remove nil (list "<fifths>0</fifths>" (if (and approx (= approx 2)) "<mode>major</mode>"))) "</key>" "<time>" (list (format nil "<beats>~D</beats>" (car signature)) (format nil "<beat-type>~D</beat-type>" (cadr signature))) "</time>") (and key (list "<clef>" (list (format nil "<sign>~:@(~a~)</sign>" (car key)) (format nil "<line>~D</line>" (cadr key))) "</clef>" )) "</attributes>")) (loop for obj in inside ;for fig in (cadr (dursdivisions self)) ;;;;;transmetre les note-types append (let* (;; from OM6: ;; (dur-beats (/ (* 1/4 (/ (om::extent obj) (om::qvalue obj))) real-beat-val)) (dur-beats (symbolic-dur obj)) ) (cons-xml-expr obj :free (* symb-beat-val dur-beats) :approx approx :part part) ;;; NOTE: KEY STOPS PROPAGATING HERE ))) "</measure>" "<!--=======================================================-->"))) (defmethod cons-xml-expr ((self voice) &key free (key '(G 2)) (approx 2) part) (declare (ignore free)) (let ((voicenum part) (measures (inside self))) (list (format nil "<part id=\"P~D\">" voicenum) (loop for mes in measures for i = 1 then (+ i 1) collect (cons-xml-expr mes :free i :key key :approx approx :part part)) "<!--=======================================================-->" "</part>"))) (defun mxml-header () (list "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<!DOCTYPE score-partwise PUBLIC \"-//Recordare//DTD MusicXML 1.1 Partwise//EN\" \"http://www.musicxml.org/dtds/partwise.dtd\">")) (defun get-midi-channels (voice) (sort (remove-duplicates (loop for c in (chords voice) append (lchan c))) '<)) (defmethod cons-xml-expr ((self poly) &key free (key '((G 2))) (approx 2) part) (declare (ignore part free)) (let ((voices (inside self))) (list "<score-partwise>" (list "<identification>" (list "<encoding>" (list (concatenate 'string "<software>" *app-name* " " *version-string* "</software>")) "</encoding>") "</identification>") (list "<part-list>" (loop for v in voices for voice-num = 1 then (+ voice-num 1) append (let ((channels (get-midi-channels v))) `( ,(format nil "<score-part id=\"P~D\">" voice-num) (,(format nil "<part-name>Part ~D</part-name>" voice-num)) ,(loop for ch in channels append `( ,(format nil "<score-instrument id=\"P~D-I~D\">" voice-num ch) ;("<instrument-name>Grand Piano</instrument-name>") "</score-instrument>" )) ,(loop for ch in channels append `( ,(format nil "<midi-instrument id=\"P~D-I~D\">" voice-num ch) ,(format nil "<midi-channel>~D</midi-channel>" ch) ; "<midi-program>1</midi-program>") "</midi-instrument>") ) "</score-part>") ) ) "</part-list>") "<!--===================================================================-->" (if (= 1 (length key)) ;;; SAME KEY FOR ALL VOICES (loop for v in voices for i = 1 then (+ i 1) append (cons-xml-expr v :part i :key (car key) :approx approx)) ;;; EACH VOICE HAS A KEY (loop for v in voices for i = 1 then (+ i 1) for k in key append (cons-xml-expr v :part i :key k :approx approx))) "</score-partwise>"))) ;;;=================================== ;;; OM INTERFACE / API ;;;=================================== (defun recursive-write-xml (stream text level) (if (listp text) (loop for elt in text do (recursive-write-xml stream elt (1+ level))) (format stream "~A~A~%" (string+ (make-sequence 'string level :initial-element #\Tab)) text))) (defun write-xml-file (list path) (WITH-OPEN-FILE (out path :direction :output :if-does-not-exist :create :if-exists :supersede) (loop for line in (mxml-header) do (format out "~A~%" line)) (recursive-write-xml out list -1))) (defmethod xml-export ((self t) &key keys approx path name) (declare (ignore (keys approx path name))) nil) (defmethod xml-export ((self voice) &key keys approx path name) (xml-export (make-instance 'poly :voices self) :keys keys :approx approx :path path :name name)) (defmethod xml-export ((self poly) &key keys approx path name) (let* ((pathname (or path (om-choose-new-file-dialog :directory (def-save-directory) :name name :prompt "New XML file" :types '("XML Files" "*.xml"))))) (when pathname (setf *last-saved-dir* (make-pathname :directory (pathname-directory pathname))) (write-xml-file (cons-xml-expr self :free 0 :key keys :approx approx) pathname) pathname))) (defmethod! export-musicxml ((self t) &optional (keys '((G 2))) (approx 2) (path nil)) :indoc '("a VOICE or POLY object" "list of voice keys" "tone subdivision approximation" "a target pathname") :initvals '(nil ((G 2)) 2 nil) :doc " Exports <self> to MusicXML format. <keys> defines the staff <approx> is the microtonal pitch approximation <path> is a pathname to write the file in " (xml-export self :keys keys :approx approx :path path)) ;;;============================================ ;;; OTHER UTILS ;;;============================================ (defmethod make-empty-voice ((signs list)) (let ((mesures (loop for i in signs collect (list i '(-1))))) (make-instance 'voice :tree (list '? mesures)))) (defmethod normalize-poly ((self poly)) "Comlpletes the poly in a manner that all voices got the same number of mesures for MusicXML export" (let* ((voices (inside self)) (signs (get-signatures self)) (lgts (loop for i in signs collect (length i))) (maxlgt (list-max lgts)) (newvoices (loop for i in voices for n in lgts for sg in signs collect (let* ((dif (- maxlgt n)) (comp (last-n sg dif)) (new-vx (make-empty-voice comp))) (concat i new-vx))))) (make-instance 'poly :voices newvoices) ))
36,874
Common Lisp
.lisp
780
34.497436
142
0.482486
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
2ba09439d55a1a9d50b70bda550242d7aca70f6023143ec976e5f71670d686fa
726
[ -1 ]
727
midi.lisp
cac-t-u-s_om-sharp/src/packages/score/import-export/midi.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;======================== ;;; MIDI TO SCORE OBJECTS ;;;======================== (defmethod midinotes-to-chords ((notes list)) (let ((chords nil)) (loop for note in (sort notes #'< :key #'midinote-onset) do (if (and (car chords) (= (midinote-onset note) (onset (car chords)))) ;;; add a note to the last chord (setf (notes (car chords)) (append (notes (car chords)) (list (make-instance 'note :midic (* (midinote-pitch note) 100) :dur (midinote-dur note) :vel (midinote-vel note) :chan (midinote-channel note) :port (midinote-port note)) ))) ;;; new chord (push (make-instance 'chord :onset (midinote-onset note) :lmidic (list (* (midinote-pitch note) 100)) :ldur (list (midinote-dur note)) :lvel (list (midinote-vel note)) :lchan (list (midinote-channel note)) :lport (list (midinote-port note))) chords))) (reverse chords) )) ;;;================================ ;;; DIRECT CONVERSIONS SELF=>SELF ;;;================================ (defmethod objfromobjs ((model midi-track) (target chord-seq)) (set-chords target (midinotes-to-chords (flat (remove nil (get-midi-notes model))))) target) (defmethod objfromobjs ((model midi-track) (target voice)) (let ((cseq (objfromobjs model (make-instance 'chord-seq))) (tempo (or (cadr (car (get-tempomap model))) (tempo target) 60))) (omquantify cseq tempo '(4 4) 8))) (defmethod objfromobjs ((model midi-track) (target multi-seq)) (let ((voices (loop for track in (remove nil (get-midi-notes model)) collect (let ((cseq (make-instance 'chord-seq))) (set-chords cseq (midinotes-to-chords track)) cseq) ))) (setf (obj-list target) voices) target)) (defmethod objfromobjs ((model midi-track) (target poly)) (let ((voices (loop for track in (remove nil (get-midi-notes model)) collect (let ((cseq (make-instance 'chord-seq)) (tempo (or (cadr (car (get-tempomap model))) 60))) (set-chords cseq (midinotes-to-chords track)) (omquantify cseq tempo '(4 4) 8)) ))) (setf (obj-list target) voices) target)) ;;;======================== ;;; SCORE OBJECTS TO MIDI ;;;======================== ;;; get-midievents is the function called by SAVE-AS-MIDI (defmethod get-midievents ((self note) &optional test) (get-midievents (list (make-instance 'MidiEvent :onset (offset self) :ev-type :KeyOn :ev-port (port self) :ev-chan (chan self) :ev-values (list (round (/ (midic self) 100)) (vel self))) (make-instance 'MidiEvent :onset (+ (offset self) (dur self)) :ev-type :KeyOff :ev-port (port self) :ev-chan (chan self) :ev-fields (list (round (/ (midic self) 100)) 0)) ) test)) (defmethod get-midievents ((self chord) &optional test) (loop for n in (notes self) append (let ((evts (get-midievents n test))) (loop for evt in evts do (setf (onset evt) (+ (onset evt) (onset self)))) evts) )) (defmethod get-midievents ((self chord-seq) &optional test) (loop for c in (chords self) append (let ((evts (get-midievents c))) ;;; do the test here: don't pass it inside to the chord/notes (because of the onset-test) (if test (remove-if-not test evts) evts)) )) (defmethod get-midievents ((self multi-seq) &optional test) (let ((evtlist (loop for voice in (obj-list self) for i from 1 append (let ((voice-evts (get-midievents voice))) (loop for evt in voice-evts do (setf (ev-track evt) i)) voice-evts)))) ;;; do the test here: don't pass it inside to the voice (because of the track-test) (get-midievents (sort evtlist #'< :key #'onset) test) )) (defmethod tempo-a-la-noire ((self number)) self) (defmethod tempo-a-la-noire ((tempo list)) (* (second tempo) (/ (first tempo) 1/4))) (defmethod get-midievents ((self voice) &optional test) (let ((evtlist (sort (cons (make-midievent :ev-type :Tempo :ev-date 0 :ev-track 0 :ev-port 0 :ev-chan 1 :ev-values (list (tempo-a-la-noire (tempo self)))) (append (loop for c in (chords self) append (get-midievents c)) (loop for m in (inside self) collect (make-midievent :ev-type :TimeSign :ev-date (beat-to-time (symbolic-date m) (tempo self)) :ev-track 0 :ev-port 0 :ev-chan 1 :ev-values (list (first (first (tree m))) (round (log (second (first (tree m))) 2)) 24 8 ))) )) #'< :key #'onset))) (if test (remove-if-not test evtlist) evtlist) )) ;;; not yet supported (defmethod has-tempo-change ((self voice)) nil) (defmethod get-midievents ((self poly) &optional test) (let* ((tempo (tempo-a-la-noire (tempo (car (obj-list self))))) (evtlist (loop for voice in (obj-list self) for i from 1 do (if (and tempo (or (has-tempo-change voice) (not (= (tempo-a-la-noire (tempo voice)) tempo)))) (setf tempo nil)) append (let ((voice-evts (cdr (get-midievents voice)))) ;;; do not take the voice tempo event (loop for evt in voice-evts do (setf (ev-track evt) i)) voice-evts)))) ;;; 1 global tempo event (setf evtlist (cons (make-midievent :ev-type :Tempo :ev-date 0 :ev-track 0 :ev-port 0 :ev-chan 1 :ev-values (list (or tempo 60))) evtlist)) ;;; do the test here: don't pass it inside to the voice (because of the track-test) (get-midievents (sort evtlist #'< :key #'onset) test) )) ;;;================================ ;;; DIRECT CONVERSION SELF=>SELF ;;;================================ (defmethod objfromobjs ((model score-element) (target midi-track)) (data-track-set-frames target (midievents-to-midinotes (get-midievents model))) target)
8,214
Common Lisp
.lisp
194
29.664948
102
0.473017
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
6b4513de0bdddc4b30d55f983e072999acd3445e4fba1a6468292d17a3339084
727
[ -1 ]
728
multiseq-poly.lisp
cac-t-u-s_om-sharp/src/packages/score/score-objects/multiseq-poly.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;=================================================== ;;; SUPERIMPOSITION OF VOICES ;;; POLY / MULTI-SEQ + MIXED-TYPES ;;;=================================================== (defclass* multi-seq (score-element collection) ((obj-list :initarg :obj-list :initarg :chord-seqs :accessor obj-list :initform nil))) (defclass* poly (multi-seq) ((obj-list :initarg :obj-list :initarg :voices :accessor obj-list :initform nil))) (defmethod chord-seqs ((self multi-seq)) (obj-list self)) (defmethod voices ((self poly)) (obj-list self)) (defmethod voice-type ((self multi-seq)) 'chord-seq) (defmethod voice-type ((self poly)) 'voice) (defmethod inside ((self multi-seq)) (obj-list self)) (defmethod num-voices ((self multi-seq)) (length (obj-list self))) (defmethod get-obj-dur ((self multi-seq)) (apply 'max (cons 0 (mapcar 'get-obj-dur (obj-list self))))) (defmethod initialize-instance :after ((self multi-seq) &rest args) (setf (obj-type self) (voice-type self))) (defmethod objfromobjs ((model multi-seq) (target multi-seq)) (setf (obj-list target) (loop for obj in (obj-list model) collect (objfromobjs obj (make-instance (voice-type target))))) target) ;;; will also work with voice/poly (defmethod objfromobjs ((model chord-seq) (target multi-seq)) (setf (obj-list target) (list (objfromobjs model (make-instance (voice-type target))))) target) (defmethod objfromobjs ((model multi-seq) (target chord-seq)) (if (> (length (obj-list model)) 1) (objfromobjs (reduce #'merger (obj-list model)) target) (objfromobjs (car (obj-list model)) target))) (defmethod initialize-instance ((self multi-seq) &rest args) (call-next-method) (setf (obj-list self) (loop for v in (list! (obj-list self)) when (or (subtypep (type-of v) 'chord-seq) (om-beep-msg "Removing voice of type ~A" (type-of v))) collect v)) self) (defmethod get-voices ((self multi-seq)) (obj-list self)) (defmethod get-voices ((self chord-seq)) (list self)) (defmethod get-voices ((self t)) nil) ;;; e.g. for a chord (defmethod chords ((self multi-seq)) (loop for v in (get-voices self) append (chords v))) (defmethod get-all-chords ((self multi-seq)) (loop for v in (get-voices self) append (get-all-chords v))) ;;;=================================================== ;;; TIME-SEQUENCE METHODS APPLIED TO POLYPHONIES ;;;=================================================== (defmethod time-sequence-update-obj-dur ((self multi-seq)) (loop for voice in (obj-list self) do (time-sequence-update-obj-dur voice))) (defmethod time-sequence-reorder-timed-item-list ((self multi-seq)) (loop for voice in (obj-list self) do (time-sequence-reorder-timed-item-list voice))) (defmethod time-sequence-update-internal-times ((self multi-seq) &optional (interpol-mode :constant-speed) (duration 10000) (modif-time nil)) (loop for voice in (obj-list self) do (time-sequence-update-internal-times voice interpol-mode duration modif-time)))
3,928
Common Lisp
.lisp
80
44.425
106
0.590065
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
adfc33913d6218326ffd28ca0f12f8a785b5ee58551b34e9f91a6d3f0bac7002
728
[ -1 ]
729
tree.lisp
cac-t-u-s_om-sharp/src/packages/score/score-objects/tree.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;; mostly imported from OM6 code (by C. Agon & G. Assayag) ;;; TOOLS TO WORK ON THE RHYTHM-TREE (list/text) REPRESENTATION (in-package :om) ;;;=================================== ;;; A ratio keeping track of denum ;;;=================================== ;;; not sure we need this anymore ? or maybe just to replace (numdenom) #| (defstruct r-ratio (num) (denom)) (defmethod r-ratio-value ((r r-ratio)) (/ (r-ratio-num r) (r-ratio-denom r))) (defmethod r-ratio-* ((r r-ratio) (n number)) (make-r-ratio :num (* (r-ratio-num r) n) :denom (r-ratio-denom r))) (defmethod r-ratio-* ((r r-ratio) (n ratio)) (make-r-ratio :num (* (r-ratio-num r) (numerator n)) :denom (* (r-ratio-denom r) (denominator n)))) |# ;;; get the absolute duration (in proportion) (defun decode-extent (dur) (cond ((listp dur) ;;; e.g. '(4 4) (/ (first dur) (second dur))) ((floatp dur) (round (abs dur))) (t ;;; hopefully this is a number (abs dur)) )) ; (reduce #'(lambda (x y) (+ (abs x) (fullratio y))) '((2 8) (3 8) (4 8) (3 8) (2 8)) :initial-value 0) ; (compute-total-extent '(1 (1 (2 5)) 1 1)) (((8 4) (1 (1 (2 5)) 1 1)) ((4 4) (1 1 5 1)))) ;;; convert to 'better' values (defun convert-extent (extent) (case extent (5 (list 4 1)) (9 (list 8 1)) (10 (list 8 2)) (11 (list 8 3)) (13 (list 12 1)) (17 (list 16 1)) (18 (list 16 2)) (19 (list 16 3)) (20 (list 16 4)) (21 (list 15 6)) (22 (list 16 6)) (23 (list 16 7)) (25 (list 24 1)) (t extent))) ;;; simplify complex subdivisions into tied/simpler ones (defun normalize-tree (tree) (labels ((normalize-recursive (tree) (cond ;;; normalize recursively (the subdiv-part) ((listp tree) (list (list (car tree) (mapcan #'normalize-recursive (cadr tree))))) ((numberp tree) ;;; a leaf (let ((converted-extent (convert-extent (abs (round tree))))) ;;; (1) convert to positive integer just to call convert-extent (if (listp converted-extent) ;;; the leaf was converted (progn (if (plusp tree) ;;; abs did not apply in (1) (progn ;;; tie the second pulse to the first pulse (setf (second converted-extent) (float (second converted-extent))) (when (floatp tree) ;;; the first pulse was already a tie (setf (first converted-extent) (float (first converted-extent))))) ;;; else: (1) abs did invert the sign: restore it (setf (first converted-extent) (- (first converted-extent)) (second converted-extent) (- (second converted-extent)))) converted-extent) ;;; nothing changes (list tree)))) ))) (list (car tree) (mapcan #'normalize-recursive (cadr tree))) )) ;;;============================================= ;;; other pre-processing of rhythm-trees ;;; from OM6 ;;; TOP-LEVEL RULES MARKED WITH -> ;;;============================================= ;Check the syntax of the tree and computes the value of '? if there is in the tree (defun subtree-extent (subtree) ;verifier qui l'appele (cond ((listp subtree) (fullratio (first subtree))) ((floatp subtree) (round (abs subtree))) ((or (ratiop subtree) (integerp subtree)) (abs subtree)))) (defun symbol->ratio (symbol) "expects symbols like |4//4| and returns a list (4 4)" (let ((string (copy-seq (symbol-name symbol)))) (loop for i from 0 to (1- (length string)) when (char= (elt string i) #\/) do (setf (elt string i) '#\Space)) (read-from-string (format nil "(~A)" string)))) (defun resolve-? (list) (cond ((numberp list) list) ((or (numberp (first list)) (listp (first list))) (if (listp (second list)) (list (first list) (mapcar #'resolve-? (second list))) (error (format nil "Invalid Rhythm Tree : ~A" list)))) ((and (symbolp (first list)) (equal (symbol-name (first list)) "?")) (let ((solved (mapcar #'resolve-? (second list)))) (list (reduce #'(lambda (x y) (+ (abs x) (subtree-extent y))) solved :initial-value 0) solved))) ((symbolp (first list)) ; ie: |4//4| (if (listp (second list)) (list (symbol->ratio (first list)) (mapcar #'resolve-? (second list))) (error (format nil "Invalid Rhythm Tree : ~A" list)))) )) ;;;=============================================== ; If only one element ;'((4 4) ((1 (1 1 1)))) = T (defun measure-single? (mes) (= (length (cadr mes)) 1)) ; If only one leaf ;'((4 4) (5)) = T (defun measure-super-single? (mes) (and (measure-single? mes) (numberp (caadr mes)))) (defun replace-num-in-tree (old new) (cond ((minusp old) (* -1 new)) ((floatp old) (* 1.0 new)) (t new))) (defun rw-singleton (list &optional reduction) (cond ((= (length list) 1) (let ((elem (first list))) (if (numberp elem) (if reduction (list (replace-num-in-tree elem reduction)) list) (if reduction (if (= (length (second elem)) 1) (rw-singleton (second elem) reduction) (list (list reduction (rw-singleton (second elem))))) (if (= (length (second elem)) 1) (rw-singleton (second elem) (car elem)) (list (list (first elem) (rw-singleton (second elem))))) )))) (t (loop for item in list append (if (numberp item) (rw-singleton (list item)) (if (= (length (second item)) 1) (rw-singleton (second item) (first item)) ;;; reduction is HERE (list (list (first item) (rw-singleton (second item)))))))))) ; -> (defun resolve-singletons (tree) (let* ((measures tree)) ; (list (car tree) (mapcar #'(lambda (mes) ;pour chaque measure (let ((sign (first mes)) (slist (second mes))) (cond ((measure-super-single? mes) ; un mesure de la forme ((4//4 (n))) avec n n number (list sign (list (replace-num-in-tree (first slist) (first sign))))) ((measure-single? mes) ;un mesure de la forme ((4//4 (g))) ou g est un groupe, donc une liste (let ((group (first slist))) (if (= (length (second group)) 1) (list sign (rw-singleton (second group) (caar mes))) (list sign (list (list (first sign) (rw-singleton (second group)))))))) (t ;un mesure de la forme ((4//4 (r1 r2 ...rn))) ou r est un groupe ou un number (list sign (rw-singleton (second mes))))))) measures) ;) )) ;;;============================================== ;;; returns top-level subdivision of the measure ;'((4 4) (3 (1 (1 1 1)) -5)) = '(3 1 5) (defun measure-repartition (mes) (loop for item in (cadr mes) collect (floor (if (numberp item) (abs item) (abs (car item)))))) (defun modulo3-p (n) (or (zerop ( mod n 3)) (= n 1))) ; -> (defun list-first-layer (tree) (loop for measure-tree in tree collect (if (measure-single? measure-tree) measure-tree (let* ((signature (car measure-tree)) (subdivs (apply '+ (measure-repartition measure-tree))) (ratio1 (/ subdivs (car signature)))) (cond ((and (integerp ratio1) (power-of-two-p ratio1)) measure-tree) ((and (power-of-two-p subdivs) (or (power-of-two-p (car signature)) (and (integerp ratio1) (modulo3-p (car signature))))) measure-tree) ((not (integerp (/ (car signature) subdivs))) (list signature (list (list (car signature) (cadr measure-tree))))) ((and (= (numerator ratio1) 1) (not (power-of-two-p (denominator ratio1))) measure-tree) (list signature (list (list (car signature) (cadr measure-tree))))) (t measure-tree))) ) ) ) ;;;=================================================================== ;;; convert long/uneven durations to even + ties (defun only-one-point (n) (cond ((floatp n) (mapcar 'float (only-one-point (round n)))) (t (if (member n '(0 1 2 3 4 6 8 12 16 32)) ;only for optimization (list n) (let ((bef (bin-value-below n))) (cond ((or (= bef n) (= (* bef 1.5) n) (= (* bef 1.75) n)) (list n)) ((> n (* bef 1.5)) (append (list (+ bef (/ bef 2))) (only-one-point (/ (- n (* bef 1.5)) 1.0)))) (t (cons bef (only-one-point (/ (- n bef) 1.0)))))))))) (defun add-measure-ties (tree) (cond ((numberp tree) (let ((convert (only-one-point (abs tree)))) (if (minusp tree) (setf convert (om* convert -1))) convert)) ((listp tree) (list (list (first tree) (mapcan #'add-measure-ties (second tree))))))) ; -> (defun add-ties-to-tree (tree) (let* ((measures tree)) ;(list (car tree) (mapcar #'(lambda (mes) (list (first mes) (mapcan #'add-measure-ties (second mes)))) measures) ;) )) ;;;=================================================================== ;;; called at voice intialization: (defun format-tree (tree) (list (car tree) (add-ties-to-tree (resolve-singletons (list-first-layer (cadr tree)))))) ;; fullratios are either ratios or lists (num denom) ;; use fullratio function to cast a fullratio to a number ;; use fdenominator and fdenominator to access to a fullratio num and denum (defmethod fullratio ((self list)) (/ (first self) (second self))) (defmethod fullratio ((self number)) self) (defmethod fullratio ((self float)) (round self)) (defmethod fdenominator ((self t)) (denominator (fullratio self))) (defmethod fdenominator ((self list)) (second self)) (defmethod fnumerator ((self t)) (numerator (fullratio self))) (defmethod fnumerator ((self list)) (first self)) (defun simplify-subtrees (subtrees) (let ((lcm (abs (reduce #'lcm subtrees :key #'(lambda (x) (fdenominator (if (listp x) (first x) x)))))) (gcd (abs (reduce #'gcd subtrees :key #'(lambda (x) (fnumerator (if (listp x) (first x) x))))))) (mapcar #'(lambda (x) (if (listp x) (list (* (fullratio (first x)) (/ lcm gcd)) (second x)) (let ((div (* (fullratio x) (/ lcm gcd)))) (if (floatp x) (float div) div)) )) subtrees) ))
11,652
Common Lisp
.lisp
270
35.062963
136
0.522884
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
56460ec066a9aa58d693df1ea083d38e0229b6b82db67559d210724d2a0402cb
729
[ -1 ]
730
score-object.lisp
cac-t-u-s_om-sharp/src/packages/score/score-objects/score-object.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;(defclass container () ; ((inside :accessor inside :initarg :inside :initform nil :documentation "the contents of the container"))) (defclass score-element (schedulable-object) ( ;;; symbolic date and symbolic-dur make sense only if the object is in a context with tempo (symbolic-date :accessor symbolic-date :initarg :symbolic-date :initform nil :documentation "date in symbolic musical time (ratio of beat)") (symbolic-dur :accessor symbolic-dur :initarg :symbolic-dur :initform nil :documentation "duration in symbolic musical time (ratio of beat)") (symbolic-dur-extent :accessor symbolic-dur-extent :initarg :symbolic-dur-extent :initform 0 :documentation "an extension of the duration (used for tied chords)") ;;; parent is not :initarg so that it is not included in om-copy (cyclic references) (parent :accessor parent :initform nil :documentation "the container group, measure or voice of a score element") ;;; approximation of pitch (in division f a tone) used essentially for MIDI playback ;;; is modified by modification of the scale parameter (pitch-approx :accessor pitch-approx :initform 2) (extras :initarg :extras :initform nil :accessor extras :type list :documentation "some 'extra' score-elements attached to this element") (group-ids :initarg :group-ids :initform nil :accessor group-ids :type list :documentation "a list of Ids identifying groups in the score") ;;; bounding-box is a cached graphic information for score display (b-box :accessor b-box :initform nil) )) ;;; this method to be defined according to the different objects' slot names etc. ;;; also allows compat with OM6 naming (defmethod inside ((self score-element)) nil) ;;; only poly has more than 1 voice (defmethod num-voices ((self score-element)) 1) (defstruct b-box (x1) (x2) (y1) (y2)) (defmethod b-box-w (b) (- (b-box-x2 b) (b-box-x1 b))) (defmethod b-box-h (b) (- (b-box-y2 b) (b-box-y1 b)))
2,789
Common Lisp
.lisp
46
56.565217
116
0.643956
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8aadfc4a7342ccc290c98b3e998925f8ce1e66919c80253afac87d0e55535bb0
730
[ -1 ]
731
ratios.lisp
cac-t-u-s_om-sharp/src/packages/score/score-objects/ratios.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ; Code from K.Haddad, O. Sandred and others ;============================================================================ ;============================================================================ ; TREE2RATIO ;============================================================================ ; util: the main function is tree2ratio (defun tree-to-ratios (tree) (loop for mesure in (cadr tree) collect (let* ((signature (car mesure)) (values (cadr mesure)) (ratios (mesure-ratios values))) (om/ (om* ratios (car signature)) (cadr signature))))) (defun mesure-ratios (list) (let ((div (round (loop for elt in list sum (abs (if (listp elt) (car elt) elt)))))) (flat (loop for elt in list collect (if (listp elt) (om* (/ (round (car elt)) div) (mesure-ratios (cadr elt))) (/ (round elt) div))) ))) ;;;------------------------- (defun get-s-from-meas (tree) (if (atom tree) tree (mapcar 'get-s-from-meas (second tree)))) (defun get-pulses (tree) (loop for elt in (cadr tree) collect (flat (get-s-from-meas elt)))) ;;;------------------------- (om::defmethod! tree2ratio ((tree t)) :initvals '((? (((4 4) (1 (1 (1 2 1 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1))))) :indoc '("a rythm tree") :icon 'tree :doc " Converts <tree> into a list of ratio where 1/4 is a quarter note, 1/8 is an eight note etc. " (let* ((res ()) (tree-formatted (if (listp (car tree)) (list (length tree) tree) tree)) (pulses (flat (get-pulses tree-formatted))) (ratios (flat (tree-to-ratios tree-formatted)))) (loop for p in pulses do (if (floatp p) (progn (setf (car res) (+ (car res) (car ratios))) (pop ratios)) (progn (push (car ratios) res) (pop ratios)))) (reverse res))) ;============================================================================ ; TREE2RATIO ;============================================================================ ;;; by O. Sandred ;offset from 1 always!!! Because otherwise the first pause ( -0!) will dissapear. (defun x-dx-pause-ok (x-list) (mapcar '* (mapcar #'(lambda (absdur) (if (> absdur 0) 1 -1)) x-list) (om::x->dx (mapcar 'abs x-list)))) (defun dx-x-pause-ok (starttime x-list) (mapcar '* (append (mapcar #'(lambda (absdur) (if (> absdur 0) 1 -1)) x-list) '(1)) (om::dx->x starttime (mapcar 'abs x-list)))) ;;;----------------------- (defun build-local-times (global-onsets global-start) (mapcar #'(lambda (onset) (if (> onset 0) (- onset (1- global-start)) (+ onset (1- global-start)))) global-onsets)) ;;;----------------------- (defun make-proportional-cell (dur-list) (mapcar #'(lambda (dur) (* dur (apply 'lcm (mapcar 'denominator dur-list)))) dur-list)) #| ;;;----------------------- ;;; NOT USED ANYMORE... since? ; redefinition for non-interger values (defun simplify-proportions (proportion-list) (let* ((list (mapcar 'round proportion-list)) (gcdl (apply 'gcd list))) (mapcar #'(lambda (value) (/ value gcdl)) list))) ; all negative numbers following eachother should be fused to single negative numbers (defun fuse-pauses (proportional-list) (let ((pointer-to-list 0)) (simplify-proportions (loop until (>= pointer-to-list (length proportional-list)) collect (if (< (nth pointer-to-list proportional-list) 0) (let ((this-pause (nth pointer-to-list proportional-list))) (incf pointer-to-list) (loop until (or (>= pointer-to-list (length proportional-list)) (> (nth pointer-to-list proportional-list) 0)) do (progn (incf this-pause (nth pointer-to-list proportional-list)) (incf pointer-to-list))) this-pause) (progn (incf pointer-to-list) (nth (1- pointer-to-list) proportional-list))))))) ;;;----------------------- |# (defun make-sub-tree (local-onset) (list 1 ; (fuse-pauses (cond ((and (or (= (car local-onset) 1) (= (car local-onset) -1))) (make-proportional-cell (x-dx-pause-ok local-onset))) (t (let ((proportional-list (make-proportional-cell (x-dx-pause-ok (cons 1 local-onset))))) (cons (float (first proportional-list)) (cdr proportional-list)))) ))) ; In this function it is possible to define more notations for special cases. (defun better-predefined-subdiv? (sub-tree) (let* ((proportional-list (cadr sub-tree)) (pauses (mapcar #'(lambda (value) (if (< value 0) -1 1)) proportional-list)) (abs-proportional-list (mapcar #'abs proportional-list)) (abs-answer (cond ((equal abs-proportional-list '(2 2 2 3 3)) (list (list 2 (list (first pauses)(second pauses)(third pauses)))(fourth pauses)(fifth pauses))) ((equal abs-proportional-list '(3 3 2 2 2)) (list (first pauses)(second pauses)(list 2 (list (third pauses)(fourth pauses)(fifth pauses))))) ((equal abs-proportional-list '(3 2 2 2 3)) (list (first pauses)(list 2 (list (second pauses)(third pauses)(fourth pauses)))(fifth pauses))) ((equal abs-proportional-list '(3.0 2 2 2 3)) (list (coerce (first pauses) 'float) (list 2 (list (second pauses)(third pauses)(fourth pauses)))(fifth pauses))) ((equal abs-proportional-list '(3 3 4 2)) (list (first pauses)(second pauses)(list 2 (list (* 2 (third pauses))(fourth pauses))))) ((equal abs-proportional-list '(4 2 3 3)) (list (list 2 (list (* 2 (first pauses))(second pauses)))(third pauses)(fourth pauses))) ((equal abs-proportional-list '(2 4 3 3)) (list (list 2 (list (first pauses)(* 2 (second pauses))))(third pauses)(fourth pauses))) ((equal abs-proportional-list '(3 3 2 4)) (list (first pauses)(second pauses)(list 2 (list (third pauses)(* 2 (fourth pauses)))))) ((equal abs-proportional-list '(3 1 1 1)) (list (first pauses)(list 1 (list (second pauses)(third pauses)(fourth pauses))))) ((equal abs-proportional-list '(3.0 1 1 1)) (list (coerce (first pauses) 'float)(list 1 (list (second pauses)(third pauses)(fourth pauses))))) ((equal abs-proportional-list '(1 1 1 3)) (list (list 1 (list (first pauses)(second pauses)(third pauses)))(fourth pauses))) (t proportional-list)))) (list 1 abs-answer))) (defun create-beat (global-onset global-start beat-length) (let ((local-onset (build-local-times global-onset global-start)) tree) (if (not local-onset) (setf local-onset (list (1+ beat-length)))) (if (= (car (last local-onset)) (- -1 beat-length)) (setf local-onset (append (butlast local-onset) (list (1+ beat-length))))) (if (/= (car (last local-onset)) (1+ beat-length)) (setf local-onset (append local-onset (list (1+ beat-length))))) (setf tree (better-predefined-subdiv? (make-sub-tree local-onset))) (if (= (length (cadr tree)) 1) (caadr tree) tree))) (defun fuse-pauses-and-tied-notes-between-beats (measure-tree no-of-beats) (let ((beat-nr 0)) (loop until (>= beat-nr no-of-beats) collect (cond ((and (typep (nth beat-nr measure-tree) 'number) (< (nth beat-nr measure-tree) 0)) (let ((value (nth beat-nr measure-tree))) (incf beat-nr) (loop until (or (typep (nth beat-nr measure-tree) 'list) (>= beat-nr no-of-beats) (and (typep (nth beat-nr measure-tree) 'integer) (> (nth beat-nr measure-tree) 0))) do (progn (decf value (truncate (abs (nth beat-nr measure-tree)))) (incf beat-nr))) value)) ((and (typep (nth beat-nr measure-tree) 'number)) (let ((value (nth beat-nr measure-tree))) (incf beat-nr) (loop until (not (typep (nth beat-nr measure-tree) 'float)) do (progn (incf value (truncate (nth beat-nr measure-tree))) (incf beat-nr))) value)) (t (incf beat-nr) (nth (1- beat-nr) measure-tree)))) )) (defun build-one-measure (local-onset no-of-beats beat-length) (let ((beatlist (om::dx->x 1 (make-list no-of-beats :initial-element beat-length))) tree) (setf tree (fuse-pauses-and-tied-notes-between-beats (loop for beat-nr from 0 to (- (length beatlist) 2) collect (let ((these-events (filter-events-between (nth beat-nr beatlist) (nth (1+ beat-nr) beatlist) local-onset))) ;check if tied pause within subtree - if yes: give startpoint as pause (if (and these-events (/= (abs (first these-events)) (nth beat-nr beatlist)) (get-onsettime-before (nth beat-nr beatlist) local-onset) (> 0 (get-onsettime-before (nth beat-nr beatlist) local-onset))) (setf these-events (append (list (- 0 (nth beat-nr beatlist))) these-events))) ;check if tied pause within subtree - if yes: give startpoint as pause (if (and (not these-events) (get-onsettime-before (nth beat-nr beatlist) local-onset) (> 0 (get-onsettime-before (nth beat-nr beatlist) local-onset))) (setf these-events (list (- 0 (nth beat-nr beatlist))))) (create-beat these-events (nth beat-nr beatlist) beat-length))) no-of-beats)) (list (list no-of-beats (/ 1 beat-length)) tree))) (defun filter-events-between (start stop onsettimes) (let ((no-low-values (member start onsettimes :test #'(lambda (item value) (<= item (abs value)))))) (reverse (member stop (reverse no-low-values) :test #'(lambda (item value) (>= item (abs value))))))) (defun get-onsettime-before (timepoint abs-rhythm) (car (member timepoint (reverse abs-rhythm) :test #'(lambda (item value) (> item (abs value)))))) (defun buildmeasure-seq (abs-rhythms timesigns) (let ((measure-start-points (om::dx->x 1 (mapcar #'(lambda (timesign) (apply '/ timesign)) timesigns)))) (loop for measure from 0 to (1- (length timesigns)) collect (let ((this-seq (filter-events-between (nth measure measure-start-points) (nth (1+ measure) measure-start-points) abs-rhythms)) (this-timesign (nth measure timesigns)) local-onset) ;check if measure starts with tied pause (if (and this-seq (/= (abs (first this-seq)) (nth measure measure-start-points)) (> 0 (get-onsettime-before (nth measure measure-start-points) abs-rhythms))) (setf this-seq (append (list (- 0 (nth measure measure-start-points))) this-seq))) (if (and (not this-seq) (> 0 (get-onsettime-before (nth measure measure-start-points) abs-rhythms))) (setf this-seq (list (- 0 (nth measure measure-start-points))))) (setf local-onset (build-local-times this-seq (nth measure measure-start-points))) (build-one-measure local-onset (car this-timesign) (/ 1 (cadr this-timesign))))))) (defun simple->tree (rhythmseq timesignseq) (let ((abs-rhythms (dx-x-pause-ok 1 (append rhythmseq '(-100))))) (list '? (buildmeasure-seq abs-rhythms timesignseq)))) ;;;----------------------- (defmethod! mktree ((rhythm list) (timesigns list)) :initvals '((1/4 1/4 1/4 1/4) (4 4)) :indoc '("list of integer ratios" "list of time signatures") :doc " Builds a hierarchical rhythm tree from a simple list of note values (<rhythm>). 1/4 is the quarter note. <timesigns> is a list of time signatures, e.g. ( (4 4) (3 4) (5 8) ... ) If a single time signature is given (e.g. (4 4)), it is extended as much as required by the 'rhythm' length. The output rhythm tree is intended for the <tree> input of a 'voice' factory box. " :icon 'tree (if (typep (car timesigns) 'list) (simple->tree rhythm timesigns) (let* ((nbmesreal (* (/ (loop for item in rhythm sum (abs item)) (car timesigns)) (cadr timesigns))) (nbmes (if (integerp nbmesreal) nbmesreal (1+ (truncate nbmesreal))))) (simple->tree rhythm (make-list nbmes :initial-element timesigns))) ))
14,785
Common Lisp
.lisp
266
41.887218
130
0.508087
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
16f01fc8332c6b06fc73579cfd4960714de2ccbb45f0cd24f99a00f67016175a
731
[ -1 ]
732
chord-seq.lisp
cac-t-u-s_om-sharp/src/packages/score/score-objects/chord-seq.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;=================================================== ;;; CHORD-SEQ IS JUST A SPECIAL KIND OF DATA-TRACK ;;;=================================================== ;;; some of the slots :initargs of INTERNAL-CHORD-SEQ are hidden in the graphical interface ;;; (almost) all slot accessors are redefined below in this file (defclass internal-chord-seq (score-element internal-data-track) ((Lmidic :initform '((6000)) :initarg :Lmidic :type list :documentation "pitches (mc): list or list of lists") (Lonset :initform '(0 1000) :initarg :Lonset :type list :documentation "onsets (ms): list") (Ldur :initform '((1000)) :initarg :Ldur :type list :documentation "durations (ms): list or list of lists") (Lvel :initform 100 :initarg :Lvel :documentation "velocities (0-127): list or list of lists") (Loffset :initform 0 :initarg :Loffset :documentation "offsets (ms): list or list of lists") (Lchan :initform 1 :initarg :Lchan :documentation "MIDI channels (1-16): list or list of lists") (Lport :initform nil :initarg :Lport :documentation "MIDI ports: list or list of lists") (Llegato :accessor Llegato :initform nil :initarg :Llegato :initarg :legato :documentation "relative chords duration (0.0-... or NIL)") (name :accessor name :initform nil :initarg :name :documentation "the name of this voice") ) ;; (:default-initargs :default-frame-type 'chord) ) (defmethod initialize-instance ((self internal-chord-seq) &rest args) (setf (default-frame-type self) 'chord) (call-next-method)) ;;; redefines only visible :initargs (defclass* chord-seq (internal-chord-seq) ((Lmidic :initform '((6000)) :initarg :LMidic :type list :documentation "pitches (mc): list or list of lists") (Lonset :initform '(0 1000) :initarg :LOnset :type list :documentation "onsets (ms): list") (Ldur :initform '((1000)) :initarg :Ldur :type list :documentation "durations (ms): list or list of lists") (Lvel :initform 100 :initarg :LVel :documentation "velocities (0-127): list or list of lists")) (:documentation " A sequence of chords. Time is expressed in absolute dates and durations. (For rhytmic structures see the VOICE object.) CHORD-SEQ is defined with: <lmidic>: a list of list of pitches (midicents: 100 = 1 half-tone - 6000 = C3); e.g. '((6000 6500) (6100 6700 7100)). Each pitch list is considered as a chord in the sequence. Single-note sequences can be specified with simple list of pitches, e.g. (6000 61000 6800) ; in this case each pitch will be considered as a single-note chord. <lonsets>: a list of onsets in milliseconds (one for each chord). If the list is shorter than the list of pitch, the last interval is repeated. <ldur>: a list or list of lists values (in milliseconds) expressing chords durations or note durations inside each chord. <lvel>: a list or list of lists of values (MIDI velocity from 0 to 127) expressing chords velocities or note durations inside each chord. <loffset>: a list or list of lists of values (milliseconds) expressing note offsets for the notes inside each chord. <lchan>: a list or list of lists of values (1-16) expressing MIDI channels for each chord or notes inside each chord. <lport>: a list or list of lists of values expressing MIDI ports for each chord or notes inside each chord. <llegato>: list of float numbers > 0.0 (or NIL), indicating the duration of chords as a ratio of inter-onsets time intervals. When applied, the ldur and loffset inputs are ignored, and note durations are set with regard to the legato value. Note: for compatibility, legato can also be specified as an integer [0-100], and is then considered a percentage value. All values (excepted lonsets and legato) are returned (in the box outputs) as list of lists (one value for each note, missing values computed from previous notes or chords). Note: the last value of <lonset> is the end of the sequence (end-time of the longest note). Internally most of these values are just used to build a list of CHORD objects, accessible with GET-CHORDS. ")) (defmethod chords ((self chord-seq)) (data-track-get-frames self)) ;;; redefined for voices and rhythmic objects (defmethod get-all-chords ((self chord-seq)) (chords self)) (defmethod set-chords ((self chord-seq) (chords list)) (data-track-set-frames self chords)) (defmethod inside ((self chord-seq)) (chords self)) (defmethod additional-class-attributes ((self chord-seq)) '(Loffset Lchan Lport Llegato extras)) ;; (defmethod data-track-frames-slot ((self chord-seq)) 'inside) ;;; redefined from time-sequence (defmethod time-sequence-default-duration ((self chord-seq)) 1000) (defmethod save-slot-value ((self chord-seq) slot-name val) (if (and (member slot-name '(lmidic lvel ldur lchan lport loffset llegato extras)) (all-equal val)) (omng-save (car val)) (call-next-method))) (defmethod do-initialize ((self chord-seq) &key Lmidic Lvel Loffset Ldur Lonset Lchan Lport Llegato) (let ((midics (list! Lmidic)) (vels (list! Lvel)) (durs (list! Ldur)) (offsets (list! Loffset)) (chans (list! Lchan)) (ports (list! Lport)) (legatos (list! Llegato)) (onsets (if (listp Lonset) Lonset (list 0 Lonset)))) (let ((chord-list (cond ;;; special cases.. ((list-subtypep midics '(chord)) ;;; this is probably a mistake but we can deal with it ;(om-print "<lmidic> slot initialized with a list of chords." "Warning") (om-copy midics)) ((list-subtypep midics '(note)) ;(om-print "<lmidic> slot initialized with a list of notes." "Warning") (mapcar #'(lambda (n) (ObjfromObjs n (make-instance 'chord))) midics)) (t (loop while (or midics vels durs offsets ports) for midic = (or (pop midics) midic) for vel = (or (pop vels) vel) for dur = (or (pop durs) dur) for offset = (or (pop offsets) offset) for chan = (or (pop chans) chan) for port = (or (pop ports) port) collect (make-instance 'chord :Lmidic (list! midic) :Lvel (list! vel) :Ldur (list! dur) :Loffset (list! offset) :Lchan (list! chan) :Lport (list! port) ))) ))) ;;; end chord-list definition (let* ((sorted-list (sort (mat-trans (list (copy-list (first-n onsets (length chord-list))) (first-n chord-list (length onsets)))) #'< :key 'car)) (unsorted-chords (nthcdr (length onsets) chord-list)) (sorted-chords (append (mapcar #'second sorted-list) unsorted-chords)) (sorted-onsets (mapcar #'first sorted-list))) (loop with defdelay = (if (>= (length sorted-onsets) 2) (- (car (last sorted-onsets)) (car (last sorted-onsets 2))) 1000) ;;; the default delay between two chords if not specified otherwise with defstart = (or (pop sorted-onsets) 0) for chord in sorted-chords for onset = defstart then (or (pop sorted-onsets) (+ onset defdelay)) for next-ontset = (or (first sorted-onsets) (+ onset defdelay)) for legato = (or (pop legatos) legato) do (setf (date chord) onset) do (when (and legato (> legato 0)) (if (integerp legato) (setf legato (/ legato 100.0))) (let ((dur (round (* (- next-ontset onset) legato)))) (loop for note in (notes chord) do (setf (offset note) 0 (dur note) dur)))) ) (set-chords self sorted-chords) self)))) (defmethod initialize-instance ((self chord-seq) &rest initargs) (call-next-method) (when t ; initargs (do-initialize self :Lmidic (slot-value self 'Lmidic) :Lvel (slot-value self 'Lvel) :Ldur (slot-value self 'Ldur) :Lonset (slot-value self 'Lonset) :Loffset (slot-value self 'Loffset) :Lchan (slot-value self 'Lchan) :Lport (slot-value self 'Lport) :Llegato (slot-value self 'Llegato) )) (setf (slot-value self 'Lmidic) nil (slot-value self 'Lvel) nil (slot-value self 'Loffset) nil (slot-value self 'Ldur) nil (slot-value self 'Lonset) nil (slot-value self 'Lchan) nil (slot-value self 'Lport) nil (slot-value self 'Llegato) nil) self) ;;; connect a list of chords to 'self' (defmethod objfromobjs ((model list) (target chord-seq)) (if (list-subtypep model 'chord) (make-instance (type-of target) :lmidic model) nil)) ;======================== ; GET/SET ACCESSORS ;======================== (defmethod Lmidic ((self chord-seq)) (loop for chord in (chords self) collect (Lmidic chord))) (defmethod Lvel ((self chord-seq)) (loop for chord in (chords self) collect (Lvel chord))) (defmethod Ldur ((self chord-seq)) (loop for chord in (chords self) collect (Ldur chord))) (defmethod Loffset ((self chord-seq)) (loop for chord in (chords self) collect (Loffset chord))) (defmethod Lchan ((self chord-seq)) (loop for chord in (chords self) collect (Lchan chord))) (defmethod Lport ((self chord-seq)) (loop for chord in (chords self) collect (Lport chord))) (defmethod Lonset ((self chord-seq)) (nconc (loop for chord in (chords self) collect (item-get-time chord)) (list (get-obj-dur self)))) (defmethod (setf Lmidic) ((Lmidic t) (self chord-seq)) (do-initialize self :Lmidic (list! Lmidic) :Lvel (Lvel self) :Ldur (Ldur self) :Loffset (Loffset self) :Lchan (Lchan self) :Lport (Lport self) :Llegato (Llegato self) :Lonset (Lonset self) )) (defmethod (setf Lvel) ((Lvel t) (self chord-seq)) (do-initialize self :Lmidic (Lmidic self) :Lvel (list! Lvel) :Ldur (Ldur self) :Loffset (Loffset self) :Lchan (Lchan self) :Lport (Lport self) :Llegato (Llegato self) :Lonset (Lonset self) )) (defmethod (setf Loffset) ((Loffset t) (self chord-seq)) (do-initialize self :Lmidic (Lmidic self) :Lvel (Lvel self) :Ldur (Ldur self) :Loffset (list! Loffset) :Lchan (Lchan self) :Lport (Lport self) :Llegato (Llegato self) :Lonset (Lonset self) )) (defmethod (setf Ldur) ((Ldur t) (self chord-seq)) (do-initialize self :Lmidic (Lmidic self) :Lvel (Lvel self) :Ldur (list! Ldur) :Loffset (Loffset self) :Lchan (Lchan self) :Lport (Lport self) :Llegato (Llegato self) :Lonset (Lonset self) )) (defmethod (setf Lonset) ((Lonset t) (self chord-seq)) (do-initialize self :Lmidic (Lmidic self) :Lvel (Lvel self) :Ldur (Ldur self) :Loffset (Loffset self) :Lchan (Lchan self) :Lport (Lport self) :Llegato (Llegato self) :Lonset (list! Lonset) )) (defmethod (setf Lchan) ((Lchan t) (self chord-seq)) (do-initialize self :Lmidic (Lmidic self) :Lvel (Lvel self) :Ldur (Ldur self) :Loffset (Loffset self) :Lchan (list! Lchan) :Lport (Lport self) :Llegato (Llegato self) :Lonset (Lonset self) )) (defmethod (setf Llegato) ((Llegato t) (self chord-seq)) (do-initialize self :Lmidic (Lmidic self) :Lvel (Lvel self) :Ldur (Ldur self) :Loffset (Loffset self) :Lchan (Lchan self) :Lport (Lport self) :Llegato (list! Llegato) :Lonset (Lonset self) )) (defmethod (setf LPort) ((LPort t) (self chord-seq)) (do-initialize self :Lmidic (Lmidic self) :Lvel (Lvel self) :Ldur (Ldur self) :Loffset (Loffset self) :Lchan (Lchan self) :Lport (list! Lport) :Llegato (Llegato self) :Lonset (Lonset self) )) ;;;====================================== ;;; EDITION ;;;====================================== (defmethod remove-from-obj ((self chord-seq) (item t)) nil) (defmethod remove-from-obj ((self chord-seq) (item chord)) (time-sequence-remove-timed-item self item nil)) (defmethod remove-from-obj ((self chord-seq) (item note)) (loop for c in (chords self) do (when (find item (notes c)) (setf (notes c) (remove item (notes c))) (when (null (notes c)) (remove-from-obj self c)) (return t)) ))
14,516
Common Lisp
.lisp
286
40.052448
335
0.57162
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
565ad295d198f8cd90089df4d5a2cc9b2f3f563a7e3f526ba13d26cc71df7c36
732
[ -1 ]
733
chord.lisp
cac-t-u-s_om-sharp/src/packages/score/score-objects/chord.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;============= ;;; NOTE ;;;============= ;;; some of the slots :initargs of INTERNAL-NOTE are hidden in the graphical interface (defclass internal-note (score-element) ((midic :initform 6000 :accessor midic :initarg :midic :type number :documentation "pitch (midicents)") (vel :initform 100 :accessor vel :initarg :vel :type number :documentation "velocity (0-127)") (dur :initform 1000 :accessor dur :initarg :dur :type number :documentation "duration (ms)") (chan :initform 1 :accessor chan :initarg :chan :type integer :documentation "MIDI channel (1-16)") (port :initform nil :accessor port :initarg :port) (offset :initform 0 :accessor offset :initarg :offset) ;;; offset makes sense only if the note is inside a chord )) ;;; redefines only visible :initargs (defclass* note (internal-note) ((midic :initform 6000 :accessor midic :initarg :midic :type number :documentation "pitch (midicents)") (vel :initform 100 :accessor vel :initarg :vel :type number :documentation "velocity (0-127)") (dur :initform 1000 :accessor dur :initarg :dur :type number :documentation "duration (ms)") (chan :initform 1 :accessor chan :initarg :chan :type integer :documentation "MIDI channel (1-16)") ) (:documentation "A simple NOTE defined with : - pitch (midicents: 100 = 1 half-tone - 6000 = C3) - velocity (MIDI velocity from 0 to 127) - duration in milliseconds - MIDI channel")) (defmethod initialize-instance ((self note) &rest args) (when (or (consp (getf args :midic)) (consp (getf args :vel)) (consp (getf args :dur)) (consp (getf args :chan)) (consp (getf args :port))) (error "NOTE attributes can not be lists!")) (call-next-method)) ;;; allow as additional slot (defmethod additional-class-attributes ((self note)) '(port)) (defmethod get-obj-dur ((self note)) (dur self)) ;;;============= ;;; CHORD ;;;============= ;;; some of the slots :initargs of INTERNAL-CHORD are hidden in the graphical interface (defclass internal-chord (data-frame score-element) ((Lmidic :initform '(6000) :initarg :Lmidic :type list :documentation "pitches (list of midicents)") (Lvel :initform '(80) :initarg :Lvel :type list :documentation "velocities (list of values 0-127)") (Loffset :initform '(0) :initarg :Loffset :type list :documentation "offsets (list of values in ms)") (Ldur :initform '(1000) :initarg :Ldur :type list :documentation "durations (list of values in ms)") (Lchan :initform '(1) :initarg :Lchan :type list :documentation "MIDI channels (list of values 0-16)") (Lport :initform nil :accessor Lport :initarg :Lport :type list :documentation "MIDI ports (list of values 0-16)") (notes :initform nil :initarg :notes :accessor notes :type list :documentation "the actual list of notes") )) ;;; redefines only visible :initargs (defclass* chord (internal-chord) ((Lmidic :initform '(6000) :initarg :Lmidic :type list :documentation "pitches (list of midicents)") (Lvel :initform '(80) :initarg :Lvel :type list :documentation "velocities (list of values 0-127)") (Loffset :initform '(0) :initarg :Loffset :type list :documentation "offsets (list of values in ms)") (Ldur :initform '(1000) :initarg :Ldur :type list :documentation "durations (list of values in ms)") ) (:documentation "A CHORD object (set of simultaneous notes) defined with <lmidic>: list of pitches (midicents: 100 = 1 half-tone - 6000 = C3) <lvel>: velocities (MIDI velocity from 0 to 127) <loffset>: offsets (delay of notes after the actual chord onset) <ldur> durations in milliseconds <lchan> MIDI channels for each note <lport> (additional/optional) MIDI port for each note (defaults to the value defined in MIDI preferences) These slots are simpel accessor for initialization. In reality the CHORD contains a list of NOTE instance.")) ;;; allow as additional slots (defmethod additional-class-attributes ((self chord)) '(onset Lchan Lport extras)) (defmethod excluded-slots-from-save ((self chord)) '(notes)) ;;; or just remove its :initarg ? (defmethod Lmidic ((self chord)) (loop for note in (notes self) collect (midic note))) (defmethod Lchan ((self chord)) (loop for note in (notes self) collect (chan note))) (defmethod Lvel ((self chord)) (loop for note in (notes self) collect (vel note))) (defmethod Ldur ((self chord)) (loop for note in (notes self) collect (dur note))) (defmethod Loffset ((self chord)) (loop for note in (notes self) collect (offset note))) (defmethod Lport ((self chord)) (loop for note in (notes self) collect (port note))) (defmethod (setf Lmidic) ((Lmidic t) (self chord)) (do-initialize self :Lmidic (list! Lmidic) :Lvel (Lvel self) :Loffset (Loffset self) :Ldur (Ldur self) :Lchan (Lchan self) :Lport (Lport self))) (defmethod (setf Lchan) ((Lchan t) (self chord)) (do-initialize self :Lmidic (Lmidic self) :Lvel (Lvel self) :Loffset (Loffset self) :Ldur (Ldur self) :Lchan (list! Lchan) :Lport (Lport self))) (defmethod (setf Lvel) ((Lvel t) (self chord)) (do-initialize self :LMidic (Lmidic self) :LVel (list! Lvel) :LOffset (Loffset self) :LDur (Ldur self) :LChan (Lchan self) :LPort (Lport self))) (defmethod (setf Loffset) ((Loffset t) (self chord)) (do-initialize self :LMidic (Lmidic self) :LVel (Lvel self) :LOffset (list! Loffset) :LDur (Ldur self) :LChan (Lchan self) :LPort (Lport self))) (defmethod (setf Ldur) ((Ldur t) (self chord)) (do-initialize self :LMidic (Lmidic self) :LVel (Lvel self) :LOffset (Loffset self) :LDur (list! Ldur) :LChan (Lchan self) :LPort (Lport self))) (defmethod (setf Lport) ((Lport t) (self chord)) (do-initialize self :LMidic (Lmidic self) :LVel (Lvel self) :LOffset (loffset self) :LDur (Ldur self) :LChan (Lchan self) :LPort (list! Lport))) ;; (NoteType 'note)) (defmethod initialize-instance ((self chord) &rest initargs) (call-next-method) (unless (listp (slot-value self 'Lmidic)) (om-print "CHORD object initialized with single value for pitch-list (converting to list)." "Warning") (setf (slot-value self 'Lmidic) (list (slot-value self 'Lmidic)))) ;;; don't do-initialize if initargs was :notes (when (intersection initargs '(:LMidic :LVel :Loffset :LDur :LChan :LPort)) (do-initialize self :Lmidic (slot-value self 'Lmidic) :Lvel (slot-value self 'Lvel) :Loffset (slot-value self 'Loffset) :Ldur (slot-value self 'Ldur) :Lchan (slot-value self 'Lchan) :Lport (slot-value self 'Lport) )) ;;; better to remove these values... ? (setf (slot-value self 'Lmidic) nil (slot-value self 'Lvel) nil (slot-value self 'Loffset) nil (slot-value self 'Ldur) nil (slot-value self 'Lchan) nil (slot-value self 'Lport) nil) self) (defmethod do-initialize ((self chord) &key LMidic LVel Loffset LDur LChan LPort) (let ((lmidic (list! lmidic)) (lvel (list! lvel)) (loffset (list! loffset)) (ldur (list! ldur)) (lchan (list! lchan)) (lport (list! lport))) (setf (notes self) (loop while Lmidic for midic = (or (pop Lmidic) midic) for vel = (or (pop Lvel) vel) for offset = (or (pop Loffset) offset) for dur = (or (pop Ldur) dur) for chan = (or (pop Lchan) chan) for port = (or (pop Lport) port) collect (make-instance 'note :midic (round midic) :vel (round vel) :dur (round dur) :offset (round offset) :chan chan :port port ))) self)) (defmethod objfromobjs ((model note) (target Chord)) (objfromobjs (list model) target)) (defmethod objfromobjs ((model list) (target Chord)) (cond ;;; a list of chords (=> merge) ((list-subtypep model 'chord) (let ((notes (flat (mapcar 'notes model)))) (objfromobjs notes target))) ;;; a list of number (probably a patching mistake, but consider it a list of pitches..) ((list-subtypep model 'number) (make-instance (type-of target) :lmidic model)) ;;; a list of notes ((list-subtypep model 'note) (let ((chord (make-instance (type-of target)))) (setf (notes chord) (mapcar 'clone model)) chord)) (t nil))) ;;; used in score utils and editor hierarchical/recursive calls (defmethod inside ((self chord)) (notes self)) (defmethod chords ((self chord)) (list self)) (defmethod chords ((self note)) (list (make-instance 'chord :notes (list self)))) (defmethod get-notes ((self chord)) (notes self)) (defmethod get-notes ((self note)) (list self)) (defmethod get-notes ((self list)) (loop for item in self append (get-notes item))) (defmethod item-get-duration ((self chord)) (if (notes self) (apply 'max (mapcar 'dur (notes self))) 0))
10,559
Common Lisp
.lisp
224
39.049107
117
0.602336
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
2ff1e9bc34f9f0966f8b340b3df39173ef91114e347d5bb1639d229f4a76e087
733
[ -1 ]
734
extras.lisp
cac-t-u-s_om-sharp/src/packages/score/score-objects/extras.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) (defclass score-extra () () (:documentation "Superclass for score extras: elements attached to chord modifying/completing their representation in score editors.")) (defclass* head-extra (score-extra) ((head-char :initarg :head-char :accessor head-char :initform nil :documentation "SMuFL char code for the note head symbol")) (:documentation "A score extra changing the note head")) (defmethod initialize-instance ((self head-extra) &rest args) (call-next-method) (when (stringp (head-char self)) (setf (head-char self) (read-from-string (head-char self))))) (defmethod format-as-osc ((self head-extra)) `("/head" ,(head-char self))) (defclass* vel-extra (score-extra) ((dx :initarg :dx :accessor dx :initform 0 :type number :documentation "horizontal shift in score units wrt. default position") (dy :initarg :dy :accessor dy :initform 0 :type number :documentation "vertical shift in score units wrt. default position")) (:documentation "A score extra forcing the explicit display of velocity in score editors")) (defclass* text-extra (score-extra) ((dx :initarg :dx :accessor dx :initform 0 :type number :documentation "horizontal shift in score units wrt. default position") (dy :initarg :dy :accessor dy :initform 0 :type number :documentation "vertical shift in score units wrt. default position") (text :initarg :text :accessor text :initform "text" :type string :documentation "the text") (font :initarg :font :accessor font :initform nil :documentation "the text font")) (:documentation "A score extra attaching a text label")) (defmethod format-as-osc ((self text-extra)) `("/text" ,(text self))) (defclass* symb-extra (score-extra) ((dx :initarg :dx :accessor dx :initform 0 :documentation "horizontal shift in score units wrt. default position") (dy :initarg :dy :accessor dy :initform 0 :documentation "vertical shift in score units wrt. default position") (symb-char :initarg :symb-char :accessor symb-char :initform nil :documentation "SMuFL char code for the score symbol")) (:documentation "A score extra attaching a score symbol")) (defmethod initialize-instance ((self symb-extra) &rest args) (call-next-method) (when (stringp (symb-char self)) (setf (symb-char self) (read-from-string (symb-char self))))) (defmethod format-as-osc ((self symb-extra)) `("/symbol" ,(symb-char self))) (defclass* score-marker (score-extra) ((data :initarg :data :accessor data :initform nil :type t :documentation "some data or label attached to the marker")) (:documentation "A score extra marking a segment or cue point in the score")) (defmethod format-as-osc ((self score-marker)) `("/marker" ,.(when (atom (data self)) (list (data self))))) ;;;================================= ;;; EXTRA(S) IN SCORE OBJECTS ;;;================================= ;;; ensure this is always a list (defmethod (setf extras) ((extras score-extra) (self chord)) (setf (extras self) (list extras))) (defmethod initialize-instance :after ((self chord) &rest initargs) (setf (extras self) (list! (extras self)))) (defmethod om-init-instance :after ((self chord-seq) &optional initargs) (let ((extras (slot-value self 'extras))) (when extras (if (listp extras) (loop for extra in extras for chord in (chords self) do (add-extras chord extra nil nil)) (add-extras self extras nil nil)) (setf (slot-value self 'extras) nil) ))) (defmethod (setf extras) ((extras list) (self chord-seq)) (loop for extra in extras for chord in (chords self) do (add-extras chord extra nil nil)) nil) (defmethod extras ((self chord-seq)) (loop for chord in (chords self) collect (extras chord))) ;;;================================= ;;; ATTACH EXTRA(S) TO SCORE OBJECTS ;;;================================= (defmethod* add-extras ((self chord) extras position &optional (newobj t)) :icon :score :initvals '(nil nil nil t) :indoc '("a chord or musical object" "a score-extra or list of score-extras" "a position in the object" "return new object") :doc "Adds 'score-extras' to a chord or a musical object. Score-extras can be objects of the following types: - head-extra (changing the note-heads) - vel-extra (displaying the velocity) - text-extra (attaching a text label) - symb-extra (attaching a score symbol) - score-marker (attaching a marker) If <newobj> is T (default), a new object is returned. If <newobj> is NIL, the modifications apply to the input object. If <self> is a CHORD: - <position> is ignored - All <extras> are attached to <self> If <self> is a sequence (CHORD-SEQ or VOICE): If <position> is a number: - All extra(s) in <extras> are attached to the chord at <position> in <self> If position is NIL: - All extra(s) in <extras> are attached to all the chords in <self> If <position> is a list: - This list is considered to contain the positions (integers) of chords to which will be attached the extra(s) If <extras> is also a list: - Each element in <extras> (can also be a sub-list) is paired to the selected chords in <position> Else, if <extras> is a single element: - A copy of the the same <extra> is attached to the chords pointed by <position>. If <self> is a polyphony (MULTI-SEQ or POLY): If <position> is a plain list: - This list is considered to contain two elements: 1) the index of a voice (starting from 0), and 2) the position of a chord in this voice. - All extra(s) in <extras> are attached to the chord at <position> in <self> If <position> is a list of list - This list is considered to contain the pairs pointing to chords, as in the previous case. If <extras> is a list: - Each element in <extras> (can also be a sub-list) is paired to the selected chords in <position> Else, if <extras> is a single element: - A copy of the the same <extra> is attached to all the chords pointed by <position> If position is NIL: - All extra(s) in <extras> are attached to all the chords in <self> Note: <position> can not be a number in this case. " (declare (ignore position)) (let ((rep (if newobj (om-copy self) self))) (setf (extras rep) (list! extras)) rep)) ;== CHORD-SEQ / VOICE: ; POSITION = NUMBER (defmethod* add-extras ((self chord-seq) extras (position number) &optional (newobj t)) (let* ((rep (if newobj (om-copy self) self)) (chord (nth position (chords rep)))) (when chord (add-extras chord extras nil nil)) rep)) ; POSITION = NON-NULL LIST / EXTRAS = LIST (defmethod* add-extras ((self chord-seq) (extras list) (position cons) &optional (newobj t)) (let ((rep (if newobj (om-copy self) self))) (loop for p in position for extra in extras do (add-extras rep extra p nil)) rep)) ; POSITION = NON-NULL LIST / EXTRAS = SINGLE ELEMENT (defmethod* add-extras ((self chord-seq) (extras score-extra) (position cons) &optional (newobj t)) (let ((rep (if newobj (om-copy self) self))) (loop for p in position do (add-extras rep (om-copy extras) p nil)) rep)) ; POSITION = NIL (defmethod* add-extras ((self chord-seq) extras (position null) &optional (newobj t)) (let ((rep (if newobj (om-copy self) self))) (loop for chord in (chords rep) do (add-extras chord (om-copy extras) nil nil)) rep)) ;== MULTI-SEQ / POLY ; POSITION = NIL (defmethod* add-extras ((self multi-seq) extras (position null) &optional (newobj t)) (let ((rep (if newobj (om-copy self) self))) (loop for v in (inside rep) do (add-extras v extras nil nil)) rep)) ; POSITION = NON-NULL LIST (defmethod* add-extras ((self multi-seq) extras (position cons) &optional (newobj t)) (let ((rep (if newobj (om-copy self) self))) (cond ;;; 1 single chord targeted ((every #'integerp position) (when (> (length position) 2) (om-print "Warning: position list in get-extra should not be of size >2 (voice-num / chord-num)")) (let ((voice (nth (car position) (inside rep)))) (when voice (add-extras voice extras (cadr position) nil)))) ;;; list of chords targeted ((every #'consp position) (if (listp extras) ;;; loop though position and extra lists (loop for pos in position for extra in extras do (add-extras rep extra pos nil)) ;;; all same extra (loop for pos in position do (add-extras rep extras pos nil)) )) (t (om-print "Error unsupported position list in ADD-EXTRAS:") (om-print position) )) rep)) ;;;================================= ;;; GET EXTRAS FROM SCORE OBJECTS ;;;================================= (defmethod* get-extras ((self chord) extra-type) :icon :score :initvals '(nil nil) :menuins '((1 (("all" nil) ("head" head-extra) ("vel" vel-extra) ("text" text-extra) ("symbol" symb-extra) ("marker" score-marker)))) :indoc '("a chord or musical object" "specific type(s) of score-extra") :doc "Returns 'score-extras' from a chord or a musical object." (if extra-type (remove-if-not #'(lambda (e) (find (type-of e) (list! extra-type) :test #'subtypep)) (extras self)) (extras self))) (defmethod* get-extras ((self chord-seq) extra-type) (loop for c in (chords self) append (get-extras c extra-type))) (defmethod* get-extras ((self multi-seq) extra-type) (loop for v in (inside self) append (get-extras v extra-type))) ;;;================================= ;;; REMOVE EXTRAS FROM SCORE OBJECTS ;;;================================= (defmethod* remove-extras ((self chord) extra-type &optional newobj) :icon :score :initvals '(nil nil nil) :menuins '((1 (("all" nil) ("head" head-extra) ("vel" vel-extra) ("text" text-extra) ("symbol" symb-extra) ("marker" score-marker)))) :indoc '("a chord or musical object" "specific type(s) of score-extra" "return new object") :doc "Removes 'score-extras' from a chord or a musical object." (let ((rep (if newobj (om-copy self) self))) (setf (extras rep) (if extra-type (remove-if #'(lambda (e) (find (type-of e) (list! extra-type) :test #'subtypep)) (extras self)) nil)) rep)) (defmethod* remove-extras ((self chord-seq) extra-type &optional newobj) (let ((rep (if newobj (om-copy self) self))) (loop for chord in (chords rep) do (remove-extras chord extra-type)) rep)) (defmethod* remove-extras ((self multi-seq) extra-type &optional newobj) (let ((rep (if newobj (om-copy self) self))) (loop for v in (inside rep) do (remove-extras v extra-type)) rep)) ; TODO: ATTACH/REMOVE/EDIT INSIDE SCORE EDITOR
11,799
Common Lisp
.lisp
248
42.370968
137
0.636959
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1e3ae1c54a216af26b60a5ad0d8d135c6264a1eb88d8acc2ba9df4dddbc020f7
734
[ -1 ]
735
voice.lisp
cac-t-u-s_om-sharp/src/packages/score/score-objects/voice.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) (defclass rhythmic-object (score-element) ((tree :initform '(1 (1 1 1 1)) :accessor tree :initarg :tree :type list :documentation "a rhythm tree") (inside :accessor inside :initform nil :documentation "internal hierarchical structure"))) (defmethod additional-slots-to-copy ((self rhythmic-object)) (append (call-next-method) '(inside))) (defmethod deep-search ((self rhythmic-object) obj) (if (find obj (inside self)) t (let ((found-inside nil)) (loop for sub in (inside self) while (not found-inside) do (setf found-inside (deep-search sub obj))) found-inside))) (defmethod deep-search ((self t) obj) nil) (defmethod (setf inside) ((newlist list) (self score-element)) (loop for elt in newlist do (setf (parent elt) self)) (setf (slot-value self 'inside) newlist)) ;;;=================================================== ;;; VOICE IS A CHORD-SEQ WHOSE STRUCTURE AND TIMING IS RULED BY A TREE ;;;=================================================== ;;; tree (text) is used to build the r-struct ;;; .. and set dates and durations to the chords ;;; r-struct is a hierarchical structure of containers (measures/groups) whose leaves are either chords or rests ;;; the chords in r-struct are simple references to the time-sequence items (defclass* voice (chord-seq rhythmic-object) ((tree :initform '(1 (((4 4) (-1 -1 -1 -1)))) :accessor tree :initarg :tree :type list :documentation "a rhythm tree (list of measure-rythm-trees)") (Lmidic :initform nil :initarg :Lmidic :initarg :chords :type list :documentation "pitches (mc)/chords: list or list of lists") (tempo :accessor tempo :initform 60 :initarg :tempo :documentation "a tempo value or tempo-map") (inside :accessor inside :initform nil :documentation "internal hierarchical structure") )) (defmethod additional-class-attributes ((self voice)) '(lvel loffset lchan lport extras)) (defmethod get-object-slots-for-undo ((self voice)) (append (call-next-method) '(tree tempo))) (defmethod restore-undoable-object-state ((self voice) (state list)) (call-next-method) (build-voice-from-tree self) self) (defmethod objFromObjs ((model chord-seq) (target voice)) (omquantify model 60 '(4 4) 8)) (defmethod get-metrics ((self voice)) (loop for measure-tree in (cadr (tree self)) collect (car measure-tree))) ;;; catch-up with default behaviour ;;; => in principle this is by default for exact same type ;(defmethod objFromObjs ((model voice) (target voice)) ; (clone-object model target)) (defmethod objFromObjs ((model voice) (target chord-seq)) (clone-object model target)) ;;; not fall back on the previous one (would loose extras) (defmethod objFromObjs ((model voice) (target voice)) (om-copy model)) ;;; SOME ADDITIONAL CLASSES TO BUILD RHYTHMIC STRUCTURES: (defclass measure (rhythmic-object) () (:default-initargs :tree '((4 4) (-1)))) (defclass group (rhythmic-object) ((numdenom :accessor numdenom :initarg :numdenom :initform nil))) (defclass continuation-chord (score-element) ((previous-chord :accessor previous-chord :initarg :previous-chord :initform nil :documentation "the tied previous element"))) (defmethod get-real-chord ((self continuation-chord)) (get-real-chord (previous-chord self))) (defmethod get-real-chord ((self chord)) self) (defclass r-rest (score-element) ()) (defmethod get-real-chord ((self r-rest)) nil) (defclass grace-note (score-element) ()) ;;; gets chords in the rhythmic structure ;;; !! different from GET-CHORDS (defmethod get-all-chords ((self rhythmic-object)) (loop for obj in (inside self) append (get-all-chords obj))) (defmethod get-all-chords ((self voice)) (loop for obj in (inside self) append (get-all-chords obj))) (defmethod get-all-chords ((self chord)) (list self)) (defmethod get-all-chords ((self continuation-chord)) (list self)) (defmethod get-all-chords ((self r-rest)) (list self)) (defmethod get-all-chords ((self t)) nil) (defmethod get-notes ((self r-rest)) nil) (defmethod get-notes ((self continuation-chord)) (get-notes (get-real-chord self))) (defmethod get-notes ((self group)) (loop for element in (inside self) append (get-notes element))) (defmethod get-notes ((self t)) nil) ; (format-tree '(((5 3) (1 3 (4 (3 1 (2 (8 1)) 2)))))) (defmethod get-obj-dur ((self voice)) (let ((last-element (last-elem (get-all-chords (last-elem (inside self)))))) (if last-element (beat-to-time (+ (symbolic-date last-element) (symbolic-dur last-element)) (tempo self)) 0))) (defmethod initialize-instance ((self voice) &rest initargs) (call-next-method) (when (list-subtypep (tree self) '(ratio number)) ;;; probably a list of ratios (setf (tree self) (mktree (tree self) '(4 4)))) ;;; compat OM 6 (temp) (when (listp (tempo self)) ;; e.g. ((1/4 60) ...) (setf (tempo self) (cadr (car (tempo self))))) ;(when (atom (car (tree self))) ; ;;; probably "old-formatted" RT, with "?" etc. ; (setf (tree self) (cadr (tree self)))) (unless (numberp (car (tree self))) (if (atom (car (tree self))) ;;; => probably "?" (setf (tree self) (list (length (cadr (tree self))) (cadr (tree self)))) (setf (tree self) (list (length (tree self)) (tree self))))) (set-tree self (slot-value self 'tree)) self) (defmethod set-tree ((self voice) (tree list)) (setf (slot-value self 'tree) (format-tree (normalize-tree tree))) (build-voice-from-tree self)) (defmethod build-voice-from-tree ((self voice)) (unless (chords self) (set-chords self (list (make-instance 'chord :lmidic '(6000))))) (build-rhythm-structure self (chords self) -1) (set-timing-from-tempo (chords self) (tempo self))) (defmethod om-init-instance ((self voice) &optional args) (let ((tempo (find-value-in-kv-list args :tempo))) (when tempo (set-timing-from-tempo (chords self) tempo)) self)) (defun beat-to-time (beat tempo) (let ((whole-dur (* 4 (/ 60000 tempo)))) (round (* beat whole-dur)))) (defun set-timing-from-tempo (chords tempo) (loop for c in chords do (setf (date c) (beat-to-time (symbolic-date c) tempo)) (setf (ldur c) (list (- (beat-to-time (+ (symbolic-date c) (symbolic-dur c) (symbolic-dur-extent c)) tempo) (beat-to-time (symbolic-date c) tempo) ))) )) (defmethod build-rhythm-structure ((self voice) chords n &key last-chord) (let ((curr-beat 0) (curr-n-chord n) (curr-last-chord last-chord)) (setf (inside self) (loop for m-tree in (cadr (tree self)) collect (let* ((m-dur (decode-extent (car m-tree))) (mesure (make-instance 'measure :tree m-tree :symbolic-date curr-beat :symbolic-dur m-dur ))) (setq curr-beat (+ curr-beat m-dur)) (multiple-value-setq (curr-n-chord curr-last-chord) (build-rhythm-structure mesure chords curr-n-chord :last-chord curr-last-chord)) mesure))) ;;; cut the end of the chords list (set-chords self (first-n (chords self) (1+ curr-n-chord))) (values curr-n-chord curr-last-chord))) ;;; the duration of a tree (defmethod tree-extent ((tree list)) (decode-extent (car tree))) ;;; the duration of a leaf (defmethod tree-extent ((tree number)) (decode-extent tree)) ;;; measure or group (defmethod build-rhythm-structure ((self rhythmic-object) chords n &key last-chord) (let ((total-dur (apply '+ (mapcar 'tree-extent (cadr (tree self))))) ;;; sum of subdivisions (curr-beat (symbolic-date self)) (s-dur (symbolic-dur self)) (curr-n-chord n) (curr-last-chord nil) (grace-note-offset 100) (current-grace-notes 0)) ;(print (list "build" self (symbolic-dur self))) (setf (inside self) ;;; with grace notes (subtree = 0) we can collect a NIL (remove nil (loop for subtree in (cadr (tree self)) collect (if (listp subtree) ;;; SUBGROUP (let* ((relative-dur (/ (car subtree) total-dur)) (sub-dur (* s-dur relative-dur)) (tree (list sub-dur (simplify-subtrees (cadr subtree)))) (group (make-instance 'group :tree tree :symbolic-date curr-beat :symbolic-dur sub-dur ))) ;;; set the "numdenom" indicator ;;; direct from OM6: probably possible to simplify ;; (print (list "group:" subtree "=>" (tree group) (symbolic-dur group))) (let* ((group-ratio (get-group-ratio (tree group))) (group-s-dur (symbolic-dur group)) (num (or group-ratio group-s-dur)) (dur-for-denom (if (= group-s-dur s-dur) group-s-dur (/ group-s-dur s-dur))) (denom (find-denom num dur-for-denom))) (when (listp denom) (setq num (car denom)) (setq denom (second denom))) (setf (numdenom group) (cond ((not group-ratio) nil) ((= (/ num denom) 1) nil) (t (reduce-num-den num denom)))) ) (setq curr-beat (+ curr-beat sub-dur)) (multiple-value-setq (curr-n-chord curr-last-chord) (build-rhythm-structure group chords curr-n-chord :last-chord (or curr-last-chord last-chord))) group) ;;; ATOM (leaf) ;;; subtree is a NUMBER (let ((sub-dur (* (symbolic-dur self) (/ (decode-extent subtree) total-dur)))) ; (print (list "CHORD" curr-n-chord subtree)) (let ((object (cond ;;; REST ((minusp subtree) (make-instance 'r-rest :symbolic-date curr-beat :symbolic-dur sub-dur )) ;;; CONTINUATION CHORD ((and (floatp subtree) ;;; keep current-chord in chord-list (important: same reference!) (>= curr-n-chord 0)) ;;; just to prevent error when a continuation chord has no previous chord (let* ((real-chord (nth curr-n-chord chords)) (cont-chord (make-instance 'continuation-chord))) (setf ;;; extends the duration of the main chord (symbolic-dur-extent real-chord) (+ (symbolic-dur-extent real-chord) sub-dur) (previous-chord cont-chord) (or curr-last-chord last-chord) (symbolic-date cont-chord) curr-beat (symbolic-dur cont-chord) sub-dur) (setq curr-last-chord cont-chord) cont-chord)) ;;; GRACE-NOTE ((zerop subtree) ;;; grace note works only if hey are less than the number of notes in the chord +1 ! (if curr-last-chord ;;; previous chord in this group ;;; post-grace notes: add them to this chord (loop with first-n = nil for n in (reverse (notes curr-last-chord)) while (not first-n) do (if (plusp (offset n)) ;; there's alraedy an offset (setf (offset n) (+ (offset n) grace-note-offset)) (progn (when (minusp (offset n)) ;;; this was already a grace note !! (om-beep-msg "Warning: too many (post) grace notes for chord!")) (setf (offset n) grace-note-offset) (setf first-n t))) finally (unless first-n (om-beep-msg "Warning: too many grace notes for chord!"))) ;;; pre-grace notes: store them until we get the chord (setf current-grace-notes (1+ current-grace-notes)) ) NIL ;;; don't collect a grace-note ) ;;; CHORD (t ;;; get the next in chord list (when (and (floatp subtree) (< curr-n-chord 0)) (om-print "Tied chord has no previous chord. Will be converted to a normal chord." "Warning")) (setq curr-n-chord (1+ curr-n-chord)) (let ((real-chord (nth curr-n-chord chords))) (unless real-chord ;;; chord-list exhausted: repeat the last one as needed to finish the tree (setq real-chord (or (clone (car (last chords))) (make-instance 'chord :lmidic '(6000)))) (setf (loffset real-chord) (list 0)) (pushr real-chord chords)) (setf (symbolic-date real-chord) curr-beat (symbolic-dur real-chord) sub-dur (symbolic-dur-extent real-chord) 0 ;;; could have been cloned from previous ) ;;; add the "pre" grace-notes (when (plusp current-grace-notes) (when (>= current-grace-notes (length (notes real-chord))) (om-beep-msg "Warning: too many (pre) grace notes for chord!")) (loop for n in (notes real-chord) for i = current-grace-notes then (- i 1) while (> i 0) do (setf (offset n) (- (* i grace-note-offset))))) (setq curr-last-chord real-chord) real-chord)) ))) ;;; udate curr-beat for the general loop (setq curr-beat (+ curr-beat sub-dur)) object) )) )) ) (values curr-n-chord (or curr-last-chord last-chord)) )) ;;;=============================================== ;;; UTILS FOR "NUMDENOM" COMPUTATION ;;; direct from OM6 ;;;=============================================== (defmethod get-group-ratio (tree) (let ((extent (car tree)) (addition (loop for item in (second tree) sum (floor (abs (if (listp item) (car item) item)))))) (cond ((= (round (abs addition)) 1) nil) ((integerp (/ extent addition)) addition) ;; never happens (?) ((and (integerp (/ extent addition)) (or (power-of-two-p (/ extent addition)) (and (integerp (/ addition extent)) (power-of-two-p (/ addition extent))))) nil) (t addition)))) (defun bin-value-below (num) (let ((cp2 (next-double-of-n num 2))) (if (= num cp2) num (/ cp2 2)))) (defun closest-double-of (num of) (let* ((high (next-double-of-n num of)) (low (/ high 2))) (if (< (- high num) (- num low)) high low))) (defun find-beat-symbol (den) (bin-value-below den)) ; Find the right denom to ratio of tuplet. (defun find-denom (num durtot) (cond ((or (is-binaire? durtot) (power-of-two-p durtot)) (get-denom-bin num)) ((is-ternaire? durtot) (get-denom-ter num)) (t (get-denom-other durtot num)))) ;;; is (denominator dur) a power of 2 (defun is-binaire? (dur) (and (= (numerator dur) 1) (= (denominator dur) (next-double-of-n (denominator dur) 2)) ;;; next-pwr-of-2, or closest ? )) (defun is-ternaire? (durtot) (and (= 3 (numerator durtot)) (is-binaire? (/ 1 (denominator durtot))) )) (defmethod get-denom-bin (num) (case num (3 2) (4 4) (5 4) (6 4) (7 4) (8 8) (9 8) (10 8) (11 8) (12 8) (13 8) (14 8) (15 16) (16 16) (otherwise (closest-double-of num 2)))) (defmethod get-denom-ter (num) (case num (2 3) (3 3) (4 3) (5 6) (6 6) (7 6) (8 6) (9 6) (10 12) (11 12) (12 12) (13 12) (14 12) (15 12) (16 12) (17 12) (otherwise (closest-double-of num 3)))) ; if the answer is a list, the num should be changed in the caller-group (defun get-denom-other (dur num) (let ((durtot (numerator dur))) (cond ((= (+ num 1) durtot) durtot) ((= num durtot) num) ((< num durtot) (list (* num 2) durtot)) ;((< num (- (* 2 durtot) 1)) durtot) ;; OJO OJO ESTOS CASOS HAY QUE VERLOS CON KARIM (t (closest-double-of num durtot)) ))) ;; returns the smallest multiples of 2 (e.g. 14/8 => 7/4) (defun reduce-num-den (num den) (if (and (evenp num) (evenp den)) (reduce-num-den (/ num 2) (/ den 2)) (list num den))) ;;;=============================================== ;;; BUILD TREE FREOM MEASURE ;;;=============================================== (defmethod build-tree ((self voice) dur) (declare (ignore dur)) (list (length (inside self)) (loop for m in (inside self) collect (build-tree m (car (tree m)))) )) (defmethod build-tree ((self rhythmic-object) dur) (list dur (let* ((proportions (mapcar #'symbolic-dur (inside self))) (pgcd (reduce #'pgcd (cons 1 proportions))) (simple-propotions (om/ proportions pgcd))) (loop for element in (inside self) for d in simple-propotions collect (build-tree element d)) ) )) (defmethod build-tree ((self chord) dur) dur) (defmethod build-tree ((self continuation-chord) dur) (float dur)) (defmethod build-tree ((self r-rest) dur) (- dur)) ;;;=============================================== ;;; FOR VOICE IT IS IMPORTANT TO KEEP A REFERENCE TO THE SAME CHORDS AS THEY ARE ;;; CONTAINED IN BOTH THE TIME-SEQUENCE, AND THE RHYTMIC STRUCTURE ;;;=============================================== ;;; continue if the lists are exhausted ?? (defmethod (setf Lmidic) ((Lmidic list) (self voice)) (loop for midics in lmidic for c in (chords self) do (setf (lmidic c) (list! midics)) )) (defmethod (setf Lvel) ((Lvel list) (self voice)) (loop for vels in lvel for c in (chords self) do (setf (lvel c) (list! vels)) )) (defmethod (setf Loffset) ((Loffset list) (self voice)) (loop for offsets in Loffset for c in (chords self) do (setf (loffset c) (list! offsets)) )) (defmethod (setf Lchan) ((Lchan list) (self voice)) (loop for chans in Lchan for c in (chords self) do (setf (lchan c) (list! chans)) )) (defmethod (setf LPort) ((LPort list) (self voice)) (loop for ports in LPort for c in (chords self) do (setf (lport c) (list! ports)) )) (defmethod (setf tree) ((tree list) (self voice)) (set-tree self tree)) ;;;====================================== ;;; EDITION ;;;====================================== ;;; REMOVE A CHORD / REPLACE WITH A REST (defmethod remove-from-obj ((self voice) (item chord)) ;;; turn all continuation chords into rests (let ((same-cont-chords nil)) (loop for c in (get-all-chords self) when (typep c 'continuation-chord) do (when (or (equal (previous-chord c) item) (find (previous-chord c) same-cont-chords)) (push c same-cont-chords))) (loop for c in same-cont-chords do (let ((rest (clone-object c (make-instance 'r-rest)))) (setf (inside (parent c)) (substitute rest c (inside (parent c)))) )) ) ;;; change the chord itself into a rest ;; (change-class item 'r-rest) (setf (inside (parent item)) (substitute (clone-object item (make-instance 'r-rest)) item (inside (parent item)))) ;;; compute new tree (let ((new-tree (build-tree self nil))) ;;; remove the chord (time-sequence-remove-timed-item self item nil) ;;; rebuild the structure (set-tree self new-tree) )) (defmethod remove-from-obj ((self voice) (item group)) ;;; turn all continuation chords into rests (let ((subst-rest (make-instance 'r-rest :symbolic-dur (symbolic-dur item) :symbolic-date (symbolic-date item) ))) (loop for c in (get-tpl-elements-of-type item 'chord) do ;;; untied continuation chords and remove the chord (let ((cont-c (find c (get-tpl-elements-of-type self 'continuation-chord) :key #'previous-chord))) (when cont-c (untie-chord self cont-c)) (time-sequence-remove-timed-item self c nil) )) (replace-in-obj self item subst-rest) (set-tree self (build-tree self nil)) )) (defmethod remove-from-obj ((self voice) (item measure)) (loop for c in (get-tpl-elements-of-type item 'chord) do ;;; untied continuation chords and remove the chord (let ((cont-c (find c (get-tpl-elements-of-type self 'continuation-chord) :key #'previous-chord))) (when cont-c (untie-chord self cont-c)) (time-sequence-remove-timed-item self c nil) )) (setf (inside self) (remove item (inside self))) (set-tree self (build-tree self nil)) ) ;;; SUBSTITUTIONS (defmethod replace-in-obj ((self score-element) (old t) (new t)) nil) ;;; replace an element (defmethod replace-in-obj ((self rhythmic-object) (old score-element) (new score-element)) (if (find old (inside self)) (setf (inside self) (substitute new old (inside self))) (loop for sub in (inside self) do (replace-in-obj sub old new)) )) ;;; replace a list by a single element (=grouping) (defmethod replace-in-obj ((self rhythmic-object) (old list) (new score-element)) (let ((pos (search old (inside self)))) (if pos (setf (inside self) (append (subseq (inside self) 0 pos) (list new) (subseq (inside self) (+ pos (length old))))) (loop for sub in (inside self) do (replace-in-obj sub old new)) ))) ;;; replace a single element by a list (=ungrouping) (defmethod replace-in-obj ((self rhythmic-object) (old score-element) (new list)) (let ((pos (position old (inside self)))) (if pos (setf (inside self) (append (subseq (inside self) 0 pos) new (subseq (inside self) (1+ pos)))) (loop for sub in (inside self) do (replace-in-obj sub old new)) ))) ;;; replace a list by a list (=useful?) (defmethod replace-in-obj ((self rhythmic-object) (old list) (new list)) (let ((pos (search old (inside self)))) (if pos (setf (inside self) (append (subseq (inside self) 0 pos) new (subseq (inside self) (+ pos (length old))))) (loop for sub in (inside self) do (replace-in-obj sub old new)) ))) ;;; TIE/UNTIE ;;; converts chord into continuation-chord (defmethod tie-chord ((self voice) (c chord) &optional rebuild) (let ((pos (position c (chords self)))) (if (= pos 0) ;; can not be tied to previous c (let ((new-c (make-instance 'continuation-chord :previous-chord (nth (1- pos) (chords self)) ))) (setf (symbolic-date new-c) (symbolic-date c) (symbolic-dur new-c) (symbolic-dur c)) (replace-in-obj self c new-c) ; remove the chord (it's not a "real" chord anymore) (time-sequence-remove-timed-item self c nil) ; rebuild the structure (when rebuild (set-tree self (build-tree self nil))) ;;; we are not able to return new-c as the rhytm-structure has been re-build anyway (unless rebuild new-c)) ))) ;;; converts continuation-chord into chord (defmethod untie-chord ((self voice) (c continuation-chord) &optional rebuild) (let* ((ref-chord (get-real-chord c)) (time-pos (beat-to-time (symbolic-date c) (tempo self))) (new-c (clone-object ref-chord))) (setf (onset new-c) time-pos (symbolic-date new-c) (symbolic-date c) (symbolic-dur new-c) (symbolic-dur c)) (replace-in-obj self c new-c) ; creates anew "real" chord in teh sequence (time-sequence-insert-timed-item-and-update self new-c (find-position-at-time self time-pos)) ;;; rebuild the structure (when rebuild (set-tree self (build-tree self nil))) new-c)) ;;; does a list of ties/unties (defmethod tie-untie ((self voice) (clist list)) (let* ((cont-chords (remove-if-not #'(lambda (c) (typep c 'continuation-chord)) clist)) (chords (remove-if-not #'(lambda (c) (typep c 'chord)) clist))) (loop for cc in cont-chords do (untie-chord self cc nil)) (loop for c in chords do (tie-chord self c nil)) ;;; rebuild the structure (set-tree self (build-tree self nil)) nil)) ;;; GROUP (defmethod group-objects ((self t) (in-voice voice)) nil) (defmethod group-objects ((self rhythmic-object) (in-voice voice)) (let* ((chords (get-tpl-elements-of-type self 'chord)) (cont-chords (get-tpl-elements-of-type self 'continuation-chord)) (new-obj (if chords (make-instance 'chord) (if cont-chords (make-instance 'cont-chords :previous-chord (previous-chord (car cont-chords))) (make-instance 'r-rest))))) (when chords (setf (notes new-obj) (remove-duplicates (get-notes chords) :key #'midic)) (loop for c in chords do (time-sequence-remove-timed-item in-voice c nil))) (setf (symbolic-date new-obj) (symbolic-date self) (symbolic-dur new-obj) (symbolic-dur self)) (when (typep new-obj 'chord) (time-sequence-insert-timed-item-and-update in-voice new-obj (find-position-at-time in-voice (beat-to-time (symbolic-date new-obj) (tempo in-voice))))) new-obj)) (defmethod group-objects ((self list) (in-voice voice)) (let* ((chords (loop for obj in self append (get-tpl-elements-of-type obj 'chord))) (cont-chords (loop for obj in self append (get-tpl-elements-of-type obj 'continuation-chord))) (new-obj (if chords (make-instance 'chord) (if cont-chords (make-instance 'continuation-chord :previous-chord (previous-chord (car cont-chords))) (make-instance 'r-rest))))) (when chords (setf (notes new-obj) (remove-duplicates (get-notes chords) :key #'midic)) (loop for c in chords do (time-sequence-remove-timed-item in-voice c nil))) (setf (symbolic-date new-obj) (list-min (mapcar #'symbolic-date self)) (symbolic-dur new-obj) (apply #'+ (mapcar #'symbolic-dur self))) (when (typep new-obj 'chord) (time-sequence-insert-timed-item-and-update in-voice new-obj (find-position-at-time in-voice (beat-to-time (symbolic-date new-obj) (tempo in-voice))))) new-obj)) (defmethod group-voice-elements ((self t) (clist list) (tpl-sequence voice)) nil) (defmethod group-voice-elements ((self rhythmic-object) (clist list) (tpl-sequence voice)) (setf clist (sort clist #'< :key #'symbolic-date)) ;(print (list "GROUPING IN" self)) ;; else: check inside (let* ((sublist (intersection clist (inside self))) (pos (and sublist (search sublist (inside self))))) (if pos ;;; same sequence in same order exists inside: a sequence of succesive elements ;;; make a new object with sub-list (let ((grouped (group-objects sublist tpl-sequence))) ;(print (list "list to group:" sublist "=>" grouped)) ;;; substitute the object (replace-in-obj self sublist grouped)) ;;; go one by one (loop for element in (inside self) do (if (and sublist (find element sublist)) ;;; group the element (let ((grouped (group-objects element tpl-sequence))) ;(print (list "element to group:" element "=>" grouped)) (when grouped (replace-in-obj self element grouped))) ;;; check for groups inside (group-voice-elements element clist tpl-sequence) )) )) ) (defmethod group ((self voice) (clist list)) (group-voice-elements self clist self) ;;; rebuild the structure (set-tree self (build-tree self nil))) ;;; SUBDIVIDE (defmethod subdivide-in-voice ((self chord) (n integer) (in-voice voice)) (let* ((new-dur (/ (symbolic-dur self) n)) (t0 (symbolic-date self)) (new-chords (loop for i from 0 to (1- n) collect (let ((c (clone-object self))) (setf (symbolic-date c) (+ t0 (* i new-dur)) (symbolic-dur c) new-dur) c))) (new-group (make-instance 'group :symbolic-date t0 :symbolic-dur (symbolic-dur self)))) (setf (inside new-group) new-chords) (replace-in-obj in-voice self new-group) (time-sequence-remove-timed-item in-voice self nil) (loop for c in new-chords do (time-sequence-insert-timed-item-and-update in-voice c (find-position-at-time in-voice (beat-to-time (symbolic-date c) (tempo in-voice))))) )) (defmethod subdivide-in-voice ((self r-rest) (n integer) (in-voice voice)) (let* ((new-dur (/ (symbolic-dur self) n)) (t0 (symbolic-date self)) (new-rests (loop for i from 0 to (1- n) collect (let ((r (clone-object self))) (setf (symbolic-date r) (+ t0 (* i new-dur)) (symbolic-dur r) new-dur) r)))) (replace-in-obj in-voice self new-rests) )) (defmethod subdivide-in-voice ((self continuation-chord) (n integer) (in-voice voice)) (let* ((new-dur (/ (symbolic-dur self) n)) (t0 (symbolic-date self)) (new-c-chords (loop for i from 0 to (1- n) collect (let ((cc (clone-object self))) (setf (symbolic-date cc) (+ t0 (* i new-dur)) (symbolic-dur cc) new-dur) cc)))) (replace-in-obj in-voice self new-c-chords) )) (defmethod subdivide ((self voice) (clist list) (n integer)) (let ((elements (loop for obj in clist append (get-tpl-elements-of-type obj '(chord continuation-chord r-rest))))) (loop for elt in elements do (subdivide-in-voice elt n self)) (set-tree self (build-tree self nil)))) ;;; BREAK (defmethod break-group-in-voice ((self group) (in-voice voice)) ;(loop for elt in (inside self) do ; (setf (symbolic-dur elt) (* (symbolic-dur self) (symbolic-dur elt)))) (replace-in-obj in-voice self (inside self)) ) (defmethod break-groups ((self voice) (glist list)) (loop for group in glist do (break-group-in-voice group self)) ;;; rebuild the structure (set-tree self (build-tree self nil)))
34,142
Common Lisp
.lisp
698
36.964183
129
0.541434
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
755eb9851a9f4af789d257dac8c032b232010cb81dabe2b98ada513248caff31
735
[ -1 ]
736
play.lisp
cac-t-u-s_om-sharp/src/packages/score/editor/play.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;=================================== ;;; PLAY (MIDI) ;;; Specific actions for score-objects playback ;;;=================================== ;;; chord-seq/voice already play (from data-track) (defmethod play-obj? ((self multi-seq)) t) (defmethod play-obj? ((self chord)) t) (defmethod play-obj? ((self note)) t) ;;;=================================================== ;;; PREFERENCE ;;;=================================================== (add-preference :score :microtone-bend "Microtone pitch bend" '(:off :auto-bend :permanent-bend :no-bend) :auto-bend '("Applies 1/8th pitch-bend to MIDI channels 1-4 during playback of score-objects" "and shift MIDI channels of micro-tonal notes when scale is 1/4 or 1/8th tone." "- 'auto-bend': applies when score objects start playing, and resets when they stop." "- 'permanent-bend': sets and keeps MIDI channels bended permamnently." "- 'no-bend': only shifts to MIDI channels 1-4 (and lets you set MIDI pitch bend)." ) 'update-global-pitch-bend) ;;; split note on channels in case of microtonal setup (4 or 8) ;;; tone = 0, 1/8 = 1, 1/4 = 2, 3/8 = 3 ;;; default bend channel 1 = 0, channel 2 = 25 mc, channel 3 = 50 mc, channel 4 = 75mc (defun update-global-pitch-bend () (if (equal :permanent-bend (get-pref-value :score :microtone-bend)) (micro-bend) (micro-reset))) (add-preference :score :osc-play-format "OSC player format" '(:note-msg :note-on-off-msg :note-bundle :chord-bundle) :note-msg '("Format of OSC messages for score objects using the :OSC player" "- 'note-msg': Simple OSC message: (\"/om#/note\" pitch velocity duration channel)." "- 'note-on-off-msg': Another message (\"/om#/note-off\" pitch channel) is sent when the note ends." "- 'note-bundle': OSC bundle with separate messages for \"/pitch\", \"/velocity\", \"/duration\", \"/channel\"." "- 'chord-bundle':OSC bundle per chord with one message for each note, and additional message(s) for extras." )) ;;;=================================================== ;;; PLAY-ACTIONS ;;;=================================================== (defmethod get-action-list-of-chord ((player (eql :midi)) notes offset interval pitch-approx &optional extras) (loop for n in notes append (let ((date (+ offset (offset n))) (channel (+ (or (chan n) 1) (if pitch-approx (micro-channel (midic n) pitch-approx) 0)))) (remove nil (list (when (in-interval date interval :exclude-high-bound t) (list date #'(lambda (note) (om-midi::midi-send-evt (om-midi:make-midi-evt :type :keyOn :chan channel :port (or (port n) (get-pref-value :midi :out-port)) :fields (list (truncate (midic note) 100) (vel note))))) (list n))) (when (in-interval (+ date (dur n)) interval :exclude-high-bound t) (list (+ date (dur n)) #'(lambda (note) (om-midi::midi-send-evt (om-midi:make-midi-evt :type :keyOff :chan channel :port (or (port n) (get-pref-value :midi :out-port)) :fields (list (truncate (midic note) 100) 0)))) (list n))) )) ))) (defmethod format-as-osc ((self t)) nil) (defmethod get-action-list-of-chord ((player (eql :osc)) notes offset interval pitch-approx &optional extras) (case (get-pref-value :score :osc-play-format) (:note-msg (loop for n in notes for date = (+ offset (offset n)) when (in-interval date interval :exclude-high-bound t) collect (list date #'(lambda (note) (osc-send `("/om#/note" ,(midic note) ,(vel note) ,(dur note) ,(or (chan note) 1)) (get-pref-value :osc :out-host) (get-pref-value :osc :out-port))) (list n)))) (:note-on-off-msg (loop for n in notes for date = (+ offset (offset n)) append (remove nil (list (when (in-interval date interval :exclude-high-bound t) (list date #'(lambda (note) (osc-send `("/om#/note-on" ,(midic note) ,(vel note) ,(dur note) ,(or (chan note) 1)) (get-pref-value :osc :out-host) (get-pref-value :osc :out-port))) (list n))) (when (in-interval (+ date (dur n)) interval :exclude-high-bound t) (list (+ date (dur n)) #'(lambda (note) (osc-send `("/om#/note-off" ,(midic note) ,(or (chan note) 1)) (get-pref-value :osc :out-host) (get-pref-value :osc :out-port))) (list n))) )))) (:note-bundle (loop for n in notes for date = (+ offset (offset n)) when (in-interval date interval :exclude-high-bound t) collect (list date #'(lambda (note) (osc-send (make-instance 'osc-bundle :messages `(("/pitch" ,(midic note)) ("/velocity" ,(vel note)) ("/duration" ,(dur note)) ("/channel" ,(or (chan note) 1)))) (get-pref-value :osc :out-host) (get-pref-value :osc :out-port))) (list n)))) (:chord-bundle (when (in-interval offset interval :exclude-high-bound t) (list (list offset #'(lambda () (osc-send (make-instance 'osc-bundle :messages (append (loop for n in notes collect `("/note" ,(midic n) ,(vel n) ,(dur n) ,(or (chan n) 1))) (remove nil (loop for e in extras collect (format-as-osc e))) )) (get-pref-value :osc :out-host) (get-pref-value :osc :out-port))) )))) (otherwise (om-beep-msg "Unknow OSC formatting option: ~a" (get-pref-value :score :osc-play-format))) )) ;;; from a chord-editor (or a sequencer...) ;;; !! negative offsets shift the chord (defmethod get-action-list-for-play ((c chord) interval &optional parent) (let ((pitch-approx (when (and (not (equal :off (get-pref-value :score :microtone-bend))) (micro-channel-on (pitch-approx c))) (pitch-approx c)))) (let ((negative-offset (max 0 (- (loop for n in (notes c) minimize (offset n)))))) (get-action-list-of-chord (player-info c) (notes c) negative-offset interval pitch-approx (extras c)) ))) (defmethod get-action-list-for-play ((n note) interval &optional parent) (let ((pitch-approx (when (and (not (equal :off (get-pref-value :score :microtone-bend))) (micro-channel-on (pitch-approx n))) (pitch-approx n)))) (get-action-list-of-chord (player-info n) (list n) 0 interval pitch-approx))) (defmethod get-action-list-of-voice (object player interval pitch-approx) (sort (loop for c in (remove-if #'(lambda (chord) (let ((t1 (+ (date chord) (list-min (loffset chord)))) (t2 (+ (date chord) (loop for n in (notes chord) maximize (+ (offset n) (dur n)))))) (or (< t2 (car interval)) (>= t1 (cadr interval))) )) (chords object)) append (get-action-list-of-chord player (notes c) (date c) interval pitch-approx (extras c))) '< :key 'car)) (defmethod get-action-list-for-play ((object chord-seq) interval &optional parent) (let ((pitch-approx (when (and (not (equal :off (get-pref-value :score :microtone-bend))) (micro-channel-on (pitch-approx object))) (pitch-approx object)))) (get-action-list-of-voice object (player-info object) interval pitch-approx))) (defmethod get-action-list-for-play ((object multi-seq) interval &optional parent) (let ((pitch-approx (when (and (not (equal :off (get-pref-value :score :microtone-bend))) (micro-channel-on (pitch-approx object))) (pitch-approx object)))) (loop for voice in (obj-list object) append (get-action-list-of-voice voice (player-info object) interval pitch-approx)))) ;;; Use during score edits: (defun close-open-chords-at-time (chords time playing-object) (let* ((pitch-approx (when (and (not (equal :off (get-pref-value :score :microtone-bend))) (micro-channel-on (pitch-approx playing-object))) (pitch-approx playing-object)))) (loop for chord in chords do (let ((onset (onset chord))) (loop for note in (notes chord) do (when (or (zerop time) (and (<= (+ onset (offset note)) time) (>= (+ onset (offset note) (dur note)) time))) (case (player-info playing-object) (:midi (let ((channel (+ (or (chan note) 1) (if pitch-approx (micro-channel (midic note) pitch-approx) 0)))) (om-midi:midi-send-evt (om-midi:make-midi-evt :type :keyoff :chan channel :port (or (port note) (get-pref-value :midi :out-port)) :fields (list (truncate (midic note) 100) 0))) )) (:osc (when (equal (get-pref-value :score :osc-play-format) :note-on-off-msg) (osc-send `("/om#/note-off" ,(midic note) ,(or (chan note) 1)) (get-pref-value :osc :out-host) (get-pref-value :osc :out-port)) )) (otherwise nil)) )))))) (defmethod send-current-midi-key-offs ((self score-element)) (close-open-chords-at-time (chords self) (get-obj-time self) self)) ;;;=================================================== ;;; MICROTONES ;;;=================================================== (defparameter *micro-channel-approx* 8) (defun micro-bend-messages (&optional port) (loop for chan from 1 to (/ *micro-channel-approx* 2) for pb from 8192 by (/ 8192 *micro-channel-approx*) ;;; 8192 = 1 tone pitch-bend collect (om-midi::make-midi-evt :type :PitchBend :date 0 :chan chan :port (or port (get-pref-value :midi :out-port)) :fields (val2lsbmsb pb)))) (defun micro-reset-messages (&optional port) (loop for chan from 1 to 4 collect (om-midi::make-midi-evt :type :PitchBend :date 0 :chan chan :port (or port (get-pref-value :midi :out-port)) :fields (val2lsbmsb 8192)))) (defun micro-bend (&optional port) (loop for pb-evt in (micro-bend-messages port) do (om-midi:midi-send-evt pb-evt))) (defun micro-reset (&optional port) (loop for pb-evt in (micro-reset-messages port) do (om-midi:midi-send-evt pb-evt))) ;; t / nil / list of approx where it must be applied (defparameter *micro-channel-mode-on* '(4 8)) (defun micro-channel-on (approx) (and approx (if (consp *micro-channel-mode-on*) (find approx *micro-channel-mode-on* :test '=) *micro-channel-mode-on*))) ; channel offset from midic (defun micro-channel (midic &optional approx) (if (micro-channel-on approx) (let ((scale-mod (/ 200 approx)) ;;; *-mod = 25 or 50 (channels-mod (/ 200 *micro-channel-approx*))) (round (* (floor (mod midic 100) scale-mod) scale-mod) channels-mod)) 0)) (defmethod collec-ports-from-object ((self t)) (remove-duplicates (mapcar #'port (get-notes self)))) ;;; chord-seq and multi-seq don't work with get-notes (defmethod collec-ports-from-object ((self chord-seq)) (remove-duplicates (loop for c in (chords self) append (collec-ports-from-object c)))) (defmethod collec-ports-from-object ((self multi-seq)) (remove-duplicates (loop for c in (inside self) append (collec-ports-from-object c)))) ;;; HOOK ON PLAYER METHODS: (defmethod player-play-object ((self scheduler) (object score-element) (caller score-editor) &key parent interval) (declare (ignore parent interval)) (setf (player-info object) (editor-get-edit-param caller :player)) (let ((approx (/ 200 (step-from-scale (editor-get-edit-param caller :scale))))) (setf (pitch-approx object) approx) (when (and (equal :midi (editor-get-edit-param caller :player)) (equal :auto-bend (get-pref-value :score :microtone-bend)) (micro-channel-on approx)) (loop for p in (collec-ports-from-object object) do (micro-bend p)))) (call-next-method)) (defmethod player-play-object ((self scheduler) (object score-element) (caller ScoreBoxEditCall) &key parent interval) (declare (ignore parent interval)) (setf (player-info object) (get-edit-param caller :player)) (let ((approx (/ 200 (step-from-scale (get-edit-param caller :scale))))) (setf (pitch-approx object) approx) (when (and (equal :midi (get-edit-param caller :player)) (equal :auto-bend (get-pref-value :score :microtone-bend)) (micro-channel-on approx)) (loop for p in (collec-ports-from-object object) do (micro-bend p)) )) (call-next-method)) (defmethod player-play-object :before ((self scheduler) (object OMSequencer) caller &key parent interval) ;;;Ajouter ici la task begin : (mp:mailbox-send (taskqueue *engine*) *taskbegin*) (declare (ignore parent interval)) (let ((micro-play-ports nil)) (loop for box in (get-boxes-of-type object 'ScoreBoxEditCall) when (equal :midi (get-edit-param box :player)) do (let ((approx (/ 200 (step-from-scale (get-edit-param box :scale)))) (object (car (value box)))) (setf (pitch-approx object) approx) (when (and (equal :auto-bend (get-pref-value :score :microtone-bend)) (micro-channel-on approx)) (setf micro-play-ports (append micro-play-ports (collec-ports-from-object object)))))) (loop for p in (remove-duplicates micro-play-ports) do (micro-bend p)) )) (defmethod player-pause-object ((self scheduler) (object score-element)) (send-current-midi-key-offs object) (call-next-method)) (defmethod player-stop-object ((self scheduler) (object score-element)) (send-current-midi-key-offs object) (when (and (equal (player-info object) :midi) (equal :auto-bend (get-pref-value :score :microtone-bend)) *micro-channel-mode-on*) (loop for p in (collec-ports-from-object object) do (micro-reset p))) (call-next-method)) (defmethod player-loop-object ((self scheduler) (object score-element)) (send-current-midi-key-offs object) (call-next-method)) (defmethod set-object-current-time ((self score-element) time) (declare (ignore time)) (send-current-midi-key-offs self) (call-next-method))
17,620
Common Lisp
.lisp
331
39.154079
130
0.512931
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
55b17bbea517b43d46c56b09e9ca3f43aff6f91b112676be31953e02c5a22f1f
736
[ -1 ]
737
chord-seq-editor.lisp
cac-t-u-s_om-sharp/src/packages/score/editor/chord-seq-editor.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;======================================================================== ;;; CHORD-SEQ EDITOR / GENERAL SCORE EDITOR ;;;======================================================================== (defclass chord-seq-editor (score-editor data-track-editor) ((recording-notes :accessor recording-notes :initform nil))) (defmethod get-editor-class ((self chord-seq)) 'chord-seq-editor) (defclass chord-seq-panel (score-view data-track-panel) () (:default-initargs :keys nil :margin-l nil :margin-r 1)) (defmethod editor-view-class ((self chord-seq-editor)) 'chord-seq-panel) (defmethod edit-time-? ((self chord-seq-editor)) t) (defmethod editor-window-init-size ((self chord-seq-editor)) (om-make-point 650 300)) ;;; this will just disable the display-mode menu (defmethod frame-display-modes-for-object ((self data-track-editor) (object score-element)) '(:chords)) ;;; offset can be :shift, :grace-notes, or :hidden (defmethod object-default-edition-params ((self chord-seq)) (append (call-next-method) '((:grid nil) (:grid-step 1000) (:stems t) (:y-shift 4) (:offsets :grace-note)))) (defmethod editor-with-timeline ((self chord-seq-editor)) nil) ;;;========================= ;;; LEFT-VIEW ;;;========================= (defclass left-score-view (score-view) ()) (defmethod left-score-view-class ((self chord-seq-editor)) 'left-score-view) (defmethod om-draw-contents ((self left-score-view)) (let* ((editor (editor self)) (scrolled (> (x1 (get-g-component editor :main-panel)) 0))) (draw-staff-in-editor-view editor self) (draw-tempo-in-editor-view editor self) (when scrolled (om-draw-rect (- (w self) 20) 0 20 (h self) :fill t :color (om-make-color .9 .9 .9 .5)) (om-draw-string (- (w self) 15) 10 "...") (om-draw-string (- (w self) 15) (- (h self) 10) "...")) )) (defmethod editor-scroll-v ((self chord-seq-editor)) nil) (defmethod make-left-panel-for-object ((editor chord-seq-editor) (object score-element) view) (declare (ignore view)) (om-make-view (left-score-view-class editor) :size (omp (* 2 (editor-get-edit-param editor :font-size)) nil) :direct-draw t :bg-color (om-def-color :white) :editor editor :scrollbars (editor-scroll-v editor) :margin-l 1 :margin-r nil :keys t :contents nil )) (defmethod om-view-scrolled ((self left-score-view) pos) ;;; for some reason the initerior size initialization doesn't work on windows... #+windows(set-interior-size-from-contents (editor self)) (om-set-scroll-position (get-g-component (editor self) :main-panel) (omp 0 (cadr pos)))) (defmethod om-view-click-handler ((self left-score-view) position) ;;; is the staff-line selected ? (let* ((editor (editor self)) (unit (font-size-to-unit (editor-get-edit-param editor :font-size))) (y-shift (editor-get-edit-param editor :y-shift)) (staff (editor-get-edit-param editor :staff)) (staff-y-minmax (staff-y-range staff y-shift unit))) (if (and (>= (om-point-y position) (car staff-y-minmax)) (<= (om-point-y position) (cadr staff-y-minmax))) (progn (set-selection editor (object-value editor)) (om-init-temp-graphics-motion self position nil :min-move 1 :motion #'(lambda (view pos) (declare (ignore view)) (when (and (> (om-point-y pos) 10) (< (om-point-y pos) (- (h self) 10))) (let ((y-diff-in-units (/ (- (om-point-y pos) (om-point-y position)) unit))) (editor-set-edit-param editor :y-shift (max 0 (+ y-shift y-diff-in-units))) (om-invalidate-view self) (om-invalidate-view (main-view editor))) )))) (set-selection editor nil)) (om-invalidate-view self) (om-invalidate-view (main-view editor)) )) ;;;========================= ;;; EDITOR ;;;========================= ;;; add a "grid" and an offset-display option (defmethod make-editor-controls ((editor chord-seq-editor)) (make-score-display-params-controls editor)) (defmethod update-view-from-ruler ((self x-ruler-view) (view chord-seq-panel)) (call-next-method) (om-invalidate-view (left-view view))) ;;; just like data-track-panel (not like score-view) (defmethod om-view-zoom-handler ((self chord-seq-panel) position zoom) (zoom-rulers self :dx (- 1 zoom) :dy 0 :center position)) ;;; leave some space (-200) for the first note... (defmethod default-editor-x-range ((self chord-seq-editor)) (let ((play-obj (get-obj-to-play self))) (if play-obj (list -200 (+ (get-obj-dur play-obj) (default-editor-min-x-range self))) (list (vmin self) (or (vmax self) (default-editor-min-x-range self)))))) (defmethod update-to-editor ((editor chord-seq-editor) (from t)) (call-next-method) (editor-invalidate-views editor)) (defmethod editor-invalidate-views ((self chord-seq-editor)) (om-invalidate-view (main-view self))) ;; mmm.. ;;; rebuild when font-size has changed, in order to adjust the left-view... (defmethod set-font-size ((self chord-seq-editor) size) (call-next-method) (build-editor-window self) (init-editor-window self)) (defmethod add-chords-allowed ((self chord-seq-editor)) t) (defmethod override-interval-interaction ((self chord-seq-panel) position) (find-score-element-at-pos (object-value (editor self)) position)) (defmethod om-view-click-handler ((self chord-seq-panel) position) (or (and (not (override-interval-interaction self position)) (handle-selection-extent self position)) (call-next-method))) ;;; => score-view ;;; in data-track-editor the selection is an index to elements in the frame sequence ;;; here in chord-seq editor the selection s a score-element (defmethod first-element-in-editor ((editor chord-seq-editor)) (car (chords (object-value editor)))) ;;; called by the "tab" action (defmethod next-element-in-editor ((editor chord-seq-editor) (element t)) (first-element-in-editor editor)) (defmethod next-element-in-editor ((editor chord-seq-editor) (element chord)) (let* ((seq (object-value editor)) (pos (position element (chords seq)))) (or (nth (1+ pos) (chords seq)) (car (chords seq))))) (defmethod next-element-in-editor ((editor chord-seq-editor) (element note)) (let* ((seq (object-value editor)) (chord (find-if #'(lambda (c) (find element (notes c))) (chords seq)))) (when chord (let ((pos (position element (notes chord)))) (or (nth (1+ pos) (notes chord)) (car (notes chord))))))) (defmethod stems-on-off ((self chord-seq-editor)) (editor-set-edit-param self :stems (not (editor-get-edit-param self :stems))) (editor-invalidate-views self)) (defmethod selected-chords ((self chord-seq-editor)) (remove-if #'(lambda (item) (not (subtypep (type-of item) 'chord))) (selection self))) (defmethod add-score-marker ((self chord-seq-editor)) (when (selected-chords self) (let ((first-chord (car (sort (selected-chords self) '< :key #'date)))) (when first-chord (store-current-state-for-undo self) (add-extras first-chord (make-instance 'score-marker) nil nil) (om-invalidate-view (main-view self))) ))) (defmethod remove-score-marker ((self chord-seq-editor)) (let ((selected-chords (selected-chords self))) (when (find-if #'(lambda (c) (get-extras c 'score-marker)) selected-chords) (store-current-state-for-undo self) (loop for item in selected-chords do (remove-extras item 'score-marker nil)) (om-invalidate-view (main-view self))))) (defmethod editor-key-action ((editor chord-seq-editor) key) (case key (#\A (align-chords-in-editor editor)) (#\S (stems-on-off editor)) (#\m (add-score-marker editor)) (#\M (remove-score-marker editor)) (otherwise (call-next-method)) ;;; => score-editor )) (defmethod extras-menus ((self chord-seq-editor)) (list (om-make-menu-item "Add chord marker [M]" #'(lambda () (add-score-marker self)) :enabled #'(lambda () (selection self))) (om-make-menu-item "Remove chord marker(s) [Shift+M]" #'(lambda () (remove-score-marker self)) :enabled #'(lambda () (selection self))))) ;;; called at add-click (defmethod get-chord-from-editor-click ((self chord-seq-editor) position) (let* ((panel (get-g-component self :main-panel)) (x-pos (max (time-to-pixel panel 0) (om-point-x position)))) (or ;;; there's a selected chord near the click (find-if #'(lambda (element) (and (typep element '(or chord r-rest)) (b-box element) (>= x-pos (b-box-x1 (b-box element))) (<= x-pos (b-box-x2 (b-box element))))) (selection self)) ;;; else, make a new chord (when (add-chords-allowed self) (let* ((time-seq (get-voice-at-pos self position)) (time-pos (pixel-to-time panel x-pos)) (new-chord (time-sequence-make-timed-item-at time-seq time-pos))) (setf (notes new-chord) nil) ;;; notes = NIL here so the duration will be 0 at updating the time-sequence (time-sequence-insert-timed-item-and-update time-seq new-chord) new-chord)) ))) ;;; redefines from data-track-editor (defmethod move-editor-selection ((self chord-seq-editor) &key (dx 0) (dy 0)) (unless (equal (editor-play-state self) :stop) (close-open-chords-at-time (get-chords-of-selection self) (get-obj-time (object-value self)) (object-value self))) (unless (zerop dx) (loop for item in (selection self) when (typep item 'chord) do (item-set-time item (max 0 (round (+ (item-get-time item) dx)))))) (unless (zerop dy) (let ((step (or (step-from-scale (editor-get-edit-param self :scale)) 100)) (notes (loop for item in (selection self) append (get-notes item)))) (loop for n in notes do (setf (midic n) (+ (midic n) (* dy step)))))) ) (defmethod score-editor-change-selection-durs ((self chord-seq-editor) delta) (when (editor-get-edit-param self :duration-display) (unless (equal (editor-play-state self) :stop) (close-open-chords-at-time (get-selected-chords self) (get-obj-time (object-value self)) (object-value self))) (let ((notes (loop for item in (selection self) append (get-notes item)))) (loop for n in notes do (setf (dur n) (max (abs delta) (round (+ (dur n) delta))))) (time-sequence-update-obj-dur (object-value self)) ))) (defmethod score-editor-delete ((self chord-seq-editor) element) (remove-from-obj (object-value self) element)) (defmethod editor-sort-frames ((self chord-seq-editor)) (time-sequence-reorder-timed-item-list (object-value self))) ;;; paste command ;;; also works for multi-seq (defmethod score-editor-paste ((self chord-seq-editor) elements) (let ((chords (mapcar #'om-copy (sort (loop for item in elements append (get-tpl-elements-of-type item '(chord))) #'< :key #'onset))) (view (get-g-component self :main-panel))) (if chords (let* ((t0 (onset (car chords))) (paste-pos (get-paste-position view)) (p0 (if paste-pos (pixel-to-time view (om-point-x paste-pos)) (+ t0 200))) (cs (get-voice-at-pos self (or paste-pos (omp 0 0))))) (loop for c in chords do (item-set-time c (+ p0 (- (item-get-time c) t0)))) (set-paste-position (omp (time-to-pixel view (+ p0 200)) (if paste-pos (om-point-y paste-pos) 0)) view) (store-current-state-for-undo self) (set-chords cs (sort (append (chords cs) chords) #'< :key #'onset)) (report-modifications self) t) (om-beep)) )) (defmethod align-chords-in-editor ((self chord-seq-editor)) (when (selection self) (store-current-state-for-undo self) (let ((selected-chords (loop for elt in (selection self) append (get-tpl-elements-of-type elt 'chord)))) (align-chords-in-sequence (object-value self) (or (editor-get-edit-param self :grid-step) 100) selected-chords) (report-modifications self) (editor-invalidate-views self)) )) (defmethod align-command ((self chord-seq-editor)) (when (selection self) #'(lambda () (align-chords-in-editor self)) )) ;;;====================================== ;;; RECORD ;;;====================================== (defmethod can-record ((self chord-seq-editor)) t) (defmethod close-recording-notes ((self chord-seq-editor)) (let ((obj (get-obj-to-play self))) (when (recording-notes self) (let ((time-ms (player-get-object-time (player self) obj)) (max-time (or (cadr (play-interval self)) (get-obj-dur obj)))) (maphash #'(lambda (pitch chord) (declare (ignore pitch)) (setf (ldur chord) (list (- (if (> time-ms (onset chord)) time-ms max-time) (onset chord))))) (recording-notes self)) (clrhash (recording-notes self)))) (time-sequence-update-obj-dur obj) )) (defmethod editor-record-on ((self chord-seq-editor)) (let ((in-port (get-pref-value :midi :in-port))) (setf (recording-notes self) (make-hash-table)) (setf (record-process self) (om-midi::portmidi-in-start in-port #'(lambda (message time) (declare (ignore time)) (when (equal :play (editor-play-state self)) (let ((time-ms (player-get-object-time (player self) (get-obj-to-play self))) (max-time (or (cadr (play-interval self)) (get-obj-dur (get-obj-to-play self)))) (pitch (car (om-midi:midi-evt-fields message)))) (case (om-midi::midi-evt-type message) (:KeyOn (let ((chord-seq (get-default-voice self)) (chord (make-instance 'chord :onset time-ms :ldur '(100) :lmidic (list (* 100 (car (om-midi:midi-evt-fields message)))) :lvel (list (cadr (om-midi:midi-evt-fields message))) :lchan (list (om-midi:midi-evt-chan message)) :lport (list (om-midi:midi-evt-port message)) ))) (setf (gethash pitch (recording-notes self)) chord) (time-sequence-insert-timed-item-and-update chord-seq chord) (update-from-internal-chords chord-seq) (report-modifications self) (update-timeline-editor self) (editor-invalidate-views self) )) (:KeyOff (let ((chord (gethash pitch (recording-notes self)))) (when chord (setf (ldur chord) (list (- (if (> time-ms (onset chord)) time-ms max-time) (onset chord)))) (remhash pitch (recording-notes self))) (editor-invalidate-views self))) (otherwise nil))))) 1 (and (get-pref-value :midi :thru) (get-pref-value :midi :thru-port)) )) (push self *running-midi-recorders*) (om-print-format "Start recording in ~A (port ~D)" (list (or (name (object self)) (type-of (get-obj-to-play self))) in-port) "MIDI") )) (defmethod editor-record-off ((self chord-seq-editor)) (when (record-process self) (om-print-format "Stop recording in ~A" (list (or (name (object self)) (type-of (get-obj-to-play self)))) "MIDI") (om-midi::portmidi-in-stop (record-process self))) (close-recording-notes self) (setf *running-midi-recorders* (remove self *running-midi-recorders*))) ; Redefined with VOICE (defmethod update-from-internal-chords ((self chord-seq)) nil) (defmethod editor-stop ((self chord-seq-editor)) (close-recording-notes self) (call-next-method)) (defmethod editor-pause ((self chord-seq-editor)) (close-recording-notes self) (call-next-method)) ;;;========================= ;;; IMPORT/EXPORT ;;;========================= (defmethod import-menus ((self chord-seq-editor)) (list (om-make-menu-item "MIDI" #'(lambda () (editor-import-midi self))) (om-make-menu-item "MusicXML" #'(lambda () (editor-import-musicxml self))) )) (defmethod export-menus ((self chord-seq-editor)) (list (om-make-menu-item "MIDI" #'(lambda () (editor-export-midi self))) (om-make-menu-item "MusicXML" #'(lambda () (editor-export-musicxml self))) )) ;;; missing om-init-instance ? (defmethod editor-import-midi ((self chord-seq-editor)) (objfromobjs (import-midi) ;; => MIDI-TRACK (object-value self)) (report-modifications self) (editor-invalidate-views self)) (defmethod editor-import-musicxml ((self chord-seq-editor)) (objfromobjs (import-musicxml) ;; => MIDI-TRACK (object-value self)) (report-modifications self) (editor-invalidate-views self)) (defmethod editor-export-midi ((self chord-seq-editor)) (save-as-midi (object-value self) nil)) (defmethod editor-export-musicxml ((self chord-seq-editor)) (export-musicxml (object-value self))) ;;;========================= ;;; DISPLAY ;;;========================= (defmethod data-track-get-x-ruler-vmin ((self chord-seq-editor)) -200) (defmethod draw-score-object-in-editor-view ((editor chord-seq-editor) view unit) (let ((obj (if (multi-display-p editor) (nth (stream-id view) (multi-obj-list editor)) (object-value editor)))) ;;; grid (when (editor-get-edit-param editor :grid) (draw-grid-on-score-editor editor view)) (when (editor-get-edit-param editor :groups) (draw-groups-on-score-editor editor)) (draw-sequence obj editor view unit))) (defmethod draw-grid-on-score-editor ((editor chord-seq-editor) view) (let ((grid-step (or (editor-get-edit-param editor :grid-step) 100))) ;; just in case.. (loop for x from (* (ceiling (x1 view) grid-step) grid-step) to (* (floor (x2 view) grid-step) grid-step) by grid-step do (let ((x-pix (time-to-pixel view x))) (om-draw-line x-pix 0 x-pix (h view) :color (om-def-color :gray) :style '(2 2)) ) ))) ;;; redefined for other objects (defmethod draw-sequence ((object chord-seq) editor view unit &optional (force-y-shift nil) voice-staff) (let ((font-size (editor-get-edit-param editor :font-size)) (staff (or voice-staff (editor-get-edit-param editor :staff))) (scale (editor-get-edit-param editor :scale)) (chan (editor-get-edit-param editor :channel-display)) (vel (editor-get-edit-param editor :velocity-display)) (port (editor-get-edit-param editor :port-display)) (dur (editor-get-edit-param editor :duration-display)) (stems (editor-get-edit-param editor :stems)) (offsets (editor-get-edit-param editor :offsets)) (y-u (or force-y-shift (editor-get-edit-param editor :y-shift)))) (when (listp staff) (setf staff (or (nth (position object (get-voices (object-value editor))) staff) (car staff)))) ;;; NOTE: so far we don't build/update a bounding-box for the chord-seq itself (might be useful in POLY).. (loop for chord in (chords object) do (setf (b-box chord) (draw-chord chord (date chord) 0 y-u 0 0 (w view) (h view) font-size :staff staff :scale scale :draw-chans chan :draw-vels vel :draw-ports port :draw-durs dur :stem stems :selection (if (find chord (selection editor)) T (selection editor)) :time-function #'(lambda (time) (time-to-pixel view time)) :offsets offsets :build-b-boxes t )) ;(draw-b-box chord) ;(mapcar 'draw-b-box (inside chord)) )))
22,182
Common Lisp
.lisp
455
39.083516
112
0.575949
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
6b4d6ceeb09cce372491b225e36fbfad45a2e7307f9e4538a56ba8ee6e0b8a57
737
[ -1 ]
738
multiseq-poly-editor.lisp
cac-t-u-s_om-sharp/src/packages/score/editor/multiseq-poly-editor.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;======================================================================== ;;; MULTI-SEQ/POLY EDITOR ;;;======================================================================== (defclass poly-editor-mixin () ()) ;;; !! The editor will inherit from data-track-editor, although MULTI-SEQ in not a data-track... (defclass multi-seq-editor (poly-editor-mixin chord-seq-editor) ()) (defmethod get-editor-class ((self multi-seq)) 'multi-seq-editor) (defclass poly-editor (poly-editor-mixin voice-editor) ()) (defmethod get-editor-class ((self poly)) 'poly-editor) (defmethod object-name-for-window-title ((self multi-seq)) "multi-seq") (defmethod object-name-for-window-title ((self poly)) "poly") (defmethod init-editor ((editor poly-editor-mixin)) (call-next-method) (update-edit-params editor)) (defmethod object-default-edition-params ((self multi-seq)) (append (call-next-method) '((:grid nil) (:grid-step 1000) (:stems t) (:y-shift (4)) (:offsets :small-notes) (:staff-list nil) ;; a list of staffs for each voice ))) ;;;======================================================================== ;;; COMMON FEATURES ;;;======================================================================== (defmethod locked ((self multi-seq)) nil) ;;;========================= ;;; Multi-STAFF ;;;========================= (defvar *default-inter-staff* 8) (defvar *min-inter-staff* 2) (defmethod update-edit-params ((editor poly-editor-mixin)) (let* ((n-voices (length (obj-list (object-value editor)))) (previous-y-list (list! (editor-get-edit-param editor :y-shift))) (previous-staff-list (editor-get-edit-param editor :staff-list))) (editor-set-edit-param editor :y-shift (loop for i from 0 to (1- n-voices) collect (or (nth i previous-y-list) *default-inter-staff*))) (editor-set-edit-param editor :staff-list (loop for i from 0 to (1- n-voices) collect (or (nth i previous-staff-list) (editor-get-edit-param editor :staff)))) )) (defmethod accum-y-shift-list ((editor poly-editor-mixin)) (let* ((y-shift (editor-get-edit-param editor :y-shift)) (staff-list (editor-get-edit-param editor :staff-list)) (accum-y-list ())) (loop with next-y = 0 for voice-shift in y-shift for staff in staff-list for i from 0 to (1- (length (obj-list (object-value editor)))) do (setf next-y (+ next-y voice-shift)) (push next-y accum-y-list) (setf next-y (+ next-y (staff-line-range staff))) finally (push next-y accum-y-list)) (reverse accum-y-list))) ;; returns the y1-y2 pairs for all staffs (defun make-staff-y-map (editor) (let* ((unit (font-size-to-unit (editor-get-edit-param editor :font-size))) (staff-list (editor-get-edit-param editor :staff-list))) (loop for ys in (butlast (accum-y-shift-list editor)) for i from 0 collect (staff-y-range (nth i staff-list) ys unit)) )) ;;;--------------------------------------------- ;;; SCORE-EDITOR REDEFINITIONS (defmethod get-total-y-shift ((editor poly-editor-mixin) voice-num) (nth voice-num (accum-y-shift-list editor))) ;;;--------------------------------------------- (defmethod editor-scroll-v ((self multi-seq-editor)) :v) (defmethod editor-scroll-v ((self poly-editor)) :v) (defmethod set-interior-size-from-contents ((self poly-editor-mixin)) (let* ((fontsize (editor-get-edit-param self :font-size)) (unit (font-size-to-unit fontsize)) (score-view (get-g-component self :main-panel)) (bottom (car (last (accum-y-shift-list self)))) (margin 5) (y (round (* (+ bottom margin) unit)))) (oa::om-set-interior-size score-view (omp (om-point-x (om-view-size score-view)) y)) (oa::om-set-interior-size (left-view score-view) (omp (om-point-x (om-view-size (left-view score-view))) y)) )) (defmethod init-editor-window :after ((self poly-editor-mixin)) (set-interior-size-from-contents self)) (defmethod get-selected-voices ((self poly-editor-mixin)) (loop for item in (selection self) when (subtypep (type-of item) 'chord-seq) collect item)) ;;;========================= ;;; LEFT VIEW (KEYS etc.) ;;;========================= (defclass poly-left-score-view (left-score-view) ()) (defmethod initialize-instance ((self poly-left-score-view) &rest args) (call-next-method) (om-add-subviews self (om-make-graphic-object 'om-icon-button :position (omp 4 4) :size (omp 12 12) :icon :edit+ :icon-pushed :edit+-pushed :action #'(lambda (item) (declare (ignore item)) (add-new-voice (editor self))) ))) ;;;--------------------------------------------- ;;; SCORE-EDITOR REDEFINITIONS (defmethod left-score-view-class ((self poly-editor-mixin)) 'poly-left-score-view) ;;;--------------------------------------------- ;;; hack / for some reason the initerior size initialization doesn't work on windows... #+windows (defmethod om-set-scroll-position :before ((self poly-left-score-view) pos) (set-interior-size-from-contents (editor self))) (defmethod om-view-click-handler ((self poly-left-score-view) position) (let* ((editor (editor self)) (staff-y-map (make-staff-y-map editor)) (selected-staff (position-if #'(lambda (range) (and (>= (om-point-y position) (car range)) (<= (om-point-y position) (cadr range)))) staff-y-map))) (if selected-staff (let* ((unit (font-size-to-unit (editor-get-edit-param editor :font-size))) (previous-y-list (editor-get-edit-param editor :y-shift))) (set-selection editor (nth selected-staff (obj-list (object-value editor)))) (om-init-temp-graphics-motion self position nil :min-move 1 :motion #'(lambda (view pos) (declare (ignore view)) (when (and (> (om-point-y pos) 10) (< (om-point-y pos) (+ (om-v-scroll-position self) (h self) -10))) (let ((y-diff-in-units (/ (- (om-point-y pos) (om-point-y position)) unit)) (new-list (copy-list previous-y-list))) (setf (nth selected-staff new-list) (max *min-inter-staff* (+ (nth selected-staff new-list) y-diff-in-units))) (editor-set-edit-param editor :y-shift new-list) (set-interior-size-from-contents (editor self)) (om-invalidate-view self) (om-invalidate-view (main-view editor))) )))) ;; no selected staff (set-selection editor nil)) (om-invalidate-view self) (om-invalidate-view (main-view editor)) )) ;;;========================= ;;; DISPLAY ;;;========================= (defmethod poly-editor-draw-staff-in-editor-view ((editor poly-editor-mixin) (self score-view)) (let* ((fontsize (editor-get-edit-param editor :font-size)) (staff-list (editor-get-edit-param editor :staff-list))) (loop for shift in (butlast (accum-y-shift-list editor)) for i from 0 do (om-with-fg-color (when (find (nth i (obj-list (object-value editor))) (selection editor)) (om-def-color :selection)) (draw-staff 0 0 shift (w self) (h self) fontsize (nth i staff-list) :margin-l (margin-l self) :margin-r (margin-r self) :keys (keys self)) )))) ;;;--------------------------------------------- ;;; SCORE-EDITOR REDEFINITIONS (defmethod draw-staff-in-editor-view ((editor poly-editor-mixin) (self score-view)) (poly-editor-draw-staff-in-editor-view editor self)) (defmethod draw-tempo-in-editor-view ((editor poly-editor) (self score-view)) (let* ((fontsize (editor-get-edit-param editor :font-size)) (unit (font-size-to-unit fontsize))) (loop for voice in (obj-list (object-value editor)) for shift in (accum-y-shift-list editor) do (draw-tempo voice (* 2 unit) (* shift unit) fontsize)) )) (defmethod draw-sequence ((object multi-seq) editor view unit &optional force-y-shift voice-staff) (loop for voice in (obj-list object) for shift in (accum-y-shift-list editor) for staff in (editor-get-edit-param editor :staff-list) do (draw-sequence voice editor view unit shift staff))) ;;;--------------------------------------------- ;;;========================= ;;; ACTIONS ;;;========================= (defmethod first-element-in-editor ((editor poly-editor-mixin)) (car (chords (car (obj-list (object-value editor)))))) (defmethod next-element-in-editor ((editor poly-editor-mixin) (element chord-seq)) (let* ((obj (object-value editor)) (pos (position element (obj-list obj)))) (or (nth (1+ pos) (obj-list obj)) (car (obj-list obj))))) (defmethod next-element-in-editor ((editor poly-editor-mixin) (element chord)) (let* ((seq (find-if #'(lambda (v) (find element (chords v))) (obj-list (object-value editor)))) (pos (position element (chords seq)))) (or (nth (1+ pos) (chords seq)) (car (chords seq))))) (defmethod next-element-in-editor ((editor poly-editor-mixin) (element note)) (let* ((seq (find-if #'(lambda (v) (find-if #'(lambda (c) (find element (notes c))) (chords v))) (obj-list (object-value editor)))) (chord (find-if #'(lambda (c) (find element (notes c))) (chords seq)))) (when chord (let ((pos (position element (notes chord)))) (or (nth (1+ pos) (notes chord)) (car (notes chord))))))) ;;; REMOVE METHODS (defmethod remove-from-obj ((self multi-seq) (item t)) nil) (defmethod remove-from-obj ((self multi-seq) (item chord)) (let ((cseq (find-if #'(lambda (cseq) (find item (data-track-get-frames cseq))) (obj-list self) ))) (when cseq (remove-from-obj cseq item)))) (defmethod remove-from-obj ((self multi-seq) (item note)) (loop for cseq in (obj-list self) while (not (remove-from-obj cseq item)))) (defmethod remove-from-obj ((self multi-seq) (item chord-seq)) (setf (obj-list self) (remove item (obj-list self)))) (defmethod remove-from-obj ((self poly) (item measure)) (let ((voice (find-if #'(lambda (v) (find item (inside v))) (obj-list self)))) (when voice (remove-from-obj voice item)))) (defmethod score-editor-handle-voice-selection ((self poly-editor-mixin) direction) (if (om-option-key-p) ;;; change order: put selected voice(s) above the previous one (let ((obj (object-value self)) (selected-voices (get-selected-voices self))) (when selected-voices (let ((posi (position (car selected-voices) (obj-list obj)))) (when posi (let ((selected-y-shifts (subseq (editor-get-edit-param self :y-shift) posi (+ posi (length selected-voices))))) ;;; the group of selected voices will move to posi+1 or posi-1 (loop for voice in selected-voices do (score-editor-update-params-before-remove self voice) (remove-from-obj obj voice)) (let ((newpos (max 0 (min (length (obj-list obj)) (+ posi direction))))) (setf (obj-list obj) (flat (insert-in-list (obj-list obj) selected-voices newpos))) (editor-set-edit-param self :y-shift (flat (insert-in-list (editor-get-edit-param self :y-shift) selected-y-shifts newpos))) )))))) ;;; change shift for selected voices (loop for obj in (get-selected-voices self) do (let ((pos (position obj (obj-list (object-value self))))) (when pos (let ((curr (nth pos (editor-get-edit-param self :y-shift)))) (editor-set-edit-param self :y-shift (subs-posn (editor-get-edit-param self :y-shift) pos (max *min-inter-staff* (+ curr direction))))) ))) )) (defmethod score-editor-update-params-before-remove ((self poly-editor-mixin) removed) (let ((pos (position removed (obj-list (object-value self))))) (when pos (editor-set-edit-param self :y-shift (remove-nth pos (editor-get-edit-param self :y-shift))) (editor-set-edit-param self :staff-list (remove-nth pos (editor-get-edit-param self :staff-list)))) (set-interior-size-from-contents self))) ;;; add chord/notes (defmethod poly-editor-get-voice-at-pos ((self poly-editor-mixin) position) (when (obj-list (object-value self)) (let* ((staff-y-map (make-staff-y-map self)) (y (om-point-y position)) (min-dist (min (abs (- y (car (car staff-y-map)))) (abs (- y (cadr (car staff-y-map)))))) (pos 0)) (loop for staff-range in (cdr staff-y-map) for p from 1 do (let ((dist (min (abs (- y (car staff-range))) (abs (- y (cadr staff-range)))))) (when (< dist min-dist) (setf pos p min-dist dist))) ) (values (nth pos (obj-list (object-value self))) pos) ))) (defmethod add-new-voice ((self poly-editor-mixin)) (let* ((obj (object-value self)) (new-voice (make-instance (voice-type obj)))) (store-current-state-for-undo self) (setf (obj-list obj) (append (obj-list obj) (list new-voice)))) (update-edit-params self) (editor-invalidate-views self) (report-modifications self) (set-interior-size-from-contents self)) (defmethod add-voices ((self poly-editor-mixin) (voices list)) (let* ((obj (object-value self))) (store-current-state-for-undo self) (setf (obj-list obj) (append (obj-list obj) voices))) (update-edit-params self) (editor-invalidate-views self) (report-modifications self) (set-interior-size-from-contents self)) ;;;--------------------------------------------- ;;; SCORE-EDITOR REDEFINITIONS (defmethod get-voice-at-pos ((self poly-editor-mixin) position) (poly-editor-get-voice-at-pos self position)) (defmethod get-all-voices ((self poly-editor-mixin)) (obj-list (object-value self))) (defmethod get-default-voice ((self poly-editor-mixin)) (or (car (get-selected-voices self)) (car (obj-list (object-value self))))) ;;;--------------------------------------------- ;;; multi-staff (defmethod set-selection ((editor multi-seq-editor) (new-selection t)) (call-next-method) (let ((selected-voices (get-selected-voices editor))) (if selected-voices (let ((selected-staffs (loop for staff in (editor-get-edit-param editor :staff-list) for voice in (get-all-voices editor) when (find voice selected-voices) collect staff))) (when (all-equal selected-staffs) (om-set-selected-item (get-g-component editor :staff-menu) (car selected-staffs)))) (om-set-selected-item (get-g-component editor :staff-menu) (editor-get-edit-param editor :staff)) )) (update-score-inspector editor)) (defmethod set-editor-staff ((editor poly-editor-mixin) new-staff) (let ((selected-voices (get-selected-voices editor)) (all-voices (get-all-voices editor)) (current-staffs (editor-get-edit-param editor :staff-list))) (assert (= (length all-voices) (length current-staffs))) (let ((new-staff-list (loop for voice in all-voices for curr-staff in current-staffs collect (if (or (null selected-voices) (find voice selected-voices)) new-staff curr-staff)))) (unless (equal current-staffs new-staff-list) (store-current-state-for-undo editor) (editor-set-edit-param editor :staff-list new-staff-list) (when (all-equal new-staff-list) (editor-set-edit-param editor :staff (car new-staff-list))) )) )) ;;; add voices (defmethod score-editor-paste ((self poly-editor-mixin) elements) (if (list-subtypep elements (voice-type (object-value self))) ;;; add voice(s) (add-voices self (mapcar #'om-copy elements)) ;;; add chords (call-next-method)))
18,893
Common Lisp
.lisp
379
38.437995
107
0.531974
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
4fec7a05f6519a060864951a78a13569d0e3a12dd01dd5d990c847ff74cc9b23
738
[ -1 ]
739
score-editor.lisp
cac-t-u-s_om-sharp/src/packages/score/editor/score-editor.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;=========================================== ;;; SCORE EDITORS (GENERAL/SHARED FEATURES) ;;;=========================================== (defclass score-editor (OMEditor undoable-editor-mixin) ((editor-window-config :accessor editor-window-config :initarg :editor-window-config :initform nil) (analysis :accessor analysis :initform nil :type abstract-analysis) )) ;;; these params are shared between the editor and the box (defmethod object-default-edition-params ((self score-element)) '((:font-size 24) (:staff :g) (:scale :scale-1/2) (:duration-display nil) (:velocity-display :hidden) (:channel-display :hidden) (:midiport-display nil) (:h-stretch 1) (:groups nil) (:group-names t) (:selected-group :all) (:player :midi))) ;;; Note: y-shift is a value or a list containing the space (in units) above the staff. (see get-total-y-shift) ;;; It is useful to control the spacing between lines (by mouse/key actions) but needs to be maintained up-to-date ;;; when voices are added/removed etc. ;;; only chord-seq-editor allows editing time (defmethod edit-time-? ((self score-editor)) nil) #| (defmethod stop-editor-callback ((self score-editor)) (om-midi::midi-all-keys-off) (call-next-method)) |# ;;;============ ;;; SCORE VIEW ;;;============ ;;; A specialized view for the display of SCORE-OBJECTs (defclass score-view (OMEditorView) ((margin-l :accessor margin-l :initarg :margin-l :initform 1) (margin-r :accessor margin-r :initarg :margin-r :initform 1) (keys :accessor keys :initarg :keys :initform t) (contents :accessor contents :initarg :contents :initform t))) ;;;======================== ;;; TIME/SPACE CONVERSIONS ;;;======================== (defmethod time-to-pixel ((self score-view) time) (let* ((ed (editor self)) (stretch (editor-get-edit-param ed :h-stretch)) (time-map (editor-get-edit-param ed :time-map))) ;(print (list ed time-map stretch)) (if (and time-map (numberp stretch)) ;;; in principle only VOICE/POLY have a time-map (let ((adjusted-stretch-factor (* stretch (font-size-to-unit (editor-get-edit-param ed :font-size))))) (* adjusted-stretch-factor (- (score-time-to-units time-map time) (score-time-to-units time-map (x1 self))))) (let ((tt (if (listp time) (car time) time))) ;;; can happen that time is a list (see draw-measure) (call-next-method self tt))))) ;;; used (only?) when we click on the view to re-position the play cursor (defmethod pixel-to-time ((self score-view) pixel) (let* ((ed (editor self)) (stretch (editor-get-edit-param ed :h-stretch)) (time-map (editor-get-edit-param ed :time-map))) (if (and time-map (numberp stretch)) (let* ((unit (font-size-to-unit (editor-get-edit-param ed :font-size))) (v0 (round (x1 self))) (v0-in-units (score-time-to-units time-map v0)) (pos-in-units (+ v0-in-units (/ pixel (* stretch unit))))) (score-units-to-time time-map pos-in-units)) (call-next-method)))) ;;; for simple views that are not x-graduated (e.g. chord) (defmethod pixel-to-time ((self om-view) x) 0) ;;;======================== ;;; DISPLAY ;;;======================== ;;; redefined for editors with several staves... (defmethod draw-staff-in-editor-view ((editor score-editor) (self score-view)) (draw-staff 0 0 (editor-get-edit-param editor :y-shift) (w self) (h self) (editor-get-edit-param editor :font-size) (editor-get-edit-param editor :staff) :margin-l (margin-l self) :margin-r (margin-r self) :keys (keys self)) ) ;;; redefined by VOICE/POLY (defmethod draw-tempo-in-editor-view ((editor score-editor) (self score-view)) nil) (defmethod om-draw-contents ((self score-view)) (let* ((editor (editor self)) (unit (font-size-to-unit (editor-get-edit-param editor :font-size)))) (om-trap-errors (draw-staff-in-editor-view editor self) (when (contents self) (draw-score-object-in-editor-view editor self unit)) ))) ;;;============ ;;; INTERACTION ;;;============ (defun point-in-bbox (p bbox) (and (>= (om-point-x p) (b-box-x1 bbox)) (<= (om-point-x p) (b-box-x2 bbox)) (>= (om-point-y p) (b-box-y1 bbox)) (<= (om-point-y p) (b-box-y2 bbox)))) (defun bbox-in-rect (bbox x1 y1 x2 y2) (and (<= x1 (b-box-x1 bbox)) (>= x2 (b-box-x2 bbox)) (<= y1 (b-box-y1 bbox)) (>= y2 (b-box-y2 bbox)))) ;;; supposing that sub-bounding-boxes are always included (defmethod find-score-element-at-pos ((object note) pos) (and (b-box object) (point-in-bbox pos (b-box object)) object)) ;;; in measure the "selectable" bounding box does not contain the internal element's bounding boxes (defmethod find-score-element-at-pos ((object measure) pos) (if (and (b-box object) (point-in-bbox pos (b-box object))) object (let ((found nil)) (loop for elem in (inside object) ;; check its children.. while (not found) do (setf found (find-score-element-at-pos elem pos))) found))) (defmethod find-score-element-at-pos ((object score-element) pos) (cond ((null (b-box object)) ;;; the object itself has no bounding box (yet?) or, we have clicked outside (let ((found nil)) (loop for elem in (inside object) ;; check its children.. while (not found) do (setf found (find-score-element-at-pos elem pos))) found)) ((point-in-bbox pos (b-box object)) ;; the object has one, and we're inside (let ((found nil)) (loop for elem in (inside object) ;; check its children.. while (not found) do (setf found (find-score-element-at-pos elem pos))) (or found object))) (t NIL) ;;; not here... )) (defmethod find-score-elements-in-area ((object score-element) x1 y1 x2 y2) (if (and (b-box object) (bbox-in-rect (b-box object) x1 y1 x2 y2)) ;; the object has one, and it's inside object ;;; the whole object is selected ;;; else: go check in the children (remove nil (flat (loop for elem in (inside object) ;; check its children.. collect (find-score-elements-in-area elem x1 y1 x2 y2)))) )) ;;; measure is special: it is selected only by clickking on the bar/signature (defmethod find-score-elements-in-area ((object measure) x1 y1 x2 y2) (flat (loop for elem in (inside object) ;; check its children.. collect (find-score-elements-in-area elem x1 y1 x2 y2)))) ;;; note: same with _all_ (not only top-level) could be useful for groups... ? (defmethod get-tpl-elements-of-type ((self score-element) type) (if (find (type-of self) (list! type)) (list self) (loop for element in (inside self) append (get-tpl-elements-of-type element type)) )) (defmethod get-tpl-elements-of-type ((self t) type) nil) ;;;====================== ;;; MOUSE ACTIONS ;;;====================== (defmethod score-object-update ((self t)) nil) (defmethod score-object-update ((self time-sequence)) (time-sequence-reorder-timed-item-list self) (time-sequence-update-obj-dur self)) ;;; overrides data-track-panel in chord-seq-editor (defmethod om-view-mouse-motion-handler ((self score-view) position) (position-display (editor self) position)) ;;; redefined with objects of several voices... (defmethod get-voice-at-pos ((self score-editor) position) (values (object-value self) 0)) (defmethod get-all-voices ((self score-editor)) (list (object-value self))) (defmethod get-default-voice ((self score-editor)) (object-value self)) (defmethod get-selected-chords ((editor score-editor)) (remove-duplicates (remove-if-not #'(lambda (elt) (typep elt 'chord)) (selection editor)))) (defmethod get-chords-of-selection ((editor score-editor)) (remove-duplicates (loop for item in (selection editor) append (if (typep item 'note) (collect-note-chords item (object-value editor)) (collect-chords item))))) ;;; redefined with objects of several voices... (defmethod get-total-y-shift ((editor score-editor) voice-num) (editor-get-edit-param editor :y-shift)) (defmethod om-view-click-handler ((self score-view) position) (let* ((editor (editor self)) (obj (object-value editor)) (ed-staff (editor-get-edit-param editor :staff)) (scale (get-the-scale (editor-get-edit-param editor :scale))) (unit (font-size-to-unit (editor-get-edit-param editor :font-size)))) (set-paste-position position self) ;;; for copy/paste (multiple-value-bind (voice pos) (get-voice-at-pos editor position) (declare (ignore pos)) (when voice (let* ((voice-pos (and (get-voices obj) (position voice (get-voices obj)))) (staff (if (listp ed-staff) (or (and voice-pos (nth voice-pos ed-staff)) (car ed-staff)) ed-staff)) (shift (+ (calculate-staff-line-shift staff) (get-total-y-shift editor voice-pos))) (clicked-pos position) (click-y-in-units (- shift (/ (om-point-y position) unit))) (clicked-pitch (line-to-pitch click-y-in-units scale)) ;;; <= scale here ??? ) (clicked-time (pixel-to-time self (om-point-x position)))) (cond ((om-add-key-down) ;;; add a note (store-current-state-for-undo editor) (let ((container-chord (get-chord-from-editor-click editor position))) (when container-chord (let ((new-note (make-instance 'note :midic clicked-pitch))) ;;; set to the same dur as others (important in voices) (when (notes container-chord) (setf (dur new-note) (list-max (ldur container-chord)))) (setf (notes container-chord) (sort (cons new-note (notes container-chord)) '< :key 'midic)) ;;; some updates of the time-sequence required here (score-object-update voice) (report-modifications editor) (editor-invalidate-views editor) (if (or (= 1 (length (notes container-chord))) (find container-chord (selection editor))) (setf (selection editor) (list container-chord)) (setf (selection editor) (list new-note))) (om-init-temp-graphics-motion self position nil :min-move 1 :motion #'(lambda (view pos) (declare (ignore view)) (let* ((new-y-in-units (- shift (/ (om-point-y pos) unit))) (new-pitch (line-to-pitch new-y-in-units scale)) (diff (- new-pitch clicked-pitch))) (unless (zerop diff) (store-current-state-for-undo editor :action :move :item (selection editor)) (loop for n in (get-notes (selection editor)) do (setf (midic n) (+ (midic n) diff))) (setf clicked-pitch new-pitch) (om-invalidate-view self)) )) :release #'(lambda (view pos) (declare (ignore view pos)) (reset-undoable-editor-action editor) (report-modifications editor)) ) (notify-scheduler obj) )))) ;; select (t (let ((selection (find-score-element-at-pos obj position))) (set-selection editor selection) (editor-invalidate-views editor) ;;; move the selection or select rectangle... (if selection ;;; move it (let ((modif nil)) (om-init-temp-graphics-motion self position nil :min-move 1 :motion #'(lambda (view pos) (declare (ignore view)) (let ((x-move (- (om-point-x pos) (om-point-x clicked-pos))) (y-move (- (om-point-y pos) (om-point-y clicked-pos)))) (when (or (and (edit-time-? editor) (> (abs x-move) 0)) (> (abs y-move) 0)) (store-current-state-for-undo editor :action :move :item (selection editor)) (when (edit-time-? editor) (let* ((new-time (pixel-to-time self (om-point-x pos))) (diff (- new-time clicked-time))) (unless (zerop diff) (setf modif t) ;;; remove-duplicates: continuation chords refer to existing notes ! (loop for c in (get-selected-chords editor) do (when (>= (+ (item-get-time c) diff) 0) (item-set-time c (+ (item-get-time c) diff)))) (setf clicked-time new-time) ))) (let* ((new-y-in-units (- shift (/ (om-point-y pos) unit))) (new-pitch (line-to-pitch new-y-in-units scale)) (diff (- new-pitch clicked-pitch))) (unless (zerop diff) (setf modif t) ;;; remove-duplicates: continuation chords refer to existing notes ! (loop for n in (remove-duplicates (get-notes (selection editor))) do (unless (equal (editor-play-state editor) :stop) (close-open-chords-at-time (get-chords-of-selection editor) (get-obj-time obj) obj)) (setf (midic n) (+ (midic n) diff))) (setf clicked-pitch new-pitch) )) (editor-invalidate-views editor)) (setf clicked-pos pos) )) :release #'(lambda (view pos) (declare (ignore view pos)) (when modif (score-object-update voice) (unless (equal (editor-play-state editor) :stop) (close-open-chords-at-time (get-chords-of-selection editor) (get-obj-time obj) obj)) (notify-scheduler obj) (reset-undoable-editor-action editor) (report-modifications editor))) )) ;;; no selection: start selection-rectangle (om-init-temp-graphics-motion self position (om-make-graphic-object 'selection-rectangle :position position :size (om-make-point 4 4)) :min-move 10 :release #'(lambda (view end-pos) (let ((x1 (min (om-point-x position) (om-point-x end-pos))) (x2 (max (om-point-x position) (om-point-x end-pos))) (y1 (min (om-point-y position) (om-point-y end-pos))) (y2 (max (om-point-y position) (om-point-y end-pos)))) (set-selection editor (find-score-elements-in-area obj x1 y1 x2 y2)) (om-invalidate-view view) )) ) ) )) ) ))))) (defmethod om-view-zoom-handler ((self score-view) position zoom) (let ((editor (editor self)) (d-size (if (> zoom 1) 1 -1))) (set-font-size editor (+ d-size (editor-get-edit-param editor :font-size))) )) ;;;====================== ;;; KEYBOARD ACTIONS ;;;====================== ;;; to be specialized for specific types of editor/objects (defmethod score-editor-delete ((self score-editor) element) nil) (defmethod score-editor-change-selection-durs ((self score-editor) delta) nil) (defmethod score-editor-handle-voice-selection ((self score-editor) direction) nil) (defmethod score-editor-update-params-before-remove ((self score-editor) removed) nil) (defmethod editor-key-action ((editor score-editor) key) (case key (:om-key-left (if (om-option-key-p) (progn (store-current-state-for-undo editor) (with-schedulable-object (object-value editor) (score-editor-change-selection-durs editor (if (om-shift-key-p) -1000 -100))) (editor-invalidate-views editor) (report-modifications editor)) (call-next-method))) (:om-key-right (if (om-option-key-p) (progn (store-current-state-for-undo editor) (with-schedulable-object (object-value editor) (score-editor-change-selection-durs editor (if (om-shift-key-p) 1000 100))) (editor-invalidate-views editor) (report-modifications editor)) (call-next-method))) ;;; if not with "option", left/right for chord-seq are handled in data-track-editor only (:om-key-up (store-current-state-for-undo editor) (score-editor-handle-voice-selection editor -1) (move-editor-selection editor :dy (if (om-shift-key-p) 12 1)) (editor-invalidate-views editor) (report-modifications editor)) (:om-key-down (store-current-state-for-undo editor) (score-editor-handle-voice-selection editor 1) (move-editor-selection editor :dy (if (om-shift-key-p) -12 -1)) (editor-invalidate-views editor) (report-modifications editor)) (:om-key-delete (with-schedulable-object (object-value editor) (delete-selection editor))) (#\g (add-selection-to-group editor)) (#\G (delete-selection-group editor)) (otherwise (call-next-method)) )) ;;; also called by cut-command: (defmethod delete-selection ((editor score-editor)) (when (selection editor) (store-current-state-for-undo editor) (unless (equal (editor-play-state editor) :stop) (close-open-chords-at-time (get-selected-chords editor) (get-obj-time (object-value editor)) (object-value editor))) (loop for element in (selection editor) do (score-editor-update-params-before-remove editor element) (score-editor-delete editor element) ) (setf (selection editor) nil) (editor-invalidate-views editor) (report-modifications editor))) ;;;====================== ;;; CONTROL PANEL ;;;====================== (defmethod set-font-size ((self score-editor) size) (let ((v (min 120 (max 8 size)))) (editor-set-edit-param self :font-size v) (when (get-g-component self :font-size-box) (om-set-selected-item (get-g-component self :font-size-box) v)))) ;;; required for after some changes or edit-param modifs ;;; (add/remove voice, change staff, etc..) ;;; redefined in multi-editors (defmethod set-interior-size-from-contents ((self score-editor)) nil) (defmethod make-score-display-params-controls ((editor score-editor)) (let* ((text-h 16) (control-h 24) (title (om-make-di 'om-simple-text :text "Editor params" :size (omp 100 22) :font (om-def-font :gui-title))) (size-item (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "size" :font (om-def-font :gui) :size (omp 30 text-h)) (set-g-component editor :font-size-box (om-make-di 'om-popup-list :items *score-fontsize-options* :size (omp 55 control-h) :font (om-def-font :gui) :value (editor-get-edit-param editor :font-size) :di-action #'(lambda (list) (set-font-size editor (om-get-selected-item list)) )))) )) (staff-item (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "staff" :size (omp 35 text-h) :font (om-def-font :gui)) (set-g-component editor :staff-menu ;; we need to change it sometimes... (om-make-di 'om-popup-list :items *score-staff-options* :size (omp 100 control-h) :font (om-def-font :gui) :value (editor-get-edit-param editor :staff) :di-action #'(lambda (list) (set-editor-staff editor (om-get-selected-item list)) (set-interior-size-from-contents editor) (report-modifications editor) ;; update the box display )))))) (scale-item (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "scale" :size (omp 35 text-h) :font (om-def-font :gui)) (om-make-di 'om-popup-list :items (mapcar #'car *all-scales*) :size (omp 100 control-h) :font (om-def-font :gui) :value (editor-get-edit-param editor :scale) :di-action #'(lambda (list) (editor-set-edit-param editor :scale (om-get-selected-item list)) (report-modifications editor) ;; update the box display ))))) (duration-item (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "durations" :size (omp 56 text-h) :font (om-def-font :gui)) (om-make-di 'om-check-box :text "" :font (om-def-font :gui) :size (omp 20 control-h) :checked-p (editor-get-edit-param editor :duration-display) :di-action #'(lambda (item) (editor-set-edit-param editor :duration-display (om-checked-p item)))) ))) (grid-numbox (om-make-graphic-object 'numbox :position (omp 0 0) :value (editor-get-edit-param editor :grid-step) :enabled (editor-get-edit-param editor :grid) :bg-color (om-def-color :white) :db-click t :decimals 0 :size (om-make-point 40 text-h) :font (om-def-font :normal) :min-val 10 :max-val 10000 :after-fun #'(lambda (item) (editor-set-edit-param editor :grid-step (value item)) (editor-invalidate-views editor)))) (grid-item (om-make-layout 'om-row-layout :align :center :delta nil :subviews (list (om-make-di 'om-simple-text :text "grid" :font (om-def-font :gui) :size (omp 56 text-h)) (om-make-di 'om-check-box :checked-p (editor-get-edit-param editor :grid) :text "" :size (om-make-point 16 control-h) :di-action #'(lambda (item) (enable-numbox grid-numbox (om-checked-p item)) (editor-set-edit-param editor :grid (om-checked-p item)) (editor-invalidate-views editor) )) (om-make-layout 'om-simple-layout :align :bottom :subviews (list grid-numbox))) )) ;;; end LET declarations ) ;;; all in a simple layout fixes refresh/redisplay ;;; problems on windows... (om-make-layout 'om-simple-layout :subviews (list (om-make-layout 'om-grid-layout :dimensions '(3 2) :delta '(10 0) :subviews (list title scale-item duration-item size-item staff-item (when (find :grid (object-default-edition-params (object-value editor)) :key #'car) ;;; not all objects have a grid... grid-item) )) )) )) (defmethod score-editor-set-window-config ((self score-editor) mode) (unless (equal (editor-window-config self) mode) (setf (editor-window-config self) mode) (let (x1 x2) (when (get-g-component self :x-ruler) (setf x1 (v1 (get-g-component self :x-ruler)) x2 (v2 (get-g-component self :x-ruler)))) (build-editor-window self) (init-editor-window self) (when (get-g-component self :x-ruler) (set-ruler-range (get-g-component self :x-ruler) x1 x2)) (update-score-inspector self t) ))) ;;; redefined for multi-seq-editor (defmethod set-editor-staff ((editor score-editor) staff) (editor-set-edit-param editor :staff staff)) ;;;====================== ;;; MENUS ;;;====================== (defun score-edit-menu-items (self) (list (om-make-menu-comp (list (om-make-menu-item "Undo" #'(lambda () (when (undo-command self) (funcall (undo-command self)))) :key "z" :enabled #'(lambda () (and (undo-command self) t))) (om-make-menu-item "Redo" #'(lambda () (when (redo-command self) (funcall (redo-command self)))) :key "Z" :enabled #'(lambda () (and (redo-command self) t))))) (om-make-menu-comp (list (om-make-menu-item "Copy" #'(lambda () (funcall (copy-command self))) :key "c" :enabled #'(lambda () (and (copy-command self) t))) (om-make-menu-item "Cut" #'(lambda () (funcall (cut-command self))) :key "x" :enabled #'(lambda () (and (cut-command self) t))) (om-make-menu-item "Paste" #'(lambda () (funcall (paste-command self))) :key "v" :enabled #'(lambda () (and (paste-command self) t))) (om-make-menu-item "Delete" #'(lambda () (funcall (clear-command self))) :enabled (and (clear-command self) t)))) (om-make-menu-comp (list (om-make-menu-item "Select All" #'(lambda () (funcall (select-all-command self))) :key "a" :enabled #'(lambda () (and (select-all-command self) t))))) (om-make-menu-comp (list (om-make-menu-item "Align Chords [Shift+A]" #'(lambda () (funcall (align-command self))) :enabled #'(lambda () (and (align-command self) t))))) (om-make-menu-comp (extras-menus self)) (om-make-menu-comp (list (om-make-menu-item "Add to group [G]" #'(lambda () (add-selection-to-group self)) :enabled #'(lambda () (and (selection self) (editor-get-edit-param self :groups))) ) (om-make-menu-item "Remove from group [Shift+G]" #'(lambda () (delete-selection-group self)) :enabled #'(lambda () (and (selection self) (editor-get-edit-param self :groups))) ))) (om-make-menu-item "Show Inspector" #'(lambda () (score-editor-set-window-config self (if (equal (editor-window-config self) :inspector) nil :inspector))) :selected #'(lambda () (equal (editor-window-config self) :inspector)) :key "i" ) )) (defmethod import-menus ((self score-editor)) nil) (defmethod export-menus ((self score-editor)) nil) (defmethod extras-menus ((self score-editor)) nil) (defmethod import-export-menu-items ((self score-editor)) (list (om-make-menu-comp (list (om-make-menu "Import..." (import-menus self) :enabled (import-menus self)) (om-make-menu "Export..." (export-menus self) :enabled (export-menus self))) ))) (defmethod om-menu-items ((self score-editor)) (remove nil (list (main-app-menu-item) (om-make-menu "File" (append (default-file-menu-items self) (import-export-menu-items self))) (om-make-menu "Edit" (score-edit-menu-items self)) (om-make-menu "Windows" (default-windows-menu-items self)) (om-make-menu "Help" (default-help-menu-items self)) ))) (defmethod select-all-command ((self score-editor)) #'(lambda () (set-selection self (get-tpl-elements-of-type (object-value self) '(chord r-rest))) (editor-invalidate-views self) )) (defmethod copy-command ((self score-editor)) (when (selection self) #'(lambda () (set-om-clipboard (mapcar #'om-copy (selection self)))))) (defmethod cut-command ((self score-editor)) (when (selection self) #'(lambda () (set-om-clipboard (mapcar #'om-copy (selection self))) (delete-selection self) (notify-scheduler (object-value self)) ))) (defmethod paste-command ((self score-editor)) (when (get-om-clipboard) #'(lambda () (score-editor-paste self (get-om-clipboard)) (notify-scheduler (object-value self)) (editor-invalidate-views self) ))) ;;; different behaviours for the different editors... (defmethod score-editor-paste ((self t) elements) nil) ;;; PASTE FROM SCORE IN PATCH (defmethod paste-command-for-view :around ((editor patch-editor) (view patch-editor-view)) (let ((clipboard (get-om-clipboard))) (if (find-if #'(lambda (elt) (subtypep (type-of elt) 'score-element)) clipboard) (let ((object (cond ((list-subtypep clipboard 'measure) ;;; make a voice boix with selected measures (let ((obj (make-instance 'voice :tree nil))) (insert-in-voice obj (reverse clipboard) 0) obj)) ((= 1 (length clipboard)) ;;; make a box with the only object in the clipboard (om-copy (car clipboard))) ((list-subtypep clipboard 'voice) ;;; make a multi-seq with the objects in the clipboard (make-instance 'poly :obj-list (mapcar #'om-copy clipboard))) ((list-subtypep clipboard 'chord-seq) ;;; make a multi-seq with the objects in the clipboard (make-instance 'multi-seq :obj-list (mapcar #'om-copy clipboard))) (t ;;; make a chord-seq from chords (let ((chords (sort (loop for item in clipboard append (get-chords item)) #'< :key #'onset))) (when chords (let ((t0 (onset (car chords)))) (loop for c in chords do (item-set-time c (- (item-get-time c) t0))) (let ((obj (make-instance 'chord-seq))) (set-chords obj chords) obj))))) ))) (if object (let ((paste-pos (or (get-paste-position view) (om-make-point (round (w view) 2) (- (h view) 60))))) (output-value-as-new-box object view paste-pos) (set-paste-position (om-add-points paste-pos (omp 20 20)) view)) (om-beep)) ) (call-next-method)) )) ;;; only works in chord-seq-editor (defmethod align-command ((self score-editor)) nil) ;;;===================================== ;;; INSPECTOR / EDIT VALUES IN SCORE ;;;===================================== (defclass score-inspector-view (inspector-view) ()) (defmethod make-editor-window-contents ((editor score-editor)) (set-g-component editor :inspector nil) (let ((main-editor-view (call-next-method))) (if (editor-window-config editor) (let ((inspector-panel (make-instance 'score-inspector-view))) (set-g-component editor :inspector inspector-panel) (om-make-layout 'om-row-layout :ratios '(9 nil 1) :subviews (list main-editor-view :separator inspector-panel ))) (om-make-layout 'om-row-layout :ratios '(1 nil) :subviews (list main-editor-view (om-make-layout 'om-column-layout :subviews (list nil ;;; space at the top (om-make-view 'om-view :size (omp 16 16) :subviews (list (om-make-graphic-object 'om-icon-button :size (omp 16 16) :position (omp 0 0) :icon :info-gray :icon-disabled :info :lock-push nil :enabled (not (equal (editor-window-config editor) :inspector)) :action #'(lambda (b) (declare (ignore b)) (score-editor-set-window-config editor (if (equal (editor-window-config editor) :inspector) nil :inspector))) ) )) nil ;;; space at the bottom )) )) ))) (defmethod update-score-inspector ((editor score-editor) &optional force) (let ((inspector (get-g-component editor :inspector))) (when (and inspector (or force (not (equal (selection editor) (object inspector))))) ;;; this equal test shoudl work if these are two lists with the same thing (set-inspector-contents inspector (selection editor)) ))) (defmethod report-modifications ((self score-editor)) (call-next-method) (editor-update-analysis self) (update-score-inspector self t)) (defmethod set-selection ((editor score-editor) (new-selection t)) (call-next-method) (update-score-inspector editor)) ;;; forbidden in voicee/poly editors (defmethod note-dur-edit-allowed ((self score-editor)) t) ;;; in principle elt is always a list (the editor selection) (defmethod set-inspector-contents ((self score-inspector-view) object) (setf (object self) object) (om-remove-all-subviews self) (let* ((editor (editor self)) (notes (loop for elt in object append (get-tpl-elements-of-type elt 'note))) (measures (loop for elt in object append (get-tpl-elements-of-type elt 'measure))) (voices (loop for elt in object append (get-tpl-elements-of-type elt 'voice))) (numbox-h 16) (text-h 16) (control-h 22) (close-button ;;; "close" button at the top-right... (om-make-layout 'om-row-layout :ratios '(100 1) :subviews (list nil (om-make-graphic-object 'om-icon-button :icon :xx :icon-pushed :xx-pushed :size (omp 12 12) :action #'(lambda (b) (declare (ignore b)) (score-editor-set-window-config editor nil)) ) ))) (notes-layout (om-make-layout 'om-column-layout :subviews (list (om-make-di 'om-simple-text :size (om-make-point 120 20) :text "Selected note(s)" :font (om-def-font :gui-b)) (if notes (om-make-layout 'om-grid-layout :dimensions '(2 6) :delta '(4 0) :subviews (list (om-make-di 'om-simple-text :size (om-make-point 50 text-h) :text "midic" :font (om-def-font :normal)) (om-make-view 'om-view :size (omp 40 numbox-h) :subviews (list (om-make-graphic-object 'numbox :size (omp 40 numbox-h) :position (omp 0 0) :font (om-def-font :normal) :bg-color (om-def-color :white) :fg-color (if (all-equal (mapcar #'midic notes)) (om-def-color :black) (om-def-color :gray)) :db-click t :min-val 0 :max-val 20000 :value (slot-value (car notes) 'midic) :after-fun #'(lambda (item) (store-current-state-for-undo editor) (loop for n in notes do (setf (slot-value n 'midic) (value item))) (update-from-editor (object editor)) (editor-invalidate-views editor)) ))) (om-make-di 'om-simple-text :size (om-make-point 50 text-h) :text "vel" :font (om-def-font :normal)) (om-make-view 'om-view :size (omp 40 numbox-h) :subviews (list (om-make-graphic-object 'numbox :size (omp 40 numbox-h) :position (omp 0 0) :font (om-def-font :normal) :bg-color (om-def-color :white) :fg-color (if (all-equal (mapcar #'vel notes)) (om-def-color :black) (om-def-color :gray)) :db-click t :min-val 0 :max-val 127 :value (slot-value (car notes) 'vel) :after-fun #'(lambda (item) (store-current-state-for-undo editor) (loop for n in notes do (setf (slot-value n 'vel) (value item))) (update-from-editor (object editor)) (editor-invalidate-views editor)) ))) (om-make-di 'om-simple-text :size (om-make-point 50 text-h) :text "dur" :font (om-def-font :normal)) (om-make-view 'om-view :size (omp 40 numbox-h) :subviews (list (om-make-graphic-object 'numbox :size (omp 40 numbox-h) :position (omp 0 0) :font (om-def-font :normal) :bg-color (om-def-color :white) :db-click t :enabled (note-dur-edit-allowed editor) :fg-color (if (and (all-equal (mapcar #'dur notes)) (note-dur-edit-allowed editor)) (om-def-color :black) (om-def-color :gray)) :min-val 0 :max-val 10000 :value (slot-value (car notes) 'dur) :after-fun #'(lambda (item) (store-current-state-for-undo editor) (loop for n in notes do (setf (slot-value n 'dur) (value item))) (update-from-editor (object editor)) (editor-invalidate-views editor)) ))) (om-make-di 'om-simple-text :size (om-make-point 50 text-h) :text "offset" :font (om-def-font :normal)) (om-make-view 'om-view :size (omp 40 numbox-h) :subviews (list (om-make-graphic-object 'numbox :size (omp 40 numbox-h) :position (omp 0 0) :bg-color (om-def-color :white) :font (om-def-font :normal) :enabled (note-dur-edit-allowed editor) :fg-color (if (and (all-equal (mapcar #'dur notes)) (note-dur-edit-allowed editor)) (om-def-color :black) (om-def-color :gray)) :db-click t :min-val -20000 :max-val 20000 :value (slot-value (car notes) 'offset) :after-fun #'(lambda (item) (store-current-state-for-undo editor) (loop for n in notes do (setf (slot-value n 'offset) (value item))) (update-from-editor (object editor)) (editor-invalidate-views editor)) ))) (om-make-di 'om-simple-text :size (om-make-point 50 text-h) :text "chan" :font (om-def-font :normal)) (om-make-view 'om-view :size (omp 40 numbox-h) :subviews (list (om-make-graphic-object 'numbox :size (omp 40 numbox-h) :position (omp 0 0) :font (om-def-font :normal) :bg-color (om-def-color :white) :fg-color (if (all-equal (mapcar #'chan notes)) (om-def-color :black) (om-def-color :gray)) :db-click t :min-val 1 :max-val 16 :value (slot-value (car notes) 'chan) :after-fun #'(lambda (item) (store-current-state-for-undo editor) (loop for n in notes do (setf (slot-value n 'chan) (value item))) (update-from-editor (object editor)) (editor-invalidate-views editor)) ))) (om-make-di 'om-simple-text :size (om-make-point 50 text-h) :text "port" :font (om-def-font :normal)) (om-make-view 'om-view :size (omp 40 numbox-h) :subviews (list (om-make-graphic-object 'numbox :size (omp 40 numbox-h) :position (omp 0 0) :bg-color (om-def-color :white) :font (om-def-font :normal) :fg-color (if (all-equal (mapcar #'port notes)) (om-def-color :black) (om-def-color :gray)) :db-click t :allow-nil -1 :min-val -1 :max-val 1000 :value (slot-value (car notes) 'port) :after-fun #'(lambda (item) (store-current-state-for-undo editor) (loop for n in notes do (setf (slot-value n 'port) (value item))) (update-from-editor (object editor)) (editor-invalidate-views editor)) ))) )) ;;; else (no notes) (om-make-di 'om-simple-text :size (om-make-point 100 text-h) :text "--" :fg-color (om-def-color :dark-gray) :focus t ;; prevents focus on other items :) :font (om-def-font :large))) )) ) (measures-layout (when measures (om-make-layout 'om-column-layout :subviews (list (om-make-di 'om-simple-text :size (om-make-point 120 20) :text "Selected measure(s)" :font (om-def-font :gui-b)) (om-make-layout 'om-row-layout :subviews (list (om-make-di 'om-simple-text :size (om-make-point 84 text-h) :text "time signature:" :font (om-def-font :gui)) (om-make-view 'om-view :size (omp 25 numbox-h) :subviews (list (om-make-graphic-object 'numbox :font (om-def-font :normal) :size (omp 25 numbox-h) :bg-color (om-def-color :white) :fg-color (if (all-equal (mapcar #'(lambda (m) (car (car (tree m)))) measures)) (om-def-color :black) (om-def-color :gray)) :db-click t :min-val 1 :max-val 120 :value (car (car (tree (car measures)))) :after-fun #'(lambda (item) (let ((temp-selection nil)) (store-current-state-for-undo editor) (loop for m in measures do (let ((container-voice (find-if #'(lambda (v) (find m (inside v))) (get-all-voices editor)))) (when container-voice (let ((pos (position m (inside container-voice))) (new-tree (list (list (value item) (cadr (car (tree m)))) (cadr (tree m))))) (push (list container-voice pos) temp-selection) (setf (nth pos (cadr (tree container-voice))) new-tree) )))) (loop for v in (remove-duplicates (mapcar #'car temp-selection)) do (build-voice-from-tree v)) ;;; restore selected measures (they have be rebuilt) (setf (selection editor) (loop for elt in temp-selection collect (nth (cadr elt) (inside (car elt))))) (update-from-editor (object editor)) (editor-invalidate-views editor))) ))) (om-make-view 'om-view :size (omp 25 numbox-h) :subviews (list (om-make-graphic-object 'numbox :size (omp 25 numbox-h) :font (om-def-font :normal) :bg-color (om-def-color :white) :fg-color (if (all-equal (mapcar #'(lambda (m) (cadr (car (tree m)))) measures)) (om-def-color :black) (om-def-color :gray)) :db-click t :min-val 1 :max-val 120 :value (cadr (car (tree (car measures)))) :after-fun #'(lambda (item) (let ((temp-selection nil)) (store-current-state-for-undo editor) (loop for m in measures do (let ((container-voice (find-if #'(lambda (v) (find m (inside v))) (get-all-voices editor)))) (when container-voice (let ((pos (position m (inside container-voice))) (new-tree (list (list (car (car (tree m))) (value item)) (cadr (tree m))))) (push (list container-voice pos) temp-selection) (setf (nth pos (cadr (tree container-voice))) new-tree) )))) (loop for v in (remove-duplicates (mapcar #'car temp-selection)) do (build-voice-from-tree v)) ;;; restore selected measures (they have be rebuilt) (setf (selection editor) (loop for elt in temp-selection collect (nth (cadr elt) (inside (car elt))))) (update-from-editor (object editor)) (editor-invalidate-views editor))) ))) NIL ;; padding )) ))) ) (voices-layout (when voices (om-make-layout 'om-column-layout :subviews (list (om-make-di 'om-simple-text :size (om-make-point 120 20) :text "Selected voice(s)" :font (om-def-font :gui-b)) (om-make-layout 'om-row-layout :subviews (list (om-make-di 'om-simple-text :size (om-make-point 80 text-h) :text "tempo:" :font (om-def-font :gui)) (om-make-view 'om-view :size (omp 30 numbox-h) :subviews (list (om-make-graphic-object 'numbox :size (omp 30 numbox-h) :font (om-def-font :normal) :bg-color (om-def-color :white) :fg-color (if (all-equal (mapcar #'tempo voices)) (om-def-color :black) (om-def-color :gray)) :db-click t :min-val 1 :max-val 600 :value (tempo (car voices)) :after-fun #'(lambda (item) (store-current-state-for-undo editor) (loop for v in voices do (setf (tempo v) (value item)) (set-timing-from-tempo (chords v) (tempo v)) ) (update-from-editor (object editor)) (editor-invalidate-views editor)) ))) ))) ))) (display-params-text-w 72) (display-params-menu-w 76) (display-params-layout (om-make-layout 'om-column-layout :delta 1 :subviews (list (om-make-di 'om-simple-text :size (om-make-point 120 20) :text "Display params" :font (om-def-font :gui-b)) (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "offsets" :font (om-def-font :gui) :size (omp display-params-text-w text-h)) (om-make-di 'om-popup-list :items '(:hidden :shift :grace-note) :size (omp display-params-menu-w control-h) :font (om-def-font :gui) :value (editor-get-edit-param editor :offsets) :di-action #'(lambda (list) (editor-set-edit-param editor :offsets (om-get-selected-item list))) ) )) (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "velocity" :size (omp display-params-text-w text-h) :font (om-def-font :gui)) (om-make-di 'om-popup-list :items '(:hidden :value :symbol :size :alpha) :size (omp display-params-menu-w control-h) :font (om-def-font :gui) :value (editor-get-edit-param editor :velocity-display) :di-action #'(lambda (list) (editor-set-edit-param editor :velocity-display (om-get-selected-item list)))) )) (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "MIDI channel" :size (omp display-params-text-w text-h) :font (om-def-font :gui)) (om-make-di 'om-popup-list :items '(:hidden :number :color :color-and-number) :size (omp display-params-menu-w control-h) :font (om-def-font :gui) :value (editor-get-edit-param editor :channel-display) :di-action #'(lambda (list) (editor-set-edit-param editor :channel-display (om-get-selected-item list)))) )) (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "MIDI port" :size (omp display-params-text-w text-h) :font (om-def-font :gui)) (om-make-di 'om-check-box :text "" :font (om-def-font :gui) :size (omp 28 20) :checked-p (editor-get-edit-param editor :port-display) :di-action #'(lambda (item) (editor-set-edit-param editor :port-display (om-checked-p item)))))) ))) (groups-layout (editor-groups-controls editor)) (analysis-layout (editor-analysis-controls editor)) (player-layout (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "Player" :size (omp 40 text-h) :font (om-def-font :gui-b)) (om-make-di 'om-popup-list :items '(:midi :osc) :size (omp 100 control-h) :font (om-def-font :gui) :value (editor-get-edit-param editor :player) :di-action #'(lambda (list) (editor-set-edit-param editor :player (om-get-selected-item list)) (report-modifications editor) ;; update the box display ))))) ) ;;; end LET (om-add-subviews self (om-make-layout 'om-simple-layout :subviews (list (om-make-layout 'om-column-layout :delta 10 :subviews (remove nil (list close-button notes-layout measures-layout voices-layout display-params-layout groups-layout analysis-layout player-layout )))))) (when editor (om-update-layout (window editor))) )) (defmethod editor-groups-controls ((editor t)) nil) (defmethod editor-analysis-controls ((editor t)) nil)
63,289
Common Lisp
.lisp
1,199
32.060884
154
0.444126
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
6e81becbee432f443a976fe9a6d421bffaa9b2995dbea263db3d2af1a0e8ef8f
739
[ -1 ]
740
chord-editor.lisp
cac-t-u-s_om-sharp/src/packages/score/editor/chord-editor.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;======================================================================== ;;; CHORD EDITOR ;;;======================================================================== (defclass chord-editor (score-editor play-editor-mixin) ((temp-arp-chord :accessor temp-arp-chord :initform nil))) (defmethod object-has-editor ((self chord)) t) (defmethod get-editor-class ((self chord)) 'chord-editor) (defmethod object-default-edition-params ((self chord)) (append (call-next-method) '((:y-shift 4) (:chord-mode :chord)))) ;;; chord-mode: ;;; - chord = play the chord (with offsets if there are offsets) ;;; - arp-up = play arpegio up ;;; - arp-up = play arpegio down ;;; - arp-order = play arpegio in order (defmethod make-editor-window-contents ((editor chord-editor)) (let* ((panel (om-make-view 'score-view :size (omp 50 100) :direct-draw t :bg-color (om-def-color :white) :scrollbars nil :editor editor)) (bottom-area (make-score-display-params-controls editor))) (set-g-component editor :main-panel panel) (om-make-layout 'om-row-layout :ratios '(99 1) :subviews (list (om-make-layout 'om-column-layout :ratios '(99 1) :subviews (list panel bottom-area)) (call-next-method))) )) (defmethod make-score-display-params-controls ((editor chord-editor)) (let ((text-h 16) (control-h 24)) (om-make-layout 'om-row-layout :subviews (list (call-next-method) :separator (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "play-mode" :size (omp 60 text-h) :font (om-def-font :gui)) (om-make-di 'om-popup-list :items '(:chord :arp-up :arp-down :arp-order) :size (omp 80 control-h) :font (om-def-font :gui) :value (editor-get-edit-param editor :chord-mode) :di-action #'(lambda (list) (editor-set-edit-param editor :chord-mode (om-get-selected-item list)) (update-arp-chord editor) (editor-invalidate-views editor) )))) nil )))) (defmethod update-to-editor ((editor chord-editor) (from t)) (call-next-method) (editor-invalidate-views editor)) (defmethod editor-invalidate-views ((self chord-editor)) (call-next-method) (om-invalidate-view (get-g-component self :main-panel))) ;;; called at add-click (defmethod get-chord-from-editor-click ((self chord-editor) position) (declare (ignore position)) (if (in-arp-mode self) (om-beep-msg "Chord-editor can not be edited in 'arp' modes") (object-value self))) (defmethod editor-key-action ((self chord-editor) key) (if (and (in-arp-mode self) (not (member key '(#\Space)))) ;; a few keys are authorized (om-beep-msg "Chord-editor can not be edited in 'arp' modes") (call-next-method))) (defmethod score-editor-delete ((self chord-editor) element) (let ((c (object-value self))) (if (equal element c) (setf (notes c) nil) (setf (notes c) (remove element (notes c)))))) (defmethod move-editor-selection ((self chord-editor) &key (dx 0) (dy 0)) (declare (ignore dx)) (let* ((chord (object-value self)) (step (or (step-from-scale (editor-get-edit-param self :scale)) 100)) (notes (if (find chord (selection self)) (notes chord) (selection self)))) (unless (equal (editor-play-state self) :stop) (close-open-chords-at-time (list chord) (get-obj-time chord) chord)) (unless (zerop dy) (loop for n in notes do (setf (midic n) (+ (midic n) (* dy step))))) )) (defmethod score-editor-change-selection-durs ((self chord-editor) delta) (let* ((chord (object-value self)) (notes (if (find chord (selection self)) (notes chord) (selection self)))) (unless (equal (editor-play-state self) :stop) (close-open-chords-at-time (list chord) (get-obj-time chord) chord)) (loop for n in notes do (setf (dur n) (max (abs delta) (round (+ (dur n) delta))))) )) ;;; SPECIAL/SIMPLE CASE FOR CHORD-EDITOR (defmethod draw-score-object-in-editor-view ((editor chord-editor) view unit) (if (and (in-arp-mode editor) (temp-arp-chord editor)) ;;; draw the arp-chard (actually it's a simple chord-seq) (loop for chord in (chords (temp-arp-chord editor)) do (setf (b-box chord) (draw-chord chord (date chord) 0 (editor-get-edit-param editor :y-shift) 0 0 (w view) (h view) (editor-get-edit-param editor :font-size) :staff (editor-get-edit-param editor :staff) :staff (editor-get-edit-param editor :staff) :scale (editor-get-edit-param editor :scale) :draw-chans (editor-get-edit-param editor :channel-display) :draw-vels (editor-get-edit-param editor :velocity-display) :draw-ports (editor-get-edit-param editor :port-display) :draw-durs (editor-get-edit-param editor :duration-display) :selection (if (find chord (selection editor)) T (selection editor)) :time-function #'(lambda (time) (let ((dur-max (get-obj-dur (temp-arp-chord editor)))) (+ 100 (* (- (w view) 150) (/ time dur-max))) )) :build-b-boxes t )) ) (let ((chord (object-value editor))) (setf (b-box chord) (draw-chord chord 0 0 (editor-get-edit-param editor :y-shift) 0 0 (w view) (h view) (editor-get-edit-param editor :font-size) :staff (editor-get-edit-param editor :staff) :scale (editor-get-edit-param editor :scale) :draw-chans (editor-get-edit-param editor :channel-display) :draw-vels (editor-get-edit-param editor :velocity-display) :draw-ports (editor-get-edit-param editor :port-display) :draw-durs (editor-get-edit-param editor :duration-display) :draw-dur-ruler t :selection (if (find chord (selection editor)) T (selection editor)) :offsets (editor-get-edit-param editor :offsets) :time-function #'(lambda (time) (if (notes chord) (let ((dur-max (loop for n in (notes chord) maximize (+ (dur n) (offset n))))) (+ (/ (w view) 2) (* (/ (- (w view) 80) 2) (/ time dur-max))) ) ;;; no contents anyway... (/ (w view) 2) )) :build-b-boxes t )) ; (draw-b-box chord) ) )) ;;;==================================== ;;; PLAY ;;;==================================== (defmethod update-arp-chord ((self chord-editor)) (setf (temp-arp-chord self) (make-arp-chord (object-value self) (editor-get-edit-param self :chord-mode)))) (defmethod in-arp-mode ((self chord-editor)) (find (editor-get-edit-param self :chord-mode) '(:arp-order :arp-up :arp-down))) (defmethod init-editor :after ((self chord-editor)) (update-arp-chord self)) (defun make-arp-chord (chord mode) (case mode (:arp-order (make-instance 'chord-seq :lmidic (lmidic chord) :lchan (lchan chord) :lport (lport chord) :lvel (lvel chord) :lonset '(0 200) :ldur 200)) (:arp-up (make-instance 'chord-seq :lmidic (sort (lmidic chord) #'<) :lchan (lchan chord) :lport (lport chord) :lvel (lvel chord) :lonset '(0 200) :ldur 200)) (:arp-down (make-instance 'chord-seq :lmidic (sort (lmidic chord) #'>) :lchan (lchan chord) :lport (lport chord) :lvel (lvel chord) :lonset '(0 200) :ldur 200)) (t chord) )) (defmethod get-obj-to-play ((self chord-editor)) (or (temp-arp-chord self) (object-value self))) (defmethod start-editor-callback ((self chord-editor)) (update-arp-chord self) (call-next-method)) (defmethod editor-pause ((self chord-editor)) (editor-stop self)) ;;; play from box (defmethod play-obj-from-value ((val chord) box) (make-arp-chord val (get-edit-param box :chord-mode)))
10,691
Common Lisp
.lisp
228
32.780702
115
0.486689
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
41450e18034ba5625b7a218b8ba633723a6ea97545c7429cb65e03ee357545be
740
[ -1 ]
741
score-boxes.lisp
cac-t-u-s_om-sharp/src/packages/score/editor/score-boxes.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;=========================== ;;; DRAW SCORE OBJECT BOXES ;;;=========================== (in-package :om) ;; we need MultiCacheBoxEditCall as some score-object (POLY/MULTI-SEQ) ;; are subclasses of COLLECTION (defclass ScoreBoxEditCall (MultiCacheBoxEditCall) ((fontsize :accessor fontsize :initform nil))) (defmethod special-box-type ((class-name (eql 'score-element))) 'ScoreBoxEditCall) (defmethod default-size ((self ScoreBoxEditCall)) (score-object-default-box-size (get-box-value self))) (defmethod score-object-default-box-size ((self t)) (omp 80 50)) (defmethod score-object-default-box-size ((self chord)) (omp 80 80)) (defmethod score-object-default-box-size ((self note)) (omp 80 80)) (add-preference-section :appearance "Score Boxes") (add-preference :appearance :score-font "Score font size" '(10 12 14 16 18 20 24 28 32) 18) (defmethod get-box-fontsize ((self ScoreBoxEditCall)) (or (fontsize self) (get-pref-value :appearance :score-font))) (defmethod set-box-fontsize ((self ScoreBoxEditCall) size) (setf (fontsize self) size)) (defmethod display-modes-for-object ((self score-element)) '(:mini-view :text :hidden)) (defmethod additional-box-attributes ((self score-element)) `((:font-size "a font size for score display" nil) (:staff "default staff configuration" ,(loop for s in *score-staff-options* collect (list (string-upcase s) s))) (:scale "default scale" ,(loop for s in *all-scales* collect (list (string (car s)) (car s)))) )) (defmethod set-edit-param ((self ScoreBoxEditCall) (param (eql :staff)) value) (call-next-method) (init-object-staff-param (get-box-value self) self value)) (defmethod init-object-staff-param ((self t) box value) (declare (ignore box value)) nil) (defmethod init-object-staff-param ((self multi-seq) box value) (set-edit-param box :staff-list (make-list (length (obj-list self)) :initial-element value))) (defmethod miniview-time-to-pixel-proportional ((object score-element) box view time) (let* ((fontsize (get-box-fontsize box)) (unit (font-size-to-unit fontsize)) (shift-x-pix (* (score-mini-view-left-shift-in-units box) unit))) (+ shift-x-pix ;; left margin *miniview-x-margin* (* (- (w view) (* *miniview-x-margin* 2) shift-x-pix) (/ time (if (plusp (get-obj-dur object)) (get-obj-dur object) 1000)))) )) (defmethod miniview-time-to-pixel-rhythmic ((object score-element) box view time) (let* ((fontsize (get-box-fontsize box)) (unit (font-size-to-unit fontsize)) (shift-x-pix (* (score-mini-view-left-shift-in-units box) unit)) (time-map (get-edit-param box :time-map))) (+ shift-x-pix (* unit (score-time-to-units time-map time))) )) ;;; all objects (except voice/poly) on a box (defmethod miniview-time-to-pixel ((object score-element) box (view omboxframe) time) (miniview-time-to-pixel-proportional object box view time)) ;;; voice on a box (defmethod miniview-time-to-pixel ((object voice) box (view omboxframe) time) (if (equal (display box) :mini-view) (miniview-time-to-pixel-rhythmic object box view time) (miniview-time-to-pixel-proportional object box view time))) (defmethod miniview-time-to-pixel ((object poly) box (view omboxframe) time) (if (equal (display box) :mini-view) (miniview-time-to-pixel-rhythmic object box view time) (miniview-time-to-pixel-proportional object box view time))) (defmethod miniview-time-to-pixel ((object multi-seq) box (view omboxframe) time) (miniview-time-to-pixel-proportional object box view time)) ;;; an objects in the sequencer tracks... (defmethod miniview-time-to-pixel ((object score-element) box (view sequencer-track-view) time) (let ((tt (if (listp time) (car time) time))) ;;; can happen that time is a list (see draw-measure) (- (time-to-pixel view (+ (box-x box) tt)) (time-to-pixel view (box-x box))) )) (defun score-mini-view-left-shift-in-units (box) (if (equal (get-edit-param box :staff) :empty) 1 5)) (defmethod get-staff-for-voice ((self score-element) (box OMBox) (n integer)) (declare (ignore n)) (get-edit-param box :staff)) (defmethod get-staff-for-voice ((self multi-seq) (box OMBox) (n integer)) (declare (ignore n)) (or (nth n (get-edit-param box :staff-list)) (call-next-method))) (defparameter *score-box-voice-margin* 8) (defmethod compute-font-size ((self score-element) (box OMBox) h y) (let* ((font-size (get-pref-value :appearance :score-font)) (unit (font-size-to-unit font-size)) (y-in-units (/ y unit)) (num-voices (num-voices self))) (when (> num-voices 0) (let* ((n-lines (loop for n from 0 to (1- num-voices) for staff = (get-staff-for-voice self box n) sum (+ *score-box-voice-margin* (staff-line-range staff)))) (draw-h (* n-lines unit))) (if (> draw-h h) ;;; there's no space: reduce font ? (setf unit (- unit (/ (- draw-h h) n-lines)) font-size (unit-to-font-size unit)) ;;; there's space: draw more in the middle (setf y-in-units (+ y-in-units (/ (round (- h draw-h) 2) unit))) ) )) (values font-size y-in-units))) (defmethod draw-mini-view ((self score-element) (box OMBox) x y w h &optional time) (om-draw-rect x y w h :fill t :color (om-def-color :white)) (multiple-value-bind (fontsize y-u) (compute-font-size self box h y) (set-box-fontsize box fontsize) (om-with-fg-color (om-make-color 0.0 0.2 0.2) (score-object-mini-view self box x y y-u w h)) )) ;;; draw on a collection box... (defmethod collection-draw-mini-view ((type score-element) list box x y w h time) (let ((voice-h (if list (/ h (length list)) h))) (loop for voice in list for i from 0 do (let ((yy (+ y 4 (* i voice-h)))) (om-draw-rect x yy w (- voice-h 2) :fill t :color (om-def-color :white)) (score-object-mini-view voice box x yy 0 w voice-h) )) )) ;;; Hacks for patch-boxes / collection boxes etc. (defmethod get-edit-param ((self OMBoxAbstraction) param) (case param (:staff :g) (otherwise nil))) (defmethod get-box-fontsize ((self OMBox)) (get-pref-value :appearance :score-font)) (defmethod set-box-fontsize ((self OMBox) size) nil) ;;; what do we do with other objects ? (defmethod score-object-mini-view ((self t) box x-pix y-pix y-u w h &optional voice-staff) t) ;;;=========================== ;;; NOTE ;;;=========================== ;;; note has no editor (at the moment) so the font-size is not used (defmethod additional-box-attributes ((self note)) `((:staff "default staff configuration" ,(loop for s in *score-staff-options* collect (list (string-upcase s) s))) (:scale "default scale" ,(loop for s in *all-scales* collect (list (string (car s)) (car s)))) )) (defmethod score-object-mini-view ((self note) box x-pix y-pix y-u w h &optional voice-staff) (let ((staff (or voice-staff (get-edit-param box :staff))) (scale (get-edit-param box :scale)) (font-size (get-box-fontsize box)) (in-sequencer? (typep (frame box) 'sequencer-track-view))) (draw-staff x-pix y-pix y-u w h font-size staff :margin-l 1 :margin-r 1 :keys (not in-sequencer?)) (draw-chord self 0 2 y-u 0 y-pix w h font-size :scale scale :staff staff :stem NIL :time-function #'(lambda (time) (declare (ignore time)) (/ w 2))) )) ;;; super-hack to edit the note as a slider (defmethod editable-on-click ((self ScoreBoxEditCall)) (special-box-click-action (get-box-value self) self) nil) (defmethod special-box-click-action ((self t) box) nil) (defmethod special-box-click-action ((self note) box) (let* ((frame (frame box)) (h (- (h frame) (* 2 *miniview-y-margin*))) (position (om-mouse-position frame)) (y-position (- (om-point-y position) *miniview-y-margin*))) (when (or (om-action-key-down) (and (om-view-container frame) (container-frames-locked (om-view-container frame)))) (multiple-value-bind (fontsize y-u) (compute-font-size self box h *miniview-y-margin*) (let* (; (fontsize (get-box-fontsize box)) (unit (font-size-to-unit fontsize)) (staff (get-edit-param box :staff)) (scale (get-the-scale (get-edit-param box :scale))) (shift (+ (calculate-staff-line-shift staff) y-u)) (click-y-in-units (- shift (/ y-position unit))) (clicked-pitch (line-to-pitch click-y-in-units scale))) (setf (midic self) clicked-pitch) (om-init-temp-graphics-motion frame position nil :motion #'(lambda (view pos) (let* ((y-position (- (om-point-y pos) *miniview-y-margin*)) (click-y-in-units (- shift (/ y-position unit))) (clicked-pitch (line-to-pitch click-y-in-units scale))) (unless (equal clicked-pitch (midic self)) (setf (midic self) clicked-pitch) (self-notify box) (om-invalidate-view view) )))) (self-notify box) (update-after-eval box) ))))) ;;;=========================== ;;; CHORD ;;;=========================== (defmethod score-object-mini-view ((self chord) box x-pix y-pix y-u w h &optional voice-staff) (let ((staff (or voice-staff (get-edit-param box :staff))) (scale (get-edit-param box :scale)) (in-sequencer? (typep (frame box) 'sequencer-track-view)) (font-size (get-box-fontsize box))) (draw-staff x-pix y-pix y-u w h font-size staff :margin-l 1 :margin-r 1 :keys (not in-sequencer?)) (when (notes self) (draw-chord self 0 0 y-u x-pix y-pix w h font-size :scale scale :staff staff :time-function #'(lambda (time) (declare (ignore time)) (/ w 2)) )) )) ;;;=========================== ;;; CHORD-SEQ ;;;=========================== (defmethod score-object-mini-view ((self chord-seq) box x-pix y-pix y-u w h &optional voice-staff) (let* ((staff (or voice-staff (get-edit-param box :staff))) (scale (get-edit-param box :scale)) (offsets (get-edit-param box :offsets)) (font-size (get-box-fontsize box)) (in-sequencer? (typep (frame box) 'sequencer-track-view))) (when (listp staff) (setf staff (or (nth (position self (get-voices (get-box-value box))) staff) (car staff)))) (draw-staff x-pix y-pix y-u w h font-size staff :margin-l 0 :margin-r 0 :keys (not in-sequencer?)) (loop for chord in (chords self) do (draw-chord chord (date chord) 0 y-u x-pix y-pix w h font-size :scale scale :staff staff :time-function #'(lambda (time) (miniview-time-to-pixel (get-box-value box) box (frame box) time)) :offsets offsets)) )) ;;;=========================== ;;; VOICE ;;;=========================== (defmethod score-object-mini-view ((self voice) box x-pix y-pix shift-y w h &optional voice-staff) (let* ((staff (or voice-staff (get-edit-param box :staff))) (font-size (get-box-fontsize box)) (unit (font-size-to-unit font-size)) (x-u (/ x-pix unit)) (y-u (/ y-pix unit)) (shift-x x-u) ; (+ (score-mini-view-left-shift-in-units box) x-u)) (frame (frame box)) (max-w (w frame)) (in-sequencer? (typep frame 'sequencer-track-view))) (if (> h 5) (progn (draw-staff x-pix y-pix shift-y w h font-size staff :margin-l 0 :margin-r 0 :keys (not in-sequencer?)) (draw-tempo self (+ x-pix 4) (+ y-pix (* unit (+ shift-y 2))) font-size) (loop with on-screen = t with prev-signature = nil for m in (inside self) for i from 1 while on-screen do (setf on-screen (< (miniview-time-to-pixel (get-box-value box) box frame (beat-to-time (symbolic-date m) (tempo self))) max-w)) ;;; we draw the measure if it begins on-screen... (when on-screen (draw-measure m (tempo self) box (frame box) :position i :with-signature (and (not in-sequencer?) (not (equal (car (tree m)) prev-signature))) :staff staff :x-shift shift-x :y-shift (+ shift-y y-u) :font-size font-size :time-function #'(lambda (time) (miniview-time-to-pixel (get-box-value box) box frame time)) )) ;;; if the end is off-screen we notify it with a little gray area at the end (when (and (equal self (car (value box))) ;; don't do it on poly boxes (> (time-to-pixel frame (beat-to-time (+ (symbolic-date m) (symbolic-dur m)) (tempo self))) max-w)) (om-draw-rect (- (w frame) 20) 0 20 (h frame) :fill t :color (om-make-color .8 .8 .8 .5)) (om-draw-string (- (w frame) 16) (- (h frame) 12) "...")) (setf prev-signature (car (tree m))) )) (om-draw-line x-pix y-pix (+ w x-pix) y-pix :style '(1 2))) )) ;;;=========================== ;;; POLY ;;;=========================== (defmethod score-object-mini-view ((self multi-seq) box x-pix y-pix y-u w h &optional voice-staff) (let* ((staff-list (or (get-edit-param box :staff-list) (make-list (length (obj-list self)) :initial-element (get-edit-param box :staff)))) (total-lines (loop for staff in staff-list sum (+ *score-box-voice-margin* (staff-line-range staff))))) (loop with y = y-pix for voice in (obj-list self) for staff in staff-list do (let ((voice-h (* h (/ (+ *score-box-voice-margin* (staff-line-range staff)) total-lines)))) (score-object-mini-view voice box x-pix y 0 w voice-h staff) (setf y (+ y voice-h))) ))) (defmethod score-object-mini-view ((self poly) box x-pix y-pix y-u w h &optional voice-staff) (call-next-method) (let ((frame (frame box))) (when (> (time-to-pixel frame (get-obj-dur self)) (w frame)) (om-draw-rect (- (w frame) 20) 0 20 (h frame) :fill t :color (om-make-color .8 .8 .8 .5)) (om-draw-string (- (w frame) 16) (- (h frame) 12) "..."))))
16,071
Common Lisp
.lisp
322
40.652174
126
0.566929
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
ceb190af5aa3ecb1211b8101d8c9f4c56e510b17669bccecd05d3591ebae1407
741
[ -1 ]
742
scales.lisp
cac-t-u-s_om-sharp/src/packages/score/editor/scales.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ; (degree line accidental) (defparameter *default-scale* '((0 0 nil) (100 0 :sharp) (200 0.5 nil) (300 0.5 :sharp) (400 1 nil) (500 1.5 nil) (600 1.5 :sharp) (700 2 nil) (800 2 :sharp) (900 2.5 nil) (1000 2.5 :sharp) (1100 3 nil))) (defparameter *1/4-scale* '((0 0 nil) (50 0 :1/4-sharp) (100 0 :sharp) (150 0 :3/4-sharp) (200 0.5 nil) (250 0.5 :1/4-sharp) (300 0.5 :sharp) (350 0.5 :3/4-sharp) (400 1 nil) (450 1 :1/4-sharp) (500 1.5 nil) (550 1.5 :1/4-sharp) (600 1.5 :sharp) (650 1.5 :3/4-sharp) (700 2 nil) (750 2 :1/4-sharp) (800 2 :sharp) (850 2 :3/4-sharp) (900 2.5 nil) (950 2.5 :1/4-sharp) (1000 2.5 :sharp) (1050 2.5 :3/4-sharp) (1100 3 nil) (1150 3 :1/4-sharp) )) (defparameter *1/8-scale* '((0 0 nil) (25 0 :1/8-sharp) (50 0 :1/4-sharp) (75 0 :3/8-sharp) (100 0 :sharp) (125 0 :5/8-sharp) (150 0 :3/4-sharp) (175 0 :7/8-sharp) (200 0.5 nil) (225 0.5 :1/8-sharp) (250 0.5 :1/4-sharp) (275 0.5 :3/8-sharp) (300 0.5 :sharp) (325 0.5 :5/8-sharp) (350 0.5 :3/4-sharp) (375 0.5 :7/8-sharp) (400 1 nil) (425 1 :1/8-sharp) (450 1 :1/4-sharp) (475 1 :3/8-sharp) (500 1.5 nil) (525 1.5 :1/8-sharp) (550 1.5 :1/4-sharp) (575 1.5 :3/8-sharp) (600 1.5 :sharp) (625 1.5 :5/8-sharp) (650 1.5 :3/4-sharp) (675 1.5 :7/8-sharp) (700 2 nil) (725 2 :1/8-sharp) (750 2 :1/4-sharp) (775 2 :3/8-sharp) (800 2 :sharp) (825 2 :5/8-sharp) (850 2 :3/4-sharp) (875 2 :7/8-sharp) (900 2.5 nil) (925 2.5 :1/8-sharp) (950 2.5 :1/4-sharp) (975 2.5 :3/8-sharp) (1000 2.5 :sharp) (1025 2.5 :5/8-sharp) (1050 2.5 :3/4-sharp) (1075 2.5 :7/8-sharp) (1100 3 nil) (1125 3 :1/8-sharp) (1150 3 :1/4-sharp) (1175 3 :3/8-sharp) )) (defparameter *all-scales* `((:scale-1/2 ,*default-scale*) (:scale-1/4 ,*1/4-scale*) (:scale-1/8 ,*1/8-scale*))) (defun get-the-scale (symb) (or (cadr (find symb *all-scales* :key #'car)) *default-scale*)) (defun step-from-scale (symb) (let ((scale (get-the-scale symb))) (- (first (second scale)) (first (first scale))))) ;;; a utility for user-code to add new scales in score editors: (defun add-scale (name scale) (let ((existing-scale (find name *all-scales* :key #'car))) (if existing-scale (setf (cadr existing-scale) scale) (pushr (list name scale) *all-scales*) )))
3,334
Common Lisp
.lisp
122
23.02459
77
0.517986
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
4724a8709b8ae593f8588768fe9d69c5798fcb0040f2f70e953e3f2f77c2f6e4
742
[ -1 ]
743
voice-editor.lisp
cac-t-u-s_om-sharp/src/packages/score/editor/voice-editor.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) ;;;======================================================================== ;;; VOICE EDITOR ;;;======================================================================== (defclass voice-editor (chord-seq-editor) ()) (defmethod get-editor-class ((self voice)) 'voice-editor) (defmethod edit-time-? ((self voice-editor)) nil) (defmethod add-chords-allowed ((self voice-editor)) nil) (defparameter *stretch-options* '(.25 .5 .75 1 1.5 2 4 :proportional)) (defmethod make-score-display-params-controls ((editor voice-editor)) (let ((text-h 16) (control-h 24)) (om-make-layout 'om-row-layout :subviews (list (call-next-method) (om-make-view 'om-view :size (omp 50 10)) (om-make-layout 'om-column-layout :subviews (list NIL (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "h-stretch" :size (omp 56 text-h) :font (om-def-font :gui)) (om-make-di 'om-popup-list :items *stretch-options* :size (omp 80 control-h) :font (om-def-font :gui) :value (editor-get-edit-param editor :h-stretch) :di-action #'(lambda (list) (editor-set-edit-param editor :h-stretch (om-get-selected-item list)) (build-editor-window editor) (init-editor-window editor) ;;; will change the ruler (editor-update-ruler editor))) )) NIL )) nil )))) ;;; no cut from voice (defmethod cut-command ((self voice-editor)) #'(lambda () (om-beep))) (defmethod score-editor-paste ((self voice-editor) elements) (let* ((view (get-g-component self :main-panel)) (paste-pos (get-paste-position view)) (target-voice (cond ((typep (car (selection self)) 'voice) (car (selection self))) ((typep (car (selection self)) 'measure) (find-if #'(lambda (v) (find (car (selection self)) (inside v))) (get-all-voices self))) (t (get-voice-at-pos self (or paste-pos (omp 0 0))))))) (cond ;;; all selection are measures ((list-subtypep elements 'measure) ;;; insert measures before selected measure (if any) or at the end (let* ( (mesure (find 'measure (selection self) :key #'type-of)) (pos-in-voice (if mesure (position mesure (inside target-voice)) (length (inside target-voice))))) (store-current-state-for-undo self) (insert-in-voice target-voice (mapcar #'om-copy elements) pos-in-voice) (report-modifications self) )) ;; otherwise collect all chords and apply to selection in voice (t (let ((copied-chords (sort (loop for item in elements append (get-tpl-elements-of-type item 'chord)) #'< :key #'onset)) (target-chords (if (selection self) (sort (loop for item in (selection self) append (get-tpl-elements-of-type item 'chord)) #'< :key #'onset) (get-tpl-elements-of-type target-voice 'chord)))) (store-current-state-for-undo self) (loop for c in copied-chords for target in target-chords do (do-initialize target :lmidic (lmidic c) :lvel (lvel c) :lchan (lchan c) :lport (lport c) ;;; dur/offset are kept from original chord :ldur (ldur target) :loffset (loffset target) ) ) (report-modifications self) t)) ))) ;;; redo time-map at editing the object ;;; the object must have been drawn (defmethod report-modifications ((self voice-editor)) (call-next-method) (editor-set-edit-param self :time-map (build-time-map (object-value self))) (editor-update-ruler self)) (defmethod note-dur-edit-allowed ((self voice-editor)) nil) ;;; voice editor has a different ruler (defclass voice-ruler (time-ruler) ()) ;;; a "fake" negative duration to allow for teh first time-signature to show (defmethod data-track-get-x-ruler-vmin ((self voice-editor)) -1400) (defmethod set-ruler-range ((self voice-ruler) v1 v2) (let* ((panel (car (related-views self)))) (call-next-method self v1 (pixel-to-time panel (+ (time-to-pixel panel v1) (om-width panel)))))) (defmethod editor-update-ruler ((self voice-editor)) (let ((ruler (get-g-component self :x-ruler))) (set-ruler-range ruler (v1 ruler) (v2 ruler)) )) (defmethod init-editor-window :after ((self voice-editor)) (editor-set-edit-param self :time-map (build-time-map (object-value self))) (editor-update-ruler self)) (defmethod make-time-ruler ((editor voice-editor) dur) (om-make-view (if (numberp (editor-get-edit-param editor :h-stretch)) 'voice-ruler 'time-ruler) :related-views (get-g-component editor :data-panel-list) :size (omp nil 20) :bg-color (om-def-color :light-gray) :vmin (data-track-get-x-ruler-vmin editor) :x1 (data-track-get-x-ruler-vmin editor) :x2 dur)) (defmethod time-to-pixel ((self voice-ruler) time) (time-to-pixel (car (related-views self)) time)) (defmethod ruler-value-to-pix ((self voice-ruler) v) (time-to-pixel (car (related-views self)) v)) (defmethod ruler-zoom-? ((self voice-ruler)) ;;; if h-stretch is a number, we are not in proportional view ;;(not (numberp (editor-get-edit-param (editor (car (related-views self))) :h-stretch))) nil) ;;;====================== ;;; ACTIONS ;;;====================== ;;; MOVE / CHANGE DURS: (defmethod move-editor-selection ((self voice-editor) &key (dx 0) (dy 0)) (declare (ignore dx)) (call-next-method self :dx 0 :dy dy)) (defmethod score-editor-change-selection-durs ((self voice-editor) delta) nil) ;;; TAB NAVIGATION: (defmethod next-element-in-editor ((editor voice-editor) (element rhythmic-object)) (car (inside element))) (defmethod next-element-in-editor ((editor voice-editor) (element score-element)) (let* ((seq (object-value editor)) (pos (position element (get-all-chords seq)))) (or (nth (1+ pos) (get-all-chords seq)) (car (get-all-chords seq))))) ;;; TURN REST INTO A CHORD: ;;; return a new chord if the clicked object is a rest (defmethod get-chord-from-editor-click ((self voice-editor) position) (let ((chord (call-next-method)) (voice (get-voice-at-pos self position))) (if chord (when (typep chord 'r-rest) (let* ((time-pos (beat-to-time (symbolic-date chord) (tempo voice)))) ;; make a real chord (change-class chord 'chord) (setf (onset chord) time-pos) (setf (notes chord) nil) ;; insert in teh actual sequence (time-sequence-insert-timed-item-and-update voice chord (find-position-at-time voice time-pos)) ;; compute new tree / rebuild the structure (set-tree voice (build-tree voice nil)) )) ;;; little hacked hooked-in here: add a measure (let ((time-pos (pixel-to-time (get-g-component self :main-panel) (om-point-x position))) (click-on-measure (find-if #'(lambda (element) (and (typep element 'measure) (b-box element) (>= (om-point-x position) (b-box-x1 (b-box element))) (<= (om-point-x position) (b-box-x2 (b-box element))))) (inside voice)))) (let ((pos (cond (click-on-measure (position click-on-measure (inside voice))) ((>= time-pos (get-obj-dur voice)) ;;; click at the end of the voice: add measure at the end (length (inside voice))) (t nil)))) (when pos (let ((m (make-instance 'measure :tree '((4 4) (-1)) :symbolic-dur 1 :symbolic-date 0 ))) (setf (inside m) (list (make-instance 'r-rest :symbolic-dur 1 :symbolic-date 0))) (insert-in-voice voice m pos) (report-modifications self) )) ) ) ) chord)) (defmethod tie-untie-selection ((editor voice-editor)) (let ((selected-chords (loop for elt in (selection editor) append (get-tpl-elements-of-type elt '(chord continuation-chord))))) (when selected-chords (store-current-state-for-undo editor) (loop for v in (get-voices (object-value editor)) do (let ((selected-chords-in-v (remove-if-not #'(lambda (c) (find c (get-all-chords v))) selected-chords))) (when selected-chords-in-v (tie-untie v selected-chords-in-v)))) (set-selection editor nil) (report-modifications editor)))) (defmethod group-selection ((editor voice-editor)) (let ((selected-chords (loop for elt in (selection editor) append (get-tpl-elements-of-type elt '(chord continuation-chord r-rest))))) (when selected-chords (store-current-state-for-undo editor) (loop for v in (get-voices (object-value editor)) do (let ((selected-chords-in-v (remove-if-not #'(lambda (c) (find c (get-all-chords v))) selected-chords))) (when selected-chords-in-v (group v selected-chords-in-v)))) (set-selection editor nil) (report-modifications editor)))) (defmethod subdivide-selection ((editor voice-editor) n) (let ((selected-chords (loop for elt in (selection editor) append (get-tpl-elements-of-type elt '(chord continuation-chord r-rest))))) (when selected-chords (store-current-state-for-undo editor) (loop for v in (get-voices (object-value editor)) do (let ((selected-chords-in-v (remove-if-not #'(lambda (c) (find c (get-all-chords v))) selected-chords))) (when selected-chords-in-v (subdivide v selected-chords-in-v n)))) (set-selection editor nil) (report-modifications editor)))) (defmethod break-selection ((editor voice-editor)) (let ((selected-groups (loop for elt in (selection editor) append (get-tpl-elements-of-type elt '(group))))) (when selected-groups (store-current-state-for-undo editor) (loop for v in (get-voices (object-value editor)) do (let ((selected-groups-in-v (remove-if-not #'(lambda (g) (deep-search v g)) selected-groups))) (when selected-groups-in-v (break-groups v selected-groups-in-v)))) (set-selection editor nil) (report-modifications editor)))) (defmethod editor-key-action ((editor voice-editor) key) (cond ; tie/untie ((equal key #\=) (tie-untie-selection editor)) ; group ((equal key #\+) (group-selection editor)) ; break ((equal key #\-) (break-selection editor)) ; subdivise ((member key '(#\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)) (let ((num (read-from-string (string key)))) (subdivide-selection editor num) )) ; otherwise (t (call-next-method)) ;;; => score-editor )) ;;; disabled from chord-seq editor: (defmethod stems-on-off ((self voice-editor)) nil) (defmethod align-chords-in-editor ((self voice-editor)) nil) ;;; When something is inserted somewhere (e.g. MIDI recording) (defmethod update-from-internal-chords ((self voice)) (let ((requantified-voice (omquantify (objfromobjs self (make-instance 'chord-seq)) (tempo self) (get-metrics self) 16))) (set-chords self (chords requantified-voice)) (set-tree self (tree requantified-voice)) )) ;;;====================== ;;; DRAW SPECIFICS ;;;====================== (defmethod draw-tempo-in-editor-view ((editor voice-editor) (self score-view)) (let* ((y-shift (editor-get-edit-param editor :y-shift)) (font-size (editor-get-edit-param editor :font-size)) (unit (font-size-to-unit font-size))) (draw-tempo (object-value editor) (* 2 unit) (* y-shift unit) font-size) )) (defmethod draw-sequence ((object voice) editor view unit &optional force-y-shift voice-staff) ;;; NOTE: so far we don't build/update a bounding-box for the containers (let* ((font-size (editor-get-edit-param editor :font-size)) (staff (or voice-staff (editor-get-edit-param editor :staff))) (h-stretch (editor-get-edit-param editor :h-stretch)) (y-u (or force-y-shift (editor-get-edit-param editor :y-shift))) (selection (selection editor))) (when (listp staff) (setf staff (or (nth (position object (get-voices (object-value editor))) staff) (car staff)))) (loop with on-screen = t with prev-signature = nil for m in (inside object) for i from 1 while on-screen do (let* ((begin (beat-to-time (symbolic-date m) (tempo object))) (end (beat-to-time (+ (symbolic-date m) (symbolic-dur m)) (tempo object))) (x1 (time-to-pixel view begin)) (x2 (time-to-pixel view end))) (if (> x1 (w view)) (setf on-screen nil) ;;; this should also take into account measures before screen ;;; else : (when (> x2 0) ;;; DRAW THIS MEASURE (draw-measure m (tempo object) (object editor) view :position i :y-shift y-u :with-signature (not (equal (car (tree m)) prev-signature)) :selection selection :staff staff :stretch h-stretch :font-size font-size ) )) (setf prev-signature (car (tree m))) ) )) )
15,880
Common Lisp
.lisp
329
36.209726
136
0.539468
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8d3bacb23f43926ba11427b6b9ac441e6e50c3366d812df99b6b5e0555d9a424
743
[ -1 ]
744
groups.lisp
cac-t-u-s_om-sharp/src/packages/score/editor/groups.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; GROUPS in score editors. ; Uses the GROUP-IDS list of score-element objects ; File author: J. Bresson, 2021 ;============================================================================ (in-package :om) (defmethod collect-group-ids ((self score-editor)) (let ((groups ())) (loop for c in (get-all-chords (object-value self)) do (loop for id in (group-ids c) unless (find id groups :test 'string-equal) do (pushr id groups))) groups)) (defmethod get-group-elements ((self score-editor) group-id) (loop for c in (get-all-chords (object-value self)) when (find group-id (group-ids c) :test 'string-equal) collect c)) (defmethod generate-group-id ((self score-editor)) (let* ((other-ids (collect-group-ids self)) (index (1+ (length other-ids))) (group-id (format nil "group~D" index))) (loop while (find group-id other-ids :test 'string-equal) do (setf group-id (format nil "group~D" (incf index)))) group-id)) (defmethod add-group-id ((self score-element) id) (setf (group-ids self) (append (group-ids self) (list id)))) (defmethod add-group-id ((self rhythmic-object) id) (call-next-method) (loop for sub in (inside self) do (add-group-id sub id))) (defmethod remove-group-id ((self score-element) id) (setf (group-ids self) (if (equal id :all) nil (remove id (group-ids self) :test 'string-equal)))) (defmethod remove-group-id ((self rhythmic-object) id) (call-next-method) (loop for sub in (inside self) do (remove-group-id sub id))) (defmethod rename-group-id ((self score-element) old-name new-name) (setf (group-ids self) (substitute new-name old-name (group-ids self) :test 'string-equal))) (defmethod rename-group-id ((self rhythmic-object) old-name new-name) (call-next-method) (loop for sub in (inside self) do (rename-group-id sub old-name new-name))) ;;; add to the current group if a group is selected ;;; create a new group if :all-groups (defmethod add-selection-to-group ((self score-editor)) (when (and (editor-get-edit-param self :groups) (selection self)) (store-current-state-for-undo self) (let ((group (if (equal (editor-get-edit-param self :selected-group) :all) (generate-group-id self) (editor-get-edit-param self :selected-group)))) (loop for item in (selection self) do (add-group-id item group)) (editor-update-analysis self) (update-group-controls self)))) ;;; delete the group(s) of selected items if :all-groups ;;; or remove the selected item from a specific group (defmethod delete-selection-group ((self score-editor)) (when (and (editor-get-edit-param self :groups) (selection self)) (store-current-state-for-undo self) (let* ((group (editor-get-edit-param self :selected-group))) (loop for item in (selection self) do (remove-group-id item group)) (editor-update-analysis self) (update-group-controls self)))) ;;; deleted the group if a specific group is selected ;;; or all groups (with warning) (defmethod delete-current-group ((self score-editor)) (let* ((group-id (editor-get-edit-param self :selected-group)) (remove-all (equal group-id :all))) (unless (and remove-all (not (om-y-or-n-dialog "This will delete all groups in the score. Do it ?"))) (store-current-state-for-undo self) (loop for c in (get-all-chords (object-value self)) do (remove-group-id c group-id)) (update-group-controls self)))) (defmethod rename-current-group ((self score-editor)) (let* ((group-id (editor-get-edit-param self :selected-group))) (unless (equal group-id :all) (let ((new-id (om-get-user-string "Enter a new name for the group" :initial-string (string group-id)))) (when new-id (store-current-state-for-undo self) (loop for c in (get-all-chords (object-value self)) do (rename-group-id c group-id new-id)) (editor-set-edit-param self :selected-group new-id) (update-group-controls self))) ))) (defmethod draw-groups-on-score-editor (editor) (let ((color (om-make-color .4 .4 .4)) (fill (om-make-color .4 .4 .4 .2)) (draw-name (editor-get-edit-param editor :group-names)) (margin-x 10) (margin-y 5)) (loop for group-id in (if (equal (editor-get-edit-param editor :selected-group) :all) (collect-group-ids editor) (list (editor-get-edit-param editor :selected-group))) do (loop for c in (get-all-chords (object-value editor)) when (and (b-box c) (find group-id (group-ids c) :test 'string-equal)) minimize (b-box-x1 (b-box c)) into x1 and minimize (b-box-y1 (b-box c)) into y1 and maximize (b-box-x2 (b-box c)) into x2 and maximize (b-box-y2 (b-box c)) into y2 finally (om-draw-rounded-rect (- x1 margin-x) (- y1 margin-y) (- x2 x1 (* -2 margin-x)) (- y2 y1 (* -2 margin-y)) :color color :round 8 :line 2) (om-draw-rounded-rect (- x1 margin-x) (- y1 margin-y) (- x2 x1 (* -2 margin-x)) (- y2 y1 (* -2 margin-y)) :color fill :fill t :round 8) (when draw-name (om-draw-string (- x1 margin-x) (+ y2 12 margin-y) group-id :color color)) (when (and (editor-get-edit-param editor :analysis) (analysis editor)) (draw-analysis-for-group (analysis editor) editor group-id x1 y1 x2 y2)) )) )) (defmethod update-group-controls ((editor score-editor)) (let ((groups (collect-group-ids editor)) (current-group-id (editor-get-edit-param editor :selected-group)) (menu (get-g-component editor :groups-menu)) (delete-button (get-g-component editor :delete-group-button)) (rename-button (get-g-component editor :rename-group-button)) (group-names-box (get-g-component editor :group-names-box)) (group-names-label (get-g-component editor :group-names-label))) (unless (find current-group-id groups :test 'string-equal) (editor-set-edit-param editor :selected-group :all) (setf current-group-id :all)) (when menu (om-set-item-list menu (append '(:all "-") (collect-group-ids editor))) (om-set-selected-item menu current-group-id) (om-enable-dialog-item menu (editor-get-edit-param editor :groups))) (when delete-button (om-enable-dialog-item delete-button (and (editor-get-edit-param editor :groups) groups))) (when rename-button (om-enable-dialog-item rename-button (and (editor-get-edit-param editor :groups) groups (not (equal current-group-id :all))))) (when group-names-box (om-enable-dialog-item group-names-box (editor-get-edit-param editor :groups))) (when group-names-label (om-set-fg-color group-names-label (if (editor-get-edit-param editor :groups) (om-def-color :black) (om-def-color :gray)))) (editor-invalidate-views editor) )) (defmethod editor-groups-controls ((editor chord-seq-editor)) (let ((groups (collect-group-ids editor))) (om-make-layout 'om-column-layout :gap 0 :subviews (list (om-make-layout 'om-row-layout :align :bottom :subviews (list (om-make-di 'om-simple-text :size (om-make-point 72 18) :text "Groups" :font (om-def-font :gui-b)) (om-make-di 'om-check-box :text "" :font (om-def-font :gui) :size (omp 20 20) :checked-p (editor-get-edit-param editor :groups) :di-action #'(lambda (item) (editor-set-edit-param editor :groups (om-checked-p item)) (update-group-controls editor))) )) (om-make-layout 'om-row-layout :align :bottom :subviews (list (set-g-component editor :groups-menu (om-make-di 'om-popup-list :items (append '(:all "-") groups) :size (omp 95 22) :font (om-def-font :gui) :enabled (editor-get-edit-param editor :groups) :value (editor-get-edit-param editor :selected-group) :di-action #'(lambda (list) (editor-set-edit-param editor :selected-group (om-get-selected-item list)) (update-group-controls editor) ))) (set-g-component editor :delete-group-button (om-make-di 'om-button :text "x" :size (omp 34 24) :font (om-def-font :gui) :enabled (and (editor-get-edit-param editor :groups) groups) :di-action #'(lambda (b) (declare (ignore b)) (delete-current-group editor)))) )) (om-make-layout 'om-row-layout :align :bottom :subviews (list ; (om-make-graphic-object 'om-item-view :size (omp 78 18)) (set-g-component editor :group-names-label (om-make-di 'om-simple-text :size (om-make-point 72 18) :text "Names" :fg-color (if (editor-get-edit-param editor :groups) (om-def-color :black) (om-def-color :gray)) :font (om-def-font :gui))) (set-g-component editor :group-names-box (om-make-di 'om-check-box :text "" :font (om-def-font :gui) :size (omp 20 20) :checked-p (editor-get-edit-param editor :group-names) :enabled (editor-get-edit-param editor :groups) :di-action #'(lambda (item) (editor-set-edit-param editor :group-names (om-checked-p item)) (update-group-controls editor)))) (set-g-component editor :rename-group-button (om-make-di 'om-button :text "Rename" :size (omp 70 24) :font (om-def-font :gui) :enabled (and (editor-get-edit-param editor :groups) groups (not (equal (editor-get-edit-param editor :selected-group) :all))) :di-action #'(lambda (b) (declare (ignore b)) (rename-current-group editor)))) )) )) ))
11,748
Common Lisp
.lisp
249
36.008032
110
0.55939
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e030712d36a1a6d3c1eb7261b6afebc77a6a3208cae23e031bc5c4c1a1f0faee
744
[ -1 ]
745
analysis.lisp
cac-t-u-s_om-sharp/src/packages/score/editor/analysis.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; TOOLS FOR MUSIC ANALYSIS ; J. Bresson 2021 ;============================================================================ (in-package :om) (defclass abstract-analysis () ()) ;;; API (defmethod update-analysis ((self abstract-analysis) (editor score-editor)) nil) (defmethod draw-analysis-for-group ((self abstract-analysis) (editor score-editor) group-id x1 y1 x2 y2) nil) (defparameter *registered-analyses* nil) (defmethod editor-update-analysis ((editor score-editor)) (when (and (editor-get-edit-param editor :analysis) (null (analysis editor))) (let ((analysis-type (editor-get-edit-param editor :selected-analysis))) (when analysis-type (setf (analysis editor) (make-instance analysis-type))))) (when (analysis editor) (update-analysis (analysis editor) editor) (editor-invalidate-views editor))) (defmethod init-editor :after ((self score-editor)) (editor-update-analysis self)) (defmethod editor-analysis-controls ((editor chord-seq-editor)) (om-make-layout 'om-column-layout :gap 0 :subviews (list (om-make-layout 'om-row-layout :align :bottom :subviews (list (om-make-di 'om-simple-text :size (om-make-point 72 18) :text "Analysis" :font (om-def-font :gui)) (om-make-di 'om-check-box :text "" :font (om-def-font :gui) :size (omp 120 20) :checked-p (editor-get-edit-param editor :analysis) :di-action #'(lambda (item) (editor-set-edit-param editor :analysis (om-checked-p item)) (let ((analysis-menu (get-g-component editor :analysis-menu))) (om-enable-dialog-item analysis-menu (om-checked-p item)) (if (om-checked-p item) (let ((analysis-type (om-get-selected-item analysis-menu))) (editor-set-edit-param editor :selected-analysis analysis-type) (setf (analysis editor) (make-instance analysis-type)) (editor-update-analysis editor)) (editor-invalidate-views editor)))) ))) (om-make-layout 'om-row-layout :align :bottom :subviews (list (set-g-component editor :analysis-menu (om-make-di 'om-popup-list :items *registered-analyses* :size (omp 120 22) :font (om-def-font :gui) :enabled (editor-get-edit-param editor :analysis) :value (editor-get-edit-param editor :selected-analysis) :di-action #'(lambda (list) (let ((analysis-type (om-get-selected-item list))) (editor-set-edit-param editor :selected-analysis analysis-type) (setf (analysis editor) (make-instance analysis-type)) (editor-update-analysis editor) )))) )) )) ) ;;;========================= ;;; Example: PCSET ANALYSIS ;;;========================= (defclass pcset-analysis (abstract-analysis) ((pcsets :accessor pcsets :initform nil :type list))) (pushr 'pcset-analysis *registered-analyses*) (defmethod update-analysis ((self pcset-analysis) (editor score-editor)) (setf (pcsets self) (loop for group-id in (collect-group-ids editor) collect (let ((chords (remove nil (mapcar #'get-real-chord (get-group-elements editor group-id))))) (when chords (list group-id (chord2c (make-instance 'chord :lmidic (remove-duplicates (apply #'append (mapcar #'lmidic chords)))) 2)) ))) )) (defmethod draw-analysis-for-group ((self pcset-analysis) (editor score-editor) group-id x1 y1 x2 y2) (declare (ignore editor)) (let ((cercle (cadr (find group-id (pcsets self) :key 'car :test 'string-equal)))) (when cercle (draw-cercle cercle x1 (+ y2 20) (- x2 x1) 120))))
5,201
Common Lisp
.lisp
108
34.759259
109
0.509181
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
640fb3f7a45ac895212911eb5fa6eafd9c3f9151daccedf821eb9784729dac03
745
[ -1 ]
746
conversions.lisp
cac-t-u-s_om-sharp/src/packages/score/functions/conversions.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson, original code from OM6 ;============================================================================ (in-package :om) (add-preference :score :diapason "Diapason" :number 440.0 "The reference A3 used for pitch-frequency conversions") ;================================== ;UTIL ;================================== (defun deep-mapcar (fun fun1 list? &rest args) "Mapcars <fun> or applies <fun1> to <list?> <args> whether <list?> is a list or not." (cond ((null list?) ()) ((not (consp list?)) (apply fun1 list? args)) (t (cons (apply #'deep-mapcar fun fun1 (car list?) args) (apply #'deep-mapcar fun fun1 (cdr list?) args))))) ;================================== ;APPROX_M ;================================== (defparameter *global-midi-approx* 2) (defmethod* approx-m ((midic t) approx &optional (ref-midic 0)) :numouts 1 :initvals '(6000 2 0) :indoc '("pitch list (midicents)" "tone division") :icon 'conversion :doc " Returns an approximation of <midic> (in midicents) to the nearest tempered division of the octave. <approx> = 1 whole tones <approx> = 2 semi tones <approx> = 4 quarter tones <approx> = 8 eight tones Floating values are allowed for <approx>. <ref-midic> is a midicent that is subtracted from <midic> before computation: the computation can then be carried on an interval rather than an absolute pitch." (if (<= approx 0) midic (round (* (floor (+ (* (- midic ref-midic) approx) 100) 200) 200) approx))) (defmethod* approx-m ((self list) approx &optional (ref-midic 0)) (if (<= approx 0) self (loop for item in self collect (approx-m item approx ref-midic)))) ;================================== ;MIDIC conversions ;================================== (defvar *diapason-midic* 6900) ;; ---- midicent -> frequency (defmethod* mc->f ((midicents number) &optional concert-pitch) :numouts 1 :initvals (list 6000 nil) :indoc '("pitch or pitch list (midicents)" "frequency (Hz)") :icon 'conversion :doc " Converts a (list of) midicent pitch(es) <midicents> to frequencies (Hz). <concert-pitch> is the reference Hz value to use in the conversion." (let ((ref-pitch (or concert-pitch (get-pref-value :score :diapason)))) (* ref-pitch (expt 2.0 (/ (- midicents *diapason-midic*) 1200.0))))) (defmethod* mc->f ((midics? list) &optional concert-pitch) (loop for item in midics? collect (mc->f item concert-pitch))) ;; ---- frequency -> midicent (defvar *lowest-freq* (* 256 (max (mc->f most-negative-fixnum) least-positive-long-float))) (defun abs-f1 (freq) (max *lowest-freq* (abs freq))) (defun f->mf (freq &optional concert-pitch) (let ((ref-pitch (or concert-pitch (get-pref-value :score :diapason)))) (+ (* (log (abs-f1 (/ freq ref-pitch))) #.(/ 1200 (log 2.0))) *diapason-midic*))) (defmethod* f->mc ((freq number) &optional (approx 100) (ref-midic 0) concert-pitch) :numouts 1 :initvals (list 440 100 0 nil) :indoc '("frequency (Hz)" "approximation" "midicenct (int)" "frequency (Hz)") :icon 'conversion :doc "Converts a frequency or list of frequencies to midicents. Approximation: - <approx> = 1 whole tones - <approx> = 2 semi tones - <approx> = 4 quarter tones - <approx> = 8 eight tones Floating values are allowed for <approx>. <ref-midic> is a midicent that is subtracted from <midic> before computation: the computation can then be carried on an interval rather than an absolute pitch. <concert-pitch> is the reference Hz value to use in the conversion. If unspecified, will use the value set in the Score preferences." (approx-m (f->mf freq concert-pitch) approx ref-midic)) (defmethod* f->mc ((freq list) &optional (approx 100) (ref-midic 0) concert-pitch) (loop for item in freq collect (f->mc item approx ref-midic concert-pitch))) ;================================== ;TEXT conversions ;================================== ;(defvar *no-sharp-read-table* (copy-readtable nil)) ;(set-syntax-from-char #\# #\K *no-sharp-read-table*) ;; ---- midic -> symbol ;; why ? ;(export '(*ascii-note-scales* *ascii-note-C-scale* *ascii-note-do-scale*)) ;;=========== ;; The scales used by the functions mc->n and n->mc: ;;=========== (defvar *ascii-note-C-scale* '(("C") ("C" . :q) ("C" . :s) ("D" . :-q) ("D") ("D" . :q) ("E" . :f) ("E" . :-q) ("E") ("E" . :q) ("F") ("F" . :q) ("F" . :s) ("G" . :-q) ("G") ("G" . :q) ("G" . :s) ("A" . :-q) ("A") ("A" . :q) ("B" . :f) ("B" . :-q) ("B") ("B" . :q))) (defvar *ascii-note-do-scale* '(("do") ("do" . :q) ("do" . :s) ("re" . :-q) ("re") ("re" . :q) ("mi" . :f) ("mi" . :-q) ("mi") ("mi" . :q) ("fa") ("fa" . :q) ("fa" . :s) ("sol" . :-q) ("sol") ("sol" . :q) ("sol" . :s) ("la" . :-q) ("la") ("la" . :q) ("si" . :f) ("si" . :-q) ("si") ("si" . :q))) (defvar *ascii-note-alterations* ;; taking care to order alterations by length of their string '((:qs "#+" +150) (:f-q "b-" -150) (:q "+" +50) (:-q "_" -50) (:s "#" +100) (:f "b" -100) (:s "d" +100))) (defun mc->n1 (midic &optional (ascii-note-scale *ascii-note-C-scale*) (middle-C 3)) "Converts <midic> to a string representing a symbolic ascii note." (let ((dmidic (/ 1200 (length ascii-note-scale))) note) (multiple-value-bind (midic/50 cents) (round midic dmidic) (multiple-value-bind (oct+2 midic<1200) (floor (* midic/50 dmidic) 1200) (setq note (nth (/ midic<1200 dmidic) ascii-note-scale)) (format nil "~A~A~A~A~A" (car note) (or (cadr (find (cdr note) *ascii-note-alterations* :key 'car)) "") (- oct+2 (- 5 middle-C)) (if (> cents 0) "+" "") (if (zerop cents) "" cents) ))))) (defun n->mc1 (str &optional (ascii-note-scale *ascii-note-C-scale*) (middle-C 3)) "Converts a string representing a symbolic ascii note to a midic." (setq str (string str)) (let ((note (some #'(lambda (note) (when (and (null (cdr note)) (eql 0 (search (car note) str :test #'string-equal))) note)) ascii-note-scale)) index midic alt) (unless note (error "Note ~S not found in scale ~%~S" str ascii-note-scale)) (setq midic (* (position note ascii-note-scale) (/ 1200 (length ascii-note-scale)))) ;; at this point: "C" -> 0 ; "D" -> 100 ; "E" -> 200 ; etc. (setq index (length (car note))) ;; alteration (when (setq alt (some #'(lambda (alt) (when (eql index (search (cadr alt) str :start2 index :test #'string-equal)) alt)) *ascii-note-alterations*)) (incf midic (third alt)) ;it's there! (incf index (length (second alt)))) ;; octave (multiple-value-bind (oct i) (parse-integer str :start index :junk-allowed t) (incf midic (* (+ oct (- 5 middle-C)) 1200)) (setq index i)) (unless (= index (length str)) (incf midic (parse-integer str :start index))) midic)) (defvar *ascii-intervals* '("1" "2m" "2M" "3m" "3M" "4" "4A" "5" "6m" "6M" "7m" "7M")) (defun int->symb1 (int) "Converts a midic interval to a symbolic interval." (multiple-value-bind (oct cents) (floor int 1200) (let ((index (/ cents 100))) (unless (typep index 'fixnum) (error "Not yet implemented")) (if (zerop oct) (nth index *ascii-intervals*) (format () "~A~@D" (nth index *ascii-intervals*) oct))))) (defmethod* int->symb ((ints list)) :initvals (list '(1 2)) :indoc '("ints") :icon 'conversion :doc "<int->symb> takes an interval expressed in midi-cents, and returns a symbolic interval name. Intervals are labeled as follows: 1 = unison 2m = minor second 2M = major second 3m = minor third 3M = major third 4 = perfect fourth 4A = tritone 5 = perfect fifth 6m = minor sixth 6M = major sixth 7m = minor seventh 7M = major seventh All intervals larger than an octave are expressed by adding or subtracting an octave displacement after the simple interval name; for example, a major tenth becomes 3M+1, etc. Note: for the time being, the program has a strange way of expressing downward intervals: it labels the interval as its inversion, and then transposes downwards as necessary. Thus, a major third down (-400 in midicents), returns 6m-1." (deep-mapcar #'int->symb #'int->symb1 ints)) (defun symb->int1 (symb) (let* ((int-str (coerce (string symb) 'list)) (neg-oct (member #\- int-str :test #'char=)) (rest-oct (or (member #\+ int-str :test #'char=) neg-oct)) (oct (if rest-oct (read-from-string (coerce (cdr rest-oct) 'string)) 0)) (pclass (coerce (butlast int-str (length rest-oct)) 'string))) (* 100 (+ (position pclass *ascii-intervals* :test #'string=) (* 12 (if neg-oct (- oct) oct)))))) (defmethod* symb->int ((symb list)) :initvals (list '(1 2)) :indoc '("ints") :icon 'conversion :doc "symb->int takes a symbolic interval name , and returns an interval expressed in midi-cents. Intervals are labeled as follows: 1 = unison 2m = minor second 2M = major second 3m = minor third 3M = major third 4 = perfect fourth 4A = tritone 5 = perfect fifth 6m = minor sixth 6M = major sixth 7m = minor seventh 7M = major seventh All intervals larger than an octave are expressed by adding or subtracting an octave displacement after the simple interval name; for example, a major tenth becomes 3M+1, etc. Note: for the time being, Patchwork has a strange way of expressing downward intervals: it labels the interval as its inversion, and then transposes downwards as necessary. Thus, a major third down 6m-1, returns -400 in midicents ." (deep-mapcar #'symb->int #'symb->int1 symb)) (defmethod* mc->n ((midicents list) &optional (middle-C 3)) :initvals '((6000) 3) :indoc '("pitch or pitch list (midicents)" "octave of middle C") :icon 'conversion :doc " Converts <midics> to symbolic (ASCII) note names. Symbolic note names follow standard notation with middle c (midicent 6000) being C3. Middle c (midicent 6000) being octave 3 by default, can be set to another octave by the optional input. Semitones are labeled with a '#' or a 'b.' Quartertone flats are labeled with a '_', and quartertone sharps with a '+' (ex. C3 a quartertone sharp (midi-cent 6050), would be labeled 'C+3'. Gradations smaller than a quartertone are expressed as the closest quartertone + or - the remaining cent value (ex. midi-cent 8176 would be expressed as Bb4-24). " (deep-mapcar 'mc->n #'(lambda (mc) (mc->n1 mc *ascii-note-C-scale* middle-C)) midicents)) (defmethod* mc->n ((midic number) &optional (middle-C 3)) (mc->n1 midic *ascii-note-C-scale* middle-C)) (defmethod* n->mc ((strs list) &optional (middle-C 3)) :initvals '(("C3") 3) :indoc '("note name or list of note names" "octave of middle C") :icon 'conversion :doc " Converts <strs> to pitch values in midicents. Symbolic note names follow standard notation with middle c (midicent 6000) being C3. Middle c (midicent 6000) being octave 3 by default, can be set to another octave by the optional input. Semitones are labeled with a '#' or a 'b.' Quartertone flats are labeled with a '_', and quartertone sharps with a '+' (ex. C3 a quartertone sharp (midi-cent 6050), would be labeled 'C+3'. Gradations smaller than a quartertone are expressed as the closest quartertone + or - the remaining cent value (ex. midi-cent 8176 would be expressed as Bb4-24). " (deep-mapcar 'n->mc #'(lambda (n) (n->mc1 n *ascii-note-C-scale* middle-C)) strs)) (defmethod* n->mc ((strs string) &optional (middle-C 3)) (car (n->mc (list strs) middle-C))) (defmethod* n->mc ((symb symbol) &optional (middle-C 3)) (n->mc (string symb) middle-C)) ;;;======================================= ;;; TEMPO ;;;======================================= (defmethod* beats->ms ((nb-beat number) (tempo number)) :initvals '(1 60) :indoc '("number of beats or beat division (ex. 1, 4, 1/8, ...)" "") :icon 'conversion :outdoc '("duration (ms)") :doc " Converts a symbolic rhythmic beat division into the corresponding duration in milliseconds. " (let ((b-ms (* 1000.0 (/ 60 tempo)))) (round (* nb-beat b-ms))) )
13,376
Common Lisp
.lisp
271
43.863469
163
0.596751
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
36a3810528847c4c0bc6eac535090c750712877ec616137db9a2e1228c303682
746
[ -1 ]
747
quantify.lisp
cac-t-u-s_om-sharp/src/packages/score/functions/quantify.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; OMQuantify ; Original quanyifier from PatchWork ; by C. Rueda, 1998 ;============================================================================ (in-package :om) (defvar *distance-weight* nil) (defvar *valid-rtm-expands* '(#\/)) (defvar *maximum-pulses* 32) (defvar *max-division* 8) (defvar *min-pulses* 5) (defvar *forbidden-rythmic-divisions* ()) (defvar *distance-function* ()) ;(setf *read-default-float-format* 'single-float) ;(setf *read-default-float-format* 'double-float) ;(setf a (coerce (/ 9 3.0) 'double-float)) ;(/ (/ 100 a) 1.0) (defvar *min-percent* 0.6) (defvar *tempo-scalers* '(1 2 3 4 5 6 7 8)) (defvar *min-tempo* 40) (defvar *max-tempo* 200) (defvar *accum-error* 0) (defvar *minimum-quant-dur* (/ 100 16)) (defvar *unquantized-notes* 0) (defvar *global-grace-notes* ()) (defvar *unit-division-hierarchy* '(1 2 4 3 6 5 8 7 10 12 16 9 14 11 13 15 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50)) (defvar *iota* 0.0001) (defvar *dist-iota* 0.03) (defvar *proportions-iota* 0.001) (defmethod* omquantify ((durs list) (tempi t) (measures list) (max/ t) &optional forbid offset precis) :initvals '((100) 60 (4 4) 8 nil 0 0.5) :icon :score :indoc '("durations" "tempo" "list of time signature(s)" "maximum subdivision" "list forbidden subdivisions" "grace-notes?" "precision (0.0-1.0)") :doc "Quantizes a list of durs in milliseconds into a metric structure. The result is a rhythm tree to be connected to the <tree> input of a voice. <durs> is a list of durations in milliseconds (or a CHORD-SEQ object). <tempi> is a tempo <measures> is a list of measure signature (e.g. ((3 4) (7 8) (1 4) ... ) ) <max/> is the maximum subdivision of the beat (8 with beat=quarter means 32nd note) <forbid> is a list of forbidden subdivision of the beat <offset> is an offset expressed as a ratio of the beat <precis> is a float in (0.0 .. 1.0) smaller values mean 'simplicity' while bigger values mean 'precision' <forbid> With this variable, you can control the subdivisions of the beats, either by avoiding them or by imposing them, at a global level or at the beat level. A simple list, such as ( 11 9 7 6), does not permit at a global level divisions by 11, 9, 7, or 6. The introduction of sub-lists at the first level indicates a control over the measures. For example, ((5 6) (7 4) () () (4 7)) indicates that in the first measure, subdivisions by 5 and by 6 are forbidden, and in the second and fifth measure, subdivisions by 7 and by 4 are forbidden. As the third and fourth sub- lists are empty lists, there are no restrictions for these measures. A second level of sub-lists will permit to control subdivisions of beats. The list ( ((5 4) () (3 6) ()) (() () ( 8 7) ()) ( 3 2) () ) indicates : first measure first beat - subdivisions by 5 and by 4 forbidden second beat : no restriction third beat : subdivisions by 3 and by 6 forbidden fourth beat : no restriction second measure first beat : no restrictions second beat : no restrictions third beat : subdivisions by 8 and by 7 forbidden fourth beat : no restrictions third measure all beats : subdivisions by 3 and by 2 forbidden fourth measure all beats : no restrictions To impose subdivisions, you add a ! at the beginning of the lists. At a global level (! 5) imposes a subdivision by five on the entire sequence (! 5 7 6) imposes a subdivision by 5, by 7, or by 6 on the entire sequence. The syntax is the same for all other levels: For measures ((! 3 4) (! 5) () () ()) and for beats ( ((! 5 4) () (! 3 6) ()) (() () ( ! 8 7) ()) (! 3 2) () ) . Of course, it is possible to mix syntaxes at the measure level as well as at the beat level. Here is an example: ( (( 5 4) () (! 3 6) ()) ((! 6) () ( 8 7) ()) (! 3 2) (6 8) )" (unless precis (setq precis 0.5)) (setf *distance-weight* (if (numberp precis) (list (list precis)) precis)) (let ((rep (quant-edit (om/ durs 10) tempi measures (if (numberp max/) (list (list max/)) max/) forbid (or offset 0) 1))) (korrected-kant (reducetree rep)))) ;;; QUANTIFY A CHORD-SEQ => VOICE (defmethod* omquantify ((self chord-seq) tempi (measures list) max/ &optional forbid offset precis) (let ((chord-seq (clone self))) (group-chords chord-seq) (make-instance 'voice :tree (omquantify (x->dx (remove-duplicates (lonset chord-seq))) tempi measures max/ forbid offset precis) :lmidic (get-chords chord-seq) :tempo (car (list! tempi))) )) ; correction by K. Haddad included in omquantify 21/10/2008 in OM 6.0.4 ; the before last duration is mostly a rest followed by a continuation-chord ; this means that the continuation chord must be rest (defun correctdashit (list) (loop for i in list collect (if (minusp (first i)) (loop for truc in i collect (if (minusp truc) (round truc) (round (* -1 truc)))) i))) (defun korrected-kant (tree) (let* ((liste (if (typep tree 'voice) (tree tree) (resolve-? tree))) (grp-pulse (group-pulses liste)) (corrected (correctdashit grp-pulse)) (tree2obj (trans-tree liste)) (tree2objclean (remove-if 'numberp (flat tree2obj)))) (loop for objs in tree2objclean for i in (flat corrected) do (setf (treeobj-tvalue objs ) i)) (trans-obj tree2obj))) (defun get-beat-duration (tempo unit) (coerce (/ 24000 tempo unit) 'double-float)) ; corrected by gas (2001) #| (defun make-a-measure (voice-ms tempo sign-denom) (declare (ignore tempo)) (list (list (reduce '+ voice-ms :key #'(lambda (x) (if (numberp x) (round (abs x)) 1))) sign-denom) voice-ms)) |# (defun make-a-measure (voice-ms tempo sign-denom measure-duration) (declare (ignore tempo)) (list (read-from-string (format nil "~A//~A" measure-duration sign-denom)) (let* ((beatsum (reduce '+ voice-ms :key #'(lambda (x) (if (numberp x) (round (abs x)) 1)))) (diff (- (- measure-duration beatsum)))) (if (< beatsum measure-duration) (append voice-ms (list diff)) voice-ms)))) (defun set-error (to from) (setf *accum-error* (- to from *iota*))) (defun reset-error () (setf *accum-error* 0)) (defun accum-error? () (plusp *accum-error*)) (defun get-accum-error () *accum-error*) (defun select-tempo (durs) (declare (ignore durs)) (warn "Automatic tempo option is no longuer available") '(60)) ;TO set max to max - 1 (defun reduit-max (form) (if (numberp form) (+ form 1) (loop for item in form collect (reduit-max item)))) (defun quant-edit (durs tempi measures max/ &optional (forbid nil) (offset 0) (autom 1)) "Quantizes a list of <durs> (100 = 1 sec.) into the given measure(s), with the given <tempi>. <max/> is the maximum unit division that is taken to be a significant duration. A list of forbidden <forbid> unit divisions can optionally be specified. The output is a list of 'measure-objects' that can be entered directly into an rtm-box." (setf max/ (reduit-max max/)) ;by AAA (let* ((tempos (if (= autom 2) (select-tempo durs) (expand-lst (list! tempi)))) ;(expand-lists (list! tempi)))) (measures-x (expand-lst measures)) (measures (if (consp (car measures-x)) measures-x (list measures-x))) (def-measure (cons (first (car (last measures))) (second (car (last measures))))) (durs (if (zerop offset) durs (cons (- (* offset (get-beat-duration (car tempos) (second (car measures))))) durs))) (positive-durs (om-abs durs)) (deftempo (car (last tempos))) (atimes (dx->x 0.0 positive-durs)) (c-time 0) result slur-fl current-tempo current-unit current-measure-dur (max-list (and max/ (if (or (null (first max/)) (consp (first max/))) max/ (list max/)))) (max-preci (and *distance-weight* (if (or (null (first *distance-weight*)) (consp (first *distance-weight*))) *distance-weight* (list *distance-weight*)))) (forbids (and forbid (if (or (null (first forbid)) (consp (first forbid))) forbid (list forbid)))) (*unquantized-notes* 0) (measure-number -1) (def-forbid (first (last forbids))) (def-max (first (last max/))) (def-preci (first (last *distance-weight*))) *global-grace-notes* old-silence (*max-division* max/)) (reset-error) (do () ;;make new measures while: ;;((or (null atimes) (>= c-time total-dur))) ((or (null atimes) (>= c-time (last-elem atimes)))) ;;((null (cdr atimes))) ;dx->x above adds extra item (setf *max-division* (or (nth (+ 1 measure-number) max-list) def-max)) (setf *distance-weight* (or (nth (+ 1 measure-number) max-preci) def-preci)) (multiple-value-bind (beats times slur? current-time) (get-rhythms atimes :tempo (setq current-tempo (or (pop tempos) deftempo)) :sign (if (car measures) ;; need current-measure-dur in call to make-a-measure below (let ((this-measure (pop measures))) (cons (setq current-measure-dur (first this-measure)) (setq current-unit (second this-measure)))) (progn (setq current-unit (cdr def-measure)) def-measure)) :start-time c-time :forbid (or (nth (incf measure-number) forbids) def-forbid) :old-slur? slur-fl) (setq atimes times c-time current-time) (setq slur-fl slur?) (if beats (multiple-value-bind (beats-with-silences modifs new-silence) (put-in-silences beats durs old-silence) (setq old-silence new-silence) (when beats-with-silences ;; add current-measure-dur to ensure complete final measure (push (make-a-measure beats-with-silences current-tempo current-unit current-measure-dur) result) ;;(push (make-a-measure beats-with-silences current-tempo current-unit) result) (setq durs (nthcdr modifs durs)))) (setq atimes nil))) ) (unless (zerop *unquantized-notes*) (if result (om-print-format "Warning: with the given constraints, ~D notes are lost while quantizing." (list *unquantized-notes*) "OMQUANTIFY") (om-print "Cannot quantize with the given constraints" "OMQUANTIFY")) (om-beep)) (setq result (nreverse result)) ;;(unless (zerop *unquantized-notes*) ;; (and result (setf (pw::extra-measure-stuff (car result)) ;; (set-grace-notes-pos *global-grace-notes* positive-durs)))) ;;(make-instance 'pw::C-measure-line :measures result) (list '? result))) (defun set-grace-notes-pos (grace-notes durs) (let ((atimes (om-round (dx->x 0 durs) 1)) (count -1)) (mapcar #'(lambda (pair) (cons (- (position (om-round (first pair) 1) atimes :test #'=) (incf count)) (cdr pair))) (sort grace-notes '< :key #'first)))) ;(put-in-silences '((1 (1)) (1 (1.0 1))) '(-10 20 20)) (defun put-in-silences (beats durs &optional prev-silence) (if (every #'plusp durs) (values beats 0 nil) (let ((count 0) new-silence) (labels ((loop-beats (beat-tree) (cond ((null beat-tree) beat-tree) ((consp (car beat-tree)) (cons (list (caar beat-tree) (loop-beats (cadar beat-tree))) (loop-beats (cdr beat-tree)))) ((not (integerp (car beat-tree))) (if (or (and (not (zerop count)) (silence? durs (1- count))) (and (zerop count) prev-silence)) (progn (setq prev-silence t new-silence t) (cons (- (truncate (car beat-tree))) (loop-beats (cdr beat-tree)))) (progn (setq prev-silence nil new-silence nil) (cons (car beat-tree) (loop-beats (cdr beat-tree)))))) ((silence? durs count) (incf count) (setq new-silence t) (cons (- (car beat-tree)) (loop-beats (cdr beat-tree)))) (t (incf count) (setq new-silence nil) (cons (car beat-tree) (loop-beats (cdr beat-tree))))))) (values (rearrange-silences (loop-beats beats)) count new-silence))))) (defun silence? (durs position) (or (not (nth position durs)) (minusp (nth position durs)))) (defun rearrange-silences (beats) (let (res ok new-beats) (labels ((loop-beats (beat-tree) (cond ((null beat-tree) beat-tree) ((consp (car beat-tree)) (setq new-beats (loop-beats (cadar beat-tree))) (if (and (every 'numberp new-beats) (every 'minusp new-beats)) (cons (- (caar beat-tree)) (loop-beats (cdr beat-tree))) (cons (list (caar beat-tree) new-beats) (loop-beats (cdr beat-tree))))) ((every 'numberp beat-tree) (setq ok nil res nil) (if (every 'minusp beat-tree) beat-tree (dolist (item beat-tree (nreverse (if res (push (apply '+ res) ok) ok))) (if (minusp item) (push item res) (if res (progn (push (apply '+ res) ok) (push item ok) (setq res nil)) (push item ok)))))) (t (cons (car beat-tree) (loop-beats (cdr beat-tree))))))) (loop-beats beats)))) (defun get-rhythms (notes &key (tempo 60) (sign '(4 . 4)) (nb-pulse-max 16) start-time old-slur? forbid) (declare (ignore nb-pulse-max)) (let* ((measure-dur (* 24000.0 (car sign) (coerce (/ 1 (* (cdr sign) tempo)) 'double-float))) (atimes notes) (beat-dur (coerce (/ measure-dur (car sign)) 'double-float)) (tmin start-time) (from-dur tmin) (to-dur (+ beat-dur tmin)) (measure-end (+ measure-dur start-time)) (forbids (if (or (null (first forbid)) (consp (first forbid))) forbid (list forbid))) (max-list (if (or (null (first *max-division*)) (consp (first *max-division*))) *max-division* (list *max-division*))) (preci-list (if (or (null (first *distance-weight*)) (consp (first *distance-weight*))) *distance-weight* (list *distance-weight*))) (default-max (first (last max-list))) (default-preci (first (last preci-list))) (default-forbid (first (last forbids))) partition beat-rythm-forms (i 0)) ; (setf *distance-weight* (or (nth i (car preci-list)) (car (last default-preci)))) (setf *max-division* (coerce (or (nth i (car max-list)) (car (last default-max))) 'double-float)) (setf *minimum-quant-dur* (/ 60 tempo *max-division*)) ; (do () ((not (and (>= (- to-dur from-dur) *minimum-quant-dur*) atimes))) (setq partition (get-list-section atimes from-dur to-dur) atimes (nthcdr (length partition) atimes)) (setq *forbidden-rythmic-divisions* (or (pop forbids) default-forbid)) (multiple-value-bind (a-section slur? prev-slur) (get-optimal-time-section partition to-dur beat-dur from-dur old-slur?) ;;tmin? (if a-section (let ((chosen-rythm (simplify (search-rythm a-section from-dur prev-slur)))) ;;tmin? (if chosen-rythm (progn (push chosen-rythm beat-rythm-forms) (setq tmin (car (last a-section)))) (progn (setq beat-rythm-forms nil atimes nil) (om-print "cannot quantize with the given constraints") (om-beep)) )) ) (setq old-slur? slur?) (psetq to-dur (min (+ to-dur beat-dur) measure-end) from-dur to-dur)) (incf i) (setf *distance-weight* (or (nth i (car preci-list)) (car (last default-preci)))) (setf *max-division* (coerce (or (nth i (car max-list)) (car (last default-max))) 'double-float)) (setf *minimum-quant-dur* (/ 60 tempo *max-division*)) ) (when (not atimes) (when old-slur? (last-division-is-silence beat-rythm-forms) (setq old-slur? nil)) (do () ((not (>= (- measure-end to-dur) *minimum-quant-dur*))) (push '(-1) beat-rythm-forms) (incf to-dur beat-dur))) (values (compound-beats (nreverse beat-rythm-forms)) atimes old-slur? to-dur beat-dur) )) (defun compound-beats (beat-list) (mapcar #'(lambda (beat) (if (null (cdr beat)) (car beat) (list 1 beat))) beat-list)) (defun last-division-is-silence (form) (let ((last-beat (last (first form)))) (setf (first last-beat) (- (floor (first last-beat)))))) (defun quanti-of (quant-structure) (cdr quant-structure)) (defun pulses-of (quant-structure) (caar quant-structure)) (defun deleted-of (quant-structure) (second (first quant-structure))) (defun search-rythm (a-section tmin prev-slur) "Finds the beat list structure corresponding to the quantized durations" (beat-structure a-section prev-slur tmin (first (last (quanti-of a-section))))) (defun beat-structure (quants slur? from to) (let* ((atimes (form-atimes-list (copy-list (quanti-of quants)) from to)) (durs (remove 0.0 (x->dx atimes) :test #'=)) (min-dur (/ (- (car (last atimes)) (first atimes)) (coerce (pulses-of quants) 'double-float))) (beats (and durs (remove 0 (if slur? (cons (float (round (pop durs) min-dur)) (mapcar #'(lambda (dur) (round dur min-dur)) durs)) (mapcar #'(lambda (dur) (round dur min-dur)) durs)) :test #'=)))) beats)) (defun form-atimes-list (times from to) (and times (if (= (first times) from) (if (= (first (last times)) to) times (nconc times (list to))) (cons from (if (= (first (last times)) to) times (nconc times (list to))))))) (defun get-list-section (list from to) (let (result (epsilon -1e-3)) (dolist (elem list) (cond ((>= (- elem to) epsilon) ;; GA 10/10/94 (> elem to) (return ())) ((>= (- elem from) epsilon) (push elem result)) (t ))) (nreverse result))) (defun simplify (beats) (and beats (if (= (length beats) 1) (list (/ (first beats) (first beats))) beats))) (defun get-optimal-time-section (list to beat-dur tmin prev-slur) "Given a beat duration span and an initial time (tmin), quantizes the attack times in list. Beat duration is beat-dur. Beat's onset time is tmin. Beat's end time is 'to'. If prev-slur is on, the first onset time of this beat should be slurred with the last one of the previous beat. Prev-slur may change in this function.If Slur? is on, last onset of this beat should be linked with first of next beat (i.e. slur? becomes prev-slur in the next call)." (let* ((atimes (and list (test-quantize-constraints list tmin beat-dur prev-slur))) (last-list (first (last list))) (q-list (and atimes (quanti-of atimes))) slur? lagging-count head end-surplus partition) (setq lagging-count (and (plusp tmin) q-list (not (= tmin (car q-list))))) (when (and (accum-error?) (not lagging-count)) ;;note deleted at the border between beats (when list (keep-unquantized-statistics (or (first list) tmin) (- tmin (get-accum-error)))) (reset-error)) (setq head (and q-list (if lagging-count (cons tmin q-list) (progn (setq prev-slur nil) q-list)))) (setq end-surplus (and head (- to (first (last head))))) (setq partition (and end-surplus (if (> end-surplus 1e-4) ; GA 21/10/94 (plusp end-surplus) (progn (reset-error) (setq slur? t) (nconc head (list to))) (if (> to last-list) (progn (set-error to last-list) head) head)))) (cond ((null partition) (if (and list (not atimes)) (progn (mapcar #'(lambda (time) (keep-unquantized-statistics to time)) (butlast list 2)) (setq prev-slur nil) (unless (or (= last-list to) (= last-list tmin) (not (rest list))) (set-error to last-list)) (values (test-quantize-constraints (list tmin to) tmin beat-dur prev-slur) t nil)) (values (test-quantize-constraints (list tmin to) tmin beat-dur prev-slur) t prev-slur))) (t (setf (rest atimes) partition) (values atimes slur? prev-slur))) )) (defun keep-unquantized-statistics (atime previous) (incf *unquantized-notes*) (when atime (push (cons previous (- atime previous)) *global-grace-notes*))) (defun test-quantize-constraints (list tmin beat-dur prev-slur) (let ((q-structures (score-approx list tmin beat-dur))) (dolist (current-atimes q-structures (less-bad-quanta q-structures list tmin beat-dur)) (unless (forbidden-structure (beat-structure current-atimes prev-slur tmin (+ tmin beat-dur))) (return (if (plusp (deleted-of current-atimes)) (less-bad-quanta (list current-atimes) list tmin beat-dur) current-atimes)) )))) (defun forbidden-structure (struct) (let ((division (apply '+ struct))) (or (> division *max-division*) (if (and (first *forbidden-rythmic-divisions*) (symbolp (first *forbidden-rythmic-divisions*)) (string= (first *forbidden-rythmic-divisions*) '!)) (not (member division (rest *forbidden-rythmic-divisions*) :test #'=)) (member division *forbidden-rythmic-divisions* :test #'=))))) (defun get-nb-error (quant) (second (first quant))) (defun get-distance (quant) (third (first quant))) (defun get-proportion-distance (quant) (fourth (first quant))) (defun get-nb-pulse (quant) (first (first quant))) (defun pulse-number (qtime nb-pulse tmax tmin) (round (* nb-pulse (- qtime tmin)) (- tmax tmin))) (defun get-all-pulse-nums (note tmax tmin) (mapcar #'(lambda (qtime) (pulse-number qtime (caar note) tmax tmin)) (cdr note))) (defun less-bad-quanta (q-structures times from dur) (let ((try (first (member 1 q-structures :test #'<= :key #'get-nb-error)))) (when try (try-eliminating-one try times from dur)))) (defun try-eliminating-one (q-structure times from dur) (dolist (current-atimes (score-approx (get-rid-of-duplicates (quanti-of q-structure) times) from dur) nil) (unless (forbidden-structure (beat-structure current-atimes nil from (+ from dur))) (return current-atimes)))) (defun get-rid-of-duplicates (x times) (cond ((not (rest x)) times) ((= (first x) (second x)) (keep-unquantized-statistics (second times) (first times)) (get-rid-of-duplicates (rest x) (rest times))) (t (cons (first times) (get-rid-of-duplicates (rest x) (rest times)))))) (defun score-approx (times tmin &optional (sec/black 1.0) nb-pulse-max) (unless nb-pulse-max (setq nb-pulse-max (min *maximum-pulses* *max-division*))) (let ((option1 (sort (compute-quanta tmin (+ tmin sec/black) nb-pulse-max times) #'quant-test1)) (option2 (sort (compute-quanta tmin (+ tmin sec/black) nb-pulse-max times) #'quant-test2))) (mapcar #'(lambda (item1 item2) (if (< (* (get-distance item1) (* 1.2 (- 1 *distance-weight*))) (* (get-distance item2) *distance-weight*) ) item1 item2)) option1 option2))) (defun is-better (n-pulse1 n-pulse2) (< (position n-pulse1 *unit-division-hierarchy*) (position n-pulse2 *unit-division-hierarchy*))) (defun quant-test1 (quant1 quant2) (cond ((< (get-nb-error quant1) (get-nb-error quant2)) t) ;;1 ((> (get-nb-error quant1) (get-nb-error quant2)) nil) ((and (is-better (get-nb-pulse quant1) (get-nb-pulse quant2)) ;;2 (< (get-proportion-distance quant1) *dist-iota*)) t) ((< (get-proportion-distance quant1) (- (get-proportion-distance quant2) *proportions-iota*)) t) ((> (get-proportion-distance quant1) (+ (get-proportion-distance quant2) *proportions-iota*)) nil))) (defun quant-test2 (quant1 quant2) (cond ((< (get-nb-error quant1) (get-nb-error quant2)) t) ;;1 ((> (get-nb-error quant1) (get-nb-error quant2)) nil) ((is-better (get-nb-pulse quant1) (get-nb-pulse quant2)) t))) (defun compute-quanta (tmin tmax max-pulses attack-times) (let (quants quantized-times) (dolist (needed-pulses (needed-pulses max-pulses attack-times tmin tmax) (nreverse quants)) (setq quantized-times (mapcar #'(lambda (time) (adjust-time-to-grid time needed-pulses tmin tmax)) attack-times)) (push (make-quanta needed-pulses (deletions quantized-times) (distance attack-times quantized-times) (proportion-distance attack-times quantized-times tmin tmax) quantized-times) quants)))) (defun make-quanta (pulses deletions euclidean-distance proportion-distance quantized-times) (cons (list pulses deletions euclidean-distance proportion-distance) quantized-times)) (defun adjust-time-to-grid (time pulses tmin tmax) (+ tmin (* (- tmax tmin) (/ pulses) (round (* (- time tmin) pulses) (- tmax tmin))))) (defun needed-pulses (nb-pulse-max attack-times tmin tmax) (if (not attack-times) '(1) (let* ((minimum-pulses (minimum-pulses attack-times tmin tmax)) (pulses (arithm-ser minimum-pulses (1- nb-pulse-max) 1))) (unless pulses (setf pulses (list (1- nb-pulse-max)))) (if nil ;; GA 10/10/94 (< (length pulses) *min-pulses*) (arithm-ser minimum-pulses (1- (max nb-pulse-max (* 2 minimum-pulses))) 1) pulses)))) (defun minimum-pulses (attack-times tmin tmax) (min *maximum-pulses* (max 1 ;;;;;(1- (length attack-times)) (truncate (- tmax tmin) (* 3 (apply 'min (- tmax tmin) (x->dx attack-times))))))) ;;euclidean distance (defun sqr (n) (* n n)) (defun distance (list qlist) (let ((accum 0.0) (length 0)) (mapc #'(lambda (x y) (incf accum (sqr (- x y))) (incf length)) list qlist) (/ (sqrt accum) (max 1.0 (float length 1.0d0))))) (defun deletions (quantized-times) (count 0 (x->dx quantized-times) :test #'=)) (defun proportion-distance (l ll tmin tmax) (win3 (remove 0 (x->dx (cons tmin (append l (list tmax)))) :test #'=) (remove 0 (x->dx (cons tmin (append ll (list tmax)))) :test #'=))) ;;;This is computer generated code from Joshua Finneberg's error measure patch [931026] ;;;function sort-list merged with om sort (defun win3 (var1 var2) (apply '+ (om^ (let (A) (mapcar #'(lambda (B) (setf A B) (om/ (apply '+ A) (length A))) (let (C D) (mapcar #'(lambda (E F) (setf C E D F) (let (G) (mapcar #'(lambda (H) (setf G H) (om^ (apply '/ (sort-list G :test '>)) '3)) (mat-trans (list C D))))) (let (J) (mapcar #'(lambda (K) (setf J K) (cond ((= (length J) 1) J) (t (g-scaling/sum J '100)))) (mapcar 'list (x-append var1 (create-list (om-abs (om- (max (length var1) (length var2)) (length var1))) 1))))) (let (M) (mapcar #'(lambda (N) (setf M N) (cond ((= (length M) 1) M) (t (g-scaling/sum M '100)))) (mapcar 'list (x-append var2 (create-list (om-abs (om- (max (length var1) (length var2)) (length var2))) 1))))) )))) 3)))
32,361
Common Lisp
.lisp
606
39.963696
149
0.535095
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
057c640a73742532b988b63657fd1be320579f410622370e3cc5cf5462348e01
747
[ -1 ]
748
trees.lisp
cac-t-u-s_om-sharp/src/packages/score/functions/trees.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; TREE FUNCTIONS ; by K. Haddad, 2004 ;============================================================================ (in-package :om) ;============================================================================== ; MAKE TREES ;============================================================================== ;-------------------------- ; PULSEMAKER ;-------------------------- (defmethod* pulsemaker ((measures list) (beat-unit list) (n-pulses list)) :initvals (list '(4 4) '(8 8) '(4 (1 1 1 1))) :indoc '("measure numerator(s)" "measure denominator(s)" "contents (pulses/subdivisions)") :icon :tree :doc " Constructs a tree starting from a (list of) measure(s) numerator(s) <measures-num> and a (list of) denominator(s) <beat-unit> filling these measures with <npulses>. " (let* ((pulses (mapcar 'cons measures (mapcar #'(lambda (x) (if (listp x) (list x) (list (om::repeat-n 1 x)))) n-pulses))) (mes (mapcar #'(lambda (x y) (list x y)) measures beat-unit)) (tree (mapcar #'(lambda (x y) (list x (list y))) mes pulses))) (list '? tree))) (defmethod* pulsemaker ((measures list) (beat-unit number) (n-pulses list)) (let* ((lght (length measures)) (bt-unt-lst (repeat-n beat-unit lght))) (pulsemaker measures bt-unt-lst n-pulses))) (defmethod* pulsemaker ((measures number) (beat-unit list) (n-pulses list)) (let* ((lght (length beat-unit)) (measure-lst (repeat-n measures lght))) (pulsemaker measure-lst beat-unit n-pulses))) (defmethod* pulsemaker ((measures number) (beat-unit number) (n-pulses list)) (let* ((lght (length n-pulses)) (bt-unt-lst (repeat-n beat-unit lght)) (measure-lst (repeat-n measures lght))) (pulsemaker measure-lst bt-unt-lst n-pulses))) ;-------------------------- ; MAKETREEGROUPS ;-------------------------- (defun grplst (lst grp) (let* ((grouped (loop for a in grp collect (prog1 (first-n lst a) (setf lst (nthcdr a lst)))))) (remove nil (if lst (x-append grouped (list lst)) grouped)))) (defmethod* maketreegroups ((figures list) (sequence list) (measures list)) :initvals (list '((1 1 1) (1 2 1) (3 4) (1 1 1 1)) '(0 3 0 2 0 1 0 0 3) '((4 4))) :indoc '("rhythm figures" "control sequence" "list of time signatures") :icon :tree :doc " Builds a Rhythm Tree starting from a a list of rhythmic figures (<figures>). <sequence> is a list of index used to pick items in <figures>. An inconsistent index (> than the length of <figures>) will produce a rest. <measures> is a list of time signatures used to build the RT. " (let* ((mesures (let* ((dernieremesure (last-elem measures)) (lgtseq (length sequence)) (lgtbeats (apply '+ (mapcar 'car measures)))) (if (> lgtseq lgtbeats) (x-append measures (repeat-n dernieremesure (ceiling (/ (- lgtseq lgtbeats) (car dernieremesure))))) measures))) (num (mapcar 'car mesures)) (denom (mapcar 'cadr mesures)) (pos (posn-match figures sequence)) (donnes (loop for i in pos collect (if (null i) -1 (list 1 i)))) (groupment (grplst donnes num))) (list '? (loop for i in num for j in denom for a in groupment collect (if (< (length a) i) (list (list i j) (x-append a (* -1 (- i (length a))))) (list (list i j) a)))))) ;============================================================================== ; INSPECT TREES ;============================================================================== ;-------------------------- ; GROUP-PULSES / N-PULSES ;-------------------------- (defun real-copy-list (list) (loop for item in list collect (cond ((listp item) (real-copy-list item)) (t item)))) (defun give-pulse (liste) (let* ((n (second liste))) (loop for item in n append (if (atom item) (list item) (give-pulse item))))) (defun pulse (mesure) (om::flat (mapcar #'(lambda (x) (give-pulse x)) mesure))) (defun pulses (mesures) "retourne le nombre de pulses (pas les pauses) d'une RTM" (om::flat (mapcar #'(lambda (x) (pulse (list x))) mesures))) (defun om-pulses (tlist) (mapcar #'(lambda (x) (pulse (list (cons '() (list x))))) tlist)) (defun find-po (list) (remove '() (mapcar #'(lambda (x y) (if (floatp x) nil y )) list (om::arithm-ser 0 (length list) 1)))) (defmethod! group-pulses ((tree list)) :initvals '((? (((4 4) (1 (1 (1 2.0 1.0 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1))))) :indoc '("a rhythm tree") :icon :tree :doc " Collects every pulses (expressed durations, including tied notes) from <tree>. " (let* ((tree2 (second (om::mat-trans (om::flat-once (om::mat-trans (rest (real-copy-list tree))))))) (the-pulses (om::flat (om-pulses tree2))) (the-pos (om::remove-dup (om::flat (list 0 (find-po the-pulses) (length the-pulses))) 'eq 1))) (if (null (find-po the-pulses)) nil (om::group-list the-pulses (om::x->dx the-pos) 'linear)))) (defmethod! n-pulses ((tree t)) :initvals '((? (((4 4) (1 (1 (1 2 1 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1))))) :indoc '("a rhythm tree") :icon :tree :doc " Returns the numbre of pulses in <tree>. " (let (( liste (if (typep tree 'voice) (tree tree) tree))) (length (remove nil (mapcar #'(lambda(x) (if (> (first x) 0) x nil)) (om::group-pulses liste)))))) ;-------------------------- ; GET-SIGNATURES ;-------------------------- (defmethod* get-signatures ((tree list)) :icon :tree :indoc '("a rhythm tree, voice or poly") :initvals (list '(? (((4 4) (1 (1 (1 2 1 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1))))) :doc " Returns the list of time signatures in the rhythm tree (<tree>). " (mapcar #'first (cadr tree))) (defmethod* get-signatures ((self voice)) (get-signatures (tree self))) (defmethod! get-signatures ((self poly)) (loop for v in (inside self) collect (get-signatures v))) ;-------------------------- ; GET-PULSE-PLACES ;-------------------------- (defmethod* get-pulse-places ((tree list)) :initvals '((? (((4 4) (1 (1 (1 2 1 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1))))) :indoc '("a rhythm tree or voice") :icon :tree :doc " Returns the positions of the pulses in <tree>. " (let* ((res nil) (n 0) (puls (group-pulses tree))) (loop for i in puls do (if (plusp (car i)) (progn (push n res) (incf n)) (incf n))) (reverse res))) (defmethod* get-pulse-places ((self voice)) (get-pulse-places (tree self))) ;-------------------------- ; GET-REST-PLACES ;-------------------------- (defmethod* get-rest-places ((tree list)) :initvals '((? (((4 4) (1 (1 (1 2 1 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1))))) :indoc '("a rhythm tree or voice") :icon :tree :doc " Returns the positions of the rests in <tree>. " (let* ((res nil) (n 0) (puls (group-pulses tree))) (loop for i in puls do (if (minusp (car i)) (progn (push n res) (incf n)) (incf n))) (reverse res))) (defmethod* get-rest-places ((self voice)) (get-rest-places (tree self))) ;============================================================================== ; TRANSFORM TREES ;============================================================================== ;The structure TREEOBJ is defined in order to access easily the tree consecutives kind: ;plusp integers, minusp integers and floats (pulse, rests and tied notes) (defstruct treeobj (tvalue 1) (tindex 0)) (defun trans-tree (tree) "transforms a rhythm tree into a tree with objects in the place of musical events: notes ,rests and tied notes." (if (atom tree) (make-treeobj :tvalue tree) (list (first tree) (mapcar 'trans-tree (second tree))))) (defun trans-obj (tree) (if (atom tree) (if (typep tree 'treeobj) (treeobj-tvalue tree) tree) (list (first tree) (mapcar 'trans-obj (second tree))))) ;;; used in some recursive functions (defvar *tree-index-count* -1) (defun trans-tree-index (tree) "transforms a rhythm tree into a tree with objects in the place of musical events: notes ,rests and tied notes and marks the index of events." (if (atom tree) (make-treeobj :tvalue tree :tindex (incf *tree-index-count*)) (list (first tree) (mapcar 'trans-tree-index (second tree))))) (defun trans-note-index (treeobjlist) "puts index only on expressed notes and not on floats or rests (for filtering purposes)." (if (atom treeobjlist) (if (and (typep treeobjlist 'treeobj) (integerp (treeobj-tvalue treeobjlist)) (plusp (treeobj-tvalue treeobjlist))) (setf (treeobj-tindex treeobjlist) (incf *tree-index-count*)) treeobjlist) (list (first treeobjlist) (mapcar #'trans-note-index (second treeobjlist))))) ;-------------------------- ; REDUCETREE ;-------------------------- (defun grouper1 (liste) "groups succesive floats" (if (null liste) liste (let* ((first (car liste)) (rest (rest liste)) ) (if (numberp first) (if (plusp first) (cons (+ first (loop while (and (numberp (first rest)) (floatp (first rest))) sum (round (pop rest)))) (grouper1 rest)) (cons first (grouper1 rest))) (cons (grouper1 first) (grouper1 rest)))))) (defun grouper2 (liste) "groups succesive rests (-1) into one" (if (null liste) liste (let* ((first (car liste)) (rest (rest liste))) (if (numberp first) (if (plusp first) (cons first (grouper2 rest)) (cons (+ first (loop while (and (integerp (first rest)) (minusp (first rest))) sum (pop rest))) (grouper2 rest))) (cons (grouper2 first) (grouper2 rest)))))) (defun grouper3 (liste) "reduces concatenated rests in the form of (1(-3)) into -1" (if (atom liste) liste (if (and (numberp (first (second liste))) (minusp (first (second liste))) (null (rest (second liste))) (not (listp (first liste)))) (- (first liste)) (list (first liste) (mapcar 'grouper3 (second liste)))))) (defmethod reduced-tree ((tree list)) (let ((liste (resolve-? tree))) (grouper3 (grouper2 (grouper1 liste))))) (defmethod* reducetree ((tree list)) :initvals '( (? (((4 4) (1 (1 (1 2.0 1.0 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 -1)))) ) :indoc '("a rhythm tree") :icon :tree :doc " Reduces and simplifies a tree by concatenating consecutive rests and floats. " (let ((liste (reduced-tree tree))) (loop while (not (equal liste tree)) do (setf tree liste) (setf liste (reduced-tree liste))) (remove nil liste))) ;-------------------------- ; TIETREE ;-------------------------- (defmethod* tietree ((tree t)) :initvals '((? (((4 4) (1 (1 (1 2 1 1)) 1 1)) (4//4 (1 (1 (1 2 1 1)) -1 1))))) :indoc '("a rhythm tree") :icon :tree :doc " Converts all rests in <tree> (a rhytm tree, VOICE or POLY object) into ties (i.e. float values in the RT). " (cond ((and (atom tree) (> tree 0)) tree) ((atom tree) (* (* tree -1) 1.0)) (t (list (first tree) (mapcar 'tietree (second tree)))))) (defmethod* tietree ((self voice)) (make-instance 'voice :tree (tietree (tree self)) :tempo (if (atom (tempo self)) (tempo self) (cadar (tempo self))) :chords (get-chords self))) (defmethod* tietree ((self poly)) (make-instance 'poly :voices (loop for v in (inside self) collect (tietree v)))) ;-------------------------- ; FILTERTREE ;-------------------------- (defun transform-notes-flt (list places) (loop while list for courant = (pop list) do (if (and (and (integerp (treeobj-tvalue courant)) (plusp (treeobj-tvalue courant))) (member (treeobj-tindex courant) places)) (progn (setf (treeobj-tvalue courant) (- (treeobj-tvalue courant))) (loop while (and list (floatp (treeobj-tvalue (car list)))) do (setf (treeobj-tvalue (car list)) (round (- (treeobj-tvalue (car list))))) (pop list)))))) (defmethod* filtertree ((tree t) (places list)) :initvals '((? (((4 4) (1 (1 (1 2 1 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1)))) (0 1)) :indoc '("a rhytm tree or voice" "a list of indices") :icon :tree :doc " Replaces expressed notes in given positions from <places> with rests. " (setf *tree-index-count* -1) (let* ((liste (if (typep tree 'voice) (tree tree) tree)) (tree2obj (trans-tree liste))) (trans-note-index tree2obj) (transform-notes-flt (remove-if 'numberp (flat tree2obj)) places) (trans-obj tree2obj))) ;-------------------------- ; REVERSETREE ;-------------------------- (defun group-ties (liste) "liste is a liste of treeobjs" (let* (res) (loop for i in liste do (cond ((and (plusp (treeobj-tvalue i)) (not (floatp (treeobj-tvalue i)))) (push (list i) res)) ((floatp (treeobj-tvalue i)) (push i (car res))) (t)) ) (loop for i in res do (if (> (length i) 1) (progn (setf (treeobj-tvalue (first i)) (round (treeobj-tvalue (first i)))) (setf (treeobj-tvalue (last-elem i)) (* 1.0 (treeobj-tvalue (last-elem i))))))))) (defun reversedties (tree) (let* ((liste (if (typep tree 'voice) (tree tree) (resolve-? tree))) (tree2obj (trans-tree liste))) (group-ties (remove-if 'numberp (flat tree2obj))) (trans-obj tree2obj))) (defun reversedtree (tree) (if (atom tree) tree (list (first tree) (reverse (mapcar 'reversedtree (second tree)))))) (defmethod* reversetree ((tree t)) :initvals '((? (((4 4) (1 (1 (1 2 1 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1))))) :indoc '("a rhythm tree or voice") :icon :tree :doc " Recursively reverses <tree>. " (reversedtree (reversedties tree))) (defmethod* reversetree ((self voice)) (reversetree (tree self))) ;-------------------------- ; ROTATETREE ;-------------------------- ;;rotate-by measure la ne veut rien dire: ;;example qud on a une seconde mesure commencant par une liaison ;;donc qui appartien t a la premiere mesure on a un probleme!!! (defmethod rotatetreepulse ((tree t) (nth integer)) "Returns a circular permutation of a copy of <tree> durations starting from its <nth> element" (let* ((ratios (tree2ratio tree)) (signatures (mapcar 'car (cadr tree))) (rotation (rotate ratios nth))) (mktree rotation signatures))) (defun get-all-treeobj (tree) (remove nil (mapcar #'(lambda (x) (if (typep x 'treeobj) x)) (flat tree)))) (defun permtree (list nth) (let* ((listobj (rotate list nth)) (vals (mapcar 'treeobj-tvalue listobj))) (loop for i from 0 to (1- (length listobj)) for a in vals collect (setf (treeobj-tvalue (nth i list)) a)))) (defmethod rotate-tree ((tree t) (nth integer)) (setf *tree-index-count* -1) (let* ((tree2obj (trans-tree-index tree)) (tree2objclean (get-all-treeobj tree2obj))) (permtree tree2objclean nth) (trans-obj tree2obj))) (defmethod* rotatetree (tree n &optional (mode 'pulse)) :initvals '((? (((4 4) (1 (1 (1 2 1 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1)))) 1 pulse) :indoc '("a rhythm tree" "a number" "rotation mode") :menuins '((2 (("pulse" 'pulse) ("prop" 'prop)))) :icon :tree :doc " Applies a rotation of <n> positions to the pulses in <tree>. <mode> = 'pulse' : applies to pulses (expressed durations). <mode> = 'prop' : applies to the tree values. " (if (equal mode 'pulse) (rotatetreepulse tree n) (rotate-tree tree n))) ;-------------------------- ; REMOVE-RESTS ;-------------------------- (defun transform-rests (list) "traces a simple list coming from trans-tree and flattened according to: if note encoutered, then floats are checked and transformed into rests, else rests encoutered and either other rests or errounous floats are transformed into notes. From Gerard." (loop while list for courant = (pop list) do (if (and (integerp (treeobj-tvalue courant)) (minusp (treeobj-tvalue courant))) (progn (setf (treeobj-tvalue courant) (- (treeobj-tvalue courant))) (loop while (and list (not (and (integerp (treeobj-tvalue (first list))) (plusp (treeobj-tvalue (first list)))))) do (setf (treeobj-tvalue (car list)) (float (abs (treeobj-tvalue (car list))))) (pop list)))))) (defmethod* remove-rests ((tree t)) :initvals '((2 (((4 4) (1 (1 (1 2 1 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1))))) :indoc '("a rhythm tree") :icon :tree :doc " Converts all rests to notes. " (let* ((liste (if (typep tree 'voice) (tree tree) tree)) (tree2obj (trans-tree liste)) (tree2objclean (remove-if 'numberp (flat tree2obj)))) (transform-rests tree2objclean) (trans-obj tree2obj))) ;-------------------------- ; SUBST-RHYTHM ;-------------------------- (defun substreeall (list pos elem) (loop for i from 0 to (length pos) for a in pos collect (if (listp (nth i elem)) (setf (treeobj-tvalue (nth a list)) (list (abs (floor (treeobj-tvalue (nth a list)))) (nth i elem))) (setf (treeobj-tvalue (nth a list)) (nth i elem))))) ;pour eviter les tree avec '?' ;ATTENTION!! numtree transforme les 5 en (4 1.0) etc... ;ceci pourrait fausser les transformations ; toutefois il est utlise pour regler l'histoire de ? (defun numtree (tree) (let* ((newvoice (make-instance 'voice :tree tree))) (tree newvoice))) ; This is for both trees from measures & VOICES (defun optimize-tree (tree) "this function optimizes trees modified by rotate-tree and subst-rhythm methods by grouping each measure as a group, in order to correctly read the new rhythm outputed." (if (or (equal '? (first tree)) (atom (first tree))) (let* ((header (first tree)) (info (second tree)) (splitree (mat-trans info)) (signatures (first splitree)) (measures (second splitree)) (opt-meas (mapcar #'(lambda (x) (list (list 1 x))) measures)) (withmes (mapcar #'(lambda (x y) (list x y)) signatures opt-meas))) (list header withmes)) (let* ((signatures (first tree)) (measures (second tree)) (opt-meas (list (list 1 measures)))) (list signatures opt-meas)))) ; In OM all 5 and 7 etc.. are transformed by voice and numtree function ; in (4 1.0) as tied notes. If we need to permut trees as expressed ; i.e 5 and not (4 1.0) use reduce mode. (here we use reducetree function!) ; and finally remove this option and put it by default in reduce mode ; for accurate computation! (defmethod* subst-rhythm ((tree t) (pos list) (elem list) &optional (option 'reduce) (output 'optimized)) :initvals '((? (((4 4) (1 (1 (1 2 1 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1)))) nil (1 2) reduce optimized) :indoc '("a rhythm tree" "list of positions" "list of new items" "option" "output") :menuins '((3 (("reduce" 'reduce) ("tied" 'tied))) (4 (("optimized" 'optimized) ("not optimized" 'not-optimized)))) :icon :tree :doc " Substitutes elements in <tree>. <elem> input is a list that can accept either atoms or lists or both. Atoms are pulses. Lists will be proportions creating groups . For example a list (1 1 1) substituting 2 will yield (2 (1 1 1)). <pos> if left nil will substitute from 0 position until the end of list <elem>. If the positions are specified (a list) each nth elem of tree being pulses will be replaced sequentially by elements from <elem>." (setf *tree-index-count* -1) (let* ((liste (if (typep tree 'voice) (if (equal option 'reduce) (reducetree (tree tree)) (tree tree)) (if (equal option 'reduce) (reducetree (numtree tree)) (numtree tree)))) (position (if (null pos) (loop for i from 0 to (1- (length elem)) collect i) (first-n pos (length elem) ))) (tree2obj (trans-tree-index liste)) (tree2objclean (remove-if 'numberp (flat tree2obj)))) (substreeall tree2objclean position elem) (case output (optimized (optimize-tree (trans-obj tree2obj))) (not-optimized (trans-obj tree2obj))))) ;-------------------------- ; INVERT-RHYTHM ;-------------------------- (defun transform (list) "traces a simple list coming from trans-tree and flattened according to: if note encoutered, then floats are checked and transformed into rests, else rests encoutered and either other rests or errounous floats are transformed into notes. From Gerard." (loop while list for courant = (pop list) do (cond ((and (integerp (treeobj-tvalue courant)) (plusp (treeobj-tvalue courant))) (setf (treeobj-tvalue courant) (- (treeobj-tvalue courant))) (loop while (and list (floatp (treeobj-tvalue (car list)))) do (setf (treeobj-tvalue (car list)) (round (- (treeobj-tvalue (car list))))) (pop list))) ((and (integerp (treeobj-tvalue courant)) (minusp (treeobj-tvalue courant))) (setf (treeobj-tvalue courant) (- (treeobj-tvalue courant))) (loop while (and list (not (and (integerp (treeobj-tvalue (first list))) (plusp (treeobj-tvalue (first list)))))) do (setf (treeobj-tvalue (car list)) (float (abs (treeobj-tvalue (car list))))) (pop list)))))) (defmethod* invert-rhythm ((tree t)) :initvals '((? (((4 4) (1 (1 (1 2 1 1)) 1 1)) ((4 4) (1 (1 (1 2 1 1)) -1 1))))) :indoc '("a rhythm tree") :icon :tree :doc " Inverts <tree> : every note becomes a rest and every rest becomes a note. " (let* ((liste (if (typep tree 'voice) (tree tree) (resolve-? tree))) (tree2obj (trans-tree liste)) (tree2objclean (remove-if 'numberp (flat tree2obj)))) (transform tree2objclean) (trans-obj tree2obj)))
23,955
Common Lisp
.lisp
576
34.628472
130
0.553948
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
11260118a52977f1a5b340aff42a1f4fde4a9067edb0f1cedebd96bc93362ac1
748
[ -1 ]
749
segmentation.lisp
cac-t-u-s_om-sharp/src/packages/score/functions/segmentation.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson 2021 ;============================================================================ (in-package :om) ;;; Utilities to work with score markers (defmethod* get-marker-times ((self chord-seq)) :doc "Extracts marker times from a score (chord-seq) using the 'score-markers'" (loop for chord in (chords self) when (get-extras chord 'score-marker) collect (date chord))) (defmethod* get-segments ((self chord-seq)) :doc "Extracts segments from a score (chord-seq) using the 'score-markers'" (let ((time-markers (cons (date (car (chords self))) (loop for chord in (cdr (chords self)) when (get-extras chord 'score-marker) collect (date chord))))) (loop for next-markers on time-markers collect (remove-extras (select self (car next-markers) (cadr next-markers)) 'score-marker nil)))) (defmethod* map-segments ((self chord-seq) function &rest args) :doc "Applies a function to all the segments in a chord-seq, and concatenates the results. <function> should accept a chord-seq as argument, and return another concatenable score object. If <function> has more arguments, they can also be passed as as many lists by adding optional inputs." (let ((results (apply #'mapcar (append (list function (get-segments self)) args)))) (if (>= (length results) 2) (reduce #'concat results) results)))
2,152
Common Lisp
.lisp
39
48.74359
102
0.57852
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
51d20f35438f74106eaa71e11f7318dd68f0517b23ce38dc0d482e9067e690e6
749
[ -1 ]
750
score-functions.lisp
cac-t-u-s_om-sharp/src/packages/score/functions/score-functions.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;============================================================================ ; ; BASIC SCORE FUNCTIONS ; ;============================================================================ (in-package :om) ;-------------------- ; DURATION ;-------------------- (defmethod* object-dur ((self score-element)) :initvals '(nil) :indoc '("a musical object") :outdoc '("duration (ms)") :icon :duration :doc "Returns the total duration of a musical object (ms)" (get-obj-dur self)) ;-------------------- ; GET-CHORDS ;-------------------- (defmethod* get-chords ((self chord-seq)) :initvals '(nil) :indoc '("a music sequence (voice, chord-seq, poly, multi-seq...)") :icon :score :doc "Extracts an ordered list (or list of list) of chords from a music sequence or superposition. Returned chords are copies of original internal chords. Time information (onset) is removed." (loop for chord in (chords self) collect (om-copy chord))) (defmethod* get-chords ((self chord)) (list (om-copy self))) (defmethod* get-chords ((self t)) nil) (defmethod* get-chords ((self multi-seq)) (loop for voice in (obj-list self) collect (get-chords voice))) (defmethod* get-chords ((self rhythmic-object)) (loop for elt in (inside self) append (get-chords elt))) ;---------------------- ; Internal version without copy ;---------------------- (defmethod collect-chords ((self t)) nil) (defmethod collect-chords ((self chord)) (list self)) (defmethod collect-chords ((self chord-seq)) (chords self)) (defmethod collect-chords ((self rhythmic-object)) (loop for elt in (inside self) append (collect-chords elt))) (defmethod collect-chords ((self multi-seq)) (loop for voice in (obj-list self) append (collect-chords voice))) (defmethod collect-note-chords ((self note) parent) (list (find-if #'(lambda (c) (find self (notes c))) (collect-chords parent)))) ;-------------------- ; ALIGN-CHORDS ;-------------------- (defmethod group-chords ((self chord-seq)) (when (chords self) (let ((new-chords (list (car (chords self))))) (loop for c in (cdr (chords self)) do (if (equal (onset c) (onset (car new-chords))) (setf (notes (car new-chords)) (append (notes (car new-chords)) (notes c))) (push c new-chords))) (set-chords self (reverse new-chords))))) ;;; destructive version: align in the sequence ;;; when slection : align only the chords in selection (defmethod align-chords-in-sequence ((self chord-seq) (unit number) &optional selection) (when (> unit 0) (loop for c in (or selection (chords self)) do (setf (onset c) (* unit (round (onset c) unit))))) (group-chords self) self) (defmethod align-chords-in-sequence ((self multi-seq) (unit number) &optional selection) (loop for seq in (obj-list self) do (if selection ;;; select chords from this voice (let ((chords-in-voice (remove-if #'(lambda (chord) (not (find chord (chords seq)))) selection))) (when chords-in-voice (align-chords-in-sequence seq unit chords-in-voice) )) ;;; align all (align-chords-in-sequence seq unit))) self) ;;; OM-patch version: creates a new object (defmethod* align-chords ((self chord-seq) (unit number)) :initvals (list nil 100) :indoc '("a chord-seq" "an integer") :icon :score :doc " Aligns chords on a grid of <unit> (ms) and groups notes falling in a same interval. " (let ((cseq (om-copy self))) (align-chords-in-sequence cseq unit) cseq)) (defmethod* align-chords ((self multi-seq) (unit number)) (make-instance 'multi-seq :obj-list (loop for cs in (obj-list self) collect (align-chords cs unit)))) (defmethod* align-chords ((self voice) (unit number)) nil) ;-------------------- ; CONCAT ;-------------------- (defmethod* concat ((s1 chord-seq) (s2 chord-seq) &optional (s2-offset nil)) :initvals '(nil nil nil) :indoc '("a musical object" "a musical object" "concat offset") :icon :score :doc "Concatenates two musical objects/sequences into a new one. Optional input <s2-offset> may be used to pass an offset value (in ms) for <s2>. Otherwise the <s2> is concatenated at the end of <s1>. <s2-offset> is ignored in the case where VOICE objects. MULTI-SEQ: global concatenation takes into account the duration of the object. POLY: each voice is concatenated, regardless of the global duration. " (let ((cs (make-instance 'chord-seq)) (new-chords (append (get-chords s1) (get-chords s2)))) (loop for c in new-chords for time in (append (time-sequence-get-times s1) (om+ (time-sequence-get-times s2) (or s2-offset (object-dur s1)))) do (item-set-time c time)) (set-chords cs new-chords) cs)) ;;; TODO: concatenate the tempo list (see below) (defmethod* concat ((s1 voice) (s2 voice) &optional s2-offset) (when (and s2-offset (not (zerop s2-offset))) (om-print "CONCAT sequences of type VOICE: s2-offset value is ignored." "Warning")) (make-instance 'voice :chords (append (get-chords s1) (get-chords s2)) :tree (let ((measures (append (second (tree s1)) (second (tree s2))))) (list (length measures) measures)) :tempo (tempo s1) ) ;;; (setf (tempo rep) (concat-tempi s1 s2)) ) #| (defun concat-tempi (voice1 voice2) (flet ((equal-tempi (t1 t2) (and (= (car t1) (car t2)) (= (second t1) (second t2)) (equal (third t1) (third t2))))) (let* ((tempo1 (tempo voice1)) (tempo2 (tempo voice2)) (newtempo (copy-list tempo1)) lasttempo) (if (second tempo1) (setf lasttempo (second (car (last (second tempo1))))) (setf lasttempo (car tempo1))) (unless (equal-tempi (car tempo2) lasttempo) (setf (nth 1 newtempo) (append (nth 1 newtempo) (list (list (list (length (inside voice1)) 0) (car tempo2)))) )) (loop for item in (second tempo2) do (setf (nth 1 newtempo) (append (nth 1 newtempo) (list (list (list (+ (length (inside voice1)) (caar item)) (second (car item))) (second item)))) )) newtempo))) |# (defmethod* concat ((s1 multi-seq) (s2 multi-seq) &optional (s2-offset nil)) (let ((offset (or s2-offset (get-obj-dur s1)))) (make-instance 'multi-seq :chord-seqs (loop with chs1 = (inside s1) with chs2 = (inside s2) while (or chs1 chs2) collect (concat (pop chs1) (pop chs2) offset))) )) (defmethod* concat ((s1 poly ) (s2 poly) &optional (s2-offset nil)) (when (and s2-offset (not (zerop s2-offset))) (om-print "CONCAT sequences of type POLY: s2-offset value is ignored." "Warning")) (make-instance 'poly :voices (mapcar #'concat (inside s1) (inside s2)))) (defmethod* concat ((s1 score-element) (s2 null) &optional (s2-offset nil)) (declare (ignore s2 s2-offset)) (clone s1)) (defmethod* concat ((s1 null) (s2 score-element) &optional (s2-offset nil)) (declare (ignore s1)) (concat (make-instance (type-of s2)) s2 s2-offset)) ;-------------------- ; MERGE ;-------------------- (defmethod* merger ((obj1 chord-seq) (obj2 chord-seq)) :initvals '(nil nil) :icon :score :indoc '("sequence" "sequence") :doc "Merges to objects to a single object of the same type. If types are different, uses the type of <obj1>. With VOICE objects, uses the tempo and metrics of <obj1>. " (let ((new-cs (make-instance 'chord-seq))) (set-chords new-cs (sort (append (get-chords obj1) (get-chords obj2)) #'< :key #'onset)) (align-chords-in-sequence new-cs 0) new-cs)) (defmethod* merger ((obj1 voice) (obj2 chord-seq)) (let ((new-cs (make-instance 'chord-seq))) (set-chords new-cs (sort (append (get-chords obj1) (get-chords obj2)) #'< :key #'onset)) (align-chords-in-sequence new-cs 0) (omquantify new-cs (tempo obj1) (get-metrics obj1) 16))) (defmethod* merger ((obj1 chord) (obj2 chord)) (let ((new-chord (make-instance 'chord))) (setf (notes new-chord) (sort (mapcar #'om-copy (append (notes obj1) (notes obj2))) #'< :key #'midic)) new-chord)) ;-------------------- ; SELECT ;-------------------- (defmethod* select ((self chord-seq) (start number) end) :initvals '(nil 0 1000) :indoc '("a sequence" "an integer" "an integer") :doc " Extracts a subseqence : when : <self> is a chord-seq, <start> and <end> are absolute positions in ms, result is a chord-seq. <self> is a voice, <start> and <end> are measure numbers, result is a voice (<end> excluded) <self> is a multi-seq, <start> and <end> are absolute positions in ms, result is a multi-seq. <self> is a poly, <start> and <end> are measure number selected in each voice (<end> excluded) if <end> is NIL, the selection runs until th end. " (unless start (setf start 0)) (if (or (< start 0) (and end (>= start end))) (om-beep-msg "select : Bad start/end values") (let ((rep (make-instance (type-of self)))) (set-chords rep (loop for chord in (data-track-get-frames self) when (and (>= (item-get-time chord) start) (or (null end) (< (item-get-time chord) end))) collect (let ((c (om-copy chord))) (setf (onset c) (- (onset chord) start)) c))) (time-sequence-update-obj-dur rep) rep) )) ;;; voice = in measure (defmethod* select ((self voice) (start number) end) (when (and end (> end (length (inside self)))) (om-beep-msg "Warning: end-of selection out of range in SELECT") (setf end nil)) (make-instance 'voice :tempo (tempo self) :chords (loop for m in (subseq (inside self) start end) append (get-chords m)) :tree (let ((measures (subseq (second (tree self)) start end))) (list (length measures) measures)))) ;;; poly/multi-seq (defmethod* select ((self multi-seq) (start number) end) (make-instance (type-of self) :obj-list (loop for v in (obj-list self) collect (select v start end)))) ;-------------------- ; INSERT ;-------------------- (defmethod* insert ((v1 voice) (v2 voice) position) :indoc '("voice" "voice" "position (voice num)") :initvals '(nil nil 0) :doc "Inserts the measures of <v2> in <v1> at <position> (position in measures)." :icon :score (let* ((pos (or position (length (inside v1)))) (before (select v1 0 pos)) (after (select v1 pos nil))) (make-instance 'voice :chords (append (get-chords before) (get-chords v2) (get-chords after)) :tree (let ((measures (append (second (tree before)) (second (tree v2)) (second (tree after)) ))) (list (length measures) measures)) ) )) ;;; destructive version, with measures (defmethod insert-in-voice ((self voice) (m list) position) (let* ((pos (or position (length (inside self)))) (before (select self 0 pos)) (after (select self pos nil))) (let ((new-chords (append (get-chords before) (apply #'append (mapcar #'get-chords m)) (get-chords after))) (new-tree (let ((measures (append (second (tree before)) (mapcar #'tree m) (second (tree after)) ))) (list (length measures) measures)))) (setf (tree self) (format-tree (normalize-tree new-tree))) (set-chords self new-chords) (build-voice-from-tree self) ))) (defmethod insert-in-voice ((v1 voice) (m measure) position) (insert-in-voice v1 (list m) position)) ;-------------------- ; SPLIT ;-------------------- ;;; by Gilbert Nouno (defmethod* split-voices ((self chord-seq) &optional (random nil)) :indoc '("a 'polyphonic' chord-seq" "random distribution strategy?") :initvals '(nil nil) :doc "Separates a CHORD-SEQ with overlapping notes into a list of monoponic CHORD-SEQs If <random> = T, voice distribution is chosen randomly. Otherwise the first available voice is selected." :icon :score (let ((chords-lists nil)) (loop for chord in (get-chords self) for time in (lonset self) for i = 0 then (1+ i) do (let ((position nil) (list-indices (arithm-ser 0 (1- (length chords-lists)) 1))) (if random (setf list-indices (permut-random list-indices))) (loop for n in list-indices while (not position) do (let ((voice? (nth n chords-lists))) (when (> time (+ (car (car voice?)) (list-max (ldur (cadr (car voice?)))))) (setf (nth n chords-lists) (cons (list time chord) (nth n chords-lists))) ;(setf voice? (cons (list time chord) voice?)) (setf position t)))) (unless position (setf chords-lists (append chords-lists (list (list (list time chord)))))) )) ;;; chords-list = ;;; (((onset1 chord1) (onset2 chord2) ...) ;;; ((onset1 chord1) (onset2 chord2) ...) ;;; ...[n times]... ) (loop for list in chords-lists collect (let ((chords (reverse (mapcar 'cadr list))) (onsets (reverse (mapcar 'car list)))) (make-instance 'chord-seq :lonset onsets :lmidic (mapcar 'lmidic chords) :ldur (mapcar 'ldur chords) :lvel (mapcar 'lvel chords) :lchan (mapcar 'lchan chords)))) )) (defmethod* true-durations ((self chord-seq)) :indoc '("a score object") :initvals '(nil) :doc "Returns a list of durations in milliseconds, including rests (as negative values), separating the notes or chords in a sequence. Overlapping events are cropped at the beginning of th enext event." :icon :score (let ((last-onset 0)) (loop for next-chords on (chords self) append (let* ((c (car next-chords)) (chord-onset (item-get-time c)) (chord-duration (item-get-duration c)) (chord-end (+ chord-onset chord-duration)) (next-onset (if (cdr next-chords) (item-get-time (cadr next-chords)) chord-end)) (new-duration (if (> chord-end next-onset) (- next-onset chord-onset) chord-duration)) (silence-before (- last-onset chord-onset))) (setq last-onset (+ chord-onset new-duration)) (if (zerop silence-before) (list new-duration) (list silence-before new-duration)))) ))
16,383
Common Lisp
.lisp
363
36.413223
136
0.559071
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
010bd9b2c6265a0899a55ce93bec901057d7a1dd0f1adf9a11e5ac4296dcb146
750
[ -1 ]
751
n-cercle.lisp
cac-t-u-s_om-sharp/src/packages/score/math/n-cercle.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ (in-package :om) (defclass* n-cercle () ((interval :initform '(60 72) :accessor cercle-interval) ;;; not used atm (could be useful for rendering...) (n :initform 12 :initarg :n :accessor n) (puntos :initform '(0 5 7) :accessor puntos :initarg :puntos)) (:documentation "A graphical object representing a series of intervals on a circle. N-CERCLE can be used to represent chords following the pitch-class set theory, or cyclic rhythmic patterns. <n> is the 'modulo' of the space <puntos> is a list of points in this space. Note: N-CERCLE can also contain a set of chords/patterns: in this case, <puntos> is a list of lists. ")) ;;; just reformat / check the values (defmethod initialize-instance :after ((self n-cercle) &key args) (declare (ignore args)) (unless (and (n self) (plusp (n self))) (om-beep-msg "N-CERCLE: N MUST BE A POSITIVE INTEGER (DEFAULT=12)") (setf (n self) 12)) (when (not (consp (car (puntos self)))) (setf (puntos self) (list (puntos self)))) (setf (puntos self) (remove nil (loop for cercle in (puntos self) collect (if (and (listp cercle) (list-subtypep cercle 'integer)) cercle (om-beep-msg (format nil "Wrong data in N-CERCLE: ~A" cercle)))))) ) ;;;============================= ;;; BOX ;;;============================= (defmethod display-modes-for-object ((self n-cercle)) '(:mini-view :text :hidden)) (defun polar2car (angle radius) (list (round (* radius (cos angle))) (round (* radius (sin angle))))) (defun draw-point-list-in-circle (angle-list cx cy r &key (thickness 1) color (lines nil) (front t)) (let ((points-xy (loop for theta in angle-list collect (multiple-value-bind (x y) (pol->car r (+ theta (/ pi -2))) (list (+ cx x) (+ cy y)))))) (om-with-line-size thickness (loop for xy in points-xy do (om-draw-circle (car xy) (cadr xy) (* 3 thickness) :color color) (when color (om-draw-circle (car xy) (cadr xy) (* 3 thickness) :color color :fill t)) ) (when lines (loop for p on (append points-xy (list (car points-xy))) when (cdr p) do (om-draw-line (car (car p)) (cadr (car p)) (car (cadr p)) (cadr (cadr p)) :line (if front (+ 1 thickness) thickness) :color color) ))) )) (defmethod draw-mini-view ((self n-cercle) (box t) x y w h &optional time) (declare (ignore time)) (om-draw-rect x y w h :color (om-def-color :white) :fill t) (draw-cercle self x y w h)) (defmethod draw-cercle ((self n-cercle) x y w h) (let ((step (/ (* pi 2) (n self))) (cx (+ x (round w 2))) (cy (+ y (round h 2))) (r (round (min w h) 2.5))) (om-draw-circle cx cy r) (draw-point-list-in-circle (loop for i from 0 to (- (n self) 1) collect (* step i)) cx cy r) (loop for point-list in (reverse (puntos self)) for i = (1- (length (puntos self))) then (- i 1) do (draw-point-list-in-circle (om* point-list step) cx cy r :color (get-midi-channel-color (1+ (mod i 16))) :lines 1) ) )) ;============================================= ;FUNCTIONS ;============================================= (defmethod* nc-rotate ((self n-cercle) n) :initvals '(nil 1) :indoc '("n-cercle" "steps") :icon :cercle :doc "Generates a N-CERCLE by rotation of <self>." (make-instance 'n-cercle :n (n self) :puntos (loop for list in (puntos self) collect (sort (loop for p in list collect (mod (+ p n) (n self))) '<)) )) (defmethod* nc-complement ((self n-cercle)) :initvals '(nil) :indoc '("n-cercle") :icon :cercle :doc "Generates the complement of <self> (N-CERCLE)." (make-instance 'n-cercle :n (n self) :puntos (loop for list in (puntos self) collect (loop for item from 0 to (- (n self) 1) when (not (find item list :test #'(lambda (a b) (= (mod a (n self)) (mod b (n self)))))) collect item)) )) (defmethod* nc-inverse ((self n-cercle)) :initvals '(nil) :indoc '("n-cercle") :icon :cercle :doc "Generates the inverse of <self> (N-CERCLE)." (make-instance 'n-cercle :n (n self) :puntos (loop for list in (puntos self) collect (sort (x->dx (reverse (dx->x 0 list))) '<)) )) ;============================================= ;CONVERSIONS ;============================================= (defmethod* chord2c ((self chord) approx) :initvals '(nil 2) :indoc '("the chord" "approx") :icon :cercle :doc "Generates a N-CERCLE representing <self> (a CHORD) on a circle with a given division of the tone (2=semitone) <approx> can be 2 (default), 4 or 8. " (let ((n (case approx (2 12) (4 24) (8 48) (otherwise 12))) (div (case approx (2 100) (4 50) (8 25) (otherwise 100)))) (make-instance 'n-cercle :n n :puntos (remove-duplicates (sort (loop for item in (om/ (om- (approx-m (Lmidic self) approx) 6000) div) collect (mod item n)) '<))))) ;;; use this for automatic conversion from CHORD to N-CERCLE (defmethod objfromobjs ((model chord) (target n-cercle)) (chord2c model 2)) (defmethod* c2chord ((self n-cercle) index base approx) :initvals '(nil 0 6000 100) :indoc '("n-cercle" "index" "initial value" "approx") :doc "Generates a CHORD starting from nth (<index>) point-list in <self> (N-CERCLE)" :icon :cercle (let ((points (puntos self))) (make-instance 'chord :lmidic (om+ base (om* approx (nth index points)))))) (defmethod* c2chord-seq ((self n-cercle) base approx) :initvals '(nil 6000 100) :indoc '("n-cercle" "initial value" "approx") :doc "Generates a sequence of chords (CHORD-SEQ) starting from all the point-lists in <self> (N-CERCLE)" :icon :cercle (let ((points (puntos self))) (make-instance 'chord-seq :lmidic (loop for item in points collect (om+ base (om* approx item)))))) (defmethod* chord-seq2c ((self chord-seq) approx) :initvals '(nil 2 ) :indoc '("the chord-seq" "approx") :doc "Returns a possible circular representations of a sequence of chords (CHORD-SEQ) with a given tone division (2=semitone). <approx> can be 2 (default), 4 or 8." :icon :cercle (let ((n (case approx (2 12) (4 24) (8 48) (otherwise 12))) (div (case approx (2 100) (4 50) (8 25) (otherwise 100)))) (make-instance 'n-cercle :n n :puntos (loop for chord in (inside self) collect (remove-duplicates (sort (loop for item in (om/ (om- (approx-m (Lmidic chord) approx) 6000) div) collect (mod item n)) '<)))))) (defmethod* c2rhythm ((self n-cercle) index signature times) :initvals '(nil 0 (12 8) 3) :indoc '("n-cercle" "index" "signature" "times" ) :doc "Generates a rhythm (VOICE) from the nth (<index>) point-list in <self> (N-CERCLE) and repeating the rhythmic pattern a given number of times." :icon :cercle (let* ((pattern (nth index (puntos self))) (intervals (x->dx pattern)) (all-intervals (append intervals (list (- (n self) (apply '+ intervals)))))) (make-instance 'voice :tree (repeat-n (list signature all-intervals) times)))) (defmethod! rhythm2c ((self voice) n) :initvals '(nil 16) :doc "Returns a possible circular representations of a rhythmic pattern (VOICE) with modulo <n>." :icon :cercle (let* ((ratio (tree2ratio (tree self))) (step (car ratio))) (loop for item in (cdr ratio) do (setf step (pgcd step item))) (setf ratio (om/ ratio step)) (make-instance 'n-cercle :n n :puntos (butlast (dx->x 0 ratio))) ))
9,504
Common Lisp
.lisp
200
37.205
151
0.521246
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
44aa6df06f7c1340c062ec34549551aa07190d338d267b7eb26e02ae87e5558f
751
[ -1 ]