]> git.donarmstrong.com Git - lilypond.git/blob - scm/part-combiner.scm
Issue 4357/5: Remove Scheme listeners as they are just callbacks now.
[lilypond.git] / scm / part-combiner.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 2004--2015 Han-Wen Nienhuys <hanwen@xs4all.nl>
4 ;;;;
5 ;;;; LilyPond is free software: you can redistribute it and/or modify
6 ;;;; it under the terms of the GNU General Public License as published by
7 ;;;; the Free Software Foundation, either version 3 of the License, or
8 ;;;; (at your option) any later version.
9 ;;;;
10 ;;;; LilyPond is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ;;;; GNU General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU General Public License
16 ;;;; along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
17
18 ;; todo: figure out how to make module,
19 ;; without breaking nested ly scopes
20
21 (define-class <Voice-state> ()
22   (event-list #:init-value '() #:accessor events #:init-keyword #:events)
23   (when-moment #:accessor moment #:init-keyword #:moment)
24   (tuning #:accessor tuning #:init-keyword #:tuning)
25   (split-index #:accessor split-index)
26   (vector-index)
27   (state-vector)
28   ;;;
29   ;; spanner-state is an alist
30   ;; of (SYMBOL . RESULT-INDEX), which indicates where
31   ;; said spanner was started.
32   (spanner-state #:init-value '() #:accessor span-state))
33
34 (define-method (write (x <Voice-state> ) file)
35   (display (moment x) file)
36   (display " evs = " file)
37   (display (events x) file)
38   (display " active = " file)
39   (display (span-state x) file)
40   (display "\n" file))
41
42 (define-method (note-events (vs <Voice-state>))
43   (define (f? x)
44     (ly:in-event-class? x 'note-event))
45   (filter f? (events vs)))
46
47 ; Return a list of note events which is sorted and stripped of
48 ; properties that we do not want to prevent combining parts.
49 (define-method (comparable-note-events (vs <Voice-state>))
50   (define (note<? note1 note2)
51     (let ((p1 (ly:event-property note1 'pitch))
52           (p2 (ly:event-property note2 'pitch)))
53       (cond ((ly:pitch<? p1 p2) #t)
54             ((ly:pitch<? p2 p1) #f)
55             (else (ly:duration<? (ly:event-property note1 'duration)
56                                  (ly:event-property note2 'duration))))))
57   ;; TODO we probably should compare articulations too
58   (sort (map (lambda (x)
59                (ly:make-stream-event
60                 (ly:make-event-class 'note-event)
61                 (list (cons 'duration (ly:event-property x 'duration))
62                       (cons 'pitch (ly:event-property x 'pitch)))))
63              (note-events vs))
64         note<?))
65
66 (define-method (rest-and-skip-events (vs <Voice-state>))
67   (define (f? x)
68     (or (ly:in-event-class? x 'rest-event)
69         (ly:in-event-class? x 'skip-event)))
70   (filter f? (events vs)))
71
72 (define-method (any-mmrest-events (vs <Voice-state>))
73   (define (f? x)
74     (ly:in-event-class? x 'multi-measure-rest-event))
75   (any f? (events vs)))
76
77 (define-method (previous-voice-state (vs <Voice-state>))
78   (let ((i (slot-ref vs 'vector-index))
79         (v (slot-ref vs 'state-vector)))
80     (if (< 0 i)
81         (vector-ref v (1- i))
82         #f)))
83
84 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
85
86 (define-class <Split-state> ()
87   ;; The automatically determined split configuration
88   (configuration #:init-value '() #:accessor configuration)
89   ;; Allow overriding split configuration, takes precedence over configuration
90   (forced-configuration #:init-value #f #:accessor forced-configuration)
91   (when-moment #:accessor moment #:init-keyword #:moment)
92   ;; voice-states are states starting with the Split-state or later
93   ;;
94   (is #:init-keyword #:voice-states #:accessor voice-states)
95   (synced  #:init-keyword #:synced #:init-value  #f #:getter synced?))
96
97
98 (define-method (write (x <Split-state> ) f)
99   (display (moment x) f)
100   (display " = " f)
101   (display (configuration x) f)
102   (if (synced? x)
103       (display " synced "))
104   (display "\n" f))
105
106 (define-method (current-or-previous-voice-states (ss <Split-state>))
107   "Return voice states meeting the following conditions.  For a voice
108 in sync, return the current voice state.  For a voice out of sync,
109 return the previous voice state."
110   (let* ((vss (voice-states ss))
111          (vs1 (car vss))
112          (vs2 (cdr vss)))
113     (if (and vs1 (not (equal? (moment vs1) (moment ss))))
114         (set! vs1 (previous-voice-state vs1)))
115     (if (and vs2 (not (equal? (moment vs2) (moment ss))))
116         (set! vs2 (previous-voice-state vs2)))
117     (cons vs1 vs2)))
118
119 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
120
121
122 (define (previous-span-state vs)
123   (let ((p (previous-voice-state vs)))
124     (if p (span-state p) '())))
125
126 (define (make-voice-states evl)
127   (let ((vec (list->vector (map (lambda (v)
128                                   (make <Voice-state>
129                                     #:moment (caar v)
130                                     #:tuning (cdar v)
131                                     #:events (map car (cdr v))))
132                                 evl))))
133     (do ((i 0 (1+ i)))
134         ((= i (vector-length vec)) vec)
135       (slot-set! (vector-ref vec i) 'vector-index i)
136       (slot-set! (vector-ref vec i) 'state-vector vec))))
137
138 (define (make-split-state vs1 vs2)
139   "Merge lists VS1 and VS2, containing Voice-state objects into vector
140 of Split-state objects, crosslinking the Split-state vector and
141 Voice-state objects
142 "
143   (define (helper ss-idx ss-list idx1 idx2)
144     (let* ((state1 (if (< idx1 (vector-length vs1)) (vector-ref vs1 idx1) #f))
145            (state2 (if (< idx2 (vector-length vs2)) (vector-ref vs2 idx2) #f))
146            (min (cond ((and state1 state2) (moment-min (moment state1) (moment state2)))
147                       (state1 (moment state1))
148                       (state2 (moment state2))
149                       (else #f)))
150            (inc1 (if (and state1 (equal? min (moment state1))) 1 0))
151            (inc2 (if (and state2 (equal? min (moment state2))) 1 0))
152            (ss-object (if min
153                           (make <Split-state>
154                             #:moment min
155                             #:voice-states (cons state1 state2)
156                             #:synced (= inc1 inc2))
157                           #f)))
158       (if state1
159           (set! (split-index state1) ss-idx))
160       (if state2
161           (set! (split-index state2) ss-idx))
162       (if min
163           (helper (1+ ss-idx)
164                   (cons ss-object ss-list)
165                   (+ idx1 inc1)
166                   (+ idx2 inc2))
167           ss-list)))
168   (list->vector (reverse! (helper 0 '() 0  0) '())))
169
170 (define (analyse-spanner-states voice-state-vec)
171
172   (define (helper index active)
173     "Analyse EVS at INDEX, given state ACTIVE."
174
175     (define (analyse-tie-start active ev)
176       (if (ly:in-event-class? ev 'tie-event)
177           (acons 'tie (split-index (vector-ref voice-state-vec index))
178                  active)
179           active))
180
181     (define (analyse-tie-end active ev)
182       (if (ly:in-event-class? ev 'note-event)
183           (assoc-remove! active 'tie)
184           active))
185
186     (define (analyse-absdyn-end active ev)
187       (if (or (ly:in-event-class? ev 'absolute-dynamic-event)
188               (and (ly:in-event-class? ev 'span-dynamic-event)
189                    (equal? STOP (ly:event-property ev 'span-direction))))
190           (assoc-remove! (assoc-remove! active 'cresc) 'decr)
191           active))
192
193     (define (active<? a b)
194       (cond ((symbol<? (car a) (car b)) #t)
195             ((symbol<? (car b) (car a)) #f)
196             (else (< (cdr a) (cdr b)))))
197
198     (define (analyse-span-event active ev)
199       (let* ((name (car (ly:event-property ev 'class)))
200              (key (cond ((equal? name 'slur-event) 'slur)
201                         ((equal? name 'phrasing-slur-event) 'tie)
202                         ((equal? name 'beam-event) 'beam)
203                         ((equal? name 'crescendo-event) 'cresc)
204                         ((equal? name 'decrescendo-event) 'decr)
205                         (else #f)))
206              (sp (ly:event-property ev 'span-direction)))
207         (if (and (symbol? key) (ly:dir? sp))
208             (if (= sp STOP)
209                 (assoc-remove! active key)
210                 (acons key
211                        (split-index (vector-ref voice-state-vec index))
212                        active))
213             active)))
214
215     (define (analyse-events active evs)
216       "Run all analyzers on ACTIVE and EVS"
217       (define (run-analyzer analyzer active evs)
218         (if (pair? evs)
219             (run-analyzer analyzer (analyzer active (car evs)) (cdr evs))
220             active))
221       (define (run-analyzers analyzers active evs)
222         (if (pair? analyzers)
223             (run-analyzers (cdr analyzers)
224                            (run-analyzer (car analyzers) active evs)
225                            evs)
226             active))
227       (sort ;; todo: use fold or somesuch.
228        (run-analyzers (list analyse-absdyn-end analyse-span-event
229                             ;; note: tie-start/span comes after tie-end/absdyn.
230                             analyse-tie-end analyse-tie-start)
231                       active evs)
232        active<?))
233
234     ;; must copy, since we use assoc-remove!
235     (if (< index (vector-length voice-state-vec))
236         (begin
237           (set! active (analyse-events active (events (vector-ref voice-state-vec index))))
238           (set! (span-state (vector-ref voice-state-vec index))
239                 (list-copy active))
240           (helper (1+ index) active))))
241
242   (helper 0 '()))
243
244 (define recording-group-functions
245   ;;Selected parts from @var{toplevel-music-functions} not requiring @code{parser}.
246   (list
247    (lambda (music) (expand-repeat-chords! '(rhythmic-event) music))
248    expand-repeat-notes!))
249
250
251 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
252 (define-public (recording-group-emulate music odef)
253   "Interpret @var{music} according to @var{odef}, but store all events
254 in a chronological list, similar to the @code{Recording_group_engraver} in
255 LilyPond version 2.8 and earlier."
256   (let*
257       ((context-list '())
258        (now-mom (ly:make-moment 0 0))
259        (global (ly:make-global-context odef))
260        (mom-listener (lambda (tev) (set! now-mom (ly:event-property tev 'moment))))
261        (new-context-listener
262         (lambda (sev)
263           (let*
264               ((child (ly:event-property sev 'context))
265                (this-moment-list (cons (ly:context-id child) '()))
266                (dummy (set! context-list (cons this-moment-list context-list)))
267                (acc '())
268                (accumulate-event-listener
269                 (lambda (ev)
270                   (set! acc (cons (cons ev #t) acc))))
271                (save-acc-listener
272                 (lambda (tev)
273                   (if (pair? acc)
274                       (let ((this-moment
275                              (cons (cons now-mom
276                                          (ly:context-property child 'instrumentTransposition))
277                                    ;; The accumulate-event-listener above creates
278                                    ;; the list of events in reverse order, so we
279                                    ;; have to revert it to the original order again
280                                    (reverse acc))))
281                         (set-cdr! this-moment-list
282                                   (cons this-moment (cdr this-moment-list)))
283                         (set! acc '()))))))
284             (ly:add-listener accumulate-event-listener
285                              (ly:context-event-source child) 'StreamEvent)
286             (ly:add-listener save-acc-listener
287                              (ly:context-event-source global) 'OneTimeStep)))))
288     (ly:add-listener new-context-listener
289                      (ly:context-events-below global) 'AnnounceNewContext)
290     (ly:add-listener mom-listener (ly:context-event-source global) 'Prepare)
291     (ly:interpret-music-expression
292      (make-non-relative-music
293       (fold (lambda (x m) (x m)) music recording-group-functions))
294      global)
295     context-list))
296
297 (define-public (make-part-combine-music parser music-list direction chord-range)
298   (let* ((m (make-music 'PartCombineMusic))
299          (m1 (make-non-relative-music (context-spec-music (first music-list) 'Voice "one")))
300          (m2  (make-non-relative-music  (context-spec-music (second music-list) 'Voice "two")))
301          (listener (ly:parser-lookup parser 'partCombineListener))
302          (evs2 (recording-group-emulate m2 listener))
303          (evs1 (recording-group-emulate m1 listener)))
304
305     (set! (ly:music-property m 'elements) (list m1 m2))
306     (set! (ly:music-property m 'direction) direction)
307     (set! (ly:music-property m 'split-list)
308           (if (and (assoc "one" evs1) (assoc "two" evs2))
309               (determine-split-list (reverse! (assoc-get "one" evs1) '())
310                                     (reverse! (assoc-get "two" evs2) '())
311                                     chord-range)
312               '()))
313     m))
314
315 (define-public (determine-split-list evl1 evl2 chord-range)
316   "@var{evl1} and @var{evl2} should be ascending. @var{chord-range} is a pair of numbers (min . max) defining the distance in steps between notes that may be combined into a chord or unison."
317   (let* ((pc-debug #f)
318          (voice-state-vec1 (make-voice-states evl1))
319          (voice-state-vec2 (make-voice-states evl2))
320          (result (make-split-state voice-state-vec1 voice-state-vec2))
321          (chord-min-diff (car chord-range))
322          (chord-max-diff (cdr chord-range)))
323
324     ;; Go through all moments recursively and check if the events of that
325     ;; moment contain a part-combine-force-event override. If so, store its
326     ;; value in the forced-configuration field, which will override. The
327     ;; previous configuration is used to determine non-terminated settings.
328     (define (analyse-forced-combine result-idx prev-res)
329
330       (define (get-forced-event x)
331         (and (ly:in-event-class? x 'part-combine-force-event)
332              (cons (ly:event-property x 'forced-type)
333                    (ly:event-property x 'once))))
334       (define (part-combine-events vs)
335         (if (not vs)
336             '()
337             (filter-map get-forced-event (events vs))))
338       ;; end part-combine-events
339
340       ;; forced-result: Take the previous config and analyse whether
341       ;; any change happened.... Return new once and permanent config
342       (define (forced-result evt state)
343         ;; sanity check, evt should always be (new-state . once)
344         (if (not (and (pair? evt) (pair? state)))
345             state
346             (if (cdr evt)
347                 ;; Once-event, leave permanent state unchanged
348                 (cons (car evt) (cdr state))
349                 ;; permanent change, leave once state unchanged
350                 (cons (car state) (car evt)))))
351       ;; end forced-combine-result
352
353       ;; body of analyse-forced-combine:
354       (if (< result-idx (vector-length result))
355           (let* ((now-state (vector-ref result result-idx)) ; current result
356                  ;; Extract all part-combine force events
357                  (evts (if (synced? now-state)
358                            (append
359                             (part-combine-events (car (voice-states now-state)))
360                             (part-combine-events (cdr (voice-states now-state))))
361                            '()))
362                  ;; result is (once-state permament-state):
363                  (state (fold forced-result (cons 'automatic prev-res) evts))
364                  ;; Now let once override permanent changes:
365                  (force-state (if (equal? (car state) 'automatic)
366                                   (cdr state)
367                                   (car state))))
368             (set! (forced-configuration (vector-ref result result-idx))
369                   force-state)
370             ;; For the next moment, ignore the once override (car stat)
371             ;; and pass on the permanent override, stored as (cdr state)
372             (analyse-forced-combine (1+ result-idx) (cdr state)))))
373     ;; end analyse-forced-combine
374
375
376     (define (analyse-time-step result-idx)
377       (define (put x . index)
378         "Put the result to X, starting from INDEX backwards.
379
380 Only set if not set previously.
381 "
382         (let ((i (if (pair? index) (car index) result-idx)))
383           (if (and (<= 0 i)
384                    (not (symbol? (configuration (vector-ref result i)))))
385               (begin
386                 (set! (configuration (vector-ref result i)) x)
387                 (put x (1- i))))))
388
389       (define (copy-state-from state-vec vs)
390         (define (copy-one-state key-idx)
391           (let* ((idx (cdr key-idx))
392                  (prev-ss (vector-ref result idx))
393                  (prev (configuration prev-ss)))
394             (if (symbol? prev)
395                 (put prev))))
396         (for-each copy-one-state (span-state vs)))
397
398       (define (analyse-notes now-state)
399         (let* ((vs1 (car (voice-states now-state)))
400                (vs2 (cdr (voice-states now-state)))
401                (notes1 (comparable-note-events vs1))
402                (notes2 (comparable-note-events vs2)))
403           (cond
404            ;; if neither part has notes, do nothing
405            ((and (not (pair? notes1)) (not (pair? notes2))))
406
407            ;; if one part has notes and the other does not
408            ((or (not (pair? notes1)) (not (pair? notes2))) (put 'apart))
409
410            ;; if either part has a chord
411            ((or (> (length notes1) 1) 
412                 (> (length notes2) 1))
413             (if (and (<= chord-min-diff 0) ; user requests combined unisons
414                      (equal? notes1 notes2)) ; both parts have the same chord
415                 (put 'chords)
416                 (put 'apart)))
417
418            ;; if the durations are different
419            ;; TODO articulations too?
420            ((and (not (equal? (ly:event-property (car notes1) 'duration)
421                               (ly:event-property (car notes2) 'duration))))
422             (put 'apart))
423
424            (else
425             ;; Is the interval outside of chord-range?
426             (if (let ((diff (ly:pitch-steps
427                              (ly:pitch-diff 
428                               (ly:event-property (car notes1) 'pitch)
429                               (ly:event-property (car notes2) 'pitch)))))
430                   (or (< diff chord-min-diff)
431                       (> diff chord-max-diff)
432                       ))
433                 (put 'apart)
434                 ;; copy previous split state from spanner state
435                 (begin
436                   (if (previous-voice-state vs1)
437                       (copy-state-from voice-state-vec1
438                                        (previous-voice-state vs1)))
439                   (if (previous-voice-state vs2)
440                       (copy-state-from voice-state-vec2
441                                        (previous-voice-state vs2)))
442                   (if (and (null? (span-state vs1)) (null? (span-state vs2)))
443                       (put 'chords))))))))
444
445       (if (< result-idx (vector-length result))
446           (let* ((now-state (vector-ref result result-idx))
447                  (vs1 (car (voice-states now-state)))
448                  (vs2 (cdr (voice-states now-state))))
449
450             (cond ((not vs1) (put 'apart))
451                   ((not vs2) (put 'apart))
452                   (else
453                    (let ((active1 (previous-span-state vs1))
454                          (active2 (previous-span-state vs2))
455                          (new-active1 (span-state vs1))
456                          (new-active2 (span-state vs2)))
457                      (if #f ; debug
458                          (display (list (moment now-state) result-idx
459                                         active1 "->" new-active1
460                                         active2 "->" new-active2
461                                         "\n")))
462                      (if (and (synced? now-state)
463                               (equal? active1 active2)
464                               (equal? new-active1 new-active2))
465                          (analyse-notes now-state)
466
467                          ;; active states different:
468                          (put 'apart)))
469
470                    ;; go to the next one, if it exists.
471                    (analyse-time-step (1+ result-idx)))))))
472
473     (define (analyse-a2 result-idx)
474       (if (< result-idx (vector-length result))
475           (let* ((now-state (vector-ref result result-idx))
476                  (vs1 (car (voice-states now-state)))
477                  (vs2 (cdr (voice-states now-state))))
478
479             (define (analyse-synced-silence)
480               (let ((rests1 (if vs1 (rest-and-skip-events vs1) '()))
481                     (rests2 (if vs2 (rest-and-skip-events vs2) '())))
482                 (cond
483
484                  ;; multi-measure rests (probably), which the
485                  ;; part-combine iterator handles well
486                  ((and (= 0 (length rests1))
487                        (= 0 (length rests2)))
488                   (set! (configuration now-state) 'unisilence))
489
490                  ;; equal rests or equal skips, but not one of each
491                  ((and (= 1 (length rests1))
492                        (= 1 (length rests2))
493                        (equal? (ly:event-property (car rests1) 'class)
494                                (ly:event-property (car rests2) 'class))
495                        (equal? (ly:event-property (car rests1) 'duration)
496                                (ly:event-property (car rests2) 'duration)))
497                   (set! (configuration now-state) 'unisilence))
498
499                  ;; rests of different durations or mixed with
500                  ;; skips or multi-measure rests
501                  (else
502                   ;; TODO For skips, route the rest to the shared
503                   ;; voice and the skip to the voice for its part?
504                   (set! (configuration now-state) 'apart-silence))
505
506                  )))
507
508             (define (analyse-unsynced-silence vs1 vs2)
509               (let ((any-mmrests1 (if vs1 (any-mmrest-events vs1) #f))
510                     (any-mmrests2 (if vs2 (any-mmrest-events vs2) #f)))
511                 (cond
512                  ;; If a multi-measure rest begins now while the other
513                  ;; part has an ongoing multi-measure rest (or has
514                  ;; ended), start displaying the one that begins now.
515                  ((and any-mmrests1
516                        (equal? (moment vs1) (moment now-state))
517                        (or (not vs2) any-mmrests2))
518                   (set! (configuration now-state) 'silence1))
519
520                  ;; as above with parts swapped
521                  ((and any-mmrests2
522                        (equal? (moment vs2) (moment now-state))
523                        (or (not vs1) any-mmrests1))
524                   (set! (configuration now-state) 'silence2))
525                  )))
526
527             (if (or vs1 vs2)
528                 (let ((notes1 (if vs1 (comparable-note-events vs1) '()))
529                       (notes2 (if vs2 (comparable-note-events vs2) '())))
530                   (cond ((and (equal? (configuration now-state) 'chords)
531                               (pair? notes1)
532                               (equal? notes1 notes2))
533                          (set! (configuration now-state) 'unisono))
534
535                         ((synced? now-state)
536                          (if (and (= 0 (length notes1))
537                                   (= 0 (length notes2)))
538                              (analyse-synced-silence)))
539
540                         (else ;; not synchronized
541                          (let* ((vss
542                                  (current-or-previous-voice-states now-state))
543                                 (vs1 (car vss))
544                                 (vs2 (cdr vss)))
545                            (if (and
546                                 (or (not vs1) (= 0 (length (note-events vs1))))
547                                 (or (not vs2) (= 0 (length (note-events vs2)))))
548                                (analyse-unsynced-silence vs1 vs2))))
549                         )))
550             (analyse-a2 (1+ result-idx)))))
551
552     (define (analyse-solo12 result-idx)
553
554       (define (previous-config vs)
555         (let* ((pvs (previous-voice-state vs))
556                (spi (if pvs (split-index pvs) #f))
557                (prev-split (if spi (vector-ref result spi) #f)))
558           (if prev-split
559               (configuration prev-split)
560               'apart)))
561
562       (define (put-range x a b)
563         ;; (display (list "put range "  x a b "\n"))
564         (do ((i a (1+ i)))
565             ((> i b) b)
566           (set! (configuration (vector-ref result i)) x)))
567
568       (define (put x)
569         ;; (display (list "putting "  x "\n"))
570         (set! (configuration (vector-ref result result-idx)) x))
571
572       (define (current-voice-state now-state voice-num)
573         (define vs ((if (= 1 voice-num) car cdr)
574                     (voice-states now-state)))
575         (if (or (not vs) (equal? (moment now-state) (moment vs)))
576             vs
577             (previous-voice-state vs)))
578
579       (define (try-solo type start-idx current-idx)
580         "Find a maximum stretch that can be marked as solo.  Only set
581 the mark when there are no spanners active.
582
583       return next idx to analyse.
584 "
585         (if (< current-idx (vector-length result))
586             (let* ((now-state (vector-ref result current-idx))
587                    (solo-state (current-voice-state now-state (if (equal? type 'solo1) 1 2)))
588                    (silent-state (current-voice-state now-state (if (equal? type 'solo1) 2 1)))
589                    (silent-notes (if silent-state (note-events silent-state) '()))
590                    (solo-notes (if solo-state (note-events solo-state) '())))
591               ;; (display (list "trying " type " at "  (moment now-state) solo-state silent-state        "\n"))
592               (cond ((not (equal? (configuration now-state) 'apart))
593                      current-idx)
594                     ((> (length silent-notes) 0) start-idx)
595                     ((not solo-state)
596                      (put-range type start-idx current-idx)
597                      current-idx)
598                     ((and
599                       (null? (span-state solo-state)))
600
601                      ;;
602                      ;; This includes rests. This isn't a problem: long rests
603                      ;; will be shared with the silent voice, and be marked
604                      ;; as unisilence. Therefore, long rests won't
605                      ;;  accidentally be part of a solo.
606                      ;;
607                      (put-range type start-idx current-idx)
608                      (try-solo type (1+ current-idx) (1+  current-idx)))
609                     (else
610                      (try-solo type start-idx (1+ current-idx)))))
611             ;; try-solo
612             start-idx))
613
614       (define (analyse-apart-silence result-idx)
615         "Analyse 'apart-silence starting at RESULT-IDX.  Return next index."
616         (let* ((now-state (vector-ref result result-idx))
617                (vs1 (current-voice-state now-state 1))
618                (vs2 (current-voice-state now-state 2))
619                (rests1 (if vs1 (rest-and-skip-events vs1) '()))
620                (rests2 (if vs2 (rest-and-skip-events vs2) '()))
621                (prev-state (if (> result-idx 0)
622                                (vector-ref result (- result-idx 1))
623                                #f))
624                (prev-config (if prev-state
625                                 (configuration prev-state)
626                                 'apart-silence)))
627           (cond
628            ;; rest with multi-measure rest: choose the rest
629            ((and (synced? now-state)
630                  (= 1 (length rests1))
631                  (ly:in-event-class? (car rests1) 'rest-event)
632                  (= 0 (length rests2))) ; probably mmrest
633             (put 'silence1))
634
635            ;; as above with parts swapped
636            ((and (synced? now-state)
637                  (= 1 (length rests2))
638                  (ly:in-event-class? (car rests2) 'rest-event)
639                  (= 0 (length rests1))) ; probably mmrest
640             (put 'silence2))
641
642            ((synced? now-state)
643             (put 'apart-silence))
644
645            ;; remain in the silence1/2 states until resync
646            ((equal? prev-config 'silence1)
647             (put 'silence1))
648
649            ((equal? prev-config 'silence2)
650             (put 'silence2))
651
652            (else
653             (put 'apart-silence)))
654
655           (1+ result-idx)))
656
657       (define (analyse-apart result-idx)
658         "Analyse 'apart starting at RESULT-IDX.  Return next index."
659         (let* ((now-state (vector-ref result result-idx))
660                (vs1 (current-voice-state now-state 1))
661                (vs2 (current-voice-state now-state 2))
662                ;; (vs1 (car (voice-states now-state)))
663                ;; (vs2 (cdr (voice-states now-state)))
664                (notes1 (if vs1 (note-events vs1) '()))
665                (notes2 (if vs2 (note-events vs2) '()))
666                (n1 (length notes1))
667                (n2 (length notes2)))
668           ;; (display (list "analyzing step " result-idx "  moment " (moment now-state) vs1 vs2  "\n"))
669           (max
670            ;; we should always increase.
671            (cond ((and (= n1 0) (= n2 0))
672                   ;; If we hit this, it means that the previous passes
673                   ;; have designated as 'apart what is really
674                   ;; 'apart-silence.
675                   (analyse-apart-silence result-idx))
676                  ((and (= n2 0)
677                        (equal? (moment vs1) (moment now-state))
678                        (null? (previous-span-state vs1)))
679                   (try-solo 'solo1 result-idx result-idx))
680                  ((and (= n1 0)
681                        (equal? (moment vs2) (moment now-state))
682                        (null? (previous-span-state vs2)))
683                   (try-solo 'solo2 result-idx result-idx))
684
685                  (else (1+ result-idx)))
686            ;; analyse-moment
687            (1+ result-idx))))
688
689       (if (< result-idx (vector-length result))
690           (let ((conf (configuration (vector-ref result result-idx))))
691             (cond
692              ((equal? conf 'apart)
693               (analyse-solo12 (analyse-apart result-idx)))
694              ((equal? conf 'apart-silence)
695               (analyse-solo12 (analyse-apart-silence result-idx)))
696              (else
697               (analyse-solo12 (1+ result-idx))))))) ; analyse-solo12
698
699     (analyse-spanner-states voice-state-vec1)
700     (analyse-spanner-states voice-state-vec2)
701     (if #f
702         (begin
703           (display voice-state-vec1)
704           (display "***\n")
705           (display voice-state-vec2)
706           (display "***\n")
707           (display result)
708           (display "***\n")))
709
710     ;; Extract all forced combine strategies, i.e. events inserted by
711     ;; \partcombine(Apart|Automatic|SoloI|SoloII|Chords)[Once]
712     ;; They will in the end override the automaically determined ones.
713     ;; Initial state for both voices is no override
714     (analyse-forced-combine 0 #f)
715     ;; Now go through all time steps in a loop and find a combination strategy
716     ;; based only on the events of that one moment (i.e. neglecting longer
717     ;; periods of solo/apart, etc.)
718     (analyse-time-step 0)
719     ;; (display result)
720     ;; Check for unisono or unisilence moments
721     (analyse-a2 0)
722     ;;(display result)
723     (analyse-solo12 0)
724     ;; (display result)
725     (set! result (map
726                   ;; forced-configuration overrides, if it is set
727                   (lambda (x) (cons (moment x) (or (forced-configuration x) (configuration x))))
728                   (vector->list result)))
729     (if #f ;; pc-debug
730         (display result))
731     result))
732
733 (define-public default-part-combine-mark-state-machine
734   ;; (current-state . ((split-state-event .
735   ;;                      (output-voice output-event next-state)) ...))
736   '((Initial . ((solo1   . (solo   SoloOneEvent Solo1))
737                 (solo2   . (solo   SoloTwoEvent Solo2))
738                 (unisono . (shared UnisonoEvent Unisono))))
739     (Solo1   . ((apart   . (#f     #f           Initial))
740                 (chords  . (#f     #f           Initial))
741                 (solo2   . (solo   SoloTwoEvent Solo2))
742                 (unisono . (shared UnisonoEvent Unisono))))
743     (Solo2   . ((apart   . (#f     #f           Initial))
744                 (chords  . (#f     #f           Initial))
745                 (solo1   . (solo   SoloOneEvent Solo1))
746                 (unisono . (shared UnisonoEvent Unisono))))
747     (Unisono . ((apart   . (#f     #f           Initial))
748                 (chords  . (#f     #f           Initial))
749                 (solo1   . (solo   SoloOneEvent Solo1))
750                 (solo2   . (solo   SoloTwoEvent Solo2))))))
751
752 (define-public (make-part-combine-marks state-machine split-list)
753   "Generate a sequence of part combiner events from a split list"
754
755   (define (get-state state-name)
756     (assq-ref state-machine state-name))
757
758   (let ((full-seq '()) ; sequence of { \context Voice = "x" {} ... }
759         (segment '()) ; sequence within \context Voice = "x" {...}
760         (prev-moment ZERO-MOMENT)
761         (prev-voice #f)
762         (state (get-state 'Initial)))
763
764     (define (commit-segment)
765       "Add the current segment to the full sequence and begin another."
766       (if (pair? segment)
767           (set! full-seq
768                 (cons (make-music 'ContextSpeccedMusic
769                                   'context-id (symbol->string prev-voice)
770                                   'context-type 'Voice
771                                   'element (make-sequential-music (reverse! segment)))
772                       full-seq)))
773       (set! segment '()))
774
775     (define (handle-split split)
776       (let* ((moment (car split))
777              (action (assq-ref state (cdr split))))
778         (if action
779             (let ((voice (car action))
780                   (part-combine-event (cadr action))
781                   (next-state-name (caddr action)))
782               (if part-combine-event
783                   (let ((dur (ly:moment-sub moment prev-moment)))
784                     ;; start a new segment when the voice changes
785                     (if (not (eq? voice prev-voice))
786                         (begin
787                           (commit-segment)
788                           (set! prev-voice voice)))
789                     (if (not (equal? dur ZERO-MOMENT))
790                         (set! segment (cons (make-music 'SkipEvent
791                                                           'duration (make-duration-of-length dur)) segment)))
792                     (set! segment (cons (make-music part-combine-event) segment))
793
794                     (set! prev-moment moment)))
795               (set! state (get-state next-state-name))))))
796
797     (for-each handle-split split-list)
798     (commit-segment)
799     (make-sequential-music (reverse! full-seq))))
800
801 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
802
803 (define-public (add-quotable parser name mus)
804   (let* ((tab (eval 'musicQuotes (current-module)))
805          (voicename (get-next-unique-voice-name))
806          ;; recording-group-emulate returns an assoc list (reversed!), so
807          ;; hand it a proper unique context name and extract that key:
808          (ctx-spec (context-spec-music mus 'Voice voicename))
809          (listener (ly:parser-lookup parser 'partCombineListener))
810          (context-list (reverse (recording-group-emulate ctx-spec listener)))
811          (raw-voice (assoc voicename context-list))
812          (quote-contents (if (pair? raw-voice) (cdr raw-voice) '())))
813
814     ;; If the context-specced quoted music does not contain anything, try to
815     ;; use the first child, i.e. the next in context-list after voicename
816     ;; That's the case e.g. for \addQuote "x" \relative c \new Voice {...}
817     (if (null? quote-contents)
818         (let find-non-empty ((current-tail (member raw-voice context-list)))
819           ;; if voice has contents, use them, otherwise check next ctx
820           (cond ((null? current-tail) #f)
821                 ((and (pair? (car current-tail))
822                       (pair? (cdar current-tail)))
823                  (set! quote-contents (cdar current-tail)))
824                 (else (find-non-empty (cdr current-tail))))))
825
826     (if (not (null? quote-contents))
827         (hash-set! tab name (list->vector (reverse! quote-contents '())))
828         (ly:music-warning mus (ly:format (_ "quoted music `~a' is empty") name)))))