Repository navigation
Expand file tree
/
Copy pathReaNotepad.lua
More file actions
5571 lines (5478 loc) · 314 KB
/
Copy pathReaNotepad.lua
File metadata and controls
5571 lines (5478 loc) · 314 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
-- @description ReaNotepad
-- @version 0.7.1
-- @author Aleksei Vorobev / Patch34
-- @link
-- GitHub repository https://github.com/patch-34/reanotepad
-- @changelog
-- Fix ReaImGui Begin/End scope handling when docking or undocking windows.
-- Match EndChild calls to successful BeginChild returns across all child windows.
-- Prevent negative note-shell widths when the Docker is narrowed below the content minimum.
-- Release 0.7.0: shared note/group action alignment and frameless menus.
-- Add group quick-add checkbox note and note checkbox toggle actions.
-- Unify font/spacing sliders, timecode navigation and timeline focus.
-- Stabilize ImGui scope pairing, note ordering and UI state handling.
-- @about
-- Structured notes for REAPER projects, tracks and media items.
-- Horizontal tabs contain independently collapsible vertical groups.
-- Text notes, checkbox notes, editable dropdowns and text import.
-- Mouse reordering of tabs and notes; note drag/drop between groups.
-- Per-note colors, colored group headings, HH:MM:SS:FF timecode navigation.
-- Owner-scoped Undo/Redo, native-note conflict checks and recovery copies.
-- Requires REAPER 7+ and ReaImGui 0.10+; SWS is not required.
-- Install: Actions > Show action list > New action > Load ReaScript.
--
-- STORAGE: Project notes use native GetSetProjectNotes. Item notes use P_NOTES.
-- Track notes use P_EXT:PATCH34_PROJECT_NOTES, stored in the .rpp project.
-- Documents use Patch34 Project Notes v3; legacy v1/v2 and plain notes remain
-- readable. Opening older notes alone does not rewrite them.
-- Old scripts may not support documents saved by this version.
-- Changes update REAPER immediately; save the project to persist to disk.
-- Recovery copies are stored under Data/Patch34_Project_Notes_Recovery.
-- Review recovery files before manually restoring them.
-- Historical storage keys, format headers and window IDs remain unchanged.
--
-- UI is adapted from Podcast HTML/DOCX Script Viewer v3.1.0-beta.1.
-- The source viewer is not modified or needed at runtime.
-- Official references: https://www.reaper.fm/sdk/reascript/reascripthelp.html
-- https://cfillion.ca/reaper_imgui_doc.html
local M = {}
local VERSION = '0.7.1'
-- ============================================================================
-- UI SETTINGS / НАСТРОЙКИ ИНТЕРФЕЙСА EDIT HERE
-- ============================================================================
-- This is the single editable block for visual layout, fonts and theme colors.
-- Numbers below are pixels unless noted; alpha values are ratios (0..1). The settings do NOT change note data.
-- Start with one change at a time; test narrow windows and REAPER Docker.
-- font_size is read from the active ImGui font every frame (do not edit it).
-- Размеры — в пикселях; прозрачность — 0..1. font_size обновляется из ImGui.
-- Note indentation reserves a safe gutter for the marker and drag handle.
-- Отступ заметки учитывает ширину маркера и области перетаскивания.
-- Native ImGui style values not overridden here inherit the REAPER/ImGui style.
-- Непереопределённые параметры нативного ImGui наследуются от REAPER/ImGui.
local UI_METRICS = {
-- Typography / Типографика: main UI font is independent of note text size slider.
font_family='sans-serif', font_size=13, -- font_size is runtime-only
tab_heading_extra_px=0, tab_arrow_extra_px=5,
note_text_min_size=12, note_text_max_size=32, note_text_default_size=16,
-- Main window / Основное окно.
window_initial_width=545, window_initial_height=615,
startup_layout_warmup_frames=2, startup_layout_warmup_alpha=0.001,
window_min_width=540, window_min_height=360,
menu_bar_height=38, menu_bar_pad_x=4,
menu_trigger_pad_x=8, menu_label_min_inset_x=6, menu_label_min_inset_y=1,
history_shortcut_gap=12, history_shortcut_min_spaces=2,
window_pad_x=12, window_pad_y=10,
frame_pad_x=6, frame_pad_y=3,
frame_rounding=3, child_rounding=0, frame_border_size=1,
-- Buttons and Controls / Кнопки и элементы управления: spacing / интервалы.
item_gap_x=8, item_gap_y=8,
group_gap=16, inner_gap=8, checkbox_label_gap=6,
checkbox_pad_y=1, read_line_gap=2,
note_checkbox_offset_y=0, -- Optical correction relative to the shared first-line center.
note_checkbox_text_gap=6, -- Space after the native checkbox; independent of item spacing.
-- Buttons and Controls / Кнопки и элементы управления.
button_pad_x=8, button_pad_y=3, button_min_height=23,
compact_button_pad_x=10, button_rounding=3,
scope_min_width=110,
dropdown_width=420, dropdown_visible_rows=8, dropdown_popup_extra_height=16,
button_border_size=1,
quick_icon_size=16, quick_icon_total_inset=7,
timecode_icon_size=14, timecode_label_gap=4,
-- Shared right alignment / Общая правая граница кнопок внутри колонки.
-- action_to_scroll_gap: distance between action-button edge and scrollbar thumb.
-- action_right_inset: move ALL column/tab/note action buttons farther left.
-- Both values are measured in pixels. Do not change each component separately.
-- action_to_scroll_gap: расстояние от кнопок до ползунка скролла.
-- action_right_inset: дополнительный сдвиг ВСЕХ правых кнопок влево.
action_to_scroll_gap=12, action_right_inset=4,
-- Shared absolute screen anchor: the right edge of the last creation button.
-- Tabs and group menus align to this anchor, without separate pixel guesses.
-- Общий экранный якорь: правый край последней кнопки верхней панели.
-- Верхняя панель определяет линию для кнопок вкладок и меню групп.
creation_toolbar_right_inset=12,
-- Horizontal tabs / Горизонтальные вкладки.
tabs_strip_height=38, tabs_strip_pad_x=8, tabs_strip_pad_y=4,
tabs_strip_label_pad_x=14, tabs_strip_gap=4, tabs_strip_min_width=56,
tabs_strip_button_gap=8, tabs_strip_active_line=2,
pointer_drag_threshold=6, tabs_drop_line_width=2,
tabs_drag_scroll_edge=24, tabs_drag_scroll_speed=360, -- pixels/second
-- Minimum safe inset when the shared anchor is unavailable or too far right.
-- Минимальный защитный отступ; не самостоятельный сдвиг относительно панели.
tabs_actions_right_inset=8,
group_header_tint_light=0.25, group_header_tint_dark=0.34,
-- Extra air between horizontal tab strip and the first group heading.
-- Воздух сверху: первая группа не прижимается к панели вкладок.
group_panel_top_padding=12,
-- Group headings use the same right-action guide as every note.
group_header_min_height=26,
-- One centered three-dot icon for both group and note action hitboxes.
group_menu_dot_radius=1.0, group_menu_dot_spacing=4.6,
-- Inline quick-add at the bottom of each expanded group.
-- circle-plus is an embedded Lucide icon, with click area independent of its image.
group_add_note_size=36, group_add_note_icon_size=25,
group_add_note_idle_alpha=0.55, group_add_note_hover_alpha=0.72,
group_add_note_top_gap=12, group_add_note_bottom_gap=8,
group_add_note_empty_top_gap=16,
-- Group heading (historically an internal column header).
tab_heading_menu_gap=4, tab_heading_min_title=18,
tab_heading_arrow_text_gap=2, tab_heading_hover_alpha=0.85,
-- Native sliders / Нативные ползунки (font and separator spacing).
slider_width=180, font_slider_min_width=100,
-- Scrollbars / Скроллбары: overlay thumb / ползунок поверх содержимого.
overlay_scroll_width=5, overlay_scroll_inset=3, overlay_scroll_margin=6,
overlay_scroll_min_thumb_height=24, overlay_scroll_min_track_height=24,
overlay_scroll_hit_pad_left=2, overlay_scroll_hit_pad_right=1,
-- Notes / Заметки.
note_padding_y=4, -- Shared internal top/bottom padding, colored or uncolored.
note_content_gap_y=4, -- Heading-to-second-row spacing; independent of outer padding.
note_indent=24, note_row_inset_x=12, note_gutter_end_gap=4, note_actions_min_content_width=48,
-- Separators are drawn only up to the shared actions edge; inset trims them.
-- Сепараторы заканчиваются у границы кнопок; inset укорачивает линию.
note_separator_right_inset=0, note_separator_thickness=1,
note_separator_height=1, note_separator_raise=5,
note_spacing_default=5, note_spacing_min=0, note_spacing_max=24, -- each side of a note separator (px)
note_edit_min_height=66, note_edit_max_height=240,
note_edit_extra_lines=3, note_edit_extra_height=12,
completed_note_alpha=0.55,
marker_fill_rounding=3, marker_fill_min_height=1,
marker_strip_offset_x=1, marker_strip_width=3, marker_strip_pad_y=2,
marker_strip_min_bottom_offset=10, marker_strip_rounding=1,
marker_menu_offset_x=3, marker_menu_side=8, marker_menu_rounding=1,
marker_menu_label_spaces=3, marker_menu_text_gap=6,
selection_text_gutter=22, selection_min_height=23, selection_bottom_pad=4,
selection_rounding=2, selection_check_right_offset=18,
editor_extra_pad_x=2, editor_extra_pad_y=2, editor_wrap_right_inset=2,
editor_newline_selection_min_width=4, editor_caret_thickness=1, editor_tab_spaces=4,
editor_caret_period=1.2, editor_caret_visible_time=0.6, -- seconds / секунды
-- Drag Handles and Drop Targets / Перетаскивание и области приёма.
drag_handle_offset_x=6,
drag_handle_width=14, drag_handle_max_height=18, drag_handle_icon_size=14,
drag_handle_dot_radius=1, drag_handle_dot_pitch=4, -- Vector grip shape, not position offsets.
drag_preview_max_chars=48,
-- Shared outline for a dragged note and new-object placement targets.
-- Общий стиль рамки перетаскиваемой заметки и области добавления объекта.
drag_note_highlight_padding_x=4, drag_note_highlight_padding_y=4, drag_note_highlight_rounding=3,
drag_note_highlight_border_thickness=1.0,
drag_note_highlight_dash=5, drag_note_highlight_gap=4,
trash_target_width=23, trash_icon_only=true, -- compact icon in the top toolbar
trash_icon_size=16, trash_icon_vertical_inset=6, trash_icon_offset_x=8,
trash_label_offset_x=30, trash_icon_label_gap=6,
trash_border_size=1, trash_hover_border_size=2,
drop_line_thickness=2, empty_tab_placement_height=38,
note_drag_scroll_edge=36, note_drag_scroll_speed=360,
-- Dialogs and Popups / Диалоги и всплывающие окна.
confirm_min_width=280, confirm_max_width=520,
popup_margin=12, popup_footer_gap=8, popup_border_size=1.5,
import_pane_min_height=56, options_panel_min_height=60,
option_input_min_width=60, option_actions_reserved_width=110,
about_pad_x=20, about_pad_y=17, about_rounding=12,
about_button_rounding=7, about_geometry_extra=2,
-- Preferred outer sizes / Предпочтительные внешние размеры.
-- Name height and About use content-measured minima; 0 means automatic.
-- Высота Name и размеры About: минимум по содержимому; 0 — автоматически.
popup_sizes={restore={580,460},name={320,0},select={500,460},import={860,440},about={0,0},note_cancel={390,146}},
}
-- Theme colors / Цвета оформления. RGBA component values are 0..255.
-- Leave historical storage keys and format headers elsewhere unchanged.
local function rgba(r,g,b,a) return (r<<24)|(g<<16)|(b<<8)|(a or 255) end
-- Theme color roles / Роли цветов тем. Native tabs/checks
-- use the agreed role mapping below; unused search/document roles are omitted.
local VIEWER_THEMES = {
paper = {
label = "Pages",
C_PAPER = rgba(217, 215, 209),
C_TEXT = rgba(28, 28, 28),
C_DIM = rgba(153, 153, 153),
C_CHROME = rgba(236, 234, 229),
C_CHROME_DEEP = rgba(208, 206, 201),
C_CHROME_TITLE = rgba(236, 234, 229),
C_HEAD = rgba(225, 223, 218),
C_HEAD_H = rgba(208, 206, 201),
C_FRAME = rgba(245, 244, 240),
C_LINE = rgba(208, 206, 201),
C_MENU_BORDER = rgba(208, 206, 201),
C_SCROLL = rgba(158, 155, 149),
C_SCROLL_H = rgba(174, 172, 166),
C_SCROLL_A = rgba(140, 137, 131),
C_SCROLL_BG = rgba(217, 215, 209),
C_VIEW_SLIDER_TRACK = rgba(200, 198, 192),
C_VIEW_SLIDER_FILL = rgba(74, 124, 199),
C_VIEW_SLIDER_KNOB_FILL = rgba(245, 244, 240),
C_VIEW_SLIDER_KNOB_OUTLINE = rgba(74, 124, 199),
C_VIEW_BUTTON_FILL = rgba(245, 244, 240),
C_VIEW_BUTTON_HOVER = rgba(236, 234, 229),
C_VIEW_BUTTON_ACTIVE = rgba(225, 223, 218),
C_VIEW_BUTTON_BORDER = rgba(208, 206, 201),
},
grey = {
label = "REAPER Grey",
C_PAPER = rgba(239, 239, 239),
C_TEXT = rgba(28, 24, 18),
C_DIM = rgba(112, 112, 112),
C_CHROME = rgba(218, 218, 218),
C_CHROME_DEEP = rgba(92, 112, 104),
C_CHROME_TITLE = rgba(112, 132, 122),
C_HEAD = rgba(202, 206, 210),
C_HEAD_H = rgba(188, 193, 198),
C_FRAME = rgba(250, 250, 250),
C_LINE = rgba(104, 120, 114),
C_MENU_BORDER = rgba(104, 120, 114, 60),
C_SCROLL = rgba(176, 176, 176),
C_SCROLL_H = rgba(154, 154, 154),
C_SCROLL_A = rgba(132, 132, 132),
C_SCROLL_BG = rgba(239, 239, 239),
C_VIEW_SLIDER_TRACK = rgba(196, 196, 196),
C_VIEW_SLIDER_FILL = rgba(86, 104, 124),
C_VIEW_SLIDER_KNOB_FILL = rgba(252, 252, 252),
C_VIEW_SLIDER_KNOB_OUTLINE = rgba(86, 104, 124),
C_VIEW_BUTTON_FILL = rgba(238, 238, 238),
C_VIEW_BUTTON_HOVER = rgba(226, 226, 226),
C_VIEW_BUTTON_ACTIVE = rgba(214, 214, 214),
C_VIEW_BUTTON_BORDER = rgba(174, 174, 174),
},
white = {
label = "Google Docs White",
C_PAPER = rgba(241, 243, 244),
C_TEXT = rgba(32, 33, 36),
C_DIM = rgba(95, 99, 104),
C_CHROME = rgba(248, 250, 253),
C_CHROME_DEEP = rgba(232, 240, 254),
C_CHROME_TITLE = rgba(248, 250, 253),
C_HEAD = rgba(232, 240, 254),
C_HEAD_H = rgba(210, 227, 252),
C_FRAME = rgba(255, 255, 255),
C_LINE = rgba(218, 220, 224),
C_MENU_BORDER = rgba(218, 220, 224),
C_SCROLL = rgba(189, 193, 198),
C_SCROLL_H = rgba(154, 160, 166),
C_SCROLL_A = rgba(128, 134, 139),
C_SCROLL_BG = rgba(241, 243, 244),
C_VIEW_SLIDER_TRACK = rgba(218, 220, 224),
C_VIEW_SLIDER_FILL = rgba(26, 115, 232),
C_VIEW_SLIDER_KNOB_FILL = rgba(255, 255, 255),
C_VIEW_SLIDER_KNOB_OUTLINE = rgba(26, 115, 232),
C_VIEW_BUTTON_FILL = rgba(255, 255, 255),
C_VIEW_BUTTON_HOVER = rgba(241, 243, 244),
C_VIEW_BUTTON_ACTIVE = rgba(232, 240, 254),
C_VIEW_BUTTON_BORDER = rgba(218, 220, 224),
},
}
-- Dark is the approved exception to the three supplied Viewer themes.
do
local bg,paper,chrome=rgba(30,32,36),rgba(37,40,45),rgba(44,47,53)
local text,dim,line=rgba(231,233,237),rgba(160,166,177),rgba(75,81,92)
local hover,accent=rgba(61,68,80),rgba(116,170,238)
VIEWER_THEMES.dark={label='Dark',C_PAPER=bg,C_FRAME=paper,C_TEXT=text,C_DIM=dim,C_CHROME=chrome,
C_CHROME_DEEP=chrome,C_CHROME_TITLE=chrome,C_HEAD=hover,C_HEAD_H=line,
C_LINE=line,C_MENU_BORDER=line,C_SCROLL=line,C_SCROLL_H=dim,C_SCROLL_A=dim,C_SCROLL_BG=bg,
C_VIEW_BUTTON_FILL=chrome,C_VIEW_BUTTON_HOVER=hover,C_VIEW_BUTTON_ACTIVE=line,C_VIEW_BUTTON_BORDER=line,
C_VIEW_SLIDER_TRACK=line,C_VIEW_SLIDER_FILL=accent,C_VIEW_SLIDER_KNOB_FILL=paper,C_VIEW_SLIDER_KNOB_OUTLINE=accent}
end
-- Shared palettes / Общие палитры (RGBA; alpha multipliers are 0..1).
-- About intentionally keeps the original theme-independent Viewer skin.
local UI_PALETTE = {
text_selection_alpha=65,
modal_dim_light=rgba(0,0,0,90), modal_dim_dark=rgba(0,0,0,140),
about={background=rgba(80,80,80,218),border=rgba(220,220,220,95),
text=rgba(245,245,245),dim=rgba(210,210,210),
button=rgba(105,105,105,230),button_hover=rgba(122,122,122,235),
button_border=rgba(230,230,230,80)},
trash={text=rgba(146,74,74,255),text_hover=rgba(181,52,52,255),
fill=rgba(146,74,74,14),fill_hover=rgba(181,52,52,48)},
drag_note_highlight_fill_alpha=0.06, drag_note_highlight_edge_alpha=120,
marker_tint_light=0.12, marker_tint_dark=0.18,
}
-- Marker palette / Палитра цветовых маркеров.
local MARKER_PALETTE = {
light={red=0xc15251ff,orange=0xb5782bff,yellow=0xa29227ff,
green=0x54816aff,blue=0x527fa1ff,purple=0x8c6ca1ff},
dark={red=0xe88a85ff,orange=0xe6b767ff,yellow=0xd6c75fff,
green=0x82b79aff,blue=0x8fb8d6ff,purple=0xbba0cdff},
}
-- Configuration guards / Ограничения настроек.
-- Dimensions are nonnegative; the checkbox optical y correction may be signed.
-- Coupled geometry also clamps to the actual available space at draw time.
do
for key,value in pairs(UI_METRICS) do
if type(value)=='number' then
assert(value==value and math.abs(value)<math.huge,'Invalid UI metric: '..key)
if key~='note_checkbox_offset_y' then
UI_METRICS[key]=math.max(0,value)
end
end
end
for _,key in ipairs({'note_text_min_size','note_text_max_size','note_text_default_size',
'button_min_height','font_slider_min_width','group_add_note_size',
'note_edit_min_height','note_edit_max_height','overlay_scroll_width',
'overlay_scroll_min_thumb_height','editor_caret_period'}) do
UI_METRICS[key]=math.max(1,UI_METRICS[key])
end
UI_METRICS.note_text_min_size=math.max(1,math.floor(UI_METRICS.note_text_min_size))
UI_METRICS.note_text_max_size=math.max(UI_METRICS.note_text_min_size,math.floor(UI_METRICS.note_text_max_size))
UI_METRICS.note_text_default_size=math.max(UI_METRICS.note_text_min_size,
math.min(UI_METRICS.note_text_max_size,math.floor(UI_METRICS.note_text_default_size)))
UI_METRICS.note_edit_max_height=math.max(UI_METRICS.note_edit_min_height,UI_METRICS.note_edit_max_height)
UI_METRICS.confirm_max_width=math.max(UI_METRICS.confirm_min_width,UI_METRICS.confirm_max_width)
UI_METRICS.dropdown_visible_rows=math.max(1,math.floor(UI_METRICS.dropdown_visible_rows))
UI_METRICS.editor_tab_spaces=math.max(1,math.floor(UI_METRICS.editor_tab_spaces))
UI_METRICS.marker_menu_label_spaces=math.floor(UI_METRICS.marker_menu_label_spaces)
UI_METRICS.history_shortcut_min_spaces=math.floor(UI_METRICS.history_shortcut_min_spaces)
UI_METRICS.drag_preview_max_chars=math.max(1,math.floor(UI_METRICS.drag_preview_max_chars))
UI_METRICS.completed_note_alpha=math.min(1,UI_METRICS.completed_note_alpha)
UI_METRICS.startup_layout_warmup_alpha=math.min(1,UI_METRICS.startup_layout_warmup_alpha)
UI_METRICS.startup_layout_warmup_frames=math.floor(UI_METRICS.startup_layout_warmup_frames)
UI_METRICS.tab_heading_hover_alpha=math.min(1,UI_METRICS.tab_heading_hover_alpha)
UI_METRICS.group_header_tint_light=math.min(1,UI_METRICS.group_header_tint_light)
UI_METRICS.group_header_tint_dark=math.min(1,UI_METRICS.group_header_tint_dark)
UI_METRICS.group_add_note_idle_alpha=math.min(1,UI_METRICS.group_add_note_idle_alpha)
UI_METRICS.group_add_note_hover_alpha=math.min(1,UI_METRICS.group_add_note_hover_alpha)
UI_METRICS.tabs_strip_height=math.max(UI_METRICS.button_min_height,UI_METRICS.tabs_strip_height)
UI_METRICS.editor_caret_visible_time=math.min(UI_METRICS.editor_caret_period,UI_METRICS.editor_caret_visible_time)
for _,dimensions in pairs(UI_METRICS.popup_sizes) do
for i=1,2 do
assert(type(dimensions[i])=='number' and dimensions[i]==dimensions[i]
and math.abs(dimensions[i])<math.huge,'Invalid popup dimension')
dimensions[i]=math.max(0,dimensions[i])
end
end
for _,key in ipairs({'marker_tint_light','marker_tint_dark',
'drag_note_highlight_fill_alpha'}) do
UI_PALETTE[key]=math.max(0,math.min(1,UI_PALETTE[key]))
end
for _,key in ipairs({'text_selection_alpha',
'drag_note_highlight_edge_alpha'}) do
UI_PALETTE[key]=math.floor(math.max(0,math.min(255,UI_PALETTE[key])))
end
end
-- ============================================================================
-- END UI SETTINGS / КОНЕЦ НАСТРОЕК ИНТЕРФЕЙСА
-- ============================================================================
local HEADER = '# Patch34 Project Notes v3'
local PREVIOUS_HEADER = '# Patch34 Project Notes v2'
local LEGACY_HEADER = '# Patch34 Project Notes v1'
local sequence = 0
local function uid() sequence = sequence + 1; return sequence end
local function norm(s) return (s:gsub('\r\n', '\n'):gsub('\r', '\n')) end
local function lines(s)
local out = {}
for l in (s .. '\n'):gmatch('(.-)\n') do out[#out + 1] = l end
return out
end
local function esc(s)
return (s:gsub('\\', '\\\\'):gsub('\n', '\\n'):gsub('\r', '\\r'):gsub('\t', '\\t'))
end
local function unesc(s)
local out, i = {}, 1
local codes = {n='\n', r='\r', t='\t', ['\\']='\\'}
while i <= #s do
local c = s:sub(i,i)
if c == '\\' then
i = i + 1
c = codes[s:sub(i,i)]
if not c then error('Unknown or incomplete escape sequence.') end
end
out[#out+1] = c
i = i + 1
end
return table.concat(out)
end
function M.text(value) return {id=uid(), kind='text', text=value or ''} end
function M.note(value,checked) return {id=uid(),kind='note',text=value or '',checked=checked==true} end
-- Preserve block identity, text, timecode metadata and color when toggling
-- a note's checkbox; storage already supports both @text and @note kinds.
function M.set_note_checkbox(block,enabled)
if enabled and block.kind=='text' then
block.kind='note';block.checked=false;return true
elseif not enabled and block.kind=='note' then
block.kind='text';block.checked=nil;return true
end
return false
end
function M.completed(b) return (b.kind=='check' or b.kind=='note') and b.checked==true end
function M.visible(b,hide) return not (hide and M.completed(b)) end
function M.display_order(column,hide,completed_last)
local order,completed={},{}
for i,b in ipairs(column.blocks) do
if M.visible(b,hide) then
local group=completed_last and M.completed(b) and completed or order
group[#group+1]=i
end
end
for _,i in ipairs(completed) do order[#order+1]=i end
return order
end
function M.block_neighbor(column,index,delta,hide,completed_last)
local order=M.display_order(column,hide,completed_last)
for position,i in ipairs(order) do
if i==index then
local neighbor=order[position+delta]
if neighbor and (not completed_last or M.completed(column.blocks[index])==M.completed(column.blocks[neighbor])) then
return neighbor
end
return nil
end
end
end
M.marker_keys={'red','orange','yellow','green','blue','purple'}
function M.valid_marker(key)
if key==nil then return true end
for _,value in ipairs(M.marker_keys) do if value==key then return true end end
return false
end
function M.selection_prune(column,selected,hide)
local available,count,visible={},0,0
for _,b in ipairs(column.blocks) do
if M.visible(b,hide) then
available[b.id]=true;visible=visible+1
if selected[b.id] then count=count+1 end
end
end
for id in pairs(selected) do if not available[id] then selected[id]=nil end end
return count,visible
end
function M.selection_all(column,selected,hide,value)
for id in pairs(selected) do selected[id]=nil end
if value then
for _,b in ipairs(column.blocks) do if M.visible(b,hide) then selected[b.id]=true end end
end
end
function M.selection_delete(column,selected,hide)
local count=0
for i=#column.blocks,1,-1 do
local b=column.blocks[i]
if selected[b.id] and M.visible(b,hide) then table.remove(column.blocks,i);count=count+1 end
end
return count
end
function M.selection_color(column,selected,hide,key)
assert(M.valid_marker(key),'Invalid color marker.')
local count=0
for _,b in ipairs(column.blocks) do
if selected[b.id] and M.visible(b,hide) and b.color~=key then b.color=key;count=count+1 end
end
return count
end
-- Explicit list markers are distinct from numbers in prose. Bare numbers
-- require an adjacent consecutive candidate; a single "2026 year" is not a list.
-- Only a leading timecode is an anchor; numbers inside prose stay ordinary
-- text. Keep its spelling in the note and resolve it again after text edits.
-- Four-field timecodes use the current project's frame rate (including DF mode).
-- The caller supplies these only when a REAPER project is available; never
-- guess an FPS for imported data. Two/three-field codes remain seconds-based.
function M.timecode_prefix(text,frame_rate,drop_frame)
local value=norm(text:sub(1,512)):gsub('^\239\187\191',''):gsub('\194\160',' ')
local first,rest=value:match('^([^\n]*)\n?(.*)$')
first=first:match('^%s*(.-)%s*$')
if first:match('^%d+[%.%):]$') or first:match('^%(%d+%)$') or first:match('^%[%d+%]$')
or first:match('^[1-9]%d?%d?$') then
first=rest:match('^%s*([^\n]*)') or ''
end
local body=first:match('^%(%d+%)%s+(.+)$') or first:match('^%[%d+%]%s+(.+)$')
or first:match('^[%d%.]+[%.%):]%s+(.+)$')
if not body then
for _,dash in ipairs({'-','–','—'}) do
body=first:match('^%d+%s*'..(dash=='-' and '%-' or dash)..'%s+(.+)$')
if body then break end
end
end
first=body or first:match('^%d+%s+(.+)$') or first
local bold=first:sub(1,2)=='**'
if bold then first=first:sub(3) end
local opener=first:sub(1,1)
local closer=opener=='[' and ']' or opener=='(' and ')' or nil
if closer then first=first:sub(2) end
local negative=first:sub(1,1)=='-'
if negative then first=first:sub(2) end
local token,tail=first:match('^([%d:.,]+)(.*)$')
if not token then return nil end
if closer then
if tail:sub(1,1)~=closer then return nil end
tail=tail:sub(2)
end
if bold then
if tail:sub(1,2)~='**' then return nil end
tail=tail:sub(3)
end
if tail~='' and not tail:match('^%s') then return nil end
local whole,fraction=token:match('^(.-)[.,](%d+)$')
if fraction and #fraction>3 then return nil end
whole=whole or token
local h,m,s,frames=whole:match('^(%d+):(%d%d):(%d%d):(%d%d)$')
local seconds
if frames then
-- Frame counts have their own precision; don't mix them with milliseconds.
if fraction or type(frame_rate)~='number' or frame_rate~=frame_rate
or frame_rate<=0 or frame_rate==math.huge then return nil end
local nominal=math.floor(frame_rate+0.5)
local hh,mm,ss,ff=tonumber(h),tonumber(m),tonumber(s),tonumber(frames)
if nominal<1 or mm>=60 or ss>=60 or ff>=nominal then return nil end
local frame_number=((hh*3600+mm*60+ss)*nominal+ff)
if drop_frame and (nominal==30 or nominal==60)
and math.abs(frame_rate-nominal*1000/1001)<0.01 then
-- SMPTE DF numbering skips 2 (or 4 at 59.94) frame labels at each
-- minute except every tenth. Reject labels that would be skipped.
local dropped=nominal==60 and 4 or 2
if mm%10~=0 and ss==0 and ff<dropped then return nil end
local minutes=hh*60+mm
frame_number=frame_number-dropped*(minutes-math.floor(minutes/10))
end
seconds=frame_number/frame_rate
else
h,m,s=whole:match('^(%d+):(%d%d):(%d%d)$')
if not h then m,s=whole:match('^(%d+):(%d%d)$') end
if not m or tonumber(s)>=60 or (h and tonumber(m)>=60) then return nil end
seconds=(tonumber(h) or 0)*3600+tonumber(m)*60+tonumber(s)
if fraction then seconds=seconds+tonumber('0.'..fraction) end
end
if seconds~=seconds or seconds>1e12 then return nil end
return negative and -seconds or seconds,(negative and '-' or '')..token
end
function M.block_time(block,frame_rate,drop_frame)
-- Detect leading timecodes regardless of historical @timecode flags.
-- v0.6.0 stored @timecode 0 for imports with splitting disabled;
-- preserving the flag in storage but ignoring it restores these notes.
if block.kind=='text' or block.kind=='note' then return M.timecode_prefix(block.text or '',frame_rate,drop_frame) end
if block.kind=='check' or block.kind=='select' then return M.timecode_prefix(block.label or '',frame_rate,drop_frame) end
end
function M.seek_position(block,offset,frame_rate,drop_frame)
local time=M.block_time(block,frame_rate,drop_frame)
if time==nil or type(offset)~='number' or offset~=offset or math.abs(offset)==math.huge then return nil end
local position=time-offset
if position~=position or math.abs(position)==math.huge then return nil end
return position
end
function M.timecode_label(time)
local sign=time<0 and '-' or ''
local ms=math.floor(math.abs(time)*1000+0.5)
local seconds=math.floor(ms/1000)
local hours=math.floor(seconds/3600)
local label=hours>0 and ('%02d:%02d:%02d'):format(hours,math.floor(seconds/60)%60,seconds%60)
or ('%02d:%02d'):format(math.floor(seconds/60),seconds%60)
if ms%1000>0 then label=label..('.%03d'):format(ms%1000):gsub('0+$','') end
return sign..label
end
-- Normalized stretch weights. New columns without a saved share receive the
-- mean share of the visible columns.
-- Keep a shared scale when only a subset is visible. Measuring a single
-- expanded column must not increase its saved weight relative to folded ones.
-- Presentation state is deliberately absent from the note format/history.
-- Preserve it across safe cache suspension and match unambiguous names on Undo.
function M.column_view_snapshot(doc)
local result={}
if not doc then return result end
for ti,tab in ipairs(doc.tabs) do
for ci,column in ipairs(tab.columns) do
result[#result+1]={tab=tab.name,name=column.name,ti=ti,ci=ci,
folded=column.folded,width=column.layout_width,board_folded=tab.folded,board_width=tab.layout_width}
end
end
return result
end
function M.restore_column_views(doc,views,exact)
local names,counts={},{}
for _,view in ipairs(views or {}) do
local key=view.tab..'\0'..view.name
names[key]=view;counts[key]=(counts[key] or 0)+1
end
local targets={}
for _,tab in ipairs(doc.tabs) do
for _,column in ipairs(tab.columns) do
local key=tab.name..'\0'..column.name
targets[key]=(targets[key] or 0)+1
end
end
local used={}
for ti,tab in ipairs(doc.tabs) do
for ci,column in ipairs(tab.columns) do
local key=tab.name..'\0'..column.name
local view=counts[key]==1 and targets[key]==1 and names[key] or nil
if exact then
view=nil
for _,candidate in ipairs(views or {}) do
if candidate.ti==ti and candidate.ci==ci and candidate.tab==tab.name and candidate.name==column.name then view=candidate;break end
end
end
if view and (exact or not used[key]) then
column.folded=view.folded;column.layout_width=view.width
tab.folded=view.board_folded;tab.layout_width=view.board_width
end
used[key]=true
end
end
end
function M.import_text(raw,strip,timecodes,frame_rate,drop_frame)
local source=norm(raw):gsub('^\239\187\191',''):gsub('\194\160',' ')
local ls=lines(source:match('^%s*(.-)%s*$'))
local function trim(x)return x:match('^%s*(.-)%s*$')end
local function candidate(x)
local prefix,body=x:match('^(%(%d+%))%s+(.+)$')
if not prefix then prefix,body=x:match('^(%[%d+%])%s+(.+)$') end
if not prefix then prefix=x:match('^(%(%d+%))$') or x:match('^(%[%d+%])$') end
if prefix then return {number=tonumber(prefix:match('%d+')),body=body,explicit=true} end
-- Keep digit runs separately so decimal values and dotted dates cannot
-- pass merely because they contain a dot. Only a final delimiter counts.
local digits,punctuation=x:match('^([%d%.]+)([%.%):])%s+')
if digits then body=x:match('^[%d%.]+[%.%):]%s+(.+)$')
else digits,punctuation=x:match('^([%d%.]+)([%.%):])$') end
if not digits then
for _,dash in ipairs({'-','–','—'}) do
digits,body=x:match('^(%d+)%s*'..(dash=='-' and '%-' or dash)..'%s+(.+)$')
if digits then punctuation=dash;break end
end
end
if digits then
local hierarchy=digits:find('.',1,true)~=nil
local valid=not digits:find('..',1,true) and not digits:match('^%.') and not digits:match('%.$')
-- A closing parenthesis explicitly marks a flat list even at large
-- indices. Ambiguous four-digit dot/colon/dash prefixes remain text.
if punctuation~=')' or hierarchy then
for part in digits:gmatch('%d+') do if #part>3 then valid=false end end
end
if hierarchy and punctuation~='.' and punctuation~=')' then valid=false end
if valid then
return {number=not hierarchy and tonumber(digits) or nil,body=body,explicit=true}
end
return nil
end
digits,body=x:match('^(%d+)%s+(.+)$')
if not digits then digits=x:match('^(%d+)$') end
-- Leading zeros and four-digit values are ambiguous identifiers/years.
if digits and #digits<=3 and not digits:match('^0') then
return {number=tonumber(digits),body=body,explicit=false}
end
end
local parsed,sequence,timed={},{},{}
local has_blank,has_numbers,has_timecodes=false,false,false
for i,line in ipairs(ls) do
local value=trim(line)
ls[i]=value
if value=='' and i>1 and i<#ls then has_blank=true end
local mark=candidate(value)
if mark then
parsed[i]=mark;sequence[#sequence+1]=mark
-- Already explicit markers can anchor adjacent bare list numbers.
mark.accepted=mark.explicit
end
end
for i,mark in ipairs(sequence) do
local previous,next_mark=sequence[i-1],sequence[i+1]
if not mark.explicit then
mark.accepted=(previous and previous.number and mark.number==previous.number+1)
or (next_mark and next_mark.number and next_mark.number==mark.number+1) or false
end
if mark.accepted then has_numbers=true end
end
if timecodes then
for i,value in ipairs(ls) do
local mark=parsed[i]
local position=M.timecode_prefix(mark and mark.accepted and mark.body or value,frame_rate,drop_frame)
if position~=nil then timed[i]=true;has_timecodes=true end
end
end
local result,part,marker,pending_list={},{},nil,false
local function flush()
local value=trim(table.concat(part,'\n'));part={}
if value=='' and marker then value=marker end
marker=nil;pending_list=false
if value~='' then result[#result+1]=value end
end
for i,line in ipairs(ls) do
local mark=parsed[i]
if line=='' then
if #part>0 then flush() end
elseif mark and mark.accepted then
flush()
if not mark.body and strip~=false then marker=line end
if strip==false or mark.body then part[#part+1]=(strip~=false and mark.body) or line end
pending_list=not mark.body
elseif timed[i] then
if #part>0 and not pending_list then flush() end
part[#part+1]=line;pending_list=false
else
if not has_blank and not has_numbers and not has_timecodes then flush() end
part[#part+1]=line;pending_list=false
end
end
flush()
return result
end
function M.column(name, text)
return {id=uid(), name=name or 'Column 1', blocks=text ~= nil and {M.text(text)} or {}}
end
function M.tab(name, text)
return {id=uid(), name=name or 'Notes', columns={M.column('Column 1',text)}}
end
-- The axis marker distinguishes vertical tabs from historical top-level tabs.
-- Historical columns retain their position; each old tab becomes a section.
function M.board_layout(doc)
if doc.layout=='columns' then return doc end
local result={layout='columns',tabs={}}
for _,old_tab in ipairs(doc.tabs) do
for ci,old_column in ipairs(old_tab.columns) do
local board=result.tabs[ci]
if not board then board=M.tab(old_column.name);board.columns={};result.tabs[ci]=board end
local name=old_tab.name
if old_column.name~=board.name then name=name..' — '..old_column.name end
local section=M.column(name);section.blocks=old_column.blocks
board.columns[#board.columns+1]=section
end
end
return result
end
function M.plain(raw)
return M.board_layout({tabs={M.tab('Notes',raw~='' and raw or nil)}})
end
function M.serialize(doc)
local out = {HEADER,'@layout columns'}
for _,tab in ipairs(doc.tabs) do
out[#out+1] = '@tab ' .. esc(tab.name)
for _,column in ipairs(tab.columns) do
out[#out+1] = '@column ' .. esc(column.name)
if column.header_color then
assert(M.valid_marker(column.header_color),'Invalid group header color.')
out[#out+1]='@groupcolor '..column.header_color
end
for _,b in ipairs(column.blocks) do
assert(M.valid_marker(b.color),'Invalid color marker.')
if b.color then out[#out+1]='@color '..b.color end
assert(b.timecode==nil or type(b.timecode)=='boolean','Invalid timecode flag.')
if b.timecode~=nil then
assert(b.kind=='text' or b.kind=='note','Timecodes require a text block.')
out[#out+1]='@timecode '..(b.timecode and '1' or '0')
end
if b.kind == 'text' or b.kind == 'note' then
out[#out+1] = b.kind=='note' and ('@note '..(b.checked and '1' or '0')) or '@text'
-- The parser normalizes all native EOL forms. Escape after that same
-- normalization, including directive-looking lines after a lone CR.
for _,l in ipairs(lines(norm(b.text))) do
-- Escape directive-looking lines and escape characters, reversibly.
out[#out+1] = l:match('^[@\\]') and '\\' .. l or l
end
out[#out+1] = '@end'
elseif b.kind == 'check' then
out[#out+1] = '@check ' .. (b.checked and '1 ' or '0 ') .. esc(b.label)
elseif b.kind == 'select' then
out[#out+1] = '@select ' .. tostring(b.selected) .. ' ' .. esc(b.label)
for _,o in ipairs(b.options) do out[#out+1] = '@option ' .. esc(o) end
out[#out+1] = '@end'
else error('Unknown block type.') end
end
out[#out+1] = '@endcolumn'
end
out[#out+1] = '@endtab'
end
return table.concat(out, '\n')
end
function M.parse(raw)
local normalized = norm(raw)
local header = normalized:match('^[^\n]*')
local legacy = header == LEGACY_HEADER
if header ~= HEADER and header ~= PREVIOUS_HEADER and not legacy then
if normalized:match('^# Patch34 Project Notes v') then
return nil, 'Unsupported notes format. Original notes were not changed.'
end
return M.plain(raw)
end
local ok, result = pcall(function()
local ls, doc, tab, column, i = lines(normalized), {tabs={}}, nil, nil, 2
local pending_color,pending_timecode
while i <= #ls do
local l = ls[i]
local before_blocks=column and #column.blocks or 0
if l=='@layout columns' and i==2 and not legacy then doc.layout='columns'
elseif l:match('^@groupcolor ') and column and not legacy and header==HEADER then
local key=l:sub(13)
assert(not column.header_color and M.valid_marker(key),'Invalid group header color.')
column.header_color=key
elseif l:sub(1,5) == '@tab ' and not tab then
tab = M.tab(unesc(l:sub(6))); doc.tabs[#doc.tabs+1] = tab
if legacy then column=tab.columns[1] else tab.columns={} end
elseif l:sub(1,8) == '@column ' and tab and not column and not legacy then
column=M.column(unesc(l:sub(9))); tab.columns[#tab.columns+1]=column
elseif l == '@endcolumn' and column and not legacy then
assert(not pending_color and pending_timecode==nil,'Block metadata has no block.');column=nil
elseif l == '@endtab' and tab then
assert(not pending_color and pending_timecode==nil,'Block metadata has no block.')
assert(legacy or not column, 'Unclosed column.')
assert(#tab.columns>0, 'Tab has no columns.')
assert(doc.layout=='columns' or #tab.columns<=8, 'A tab supports up to 8 columns.')
tab=nil; column=nil
elseif l:match('^@color ') and column and not legacy then
local key=l:sub(8)
assert(not pending_color and M.valid_marker(key),'Invalid or repeated color marker.')
pending_color=key
elseif (l=='@timecode' or l:match('^@timecode [01]$')) and column and not legacy then
assert(pending_timecode==nil,'Repeated timecode flag.')
pending_timecode=l~='@timecode 0'
elseif (l == '@text' or l:match('^@note [01]$')) and column then
local content = {}; i = i + 1
while i <= #ls and ls[i] ~= '@end' do
local t = ls[i]
if t:sub(1,1) == '\\' then
assert(t:sub(2,2) == '\\' or t:sub(2,2) == '@', 'Invalid text escape.')
t = t:sub(2)
else assert(t:sub(1,1) ~= '@', 'Unescaped directive inside text.') end
content[#content+1] = t; i = i + 1
end
assert(ls[i] == '@end', 'Unclosed text block.')
column.blocks[#column.blocks+1] = l=='@text' and M.text(table.concat(content,'\n')) or M.note(table.concat(content,'\n'),l=='@note 1')
elseif l:match('^@check [01] ') and column then
column.blocks[#column.blocks+1] = {id=uid(),kind='check',checked=l:sub(8,8)=='1',label=unesc(l:sub(10))}
elseif l:match('^@select %d+ ') and column then
local n, label = l:match('^@select (%d+) (.*)$')
local b = {id=uid(),kind='select',label=unesc(label),selected=tonumber(n),options={}}
i = i + 1
while i <= #ls and ls[i]:sub(1,8) == '@option ' do
b.options[#b.options+1] = unesc(ls[i]:sub(9)); i = i + 1
end
assert(ls[i]=='@end', 'Unclosed dropdown block.')
assert(#b.options>0 and b.selected>=1 and b.selected<=#b.options, 'Invalid dropdown selection.')
column.blocks[#column.blocks+1] = b
elseif l == '' and not tab then -- allow a trailing native-editor newline
else error('Unexpected line ' .. i .. ': ' .. l:sub(1,70)) end
if column and #column.blocks>before_blocks then
local block=column.blocks[#column.blocks]
assert(pending_timecode==nil or block.kind=='text' or block.kind=='note','Timecodes require a text block.')
block.color=pending_color;pending_color=nil
block.timecode=pending_timecode;pending_timecode=nil
end
i = i + 1
end
assert(not pending_color and pending_timecode==nil,'Block metadata has no block.')
assert(not tab, 'Unclosed tab.')
assert(#doc.tabs>0, 'Document has no tabs.')
assert(doc.layout~='columns' or #doc.tabs<=8,'A document supports up to 8 columns.')
return M.board_layout(doc)
end)
if ok then return result end
return nil, tostring(result)
end
function M.move(list, index, delta)
local to = index + delta
if to < 1 or to > #list then return index end
list[index], list[to] = list[to], list[index]
return to
end
-- Unlike swapping, a nonadjacent move preserves the relative order of every
-- other note. This matters when Completed notes last changes display order.
function M.move_to(list,index,to)
if index < 1 or index > #list or to < 1 or to > #list or index==to then return index end
table.insert(list,to,table.remove(list,index))
return to
end
-- "before" is a stable destination identity; nil means the end of the list.
function M.reorder_tab(doc,id,before,active)
local source,target
for i,tab in ipairs(doc.tabs) do
if tab.id==id then source=i end
if tab.id==before then target=i end
end
if not source or (before~=nil and not target) then return active,false end
target=target or (#doc.tabs+1)
if source<target then target=target-1 end
if source==target then return active,false end
local selected=doc.tabs[active]
table.insert(doc.tabs,target,table.remove(doc.tabs,source))
for i,tab in ipairs(doc.tabs) do if tab==selected then return i,true end end
return math.min(active or 1,#doc.tabs),true
end
function M.note_row_layout(text_h,checkbox_h,checked,metrics,min_height)
local height=math.max(text_h,checked and checkbox_h or 0,min_height or 0)
return {height=height,text_y=(height-text_h)*0.5,
checkbox_y=(height-checkbox_h)*0.5+metrics.note_checkbox_offset_y,
center=height*0.5}
end
function M.remove_option(b, index)
if #b.options <= 1 then return end
table.remove(b.options,index)
if index < b.selected then b.selected = b.selected - 1
elseif index == b.selected then b.selected = math.min(index,#b.options) end
end
function M.move_option(b, index, delta)
local to = M.move(b.options,index,delta)
if b.selected == index then b.selected = to
elseif b.selected == to then b.selected = index end
end
-- Compare against the exact last native read, not against re-serialized content.
function M.write_raw(session, api, next_raw)
-- Record intent without writing again if any host call throws.
session.write_attempt=next_raw;session.write_stage='checking'
local owner=session.target or session.proj
if not api.valid(owner) then return false, 'The note owner was removed or its project was closed.' end
local current = api.read(owner)
if current ~= session.raw then
session.conflict = current
return false, 'Native notes changed. The local draft has not been written.'
end
session.write_stage='writing'
local written,write_error=api.write(owner,next_raw)
if written~=true then session.write_stage='rejected';return false,write_error or 'REAPER could not write these notes.' end
session.write_stage='verifying'
local actual = api.read(owner)
-- Native editors may normalize EOLs or add a newline after @endtab.
-- Trailing text-block newlines remain inside @text/@end and are significant.
local same = norm(actual) == norm(next_raw)
if not same and (next_raw:sub(1,#HEADER)==HEADER or next_raw:sub(1,#PREVIOUS_HEADER)==PREVIOUS_HEADER
or next_raw:sub(1,#LEGACY_HEADER)==LEGACY_HEADER) then
same = norm(actual):gsub('\n+$','') == norm(next_raw):gsub('\n+$','')
end
if not same then
session.conflict = actual
return false, 'REAPER did not return the complete saved document.'
end
session.raw = actual; session.dirty = false; session.conflict = nil
session.write_stage='confirmed'
api.mark(owner)
return true
end
function M.write(session, api)
if not session.dirty then return true end
session.write_stage='validating';session.write_attempt=nil
local ok,next_raw=pcall(M.serialize,session.doc)
if not ok then
session.write_stage='validation_rejected'
return false,'Could not serialize the local draft: '..tostring(next_raw)
end
session.write_attempt=next_raw
local verified,err=M.parse(next_raw)
if not verified then
session.write_stage='validation_rejected'
return false,'Generated notes failed validation. Native notes were not changed: '..tostring(err)
end
-- Exact raw restoration in history_step has its own allow_invalid guard;
-- only newly generated documents must pass this preflight.
return M.write_raw(session,api,next_raw)
end
function M.history_new() return {undo={},redo={},key=nil,time=0} end
local function history_push(stack,state)
stack[#stack+1]=state
local bytes=0
for _,item in ipairs(stack) do bytes=bytes+#item.raw end
while #stack>1 and (#stack>100 or bytes>16*1024*1024) do
bytes=bytes-#stack[1].raw; table.remove(stack,1)
end
end
function M.history_record(h,before,after,key,now,action)
if before.raw==after then return end
if not (key and h.key==key and now-h.time<0.8 and #h.redo==0) then
history_push(h.undo,{raw=before.raw,active=before.active,allow_invalid=before.allow_invalid,action=action or 'change'})
end