-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrackerPage.lua
More file actions
1476 lines (1331 loc) · 56.2 KB
/
trackerPage.lua
File metadata and controls
1476 lines (1331 loc) · 56.2 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/trackerPage.md for the model.
--invariant: page is render + input only; tracker state lives in tv/ec/tm, never cached
--invariant: cm/tv read fresh each frame; only ephemeral UI state persists across frames
--invariant: page-persistent state: gridX/Y, dragging, modalState, picker*, laneConsumed
--invariant: col.x == nil is the visibility predicate; per-column draws must gate on it
--invariant: cell coords 0-indexed; header rows at -HEADER, row-num gutter at -GUTTER
--invariant: writes go through tv or cmgr commands; page never reaches into tm
local util = require 'util'
local timing = require 'timing'
local tuning = require 'tuning'
local groups = require 'groups'
if not reaper.ImGui_GetBuiltinPath then
return reaper.MB('ReaImGui is not installed or too old.', 'My script', 0)
end
package.path = reaper.ImGui_GetBuiltinPath() .. '/?.lua;' .. package.path
local ImGui = require 'imgui' '0.10'
--contract: owns and constructs the tracker substack (mm/tm/tv/am)
--contract: coord hands primitives, never the substack
--contract: take arrives later via tp:bind from coord's poll loop
local cm, cmgr, chrome, gui = (...).cm, (...).cmgr, (...).chrome, (...).gui
local function print(...)
return util.print(...)
end
local mm = util.instantiate('midiManager', { take = nil })
local tm = util.instantiate('trackerManager', { mm = mm, cm = cm })
local gm = util.instantiate('groupManager', { tm = tm, cm = cm })
local tv = util.instantiate('trackerView', { tm = tm, cm = cm, cmgr = cmgr, gm = gm })
local am = util.instantiate('arrangeManager', { cm = cm, tm = tm })
---------- PRIVATE
local GUTTER = 5 -- in grid chars: 3-char row num + spacer + region slot
local HEADER = 3 -- in grid rows
local gridX = nil
local gridY = nil
local gridOriginX = 0
local gridOriginY = 0
local gridWidth = 0
local gridHeight = 0
local chanX, chanW, chanOrder, totalWidth = {}, {}, {}, 0
--contract: clears col.x on every col before assigning; off-screen cols stay nil
local function layoutColumns(cols, scrollCol)
for _, col in ipairs(cols) do col.x = nil end
local cX, cW, cOrder = {}, {}, {}
local cx = 0
for i = scrollCol, #cols do
local col = cols[i]
if cx + col.width > gridWidth then break end
col.x = cx
local chan = col.midiChan
if cX[chan] == nil then
cX[chan] = cx
util.add(cOrder, chan)
end
cW[chan] = (cx + col.width) - cX[chan]
cx = cx + col.width + 1
end
return cX, cW, cOrder, math.max(0, cx - 1)
end
local ctx, font, uiFont = gui.ctx, gui.font, gui.uiFont
local dragging = false -- tracker-grid selection drag: click → held → release
local modalState = nil
local swingEditor = util.instantiate('swingEditor',
{ tv = tv, cm = cm, chrome = chrome, ctx = ctx, am = am })
local curveEd = util.instantiate('curveEditor', { ctx = ctx })
local laneConsumed = false
local toolbar -- lazy: chrome may be nil at construction in tests
-- Group quick-verb state and lifetime moved to trackerView (this page is
-- pure render/UI). The 'region' overlay keymap and the
-- tv:wireGroupLifetime call stay here.
local paintLast = nil -- region-paint per-cell debounce
----- Cell renderers
local function renderNote(evt, col, row)
local function noteName(pitch)
local NOTE_NAMES = {'C-','C#','D-','D#','E-','F-','F#','G-','G#','A-','A#','B-'}
local oct = math.floor(pitch / 12) - 1
local octChar = oct >= 0 and tostring(oct) or 'M'
return NOTE_NAMES[(pitch % 12) + 1] .. octChar
end
local showDelay = col and col.showDelay
local showSample = col and col.trackerMode
if not evt then
local s = '···' .. (showSample and ' ··' or '') .. ' ··'
if showDelay then s = s .. ' ···' end
return s
end
local label
if evt.type ~= 'pa' then
label = select(1, tv:noteProjection(evt)) or noteName(evt.pitch)
end
local isPA = evt.type == 'pa'
local noteTxt = isPA and '···' or label
local velTxt = evt.vel and string.format('%02X', evt.vel) or '··'
local sampleTxt = showSample and (' ' .. (isPA and '··' or string.format('%02X', evt.sample or 0))) or ''
local text = noteTxt .. sampleTxt .. ' ' .. velTxt
-- Sample digits sit at fixed positions 5,6 (after 'C-4 '). Shadowed
-- and negative-delay overrides occupy disjoint ranges, so they coexist.
local overrides
if showSample and evt.sampleShadowed then
overrides = { [5] = 'shadowed', [6] = 'shadowed' }
end
-- delayC is the realised-frame delay; divergence (delay ~= delayC) means
-- the authored intent couldn't be realised (raw clamped at 0 or by
-- step 4.8's same-pitch onset floor). tp signals it with a small star.
local divergent = evt.delayC ~= nil and evt.delayC ~= (evt.delay or 0)
if showDelay then
local d = evt.delay or 0
if d == 0 then
return text .. ' ···', nil, overrides, divergent
end
text = text .. ' ' .. string.format('%03d', math.abs(d))
if d < 0 then
local n = #text
overrides = overrides or {}
overrides[n-2], overrides[n-1], overrides[n] = 'negative', 'negative', 'negative'
end
end
return text, nil, overrides, divergent
end
local function renderPB(evt)
if evt and not evt.hidden and evt.val then
if evt.val < 0 then return string.format('%04d', math.abs(evt.val)), 'negative'
else return string.format('%04d', math.floor(evt.val)) end
else return '····' end
end
local function renderCC(evt)
if evt and evt.val then return string.format('%02X', evt.val)
else return '··' end
end
local renderFns = {
note = renderNote,
pb = renderPB,
cc = renderCC,
pa = renderCC,
at = renderCC,
pc = renderCC,
}
local function renderCell(evt, col, row)
local fn = renderFns[col.type]
if fn then return fn(evt, col, row) end
end
-- Offset (in grid cells) of the gap that sits just before the 3 delay
-- digits in a note cell. The * marker is dropped here. Layout: pitch(3)
-- + optional sample(3) + ' ' + vel(2). The next char is the separator
-- space-before-delay -- our marker slot.
local function delayMarkerOffset(col)
return 3 + (col.trackerMode and 3 or 0) + 1 + 2
end
----- Drawing
local function printer(ctx, gX, gY, x0, y0)
local drawList = ImGui.GetWindowDrawList(ctx)
local halfW = math.floor(gX / 2)
local halfH = math.floor(gY / 2)
local pt = {}
local function drawTextAt(xpos, ypos, txt, c)
for char in txt:gmatch(utf8.charpattern) do
ImGui.DrawList_AddText(drawList, xpos, ypos+1, chrome.colour(c), char)
xpos = xpos + gX
end
end
function pt:text(x, y, txt, c, font)
if font then
ImGui.PushFont(ctx, font, 15)
end
drawTextAt(x0 + x * gX, y0 + y * gY - 1, txt, c)
if font then
ImGui.PopFont(ctx)
end
end
function pt:textCentred(x1, x2, y, txt, c)
local textWidth = ImGui.CalcTextSize(ctx, txt)
local maxWidth = (x2 - x1 + 1) * gX
local offset = math.floor((maxWidth - textWidth) / 2)
drawTextAt(x0 + x1 * gX + offset, y0 + y * gY, txt, c)
end
function pt:textCentredSmall(x1, x2, y, txt, size, c)
local scale = size / 15
local textWidth = ImGui.CalcTextSize(ctx, txt) * scale
local maxWidth = (x2 - x1 + 1) * gX
local xPos = x0 + x1 * gX + math.floor((maxWidth - textWidth) / 2)
ImGui.DrawList_AddTextEx(drawList, font, size, xPos, y0 + y * gY, chrome.colour(c), txt)
end
-- Small glyph centred in a single grid cell. Used for the * marker
-- that tp drops next to a note's delay field when authored delay
-- could not be realised (delay ~= delayC).
function pt:smallGlyph(x, y, txt, size, c)
local scale = size / 15
local textWidth = ImGui.CalcTextSize(ctx, txt) * scale
local xPos = x0 + x * gX + math.floor((gX - textWidth) / 2)
local yPos = y0 + y * gY + math.floor((gY - size) / 2)
ImGui.DrawList_AddTextEx(drawList, font, size, xPos, yPos, chrome.colour(c), txt)
end
function pt:vLine(x, y1, y2, c)
ImGui.DrawList_AddLine(drawList, x0 + x * gX + halfW, y0 + y1 * gY, x0 + x * gX + halfW, y0 + y2 * gY + gY, chrome.colour(c), 1)
end
function pt:hLine(x1, x2, y, c, yOff)
local yPos = y0 + (y + (yOff or 0)) * gY
ImGui.DrawList_AddLine(drawList, x0 + x1 * gX, yPos, x0 + x2 * gX + gX, yPos, chrome.colour(c), 1)
end
function pt:box(x1, x2, y1, y2, c)
ImGui.DrawList_AddRectFilled(drawList, x0 + x1 * gX, y0 + y1 * gY, x0 + x2 * gX + gX, y0 + y2 * gY + gY, chrome.colour(c))
end
return pt
end
--contract: returns 0 when laneStrip.visible is false; layout and draw branch on this
local function laneStripRows()
if not cm:get('laneStrip.visible') then return 0 end
return cm:get('laneStrip.rows') or 0
end
-- Off=group 1, saved lib=group 2, unseeded preset (+ prefix)=group 3.
local function libPickerItems(current, lib, presets, excludePresets)
local items = { { label = 'Off', key = nil, group = 1, current = current == nil } }
local libNames = {}
for k in pairs(lib) do libNames[#libNames + 1] = k end
table.sort(libNames)
for _, name in ipairs(libNames) do
items[#items + 1] = { label = name, key = name, group = 2, current = current == name }
end
local presetNames = {}
for k in pairs(presets) do
if not (excludePresets and excludePresets[k]) and not lib[k] then
presetNames[#presetNames + 1] = k
end
end
table.sort(presetNames)
for _, name in ipairs(presetNames) do
items[#items + 1] = { label = '+ ' .. name, key = name, group = 3, current = false }
end
return items
end
-- Seed lib if absent before committing to slot.
local function pickTemper(name)
if name and not cm:get('tempers')[name] then
tv:setTemper(name, tuning.presets[name])
end
tv:setTemperSlot(name)
end
local function pickSwing(name) tv:setSwingSlot(name) end
local function pickColSwing(chan, name) tv:setColSwingSlot(chan, name) end
-- 'identity' is the explicit no-swing sentinel (schema default); shown as
-- "Off" in the button, hidden from the picker rows.
local SWING_PRESET_EXCLUDE = { identity = true }
-- Hex stays visible when unassigned so `<`/`>` advertise their step.
-- No "Off" row — every slot is real.
local function drawSampleDropdown()
local cur = cm:get('currentSample')
local entries = cm:get('slotEntries') or {}
local curName = entries[cur] and entries[cur].name
local indices = {}
for idx, e in pairs(entries) do
if e.path then indices[#indices + 1] = idx end
end
table.sort(indices)
local items = {}
for _, idx in ipairs(indices) do
items[#items + 1] = {
label = string.format('%02X %s', idx, entries[idx].name or ''),
key = idx,
group = 1,
current = idx == cur,
}
end
chrome.drawPicker {
kind = 'sample',
heading = 'Sample',
buttonLabel = string.format('%02X', cur) .. (curName and (' ' .. curName) or ''),
width = 220,
items = items,
onPick = function(idx) cm:set('take', 'currentSample', idx) end,
}
end
-- Each render closure reads cm/tv fresh; segments declared once, reused per frame.
--shape: ToolbarSegment = { id, render = fn(), visible? = fn() -> bool }
local toolbarSegments = {
{
id = 'rowsPerBeat',
render = function()
local rowPerBeat = cm:get('rowPerBeat')
ImGui.AlignTextToFramePadding(ctx)
chrome.headingLabel('RPB')
ImGui.SameLine(ctx, 0, 8)
local textW = ImGui.CalcTextSize(ctx, '32')
local btnW = ImGui.GetFrameHeight(ctx)
ImGui.SetNextItemWidth(ctx, textW + btnW * 2 + 16)
-- Spinner FramePadding shrinks at 9→10 so the buttons don't
-- crowd the two-digit field.
ImGui.PushStyleVar(ctx, ImGui.StyleVar_FramePadding, rowPerBeat > 9 and 5 or 8, 3)
local changed, n = ImGui.InputInt(ctx, '##rpb', rowPerBeat, 1, 4)
ImGui.PopStyleVar(ctx, 1)
if changed then tv:setRowPerBeat(util.clamp(n, 1, 32)) end
end,
},
{
id = 'tuning',
render = function()
chrome.headingLabel('Tuning')
ImGui.SameLine(ctx, 0, 8)
local cur = cm:get('temper')
chrome.drawPicker {
kind = 'temper',
buttonLabel = cur or 'Off',
width = 120,
items = libPickerItems(cur, cm:get('tempers'), tuning.presets),
onPick = pickTemper,
}
end,
},
{
id = 'swing',
render = function()
chrome.headingLabel('Swing')
ImGui.SameLine(ctx, 0, 8)
do
local cur = cm:get('swing')
chrome.drawPicker {
kind = 'swing', heading = 'Take',
buttonLabel = cur == 'identity' and 'Off' or cur,
width = 120,
items = chrome.libPicker('swings', cur, SWING_PRESET_EXCLUDE),
onPick = pickSwing,
}
end
-- Per-column swing in the same segment; channel from cursor's column.
local cursorCol = tv.grid.cols[tv:ec():col()]
local chan = cursorCol and cursorCol.midiChan
ImGui.SameLine(ctx, 0, 8)
chrome.disabledIf(not chan, function()
local cur = chan and cm:get('colSwing')[chan] or nil
chrome.drawPicker {
kind = 'colSwing', heading = 'Ch',
buttonLabel = cur or 'Off',
width = 120,
items = chrome.libPicker('swings', cur, SWING_PRESET_EXCLUDE),
onPick = function(name) pickColSwing(chan, name) end,
}
end)
end,
},
{
id = 'sample',
visible = function() return cm:get('trackerMode') end,
render = function() drawSampleDropdown() end,
},
{
id = 'graph',
render = function()
chrome.headingLabel('Graph')
ImGui.SameLine(ctx, 0, 8)
local cv, newVis = chrome.checkbox('##', cm:get('laneStrip.visible'))
if cv then cm:set('global', 'laneStrip.visible', newVis) end
end,
},
}
-- While the swing editor is open, the tracker body is replaced and
-- only swing-related toolbar segments stay live (the picker is how
-- the user switches what they're editing). Other segments grey out.
local function drawTrackerToolbarBits()
toolbar = toolbar or chrome.makeToolbar()
if not swingEditor:isOpen() then return toolbar(toolbarSegments) end
local wrapped = {}
for i, seg in ipairs(toolbarSegments) do
if seg.id == 'swing' then
wrapped[i] = seg
else
wrapped[i] = {
id = seg.id, visible = seg.visible,
render = function() chrome.disabledIf(true, seg.render) end,
}
end
end
toolbar(wrapped)
end
--contract: must run before draws reading chanX/chanW/chanOrder/totalWidth/gridHeight
--contract: calls tv:setGridSize so tv scroll math sees the live viewport
local function computeLayout(budgetW, budgetH)
local grid = tv.grid
local _, scrollCol = tv:scroll()
if not gridX then
local charW, charH = ImGui.CalcTextSize(ctx, 'W')
gridX = 2 * math.ceil(charW / 2) - 1
gridY = 2 * math.ceil(charH / 2) - 1
end
gridWidth = math.max(1, math.floor(budgetW / gridX) - GUTTER)
local laneRows = laneStripRows()
gridHeight = math.max(1, math.floor(budgetH / gridY) - HEADER - 1 - laneRows)
tv:setGridSize(gridWidth, gridHeight)
chanX, chanW, chanOrder, totalWidth = layoutColumns(grid.cols, scrollCol)
end
----- Lane strip
--invariant: lane strip renders only cc/pb/at; other types show as tinted background
local laneRenderable = { cc = true, pb = true, at = true }
local LANE_ROW_MIN = 3
local LANE_ROW_MAX = 32
--contract: publishes laneConsumed=true if curve editor claimed input this frame
--contract: handleMouse short-circuits on laneConsumed
local function drawLaneStrip()
local laneRows = laneStripRows()
if laneRows <= 0 then laneConsumed = false; return end
local px, py = ImGui.GetCursorScreenPos(ctx)
local x0 = px + GUTTER * gridX
local y0 = py
local w = totalWidth * gridX
local h = laneRows * gridY
local drawList = ImGui.GetWindowDrawList(ctx)
local scrollRow = select(1, tv:scroll())
local numRows = tv.grid.numRows or 0
-- rowSpan = rows actually rendered (matches grid below).
local rowSpan = math.max(1, math.min(gridHeight, numRows - scrollRow))
local function rowToX(row) return x0 + (row - scrollRow) / rowSpan * w end
local pad = gridY / 2
local yTop = y0 + pad
local yBot = y0 + h - pad
if w > 0 then
local barCol, beatCol, dividerCol =
chrome.colour('rowBarStart'), chrome.colour('rowBeat'), chrome.colour('laneRowDivider')
for row = scrollRow, scrollRow + rowSpan - 1 do
local x = math.floor(rowToX(row)) + 0.5
local isBar, isBeat = tv:rowBeatInfo(row)
if isBar or isBeat then
local x2 = math.floor(rowToX(row + 1)) + 0.5
ImGui.DrawList_AddRectFilled(drawList, x, yTop, x2, yBot, isBar and barCol or beatCol)
end
ImGui.DrawList_AddLine(drawList, x, yTop, x, yBot, dividerCol, 1)
end
end
-- Claim the curve rect as a real item so empty-space drags don't
-- fall through to the parent window. IsItemActive keeps the strip
-- "hovered" through a held drag even if the mouse leaves the rect.
local cbX, cbY = ImGui.GetCursorScreenPos(ctx)
ImGui.SetCursorScreenPos(ctx, x0, yTop)
ImGui.InvisibleButton(ctx, '##laneStripHit', math.max(1, w), math.max(1, yBot - yTop))
local stripHovered = ImGui.IsItemHovered(ctx) or ImGui.IsItemActive(ctx)
ImGui.SetCursorScreenPos(ctx, cbX, cbY)
laneConsumed = false
local colIdx = tv:ec():col()
local col = tv.grid.cols[colIdx]
if w > 0 and col and laneRenderable[col.type] then
local chan = col.midiChan
local visible = {}
for _, evt in ipairs(col.events) do
if not evt.hidden then util.add(visible, evt) end
end
local vMin, vMax
if col.type == 'pb' then
local cents = (cm:get('pbRange') or 2) * 100
vMin, vMax = -cents, cents
else
vMin, vMax = 0, 127
end
laneConsumed = curveEd:frame {
drawList = drawList,
rect = { x0 = x0, yTop = yTop, w = w, h = yBot - yTop },
vMin = vMin, vMax = vMax,
tMin = scrollRow, tMax = scrollRow + rowSpan,
events = visible,
tOf = function(evt) return tv:ppqToRow(evt.ppq, chan) end,
-- t is in row-space; map fracT back to ppq before sampling so
-- tv:rowToPPQ's integer rounding doesn't plateau the curve.
evalCurve = function(A, B, fracT)
local fracP = A.ppq + fracT * (B.ppq - A.ppq)
return tv:sampleCurve(A, B, fracP)
end,
snap = function(t) return util.round(t) end,
hovered = stripHovered,
dragId = colIdx,
colours = {
axis = chrome.colour('laneAxis'),
envelope = chrome.colour('laneEnvelope'),
anchor = chrome.colour('laneAnchor'),
anchorActive = chrome.colour('laneAnchorActive'),
},
callbacks = {
onMove = function(idx, newT, newVal) tv:moveLaneEvent(col, idx, newT, newVal) end,
onMoveFree = function(idx, newT, newVal) tv:moveLaneEvent(col, idx, newT, newVal) end,
onInsert = function(t, val) return tv:addLaneEvent(col, colIdx, tv:rowToPPQ(t, chan), val) end,
onDelete = function(idx) tv:deleteLaneEvent(col, idx) end,
onTension = function(idx, tau) tv:setLaneTension (col, idx, tau) end,
onCycleShape = function(idx) tv:cycleLaneShape (col, idx) end,
},
}
end
if w > 0 then
ImGui.DrawList_AddRect(drawList, x0, yTop, x0 + w, yBot, chrome.colour('rowBeat'), 0, 0, 1)
end
ImGui.Dummy(ctx, (totalWidth + GUTTER) * gridX, h)
local cx, cy = ImGui.GetCursorScreenPos(ctx)
local rows = cm:get('laneStrip.rows') or 0
ImGui.SetCursorScreenPos(ctx, px - 2, yTop)
if ImGui.SmallButton(ctx, '-##laneRows') then
cm:set('global', 'laneStrip.rows', math.max(LANE_ROW_MIN, rows - 1))
end
ImGui.SameLine(ctx, 0, 2)
if ImGui.SmallButton(ctx, '+##laneRows') then
cm:set('global', 'laneStrip.rows', math.min(LANE_ROW_MAX, rows + 1))
end
ImGui.SetCursorScreenPos(ctx, cx, cy)
end
--contract: assumes computeLayout ran this frame; reads chanX/W/Order, gridOriginX/Y
local function drawTracker()
local grid = tv.grid
local ec = tv:ec()
local cursorRow, cursorCol, cursorStop = ec:pos()
local scrollRow, scrollCol, lastVisCol = tv:scroll()
local px, py = ImGui.GetCursorScreenPos(ctx)
gridOriginX = px + GUTTER * gridX
gridOriginY = py + HEADER * gridY
local numRows = grid.numRows or 0
local draw = printer(ctx, gridX, gridY, gridOriginX, gridOriginY)
-- Solo (amber) wins over mute (red): audibility semantic.
draw:text(-GUTTER, -HEADER, 'Row', 'accent')
for chan = 1, 16 do
if chanX[chan] then
local key = tv:isChannelSoloed(chan) and 'solo'
or tv:isChannelMuted(chan) and 'mute'
or 'accent'
draw:textCentred(chanX[chan], chanX[chan] + chanW[chan] - 1,
-HEADER, 'Ch ' .. chan, key)
end
end
local laneByChan = {}
for _, col in ipairs(grid.cols) do
local sub
if col.type == 'note' then
local n = (laneByChan[col.midiChan] or 0) + 1
laneByChan[col.midiChan] = n
sub = tostring(n)
elseif col.type == 'cc' then
sub = tostring(col.cc)
end
if col.x then
local xr = col.x + col.width - 1
draw:textCentred(col.x, xr, -2.1, col.label)
if sub then
draw:textCentredSmall(col.x, xr, -1.2, sub, 14, 'accent')
end
end
end
draw:hLine(-GUTTER, totalWidth - 1, 0, 'text', -0.25)
-- for i = 1, #chanOrder - 1 do
-- local chan = chanOrder[i]
-- draw:vLine(chanX[chan] + chanW[chan], -HEADER, gridHeight - 1, 'separator')
-- end
for y = 0, gridHeight - 1 do
local row = scrollRow + y
if row >= numRows then break end
local isBarStart, isBeatStart = tv:rowBeatInfo(row)
if isBarStart or isBeatStart then
local style = isBarStart and 'rowBarStart' or 'rowBeat'
for chan = 1, 16 do
if chanX[chan] then
draw:box(chanX[chan], chanX[chan] + chanW[chan] - 1, y, y, style)
end
end
end
local rowNumCol = (isBeatStart and 'text') or 'inactive'
draw:text(-GUTTER, y, string.format('%03d', row), rowNumCol)
end
local drawList = ImGui.GetWindowDrawList(ctx)
-- Mirror regions. Before tails/cells so per-cell text reads over the
-- wash. A per-group hue washes the whole instance area (membership =
-- selected streams x time span); overridden/conflicted cells
-- overpaint a louder state colour. The wash is always on (group viz);
-- the region-cursor instance's 2px border + the x=-1 cursor gutter
-- are region-mode affordances, shown only while authoring. Outside
-- region mode the instance the caret sits inside gets a quieter 1px
-- border (a "you are here"). A conflicted instance always outlines --
-- a data problem worth seeing in any mode.
local logPerRow = tv:logPerRow()
local cursorPpq = cursorRow * logPerRow
local inRegion = tv:ec():isInRegionMode()
local rc = inRegion and tv:ec():regionCursor()
for _, inst in ipairs(gm:eachInstance()) do
local rect = inst.rect
local ppqLo = inst.anchor.ppq
local ppqHi = ppqLo + rect.dur
local yLo = math.max(math.floor(ppqLo / logPerRow + 0.5) - scrollRow, 0)
local yHi = math.min(math.floor(ppqHi / logPerRow + 0.5) - scrollRow, gridHeight)
if yHi > yLo then
local baseTint = groups.regionKey(inst.colour, 'tint')
local xMin, xMax, conflicted, cursorIn
for x, col in ipairs(grid.cols) do
if col.x then
local off, sid = tv:streamRefAt(x, inst.anchor.chan)
if off and rect.streams[off] and rect.streams[off][sid] then
local x1, x2 = col.x, col.x + col.width - 1
xMin = math.min(xMin or x1, x1)
xMax = math.max(xMax or x2, x2)
draw:box(x1, x2, yLo, yHi - 1, baseTint)
for y = yLo, yHi - 1 do
local evt = col.cells and col.cells[scrollRow + y]
local st = evt and evt.uuid and gm:stateOf(evt.uuid)
if st == 'conflicted' then conflicted = true end
local key = st and groups.tintKey(st)
if key then draw:box(x1, x2, y, y, key) end
end
if x == cursorCol and cursorPpq >= ppqLo and cursorPpq < ppqHi then
cursorIn = true
end
end
end
end
if xMin then
local isCursorInst = rc and rc.groupId == inst.groupId
and rc.instId == inst.instId
local plainCursorIn = cursorIn and not inRegion
if conflicted or isCursorInst or plainCursorIn then
local outCol = chrome.colour(groups.outlineKey(
conflicted and 'conflicted' or 'synced', inst.colour))
ImGui.DrawList_AddRect(drawList,
gridOriginX + xMin * gridX, gridOriginY + yLo * gridY,
gridOriginX + (xMax + 1) * gridX, gridOriginY + yHi * gridY,
outCol, 0, 0, isCursorInst and 2 or 1)
end
if inRegion and cursorIn then draw:box(-1, -1, yLo, yHi - 1, baseTint) end
end
end
end
local tailCol = chrome.colour('tail')
local viewTop = scrollRow
local viewBot = scrollRow + gridHeight
for _, col in ipairs(grid.cols) do
if col.x and col.tails then
for _, tail in ipairs(col.tails) do
if tail.endRow > viewTop and tail.startRow < viewBot then
local y1 = gridOriginY + math.max(tail.startRow - scrollRow, 0) * gridY
local y2 = gridOriginY + math.min(tail.endRow - scrollRow, gridHeight) * gridY
local x1 = gridOriginX + col.x * gridX
local r = 5
-- ImGui.DrawList_AddRectFilled(drawList, x1+1, y1-1, x1 + 6, y1+1, tailCol, 1)
-- ImGui.DrawList_AddRectFilled(drawList, x1+5, y1, x1+7, y2, tailCol)
-- ImGui.DrawList_AddRectFilled(drawList, x1+1, y2-1, x1 + 6, y2+1, tailCol, 1)
ImGui.DrawList_PathClear(drawList)
-- ImGui.DrawList_PathLineTo(drawList, x1-1, y1)
ImGui.DrawList_PathArcTo( drawList, x1, y1+r, r, 3*math.pi/2, math.pi)
ImGui.DrawList_PathLineTo(drawList, x1-r, y1+r+1)
ImGui.DrawList_PathLineTo(drawList, x1-r, y2-r-1)
ImGui.DrawList_PathArcTo( drawList, x1, y2-r, r, math.pi, math.pi/2)
-- ImGui.DrawList_PathLineTo(drawList, x1+1, y2)
ImGui.DrawList_PathStroke(drawList, tailCol, ImGui.DrawFlags_None, 1.5)
ImGui.DrawList_PathClear(drawList)
end
end
end
end
for y = 0, gridHeight - 1 do
local row = scrollRow + y
if row >= numRows then break end
for x, col in ipairs(grid.cols) do
if col.x then
local evt = col.cells and col.cells[row]
local ghost = not evt and col.ghosts and col.ghosts[row]
local text, textCol, overrides, divergent
if ghost then
local cellCol
text, cellCol = renderCell({ val = ghost.val }, col, row)
textCol = cellCol == 'negative' and 'ghostNegative' or 'ghost'
else
text, textCol, overrides, divergent = renderCell(evt, col, row)
if col.overflow and col.overflow[row] then textCol, overrides = 'overflow', nil end
textCol = textCol or 'text'
if textCol == 'text' and col.offGrid and col.offGrid[row] then
textCol = 'offGrid'
end
end
local muted = tv:isChannelEffectivelyMuted(col.midiChan)
if muted then textCol, overrides, divergent = 'inactive', nil, false end
if not text then text = '' end
local cx, i = col.x, 0
for ch in text:gmatch(utf8.charpattern) do
i = i + 1
local c = (overrides and overrides[i]) or (ch == '·' and 'inactive' or textCol)
draw:text(cx, y, ch, c)
cx = cx + 1
end
if divergent and col.showDelay then
draw:smallGlyph(col.x + delayMarkerOffset(col), y, '*', 9, textCol)
end
end
end
end
if tv:activeTemper() then
local barCol = chrome.colour('accent')
for _, col in ipairs(grid.cols) do
if col.x and col.type == 'note' and col.cells then
local x0 = gridOriginX + col.x * gridX
local x1 = x0 + 3 * gridX
local cx = (x0 + x1) / 2
local halfW = (x1 - x0) / 2 - 1
for y = 0, gridHeight - 1 do
local row = scrollRow + y
if row >= numRows then break end
local evt = col.cells[row]
if evt and evt.pitch then
local _, gap, halfGap = tv:noteProjection(evt)
if gap and gap ~= 0 and halfGap > 0 then
local yTop = gridOriginY + y * gridY + 1
local offset = util.clamp(gap / halfGap, -1, 1) * halfW
ImGui.DrawList_AddLine(drawList, x0, yTop, x1, yTop, barCol, 1)
local tickX = cx + offset
ImGui.DrawList_AddLine(drawList, tickX, yTop - 1, tickX, yTop + 2, barCol, 1)
end
end
end
end
end
end
if ec:hasSelection() then
local r1, r2, c1i, c2i = ec:region()
if c2i >= scrollCol and c1i <= lastVisCol then
local yFrom = math.max(r1 - scrollRow, 0)
local yTo = math.min(r2 - scrollRow, gridHeight - 1)
local c1, c2 = grid.cols[c1i], grid.cols[c2i]
local s1 = ec:selectionStopSpan(c1i)
local _,s2 = ec:selectionStopSpan(c2i)
local x1 = c1.x and c1.x + c1.stopPos[s1] or 0
local x2 = c2.x and c2.x + c2.stopPos[s2] or totalWidth
draw:box(x1, x2, yFrom, yTo, 'selection')
end
end
local col = grid.cols[cursorCol]
if col and col.x then
local stopOffset = (col.stopPos and col.stopPos[cursorStop]) or 0
local charX = col.x + stopOffset
local charY = cursorRow - scrollRow
draw:box(charX, charX, charY+0.1, charY-0.1, 'cursor')
local evt = col.cells and col.cells[cursorRow]
local text = renderCell(evt, col, cursorRow)
local ch = utf8.offset(text, stopOffset + 1) and text:sub(utf8.offset(text, stopOffset + 1), utf8.offset(text, stopOffset + 2) - 1) or ''
if ch ~= '' then draw:text(charX, charY, ch, 'cursorText') end
end
-- Reserve content space so ImGui knows the drawable area
ImGui.Dummy(ctx, (totalWidth + GUTTER) * gridX, (gridHeight + HEADER) * gridY)
end
local function drawStatusBar()
-- ctx and grid.cols are built together in tv:rebuild; an empty grid
-- (no take yet on script reopen) means ctx is nil. Match renderBody's
-- placeholder guard rather than indexing a nil ctx via barBeatSub.
if #tv.grid.cols == 0 then return end
local ec = tv:ec()
local cursorRow, cursorCol = ec:row(), ec:col()
local rowPerBeat = cm:get('rowPerBeat')
local currentOctave = cm:get('currentOctave')
local advanceBy = cm:get('advanceBy')
local sampleSuffix = ''
if cm:get('trackerMode') then
local slot = cm:get('currentSample')
local entry = (cm:get('slotEntries') or {})[slot]
local name = entry and entry.name
sampleSuffix = string.format(' | Sample: %02X', slot)
.. (name and (' ' .. name) or '')
end
local col = tv.grid.cols[cursorCol]
local bar, beat, sub = tv:barBeatSub(cursorRow)
local colLabel = col and col.label or '?'
-- statusBar is rendered inside its own chrome BeginChild whose outer
-- Col_Text push is `statusBar.text`; we just print, no inner push.
ImGui.Text(ctx, string.format(
'%s | %d:%d.%d/%d | Octave: %d | Advance: %d%s',
colLabel, bar, beat, sub, rowPerBeat, currentOctave, advanceBy, sampleSuffix
))
end
----- Input
-- Tracker-scope bindings. Globals (playPause, stop) are bound on the
-- root scope by Main(); the dispatcher walks active-then-root.
cmgr:scope('tracker'):bindAll{
cursorUp = { ImGui.Key_UpArrow, {ImGui.Key_P, ImGui.Mod_Super} },
cursorDown = { ImGui.Key_DownArrow, {ImGui.Key_N, ImGui.Mod_Super} },
cursorLeft = { ImGui.Key_LeftArrow, {ImGui.Key_B, ImGui.Mod_Super} },
cursorRight = { ImGui.Key_RightArrow, {ImGui.Key_F, ImGui.Mod_Super} },
goTop = { ImGui.Key_Home, {ImGui.Key_Comma, ImGui.Mod_Ctrl, ImGui.Mod_Shift} },
goBottom = { ImGui.Key_End, {ImGui.Key_Period, ImGui.Mod_Ctrl, ImGui.Mod_Shift} },
pageUp = { ImGui.Key_PageUp },
pageDown = { ImGui.Key_PageDown },
colLeft = { {ImGui.Key_B, ImGui.Mod_Ctrl} },
colRight = { {ImGui.Key_F, ImGui.Mod_Ctrl} },
channelLeft = { {ImGui.Key_Tab, ImGui.Mod_Shift} },
channelRight = { ImGui.Key_Tab },
noteOff = { ImGui.Key_1 },
shrinkNote = { {ImGui.Key_UpArrow, ImGui.Mod_Super, ImGui.Mod_Shift} },
growNote = { {ImGui.Key_DownArrow, ImGui.Mod_Super, ImGui.Mod_Shift} },
nudgeBack = { {ImGui.Key_UpArrow, ImGui.Mod_Super} },
nudgeForward = { {ImGui.Key_DownArrow, ImGui.Mod_Super} },
eventShiftLeft = {{ImGui.Key_LeftArrow, ImGui.Mod_Super} },
eventShiftRight = {{ImGui.Key_RightArrow, ImGui.Mod_Super} },
insertRowCol = { {ImGui.Key_DownArrow, ImGui.Mod_Ctrl} },
deleteRowCol = { {ImGui.Key_UpArrow, ImGui.Mod_Ctrl} },
addTypedCol = { {ImGui.Key_RightArrow, ImGui.Mod_Ctrl} },
hideExtraCol = { {ImGui.Key_LeftArrow, ImGui.Mod_Ctrl} },
delete = { ImGui.Key_Period },
interpolate = { {ImGui.Key_I, ImGui.Mod_Ctrl} },
selectUp = { {ImGui.Key_UpArrow, ImGui.Mod_Shift} },
selectDown = { {ImGui.Key_DownArrow, ImGui.Mod_Shift} },
selectLeft = { {ImGui.Key_LeftArrow, ImGui.Mod_Shift} },
selectRight = { {ImGui.Key_RightArrow, ImGui.Mod_Shift} },
cycleBlock = { {ImGui.Key_Space, ImGui.Mod_Super} },
cycleVBlock = { {ImGui.Key_O, ImGui.Mod_Super} },
swapBlockEnds = { {ImGui.Key_GraveAccent, ImGui.Mod_Ctrl} },
selectClear = { {ImGui.Key_G, ImGui.Mod_Super} },
cut = { {ImGui.Key_W, ImGui.Mod_Super}, {ImGui.Key_X, ImGui.Mod_Ctrl} },
copy = { {ImGui.Key_W, ImGui.Mod_Ctrl}, {ImGui.Key_C, ImGui.Mod_Ctrl} },
paste = { {ImGui.Key_Y, ImGui.Mod_Super}, {ImGui.Key_V, ImGui.Mod_Ctrl} },
duplicateDown = { {ImGui.Key_D, ImGui.Mod_Ctrl} },
deleteSel = { ImGui.Key_Delete },
nudgeCoarseUp = { {ImGui.Key_Equal, ImGui.Mod_Ctrl} },
nudgeCoarseDown = { {ImGui.Key_Minus, ImGui.Mod_Ctrl} },
nudgeFineUp = { {ImGui.Key_Equal, ImGui.Mod_Shift} },
nudgeFineDown = { {ImGui.Key_Minus, ImGui.Mod_Shift} },
scaleHalf = { {ImGui.Key_9, ImGui.Mod_Shift} }, -- '('
scaleDouble = { {ImGui.Key_0, ImGui.Mod_Shift} }, -- ')'
doubleRPB = { {ImGui.Key_Equal, ImGui.Mod_Super} },
halveRPB = { {ImGui.Key_Minus, ImGui.Mod_Super} },
setRPB = { {ImGui.Key_Z, ImGui.Mod_Super} },
takeProperties = { {ImGui.Key_Backspace, ImGui.Mod_Ctrl} },
matchGridToCursor = { {ImGui.Key_G, ImGui.Mod_Super, ImGui.Mod_Shift} },
groupMark = { {ImGui.Key_M, ImGui.Mod_Ctrl} },
groupDuplicate = { {ImGui.Key_D, ImGui.Mod_Ctrl, ImGui.Mod_Shift} },
groupPaste = { {ImGui.Key_V, ImGui.Mod_Ctrl, ImGui.Mod_Shift} },
groupLocalToggle = { {ImGui.Key_M, ImGui.Mod_Super} },
regionEnter = { {ImGui.Key_R, ImGui.Mod_Super} },
groupInstPrev = { ImGui.Key_LeftBracket },
groupInstNext = { ImGui.Key_RightBracket },
inputOctaveUp = { {ImGui.Key_8, ImGui.Mod_Shift} },
inputOctaveDown = { ImGui.Key_Slash },
inputSampleUp = { {ImGui.Key_Period, ImGui.Mod_Shift} }, -- '>'
inputSampleDown = { {ImGui.Key_Comma, ImGui.Mod_Shift} }, -- '<'
playFromTop = { ImGui.Key_F6 },
playFromCursor = { ImGui.Key_F7 },
openTemperPicker = { {ImGui.Key_T, ImGui.Mod_Super} },
openSwingPicker = { {ImGui.Key_S, ImGui.Mod_Super} },
openSwingEditor = { {ImGui.Key_E, ImGui.Mod_Super} },
quantize = { {ImGui.Key_Q, ImGui.Mod_Ctrl} },
quantizeKeepRealised = { {ImGui.Key_Q, ImGui.Mod_Ctrl, ImGui.Mod_Shift} },
}
for i = 0, 9 do
cmgr:scope('tracker'):bind('advBy' .. i, { {ImGui.Key_0 + i, ImGui.Mod_Ctrl} })
end
--contract: returns (col, stop, fracX) or (nil, nil, fracX)
--invariant: fracX is separate so callers distinguish 'past last col' from 'inside col N'
local function nearestStop(mouseX, mouseY)
local grid = tv.grid
local fracX = (mouseX - gridOriginX) / gridX
local bestCol, bestStop, bestDist = nil, nil, math.huge
for i, col in ipairs(grid.cols) do
if col.x then
for s, pos in ipairs(col.stopPos) do
local dist = math.abs(fracX - col.x - pos - 0.5)
if dist < bestDist then
bestCol, bestStop, bestDist = i, s, dist
end
end
end
end
return bestCol, bestStop, fracX
end
--contract: bails if laneConsumed; lane strip wins gestures over the tracker grid
--contract: right-click on channel-label row toggles mute
--contract: click on label rows selects channel/column
--contract: body click moves cursor and arms drag
local function handleMouse()
if laneConsumed then return end
local grid = tv.grid
local ec = tv:ec()
local cursorRow, cursorCol, cursorStop = ec:pos()
local scrollRow, scrollCol, lastVisCol = tv:scroll()
local clicked = ImGui.IsMouseClicked(ctx, 0)
local rightClicked = ImGui.IsMouseClicked(ctx, 1)
local held = ImGui.IsMouseDown(ctx, 0)
-- Region sculpt paint: shift-drag adds the column's stream to the
-- active group, alt-drag removes it; debounced per cell via paintLast.
local rc = ec:regionCursor()
if ec:isInRegionMode() and rc and held and ImGui.IsWindowHovered(ctx) then
local mods = ImGui.GetKeyMods(ctx)
local add = (mods & ImGui.Mod_Shift) ~= 0
local sub = (mods & ImGui.Mod_Alt) ~= 0
if add or sub then
local mouseX, mouseY = ImGui.GetMousePos(ctx)
local charY = math.floor((mouseY - gridOriginY) / gridY)
if charY >= 0 and charY < gridHeight then
local col = nearestStop(mouseX, mouseY)
local cell = col and (col .. (add and '+' or '-'))
if col and cell ~= paintLast then
paintLast = cell
tv:paintRegionStream(rc.groupId, rc.instId, col, add)
end
end
return
end
elseif ec:isInRegionMode() and not held then
paintLast = nil
end
if rightClicked and ImGui.IsWindowHovered(ctx) then
local mouseX, mouseY = ImGui.GetMousePos(ctx)
local charY = math.floor((mouseY - gridOriginY) / gridY)
local col, _, fracX = nearestStop(mouseX, mouseY)
if col and charY == -HEADER and fracX >= 0 then
local last = grid.cols[col]
if fracX < last.x + last.width + 1 then
tv:toggleChannelMute(last.midiChan)
end
end
return
end
if clicked and ImGui.IsWindowHovered(ctx) then
local mouseX, mouseY = ImGui.GetMousePos(ctx)
local charY = math.floor((mouseY - gridOriginY) / gridY)
local col, stop, fracX = nearestStop(mouseX, mouseY)
if not col then return end
if charY < -HEADER or charY >= gridHeight then return end