-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrackerView.lua
More file actions
2016 lines (1768 loc) · 70.1 KB
/
trackerView.lua
File metadata and controls
2016 lines (1768 loc) · 70.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- See docs/trackerView.md for the model.
--invariant: rows 0-indexed, cols 1-indexed, channels 1..16, stops 1-indexed
--invariant: vm.grid is a live handle — rm reads it each frame; mutated in place on rebuild, never reassigned
--invariant: rm is pull-only — vm fires no render callbacks; rm queries vm.grid / vm:ec() / vm:rowPerBar() each frame
--invariant: all writes funnel through tm (addEvent/assignEvent/deleteEvent/flush); vm never touches mm
--invariant: vm works in logical time and detune-intent for pitch — never reads/writes raw pb directly (see docs/tuning.md)
--invariant: authoring stamps evt.rpb = currentRpb() and evt.ppq = row · logPerRow before tm:addEvent
--invariant: off-grid edits snap evt.ppq to cursor row; delay survives, rpb restamps to current
--invariant: clipboard encodes rows in source's logical frame; paste decodes against dest's rpb — symmetric on (row, chan), not absolute ppq
--shape: grid = { cols = {<col>...}, chanFirstCol = {[chan]=i}, chanLastCol = {[chan]=i}, lane1Col = {[chan]=<col>}, numRows = int }
--shape: gridCol = { type, midiChan, lane?, cc?, label, events, width, parts, stopPos, partAt, partStart, showDelay, cells={[y]=evt}, overflow={[y]=true}, offGrid={[y]=true}, ghosts={[y]={val,fromEvt,toEvt}}, tails? }
--shape: selection = { row1, row2, col1, col2, part1, part2 } -- part names: 'pitch'|'vel'|'delay' on note, 'pb' on pb, 'val' on scalar
--shape: plan = { col, e, [newppq], [newEndppq], [newDelay] } -- consumed by writePlans / conformOverlaps
local util = require 'util'
local timing = require 'timing'
local tuning = require 'tuning'
local tm, cm, cmgr = (...).tm, (...).cm, (...).cmgr
local function print(...)
return util.print(...)
end
---------- STATE
local resolution = 240
local rowPerBar = 16
local length = 0
local timeSigs = {}
local scrollCol = 1
local scrollRow = 0
local gridWidth = 0
local gridHeight = 0
local grid = {
cols = {},
chanFirstCol = {},
chanLastCol = {},
}
local tv = {}
tv.grid = grid -- live handle for rm; mutated in place on rebuild
local ec, clipboard, ctx
---------- SHARED HELPERS
----- Note geometry (used by editing, adjust*, nudge, quantizeKeepRealised)
-- prev maximises endppq; nxt minimises ppq.
local function neighbourEvents(cols, ppq, pred)
local prev, nxt
for _, c in ipairs(cols) do
local p = util.seek(c.events, 'before', ppq, pred)
local n = util.seek(c.events, 'after', ppq, pred)
if p and (not prev or p.endppq > prev.endppq) then prev = p end
if n and (not nxt or n.ppq < nxt.ppq ) then nxt = n end
end
return prev, nxt
end
local function notePreds(excludeEvt)
local pitch = excludeEvt and excludeEvt.pitch
return function(e) return util.isNote(e) and e ~= excludeEvt and e.pitch ~= pitch end,
function(e) return util.isNote(e) and e ~= excludeEvt and e.pitch == pitch end
end
-- Diff-pitch col-local with `overlapOffset` leniency (matches column allocator).
-- Same-pitch chan-wide with no leniency: MIDI permits one voice per (chan, pitch).
local function overlapBounds(col, ppq, excludeEvt, allowOverlap)
local lenient = allowOverlap and cm:get('overlapOffset') * resolution or 0
local diff, same = notePreds(excludeEvt)
local prevD, nextD = neighbourEvents({col}, ppq, diff)
local prevS, nextS = neighbourEvents(tm:getChannel(col.midiChan).columns.notes, ppq, same)
local minStart = math.max(prevD and (prevD.endppq - lenient) or 0, prevS and prevS.endppq or 0)
local maxEnd = math.min(nextD and (nextD.ppq + lenient) or length, nextS and nextS.ppq or length)
return minStart, maxEnd
end
-- Row-space sibling of overlapBounds. e.ppq is exact logical-ppq
-- post-projection; lenient diff edges add slack in the same frame.
local function rowBounds(col, ppq, excludeEvt, allowOverlap)
local chan, logPerRow = col.midiChan, ctx:ppqPerRow()
local lenient = allowOverlap and cm:get('overlapOffset') * resolution or 0
local diff, same = notePreds(excludeEvt)
local prevD, nextD = neighbourEvents({col}, ppq, diff)
local prevS, nextS = neighbourEvents(tm:getChannel(chan).columns.notes, ppq, same)
local function startL(e, slack) return e.ppq + slack end
local function endL (e, slack) return e.endppq + slack end
local fullL = grid.numRows * logPerRow
local prevEndL = math.max(prevD and endL (prevD, -lenient) or 0, prevS and endL (prevS, 0) or 0)
local nextStartL = math.min(nextD and startL(nextD, lenient) or fullL, nextS and startL(nextS, 0) or fullL)
return math.ceil(prevEndL / logPerRow), math.floor(nextStartL / logPerRow)
end
--contract: resolves overlap excess in a per-column plan list; mutates plan entries in place. Tail-overlap clips predecessor's tail (legato — onset stays); same-onset shifts the later-source-ppq one by 1 ppq. Non-note plans/cols skipped; unplanned col-mates treated as fixed
local function conformOverlaps(plans)
local lenient = cm:get('overlapOffset') * resolution
local plansByCol = {}
for _, p in ipairs(plans) do
if util.isNote(p.e) then
plansByCol[p.col] = plansByCol[p.col] or {}
util.add(plansByCol[p.col], p)
end
end
for col, colPlans in pairs(plansByCol) do
local planByEvt = {}
for _, p in ipairs(colPlans) do planByEvt[p.e] = p end
local timeline = {}
for _, e in ipairs(col.events) do
if util.isNote(e) then
local p = planByEvt[e]
util.add(timeline, { e = e, plan = p,
ppq = (p and p.newppq) or e.ppq,
endppq = (p and p.newEndppq) or e.endppq })
end
end
table.sort(timeline, function(a, b)
if a.ppq ~= b.ppq then return a.ppq < b.ppq end
return a.e.ppq < b.e.ppq
end)
local function nudgePpq(plan, e, delta)
plan.newppq = (plan.newppq or e.ppq) + delta
end
for i = 2, #timeline do
local prev, curr = timeline[i - 1], timeline[i]
-- Same-onset shift first. The later-source-ppqL one (curr by
-- sort tie-break) moves up 1 ppq; if it's fixed, prev moves
-- back instead — rare, only when a planned event happens to
-- round onto an unplanned col-mate's ppq.
if prev.ppq == curr.ppq then
if curr.plan then
nudgePpq(curr.plan, curr.e, 1)
curr.ppq = curr.ppq + 1
elseif prev.plan then
nudgePpq(prev.plan, prev.e, -1)
prev.ppq = prev.ppq - 1
end
end
-- Tail-overlap clip on the post-shift state. Predecessor's
-- tail clips first (legato — onset stays); only when the
-- predecessor is fixed does the successor's onset lift.
local threshold = (prev.e.pitch == curr.e.pitch) and 0 or lenient
local excess = prev.endppq - curr.ppq - threshold
if excess > 0 then
if prev.plan then
local clipped = math.max(prev.ppq + 1,
(prev.plan.newEndppq or prev.e.endppq) - excess)
prev.plan.newEndppq = clipped
prev.endppq = clipped
elseif curr.plan then
local lifted = math.min(curr.endppq - 1, curr.ppq + excess)
nudgePpq(curr.plan, curr.e, lifted - curr.ppq)
curr.ppq = lifted
end
end
end
end
end
local function writePlans(plans)
for _, p in ipairs(plans) do
local u = {}
if p.newppq ~= nil then u.ppq = p.newppq end
if p.newDelay ~= nil then u.delay = p.newDelay end
if util.isNote(p.e) and p.newEndppq ~= nil then u.endppq = p.newEndppq end
tm:assignEvent(p.e, u)
end
end
-- Two bounds: same-pitch chan-wide (MIDI one-voice-per-pair) at the prior
-- note's endppq, and same-column any-pitch at neighbour's realised onset
-- (so realised order = logical order within every column — the pb model
-- leans on this).
-- Floor at 0; ceiling at n.endppq − 1 so realised duration ≥ 1 ppq.
local function delayRange(col, n)
local sameP = function(e) return util.isNote(e) and e ~= n and e.pitch == n.pitch end
local prevSame = neighbourEvents(tm:getChannel(col.midiChan).columns.notes, n.ppq, sameP)
local prevSameEnd = prevSame and prevSame.endppq
local prev = util.seek(col.events, 'before', n.ppq, util.isNote)
local nextE = util.seek(col.events, 'after', n.ppq, util.isNote)
local realised = function(e) return e.ppq + timing.delayToPPQ(e.delay or 0, resolution) end
local minStart = math.max(prevSameEnd or 0,
prev and (realised(prev) + 1) or 0)
local maxStart = math.min(n.endppq - 1,
nextE and (realised(nextE) - 1) or math.huge)
return timing.ppqToDelay(minStart - n.ppq, resolution),
timing.ppqToDelay(maxStart - n.ppq, resolution)
end
----- Show events by column, used by lots of selection ops
local function eventsByCol()
local r1, r2, c1, c2, part1, part2 = ec:region()
local singleNotePart = (c1 == c2 and part1 == part2
and grid.cols[c1] and grid.cols[c1].type == 'note') and part1 or nil
local result = {}
for ci = c1, c2 do
local col = grid.cols[ci]
if not col then goto nextCol end
local startppq, endppq = ctx:rowToPPQ(r1, col.midiChan), ctx:rowToPPQ(r2 + 1, col.midiChan)
local locs = {}
-- Keyed by event reference, not loc: notes and CCs use disjoint loc
-- spaces, so a PA (cc loc=N) and a note (note loc=N) can collide.
for evt in util.between(col.events, startppq, endppq) do
locs[evt] = evt
end
local part = col.type == 'note' and (singleNotePart or 'pitch') or 'val'
util.add(result, { col = col, locs = locs, part = part })
::nextCol::
end
return result
end
----- Frames & timing
local function logPerRowFor(rpb)
local denom = (timeSigs[1] and timeSigs[1].denom) or 4
return timing.logPerRow(rpb, denom, resolution)
end
local isFrameChange, currentRpb, releaseTransientFrame do
local FRAME_KEYS = { rowPerBeat = true }
--contract: a write to a FRAME_KEYS member at any tier other than 'transient' counts as a real frame change — fires releaseTransientFrame from configCallback
function isFrameChange(change)
return FRAME_KEYS[change.key] and change.level ~= 'transient'
end
function currentRpb() return cm:get('rowPerBeat') end
-- Returns true iff a transient override was released.
function releaseTransientFrame()
if cm:getAt('transient', 'rowPerBeat') == nil then return false end
local oldRPB = cm:get('rowPerBeat')
cm:assign('transient', { rowPerBeat = util.REMOVE })
local newRPB = cm:get('rowPerBeat')
if newRPB ~= oldRPB then
ec:rescaleRow(oldRPB, newRPB)
tv:rebuild(false)
end
return true
end
end
-- Pass rowE for span events (notes).
local function assignStamp(evt, chan, rowS, rowE)
local rpb = currentRpb()
local logPerRow = logPerRowFor(rpb)
local s = { ppq = rowS * logPerRow, rpb = rpb }
if rowE then s.endppq = rowE * logPerRow end
tm:assignEvent(evt, s)
end
--contract: whenever a note's tail moves: rebases evt.rpb to current alongside the new endppq
local function assignTail(evt, chan, endppq)
tm:assignEvent(evt, { endppq = endppq, rpb = currentRpb() })
end
local function matchGridToCursor()
if releaseTransientFrame() then return end
local col = grid.cols[ec:col()]
local evt = col and col.type == 'note' and col.cells and col.cells[ec:row()]
if not (evt and evt.rpb) then return end
-- Rescale ec before the cm:assign so the rebuild it fires sees ec
-- already aligned to the new rpb.
local oldRPB = cm:get('rowPerBeat')
if evt.rpb ~= oldRPB then ec:rescaleRow(oldRPB, evt.rpb) end
cm:assign('transient', { rowPerBeat = evt.rpb })
end
function tv:setRowPerBeat(n)
n = util.clamp(n, 1, 32)
if n == cm:get('rowPerBeat') then return end
-- Release before cm:set: otherwise configCallback sees a non-transient
-- frame-key write and rescales ec on top of our own rescaleRow below.
-- Release may itself rescale; re-read so our rescale is from the
-- post-release rpb (no-op if release already landed us at n).
releaseTransientFrame()
ec:rescaleRow(cm:get('rowPerBeat'), n)
cm:set('track', 'rowPerBeat', n)
end
-- props = { name, rows, mode = 'resize'|'rescale'|'tile' }; mode defaults to 'resize'.
tv.applyTakeProperties = util.atomic('Take properties', function(self, props)
if props.name ~= tm:name() then tm:setName(props.name) end
local newPpq = props.rows * ctx:ppqPerRow()
if newPpq ~= (tm:length() or 0) then
local mode = props.mode or 'resize'
if mode == 'rescale' then tm:rescaleLength(newPpq)
elseif mode == 'tile' then tm:tileLength(newPpq)
else tm:setLength(newPpq)
end
end
end)
-- Slot selections (temper, swing) are views over the data, not data
-- themselves. Mirroring at project+track means a fresh take inherits
-- the most recent selection, while takes on an existing track inherit
-- from their siblings via the track-level value.
local function writeShared(key, value)
if value == nil or value == '' then
cm:remove('project', key)
cm:remove('track', key)
else
cm:set('project', key, value)
cm:set('track', key, value)
end
end
function tv:setSwingSlot(name) writeShared('swing', name) end
function tv:setTemperSlot(name) writeShared('temper', name) end
-- colSwing is a per-channel map; cross-track bleed via project would
-- mean track A's per-channel pattern surfaces on a fresh track B until
-- B overrides every entry. Keep it track-scoped.
function tv:setColSwingSlot(chan, name)
local map = cm:get('colSwing')
map[chan] = (name ~= '' and name) or nil
cm:set('track', 'colSwing', map)
end
function tv:setSwingComposite(name, composite)
if not name or name == '' then return end
local lib = cm:getAt('project', 'swings') or {}
lib[name] = composite
cm:set('project', 'swings', lib)
end
function tv:setTemper(name, temper)
if not name or name == '' then return end
local lib = cm:getAt('project', 'tempers') or {}
lib[name] = temper
cm:set('project', 'tempers', lib)
end
----- Mute / solo
local pushMute do
local effectiveMuted = {}
local function toggleChannelFlag(key, chan)
local s = cm:get(key)
s[chan] = (not s[chan]) or nil
cm:set('take', key, s)
end
--contract: effective mute = persistent-mute ∪ solo-implied mute; when any channel soloed, non-soloed forced muted and soloed forced audible (DAW solo-wins). Both sets persist in cm so reload's tm:lastMuteSet matches the wire
function pushMute()
local m = cm:get('mutedChannels')
local s = cm:get('soloedChannels')
if next(s) then
for c = 1, 16 do
if s[c] then m[c] = nil
else m[c] = true end
end
end
effectiveMuted = m
if tm then tm:setMutedChannels(effectiveMuted) end
end
function tv:isChannelMuted(chan) return cm:get('mutedChannels')[chan] == true end
function tv:isChannelSoloed(chan) return cm:get('soloedChannels')[chan] == true end
function tv:isChannelEffectivelyMuted(chan) return effectiveMuted[chan] == true end
function tv:toggleChannelMute(chan) toggleChannelFlag('mutedChannels', chan) end
function tv:toggleChannelSolo(chan) toggleChannelFlag('soloedChannels', chan) end
end
----- Audition
local audition, killAudition do
local auditionNote = nil -- { chan, pitch } (chan is 0-indexed for MIDI)
local auditionTime = 0 -- reaper.time_precise() when note was sent
local AUDITION_TIMEOUT = 0.8 -- seconds
function killAudition()
if not auditionNote then return end
reaper.StuffMIDIMessage(0, 0x80 | auditionNote.chan, auditionNote.pitch, 0)
auditionNote = nil
end
function audition(pitch, vel, chan)
killAudition()
local midiChan = (chan or 1) - 1
reaper.StuffMIDIMessage(0, 0x90 | midiChan, pitch, vel or 100)
auditionNote = { chan = midiChan, pitch = pitch }
auditionTime = reaper.time_precise()
end
function tv:tick()
if auditionNote and reaper.time_precise() - auditionTime > AUDITION_TIMEOUT then
killAudition()
end
end
end
----- Viewport
local followViewport do
local function lastVisibleFrom(startCol)
local used = 0
local last = startCol - 1
for i = startCol, #grid.cols do
local w = grid.cols[i].width + (i > startCol and 1 or 0)
if used + w > gridWidth then break end
used = used + w
last = i
end
return last
end
function followViewport()
local maxRow = math.max(0, (grid.numRows or 1) - 1)
local cRow, cCol = ec:row(), ec:col()
-- Row follow (skip before gridHeight is set to avoid inverted bounds)
if gridHeight > 0 then
local maxScroll = math.max(0, maxRow - gridHeight + 1)
scrollRow = util.clamp(scrollRow,
math.max(0, cRow - gridHeight + 1),
math.min(cRow, maxScroll))
end
scrollCol = util.clamp(scrollCol, 1, #grid.cols)
if cCol < scrollCol then
scrollCol = cCol
elseif cCol > lastVisibleFrom(scrollCol) then
while scrollCol < cCol do
scrollCol = scrollCol + 1
if cCol <= lastVisibleFrom(scrollCol) then break end
end
end
end
function tv:scroll()
return scrollRow, scrollCol, lastVisibleFrom(scrollCol)
end
end
----- Editing
do
local hexDigit = {}
for i = 0, 9 do hexDigit[string.byte(tostring(i))] = i end
for i = 0, 5 do
hexDigit[string.byte('a') + i] = 10 + i
hexDigit[string.byte('A') + i] = 10 + i
end
-- Caller has already pinned (ppq, ppqL, rpb) onto `update`.
local function placeNewNote(col, update)
local last = util.seek(col.events, 'before', update.ppq, util.isNote)
local next = util.seek(col.events, 'after', update.ppq, util.isNote)
if last and last.endppq >= update.ppq then
assignTail(last, col.midiChan, update.ppq)
end
update.vel = last and last.vel or cm:get('defaultVelocity')
update.endppq = next and next.ppq or length
update.lane = col.lane
if cm:get('trackerMode') then update.sample = cm:get('currentSample') end
update.evType = 'note'
tm:addEvent(update)
end
local function notePAEvents(col, pitch, startppq, endppq)
local pas = {}
for _, evt in ipairs(col.events) do
if evt.type == 'pa' and evt.pitch == pitch
and evt.ppq >= startppq and evt.ppq <= endppq then
util.add(pas, evt)
end
end
return pas
end
--contract: single typed-input entry point; dispatches on (col.type, stop, evt-kind). Off-grid edits run through `snap` to repin evt.ppq to cursor row and restamp frame; commit flushes, advances by advanceBy, and may audition
function tv:editEvent(col, evt, stop, char, half)
if not col then return end
local type = col.type
local rpbNow = currentRpb()
local logPerRowNow = logPerRowFor(rpbNow)
local cursorppq = ec:row() * logPerRowNow
local function commit(auditionPitch, auditionVel)
tm:flush()
ec:advance()
killAudition()
if auditionPitch then audition(auditionPitch, auditionVel or 100, col.midiChan) end
end
local function snap(update)
if not evt or evt.ppq == cursorppq then return update end
update.ppq = cursorppq
update.rpb = rpbNow
if evt.endppq then
update.endppq = cursorppq + (evt.endppq - evt.ppq)
end
return update
end
-- Within a part the cursor walks left-to-right (digit 0 = MS char,
-- digit (width-1) = LS char). setDigit speaks position-from-LS, so
-- the part's char-position is `(width - 1) - digit`.
local part = col.partAt[stop]
local digit = stop - col.partStart[stop]
if type == 'note' then
if part == 'pitch' and digit == 0 then
local nk = cmgr:noteChars(char); if not nk then return end
local pitch = util.clamp((cm:get('currentOctave') + 1 + nk[2]) * 12 + nk[1], 0, 127)
local detune = 0
local temper = ctx:activeTemper()
if temper then pitch, detune = tuning.snap(temper, pitch, 0) end
if util.isNote(evt) then
local upd = { pitch = pitch, detune = detune }
if cm:get('trackerMode') then upd.sample = cm:get('currentSample') end
tm:assignEvent(evt, snap(upd))
return commit(pitch, evt.vel)
end
-- PA cell → wipe host's PA tail, then fall through
if evt and evt.type == 'pa' then
local host = util.seek(col.events, 'before', evt.ppq, util.isNote)
if host and host.endppq > evt.ppq then
for _, pa in ipairs(notePAEvents(col, host.pitch, evt.ppq, host.endppq)) do
tm:deleteEvent(pa)
end
else
tm:deleteEvent(evt)
end
end
local new = {
pitch = pitch, detune = detune,
ppq = cursorppq,
chan = col.midiChan, rpb = rpbNow,
}
placeNewNote(col, new)
return commit(pitch, new.vel)
elseif part == 'pitch' then -- octave digit
if not util.isNote(evt) then return end
local oct
if char == string.byte('-') then oct = -1
else
local d = char - string.byte('0')
if d < 0 or d > 9 then return end
oct = d
end
local pitch = util.clamp((oct + 1) * 12 + evt.pitch % 12, 0, 127)
tm:assignEvent(evt, { pitch = pitch })
return commit(pitch, evt.vel)
-- sample: 2 hex nibbles, 0..127.
elseif part == 'sample' then
if not util.isNote(evt) then return end
local d = hexDigit[char]; if not d then return end
local newSample = util.clamp(
util.setDigit(evt.sample or 0, d, 1 - digit, 16, half), 0, 127)
tm:assignEvent(evt, { sample = newSample })
commit()
-- After flush so the configChanged-driven rebuild reads the
-- already-written sample rather than racing the queued assign.
cm:set('take', 'currentSample', newSample)
return
-- delay: signed decimal milli-QN, 3 digits, ±999
elseif part == 'delay' then
if not util.isNote(evt) then return end
local old = evt.delay
local newDelay
if char == string.byte('-') then
if old == 0 then return end
newDelay = -old
else
local d = char - string.byte('0')
if d < 0 or d > 9 then return end
local sign = old < 0 and -1 or 1
local mag = util.clamp(util.setDigit(math.abs(old), d, 2 - digit, 10, half), 0, 999)
newDelay = sign * mag
end
local minD, maxD = delayRange(col, evt)
newDelay = util.clamp(newDelay, math.ceil(minD), math.floor(maxD))
tm:assignEvent(evt, { delay = newDelay })
return commit()
-- velocity nibble (on note) or PA value
else -- part == 'vel'
local d = hexDigit[char]; if not d then return end
local function newVel(old)
return util.clamp(util.setDigit(old, d, 1 - digit, 16, half), 1, 127)
end
if evt and evt.type == 'pa' then
tm:assignEvent(evt, snap({ vel = newVel(evt.vel) }))
return commit()
end
if evt then
tm:assignEvent(evt, { vel = newVel(evt.vel) })
return commit()
end
if cm:get('polyAftertouch') then
local note = util.seek(col.events, 'before', cursorppq, util.isNote)
if note and note.endppq > cursorppq then
tm:addEvent({
evType = 'pa',
ppq = cursorppq,
chan = col.midiChan,
pitch = note.pitch, vel = newVel(0),
rpb = currentRpb(),
})
return commit()
end
end
return
end
end
-- non-note columns
local update
if util.oneOf('cc at pc', type) then
local d = hexDigit[char]; if not d then return end
update = { val = util.clamp(util.setDigit(evt and evt.val or 0, d, 1 - digit, 16, half), 0, 127) }
elseif type == 'pb' then
local old = evt and evt.val or 0
if char == string.byte('-') then
if old == 0 then return end
update = { val = -old }
else
local d = char - string.byte('0')
if d < 0 or d > 9 then return end
local sign = old < 0 and -1 or 1
update = { val = sign * util.setDigit(math.abs(old), d, 3 - digit, 10, half) }
end
else
return
end
if evt then
tm:assignEvent(evt, snap(update))
else
if type == 'cc' then util.assign(update, { cc = col.cc }) end
util.assign(update, {
ppq = cursorppq,
chan = col.midiChan, rpb = rpbNow,
})
update.evType = type
tm:addEvent(update)
end
commit()
end
end
----- Lane-strip edits (drag, add, delete, shape, tension)
-- Skips hidden absorbers; returns nil if i out of range.
local function visibleAt(col, i)
if not col or not col.events then return end
local k = 0
for _, e in ipairs(col.events) do
if not e.hidden then
k = k + 1
if k == i then return e end
end
end
end
--contract: clamps newppq strictly inside (prev.ppq, next.ppq) by ±1 — necessary-and-sufficient invariant for identity-by-visible-index to survive the post-flush rebuild
function tv:moveLaneEvent(col, i, toRow, toVal)
if not col or not col.events then return end
if not util.oneOf('cc pb at', col.type) then return end
local visible = {}
for _, e in ipairs(col.events) do
if not e.hidden then util.add(visible, e) end
end
local evt = visible[i]
if not evt then return end
local chan = col.midiChan
local prev, next = visible[i-1], visible[i+1]
local newppq = ctx:rowToPPQ(toRow, chan)
if prev and newppq <= prev.ppq then newppq = prev.ppq + 1 end
if next and newppq >= next.ppq then newppq = next.ppq - 1 end
if prev and newppq <= prev.ppq then return end -- gap < 2 ppq, nowhere to go
tm:assignEvent(evt, { val = toVal, ppq = newppq, rpb = currentRpb() })
tm:flush()
end
-- Inherits prev visible's envelope shape so prev→next curve survives the new midpoint.
-- Returns the new event's visible index post-flush for drag-seed.
function tv:addLaneEvent(col, colIdx, ppq, val)
if not col or not util.oneOf('cc pb at', col.type) then return end
local chan = col.midiChan
local prev = util.seek(col.events, 'before', ppq,
function(e) return not e.hidden end)
local update = {
val = val,
ppq = ppq,
chan = chan,
rpb = currentRpb(),
shape = prev and prev.shape or nil,
}
if col.type == 'cc' then update.cc = col.cc end
update.evType = col.type
tm:addEvent(update)
tm:flush()
local newCol = grid.cols[colIdx]
if not newCol then return end
local idx = 0
for _, e in ipairs(newCol.events) do
if not e.hidden then
idx = idx + 1
if e.ppq == ppq then return idx end
end
end
end
function tv:deleteLaneEvent(col, i)
if not col or not util.oneOf('cc pb at', col.type) then return end
local evt = visibleAt(col, i)
if not evt then return end
tm:deleteEvent(evt)
tm:flush()
end
-- Set bezier tension on the i-th visible event. Forces shape to bezier
-- so the tension is honoured (REAPER ignores tension on other shapes).
function tv:setLaneTension(col, i, tension)
if not col or not util.oneOf('cc pb at', col.type) then return end
local A = visibleAt(col, i)
if not A then return end
tm:assignEvent(A, { tension = tension, shape = 'bezier' })
tm:flush()
end
----- Interpolation
local interpolate, interpolateValues do
local interpolable = { cc = true, pb = true, at = true }
local shapeCycle = { 'step', 'linear', 'slow', 'fast-start', 'fast-end', 'bezier' }
local function nextShape(s)
for i, n in ipairs(shapeCycle) do
if n == s then return shapeCycle[(i % #shapeCycle) + 1] end
end
return 'linear'
end
local function cycleShape(col, A)
if not A then return end
tm:assignEvent(A, { shape = nextShape(A.shape or 'step') })
end
-- Cycle the segment-owner's shape on the i-th visible event in a
-- cc/pb/at column. Segment-owner = left endpoint (REAPER convention:
-- A.shape governs the curve from A to next).
function tv:cycleLaneShape(col, i)
if not col or not interpolable[col.type] then return end
local A = visibleAt(col, i)
if not A then return end
cycleShape(col, A)
tm:flush()
end
function interpolate()
if ec:hasSelection() then
local r1, r2 = ec:region()
local plans = {}
for col in ec:eachSelectedCol() do
if interpolable[col.type] then
local startppq = ctx:rowToPPQ(r1, col.midiChan)
local endppq = ctx:rowToPPQ(r2 + 1, col.midiChan)
local evts = {}
for evt in util.between(col.events, startppq, endppq) do
evts[#evts + 1] = evt
end
plans[#plans + 1] = { col = col, evts = evts }
end
end
for _, p in ipairs(plans) do
for i = 1, #p.evts - 1 do cycleShape(p.col, p.evts[i]) end
end
tm:flush()
return
end
local col = grid.cols[ec:col()]
if not (col and interpolable[col.type]) then return end
local r = ec:row()
local ghost = col.ghosts and col.ghosts[r]
local A = ghost and ghost.fromEvt
or (col.cells and col.cells[r])
or util.seek(col.events, 'before', ctx:rowToPPQ(r + 1, col.midiChan))
if not A then return end
cycleShape(col, A); tm:flush()
end
-- Returns nil for non-interpolable cols so callers can assign unconditionally.
function interpolateValues(col)
if not interpolable[col.type] then return end
local events, chan, occupied = col.events, col.midiChan, col.cells
local ghosts = {}
for i = 1, #events - 1 do
local A, B = events[i], events[i + 1]
if A.shape and A.shape ~= 'step' then
local rA = ctx:ppqToRow(A.ppq, chan)
local rB = ctx:ppqToRow(B.ppq, chan)
for y = util.round(rA) + 1, util.round(rB) - 1 do
if y >= 0 and y < grid.numRows and not (occupied and occupied[y]) then
local val = tm:interpolate(A, B, ctx:rowToPPQ(y, chan))
ghosts[y] = { val = util.round(val), fromEvt = A, toEvt = B }
end
end
end
end
return ghosts
end
end
----- Duration & position
local noteOff, adjustDuration, adjustPosition do
local function cursorNoteBefore()
local col = grid.cols[ec:col()]
if not (col and col.type == 'note') then return end
local cursorppq = ctx:rowToPPQ(ec:row(), col.midiChan)
return col, util.seek(col.events, 'at-or-before', cursorppq, util.isNote)
end
local function applyNoteOff(col, last, targetppq, undo)
if undo then
local next = util.seek(col.events, 'at-or-after', targetppq, util.isNote)
local newEnd = next and next.ppq or length
assignTail(last, col.midiChan, newEnd)
elseif last.ppq >= targetppq then
tm:deleteEvent(last)
else
local _, maxEnd = overlapBounds(col, last.ppq, last, true)
local newEnd = util.clamp(targetppq, last.ppq + 1, maxEnd)
assignTail(last, col.midiChan, newEnd)
end
end
function noteOff()
if ec:hasSelection() then
local r1 = ec:region()
local hits = {}
for col in ec:eachSelectedCol() do
if col.type == 'note' then
local chan = col.midiChan
local targetppq = ctx:rowToPPQ(r1, chan)
local nextPPQ = ctx:rowToPPQ(r1 + 1, chan)
local last = util.seek(col.events, 'before', nextPPQ, util.isNote)
if last then util.add(hits, { col = col, note = last, targetppq = targetppq }) end
end
end
if #hits == 0 then return end
local undo = true
for _, h in ipairs(hits) do
if h.note.endppq ~= h.targetppq then undo = false; break end
end
for _, h in ipairs(hits) do applyNoteOff(h.col, h.note, h.targetppq, undo) end
tm:flush()
return
end
local _, ccol, cstop = ec:pos()
local col = grid.cols[ccol]
if not (col and col.type == 'note'
and ec:cursorPart() == 'pitch'
and cstop == col.partStart[cstop]) then
return false
end
local r = ec:row()
local cursorppq = ctx:rowToPPQ(r, col.midiChan)
local nextCursorPPQ = ctx:rowToPPQ(r + 1, col.midiChan)
local last = util.seek(col.events, 'before', nextCursorPPQ, util.isNote)
if not last then return end
applyNoteOff(col, last, cursorppq, last.endppq == cursorppq)
tm:flush()
end
local function adjustDurationCore(col, note, rowDelta)
local chan = col.midiChan
local logPerRow = ctx:ppqPerRow()
local curRow = note.endppq / logPerRow
local newRow = util.clamp(util.round(curRow + rowDelta), 0, grid.numRows)
local minPPQ = math.min(note.endppq, ctx:rowToPPQ(ctx:snapRow(note.ppq, chan) + 1, chan))
local _, maxPPQ = overlapBounds(col, note.ppq, note, true)
local newppq = util.clamp(ctx:rowToPPQ(newRow, chan), minPPQ, maxPPQ)
if newppq == note.endppq then return end
assignTail(note, chan, newppq)
end
function adjustDuration(rowDelta)
rowDelta = rowDelta * (cmgr:consumePrefix() or 1)
if ec:hasSelection() then
for _, group in ipairs(eventsByCol()) do
if group.col.type == 'note' then
for _, note in pairs(group.locs) do
adjustDurationCore(group.col, note, rowDelta)
end
end
end
else
local col, note = cursorNoteBefore()
if note then adjustDurationCore(col, note, rowDelta) end
end
tm:flush()
end
local function adjustPositionMulti(rowDelta)
if rowDelta == 0 then return end
local logPerRow = ctx:ppqPerRow()
local runs = {}
for _, g in ipairs(eventsByCol()) do
if g.col.type == 'note' then
local ns = {}
for _, n in pairs(g.locs) do
util.add(ns, n)
end
if #ns > 0 then
table.sort(ns, function(a, b) return a.ppq < b.ppq end)
if rowDelta > 0 then
local _, maxRow = rowBounds(g.col, ns[#ns].ppq, ns[#ns], true)
if maxRow - ns[#ns].endppq / logPerRow < rowDelta then return end
else
local minRow = rowBounds(g.col, ns[1].ppq, ns[1], true)
if minRow - ns[1].ppq / logPerRow > rowDelta then return end
end
util.add(runs, { col = g.col, notes = ns })
end
end
end
if #runs == 0 then return end
-- resizeNote moves PBs in the note's ppq range; within each run, process in
-- the direction that keeps shifted PBs out of unprocessed notes' ranges.
for _, r in ipairs(runs) do
local chan = r.col.midiChan
local notes = r.notes
local s, e, step = 1, #notes, 1
if rowDelta > 0 then s, e, step = #notes, 1, -1 end
for i = s, e, step do
local n = notes[i]
local rowS = ctx:ppqToRow(n.ppq, chan) + rowDelta
local rowE = ctx:ppqToRow(n.endppq, chan) + rowDelta
assignStamp(n, chan, rowS, rowE)
end
end
tm:flush()
ec:shiftSelection(rowDelta)
end
-- Off-grid neighbours pull integer row inward via ceil/floor (item-start
-- guard: ceil(0) = 0 catches newStart = -1); on-grid under non-trivial
-- swing reads ppqL exactly so round-trip noise can't refuse the slot.
-- Cursor follows by rowDelta unless that row already holds another note.
function adjustPosition(rowDelta)
rowDelta = rowDelta * (cmgr:consumePrefix() or 1)
if ec:hasSelection() then return adjustPositionMulti(rowDelta) end
local col, note = cursorNoteBefore()
if not col or not note then return end
local chan = col.midiChan
local newStart = ctx:snapRow(note.ppq, chan) + rowDelta
local newEnd = ctx:snapRow(note.endppq, chan) + rowDelta
local minRow, maxRow = rowBounds(col, note.ppq, note, true)