-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.odin
More file actions
1939 lines (1752 loc) · 62.8 KB
/
Copy pathmain.odin
File metadata and controls
1939 lines (1752 loc) · 62.8 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
package main
import c "core:c"
import "core:fmt"
import "core:mem"
import "core:os"
import "core:sort"
import "core:strings"
import "core:time"
import gl "vendor/gl"
import ig "vendor/imgui"
import sdl_impl "vendor/imgui/backends"
import gl_impl "vendor/imgui/backends/opengl3"
import imn "vendor/imnodes"
import sdl "vendor:sdl3"
BUF_LEN :: 4096
// Custom owner-drawn titlebar geometry (device pixels).
WINDOW_BUTTON_WIDTH :: 40.0
WINDOW_CONTROLS_WIDTH :: 3 * WINDOW_BUTTON_WIDTH
FileDialog :: struct {
show: bool,
dirty: bool,
selected_file: i32,
path_buffer: [BUF_LEN]u8,
items_in_folder: [dynamic]DirectoryItem,
arena: mem.Dynamic_Arena,
}
SchemaWindow :: struct {
show: bool,
selected_table: i32,
}
AppState :: struct {
window: ^sdl.Window,
schema_name: string,
schema_dirty: bool,
schema: Schema,
file_dialog: FileDialog,
schema_window: SchemaWindow,
diagram_state: DiagramState,
// Titlebar window-control icons (PNG -> GL textures).
icon_min, icon_max, icon_restore, icon_close, icon_folder, icon_page: ig.TextureRef,
// Bold weight of the UI font, used for diagram node titles.
font_bold: ^ig.Font,
// Actual height of the main menu bar (font-size driven), used to offset the
// dockspace below the titlebar and to size the window-control hit-test region.
titlebar_height: f32,
// Right edge (ImGui px) of the interactive menu area in the titlebar. The
// hit-test returns NORMAL here so menu clicks reach ImGui instead of starting
// a window drag.
titlebar_menu_end: f32,
// Drag fallback used when the platform has no native hit-test (SetWindowHitTest).
drag_manual: bool,
drag_begin: bool,
drag_mouse_start: ig.Vec2,
drag_win_x, drag_win_y: i32,
}
DiagramLayoutKey :: struct {
seed: GlobalTableIndex,
visible_sum: u64,
}
DiagramState :: struct {
seed_table: GlobalTableIndex,
show_from_seed_table: bool,
degrees: u8,
visible_tables: [dynamic]GlobalTableIndex,
// Request the seed node be selected in the node editor on the next frame.
// Selection must wait until the node has been rendered (ImNodes asserts
// SelectNode on a node that isn't in its pool), so retargets from the
// schema list or a fresh schema load set this instead of selecting now.
pending_seed_selection: bool,
// Which seed + visible set the current layout was computed for; a refresh
// with an unchanged view keeps the positions (and any drags).
layout_key: DiagramLayoutKey,
// Grid-space positions of every table that has been shown, keyed by table
// index. Mirrored from ImNodes every frame (drags included) so the layout
// only changes when the view (seed or visible set) changes.
layout: map[GlobalTableIndex]ig.Vec2,
// Real rendered size (grid px) of every table ImNodes has drawn at least
// once, mirrored back every frame the same way `layout` is. A table with
// no entry yet falls back to estimate_node_size until it's first drawn.
node_size: map[GlobalTableIndex]ig.Vec2,
// Rank -> top-to-bottom table order from the last full layout pass.
// pack_layer_positions reuses this to repack coordinates (e.g. once real
// sizes are known) without redoing BFS ranking or crossing reduction.
layer_order: [dynamic][dynamic]GlobalTableIndex,
// Set by layout_visible_tables when the pass placed any table using an
// estimated size (i.e. a table ImNodes hasn't drawn before). Consumed one
// frame later, once that table's real size has been mirrored into
// node_size, to repack positions precisely.
pending_size_refine: bool,
// Set when the visible set was re-laid-out: the next editor frame pans so
// the whole diagram sits at the centre of the viewport.
pending_focus_view: bool,
// Press tracking for click-vs-drag: when the mouse goes down over a table
// node its id and press position are recorded; the retarget only fires if
// the release stays within the drag threshold. A drag (node moved) is
// never a click.
click_candidate_node: i32,
click_candidate_mouse: ig.Vec2,
}
DirectoryItemType :: enum {
Directory,
File,
}
DirectoryItem :: struct {
name: cstring,
path: cstring,
type: DirectoryItemType,
}
GlobalColumnIndex :: distinct u32 // All tables will have at least one column therefore we don't need a sentinel value
GlobalForeignKeyIndex :: distinct u32 // There may be tables with no FK, but we will deal with that with a simple bool
GlobalTableIndex :: distinct u32
Column :: struct {
name: string,
type: string,
composite_key_index: u32,
not_null: bool,
}
Table :: struct {
name: string,
from_column: GlobalColumnIndex,
to_column: GlobalColumnIndex,
from_foreign_key: GlobalForeignKeyIndex,
to_foreign_key: GlobalForeignKeyIndex,
has_foreign_keys: bool,
}
ForeignKey :: struct {
from: GlobalColumnIndex,
to: GlobalColumnIndex,
from_column: string, // Temporary value to test that we have things working before we start doing the whole index setup
to_table: string,
to_column: string,
resolved_to_index: bool,
}
Schema :: struct {
database_name: string,
tables: [dynamic]Table,
columns: [dynamic]Column,
foreign_keys: [dynamic]ForeignKey,
arena: mem.Dynamic_Arena,
allocator: mem.Allocator,
}
convert_odin_string_to_begin_and_end_cstrings :: proc(
s: string,
) -> (
begin: cstring,
end: cstring,
) {
return cstring(raw_data(s)), cstring(&raw_data(s)[len(s)])
}
// -1 is the sentinel value, having a bool as well provides no real benefit at the moment, that is something that might change
// if we want to use or_* at the call sites.
//
// Binary search: load_schema appends tables in ascending column order, so
// from_column/to_column ranges are sorted and non-overlapping. This is on
// the hot path for every FK lookup (linked_tables, link drawing) — layered
// layout on a large schema calls it often enough that a linear scan turns
// O(tables) per call into O(tables) per FK, which is the difference between
// a layout pass finishing instantly and taking seconds on a few thousand
// tables.
find_table_by_column :: proc(tables: []Table, column: GlobalColumnIndex) -> int {
lo, hi := 0, len(tables) - 1
for lo <= hi {
mid := lo + (hi - lo) / 2
t := tables[mid]
if column < t.from_column {
hi = mid - 1
} else if column >= t.to_column {
lo = mid + 1
} else {
return mid
}
}
return -1
}
collect_visible_tables :: proc(
schema: ^Schema,
state: DiagramState,
) -> (
tables: [dynamic]GlobalTableIndex,
) {
if !state.show_from_seed_table ||
state.degrees == 0 ||
state.seed_table >= GlobalTableIndex(len(schema.tables)) {
// Seed table gone (e.g. after loading a different DB) — show everything.
for i in 0 ..< len(schema.tables) do append(&tables, GlobalTableIndex(u32(i)))
return
}
depth := make(map[GlobalTableIndex]u8, context.temp_allocator)
defer delete(depth)
queue := make([dynamic]GlobalTableIndex, context.temp_allocator)
defer delete(queue)
head: int
append(&queue, state.seed_table)
depth[state.seed_table] = 0
append(&tables, state.seed_table)
for head < len(queue) {
current := queue[head]
head += 1
current_depth := depth[current]
if current_depth >= state.degrees {
continue
}
{
linked := linked_tables(schema, current)
defer delete(linked)
for t in linked {
if !(t in depth) {
depth[t] = current_depth + 1
append(&tables, t)
append(&queue, t)
}
}
}
}
return
}
refresh_diagram :: proc(schema: ^Schema, state: ^DiagramState) {
delete(state.visible_tables)
state.visible_tables = collect_visible_tables(schema, state^)
if layout_visible_tables(schema, state) {
// The visible set was re-laid-out, so centre the diagram in the editor
// viewport on the next frame.
state.pending_focus_view = true
}
}
// Seed the degree filter at a table and refresh the visible set. Out-of-range
// seeds (no tables loaded yet) are a no-op.
set_diagram_seed :: proc(schema: ^Schema, state: ^DiagramState, seed: GlobalTableIndex) {
if seed >= GlobalTableIndex(len(schema.tables)) {
return
}
state.seed_table = seed
state.show_from_seed_table = true
refresh_diagram(schema, state)
}
show_all_tables :: proc(schema: ^Schema, state: ^DiagramState) {
state.show_from_seed_table = false
refresh_diagram(schema, state)
}
// Layered (Sugiyama-style) layout tuning, all in grid px. Ranks — one per hop
// distance from the seed — stack left-to-right; within a rank, tables run
// top-to-bottom and wrap into a new sub-column once the rank grows taller
// than MAX_RANK_HEIGHT, so a flat schema with hundreds of tables in one rank
// doesn't become a single absurdly tall column. Real per-table sizes (from
// node_size_for) drive every spacing decision, so packed tables never
// overlap.
//
// Left-to-right, not top-to-bottom: ImNodes always draws an input pin on a
// node's left edge and an output pin on its right, and its link curve is a
// horizontal S — control points offset purely along x by a quarter of the
// pin-to-pin distance (see GetCubicBezier in imnodes.cpp), regardless of how
// much of that distance is actually vertical. Laid out top-to-bottom, two
// pins mostly separated by a big vertical rank gutter still bulge sideways
// by a quarter of that (mostly-vertical) distance, which is enough to swing
// into a neighbouring table in the same rank. Ranking left-to-right instead
// makes the pin-to-pin distance mostly horizontal, so that same bulge lands
// inside the gutter it was already given rather than sideways into a
// sibling — and it matches the pins' fixed sides: the rank relaxation pass
// in compute_layer_order keeps a referencing ("many"/input) table at a rank
// at or after the table it references ("one"/output), so a link's output
// pin is (almost always) at or left of its input pin, which is exactly the
// direction ImNodes' left-input/right-output curve shape wants.
LAYER_GUTTER_X :: 140.0
SUBCOL_GUTTER_X :: 40.0
NODE_GAP_Y :: 50.0
MAX_RANK_HEIGHT :: 1400.0
// Crossing-reduction (barycenter) and straightening sweep counts. Almost
// every FK link connects same-rank or adjacent-rank tables (the rank
// relaxation pass below only occasionally pushes one more than one rank
// away), so a handful of sweeps is enough to converge — this is the same
// cheap heuristic Graphviz's `dot` and dagre use for layered graphs.
ORDER_SWEEPS :: 4
STRAIGHTEN_SWEEPS :: 3
// Iteration cap for the rank relaxation pass in compute_layer_order. A real
// schema's FK dependency chain converges in a handful of passes; this only
// guards against a pathological FK cycle spinning forever.
RANK_RELAX_MAX_ITER :: 64
// Fallback node size for a table ImNodes hasn't drawn yet, so the very first
// layout pass has a sane size to pack against before the real size (mirrored
// back after that first frame) triggers a precise repack. Rough character-
// width heuristic — it only needs to be in the right ballpark for one frame.
EST_CHAR_WIDTH :: 7.0
EST_WIDTH_PAD :: 36.0
EST_MIN_WIDTH :: 140.0
EST_HEADER_HEIGHT :: 34.0
EST_ROW_HEIGHT :: 20.0
estimate_node_size :: proc(schema: ^Schema, table_idx: GlobalTableIndex) -> ig.Vec2 {
table := schema.tables[table_idx]
max_chars := len(table.name)
for column in schema.columns[table.from_column:table.to_column] {
if len(column.name) > max_chars {
max_chars = len(column.name)
}
}
width := max(EST_MIN_WIDTH, f32(max_chars) * EST_CHAR_WIDTH + EST_WIDTH_PAD)
column_count := max(1, int(table.to_column) - int(table.from_column))
height := EST_HEADER_HEIGHT + f32(column_count) * EST_ROW_HEIGHT
return ig.Vec2{width, height}
}
// Best known size for a table: the real ImNodes-rendered size once it has
// been drawn at least once this session, otherwise an estimate.
node_size_for :: proc(
schema: ^Schema,
state: ^DiagramState,
table_idx: GlobalTableIndex,
) -> ig.Vec2 {
if size, cached := state.node_size[table_idx]; cached {
return size
}
return estimate_node_size(schema, table_idx)
}
delete_layer_order :: proc(layers: [dynamic][dynamic]GlobalTableIndex) {
for layer in layers {
delete(layer)
}
delete(layers)
}
RankEntry :: struct {
table: GlobalTableIndex,
key: f32,
}
compare_rank_entries :: proc(a, b: RankEntry) -> int {
if a.key < b.key {
return -1
}
if a.key > b.key {
return 1
}
return 0
}
// Reorders one rank in place to minimise edge crossings against ref_rank,
// using the classic barycenter heuristic: each table moves toward the
// average rank-order position of its neighbours in ref_rank. A table with no
// neighbour there keeps its current slot (key = its own index), so isolated
// tables don't get shuffled arbitrarily. merge_sort_proc is stable, so ties
// (equal barycenter) keep their previous relative order instead of
// oscillating between sweeps.
reorder_rank_by_neighbors :: proc(
layers: [dynamic][dynamic]GlobalTableIndex,
neighbors: map[GlobalTableIndex][dynamic]GlobalTableIndex,
rank_of: map[GlobalTableIndex]u32,
pos_in_rank: ^map[GlobalTableIndex]int,
rank: u32,
ref_rank: u32,
) {
row := layers[rank]
if len(row) <= 1 {
return
}
entries := make([dynamic]RankEntry, 0, len(row), context.temp_allocator)
for t, i in row {
linked := neighbors[t]
sum: f32 = 0
count: f32 = 0
for n in linked {
if rank_of[n] == ref_rank {
sum += f32(pos_in_rank[n])
count += 1
}
}
key := f32(i)
if count > 0 {
key = sum / count
}
append(&entries, RankEntry{table = t, key = key})
}
sort.merge_sort_proc(entries[:], compare_rank_entries)
for e, i in entries {
row[i] = e.table
pos_in_rank[e.table] = i
}
}
// Pulls a single-subcolumn rank's tables vertically toward the average y of
// their neighbours in ref_rank, then resolves top-to-bottom so minimum
// spacing is never violated — order is untouched, so this can only reduce
// edge slant, never introduce a new crossing or an overlap. Wrapped ranks
// (more than one sub-column) are left at their packed position: straightening
// a wrapped grid is a different problem and not worth the complexity here.
straighten_rank :: proc(
schema: ^Schema,
state: ^DiagramState,
layers: [dynamic][dynamic]GlobalTableIndex,
neighbors: map[GlobalTableIndex][dynamic]GlobalTableIndex,
rank_of: map[GlobalTableIndex]u32,
rank: u32,
ref_rank: u32,
) {
col := layers[rank]
if len(col) <= 1 {
return
}
if state.layout[col[0]].x != state.layout[col[len(col) - 1]].x {
return
}
prev_bottom: f32
for t, i in col {
linked := neighbors[t]
sum: f32 = 0
count: f32 = 0
for n in linked {
if rank_of[n] == ref_rank {
sum += state.layout[n].y
count += 1
}
}
pos := state.layout[t]
size := node_size_for(schema, state, t)
desired := pos.y
if count > 0 {
desired = sum / count
}
if i > 0 {
// Positions are top-left (ImNodes' convention — see
// SetNodeGridSpacePos), so the minimum next y is the previous
// node's bottom edge plus the gap, no half-heights involved.
min_y := prev_bottom + NODE_GAP_Y
if min_y > desired {
desired = min_y
}
}
pos.y = desired
state.layout[t] = pos
prev_bottom = pos.y + size.y
}
}
// Packs every rank's tables into non-overlapping grid-space positions using
// each table's best known size, wrapping a rank into new sub-columns once it
// grows past MAX_RANK_HEIGHT. Runs standalone (no BFS, no reordering) so it
// can cheaply repack once real ImNodes sizes replace first-pass estimates.
pack_layer_positions :: proc(
schema: ^Schema,
state: ^DiagramState,
layers: [dynamic][dynamic]GlobalTableIndex,
) {
x_cursor: f32 = 0
for r in 0 ..< len(layers) {
col := layers[r]
if len(col) == 0 {
// Rank relaxation can leave a rank completely empty (a hop can
// jump straight from N to N+2). Still advance x_cursor — every
// rank index must own a distinct x, or the next non-empty rank
// silently reuses this one's x and collides with it.
x_cursor += LAYER_GUTTER_X
continue
}
sub_starts := make([dynamic]int, 0, 4, context.temp_allocator)
append(&sub_starts, 0)
y_cursor: f32 = 0
for t, i in col {
size := node_size_for(schema, state, t)
if i > sub_starts[len(sub_starts) - 1] && y_cursor + size.y > MAX_RANK_HEIGHT {
append(&sub_starts, i)
y_cursor = 0
}
y_cursor += size.y + NODE_GAP_Y
}
append(&sub_starts, len(col))
rank_width: f32 = 0
for s in 0 ..< len(sub_starts) - 1 {
start := sub_starts[s]
end := sub_starts[s + 1]
y: f32 = 0
sub_width: f32 = 0
for i in start ..< end {
t := col[i]
size := node_size_for(schema, state, t)
state.layout[t] = ig.Vec2{x_cursor + rank_width, y}
y += size.y + NODE_GAP_Y
if size.x > sub_width {
sub_width = size.x
}
}
total_height := y - NODE_GAP_Y
for i in start ..< end {
pos := state.layout[col[i]]
pos.y -= total_height * 0.5
state.layout[col[i]] = pos
}
rank_width += sub_width + SUBCOL_GUTTER_X
}
rank_width -= SUBCOL_GUTTER_X
x_cursor += rank_width + LAYER_GUTTER_X
}
// Straightening: alternate sweeps pulling each rank toward its parent
// rank, then toward its child rank, so parents tend to centre over their
// children like a conventional tree layout instead of sitting wherever
// the initial top-to-bottom pack put them.
if len(layers) < 2 {
return
}
visible := make(map[GlobalTableIndex]bool, context.temp_allocator)
for row in layers {
for t in row {
visible[t] = true
}
}
neighbors := make(map[GlobalTableIndex][dynamic]GlobalTableIndex, context.temp_allocator)
rank_of := make(map[GlobalTableIndex]u32, context.temp_allocator)
for r in 0 ..< len(layers) {
for t in layers[r] {
rank_of[t] = u32(r)
linked := linked_tables(schema, t)
defer delete(linked)
list := make([dynamic]GlobalTableIndex, 0, len(linked), context.temp_allocator)
for n in linked {
if visible[n] {
append(&list, n)
}
}
neighbors[t] = list
}
}
for _ in 0 ..< STRAIGHTEN_SWEEPS {
for r in 1 ..< len(layers) {
straighten_rank(schema, state, layers, neighbors, rank_of, u32(r), u32(r) - 1)
}
for r := len(layers) - 2; r >= 0; r -= 1 {
straighten_rank(schema, state, layers, neighbors, rank_of, u32(r), u32(r) + 1)
}
}
}
// Ranks every visible table by hop distance from the seed (BFS through both
// FK directions — the same neighbourhood rule as collect_visible_tables),
// relaxes that into a longest-path rank using FK direction (see the rank
// relaxation pass below), then reorders each rank with a few barycenter
// sweeps to reduce edge crossings against the ranks before and after it.
// Returns the final top-to-bottom order per rank, allocated with the default
// allocator since the caller keeps it around for a later size-refine repack.
compute_layer_order :: proc(
schema: ^Schema,
state: ^DiagramState,
) -> (
layers: [dynamic][dynamic]GlobalTableIndex,
) {
visible := make(map[GlobalTableIndex]bool, context.temp_allocator)
for t in state.visible_tables {
visible[t] = true
}
hop := make(map[GlobalTableIndex]u32, context.temp_allocator)
queue := make([dynamic]GlobalTableIndex, context.temp_allocator)
append(&queue, state.seed_table)
hop[state.seed_table] = 0
for head := 0; head < len(queue); head += 1 {
current := queue[head]
current_hop := hop[current]
linked := linked_tables(schema, current)
for neighbor in linked {
if !visible[neighbor] {
continue
}
if neighbor in hop {
continue
}
hop[neighbor] = current_hop + 1
append(&queue, neighbor)
}
delete(linked)
}
// Same-rank FK edges (e.g. two direct children of the seed that also
// reference each other) would otherwise force that link to loop
// sideways across the row, cutting through whatever sits between them.
// Relax hop into a longest-path rank using the FK's actual direction:
// the referencing ("many") table always ends up at least one rank
// below the table it references, turning a same-rank link into a
// normal top-to-bottom one. The iteration cap bounds the cost on a
// pathological FK cycle; real schemas converge in a handful of passes.
for _ in 0 ..< RANK_RELAX_MAX_ITER {
changed := false
for fk in schema.foreign_keys {
from_i := find_table_by_column(schema.tables[:], fk.from)
to_i := find_table_by_column(schema.tables[:], fk.to)
if from_i < 0 || to_i < 0 {
continue
}
from_t := GlobalTableIndex(u32(from_i))
to_t := GlobalTableIndex(u32(to_i))
// A self-referencing FK (e.g. cards.parent_id -> cards.id) has
// from_t == to_t, so from_hop and to_hop are the same map read —
// "at least one rank below itself" is never satisfiable, so
// without this guard the condition below stays true forever,
// walking the table's own rank up by exactly one every single
// pass until the iteration cap, stranding it (and everything
// beyond it) tens of ranks away from the rest of the layout.
if from_t == state.seed_table || from_t == to_t || !visible[from_t] || !visible[to_t] {
continue
}
from_hop, from_ok := hop[from_t]
to_hop, to_ok := hop[to_t]
if !from_ok || !to_ok {
continue
}
if from_hop <= to_hop {
hop[from_t] = to_hop + 1
changed = true
}
}
if !changed {
break
}
}
max_hop: u32 = 0
for t in state.visible_tables {
if h := hop[t]; h > max_hop {
max_hop = h
}
}
outer_rank := max_hop + 1 // tables the seed can't reach
work := make([dynamic][dynamic]GlobalTableIndex, context.temp_allocator)
for _ in 0 ..= int(outer_rank) {
append(&work, make([dynamic]GlobalTableIndex, context.temp_allocator))
}
for t in state.visible_tables {
h, reached := hop[t]
if !reached {
h = outer_rank
}
append(&work[h], t)
}
// Initial order within each rank is just bucket (visible_tables) order —
// rank relaxation above means a table's rank no longer always matches
// its BFS-tree parent's rank, so grouping by BFS parent here could put a
// table in the wrong rank's order entirely. The barycenter sweeps below
// converge to a good order from any starting point, so this heuristic
// isn't needed for correctness or for a reasonable result.
neighbors := make(map[GlobalTableIndex][dynamic]GlobalTableIndex, context.temp_allocator)
rank_of := make(map[GlobalTableIndex]u32, context.temp_allocator)
pos_in_rank := make(map[GlobalTableIndex]int, context.temp_allocator)
for r in 0 ..< len(work) {
for t, i in work[r] {
rank_of[t] = u32(r)
pos_in_rank[t] = i
linked := linked_tables(schema, t)
defer delete(linked)
list := make([dynamic]GlobalTableIndex, 0, len(linked), context.temp_allocator)
for n in linked {
if visible[n] {
append(&list, n)
}
}
neighbors[t] = list
}
}
for sweep in 0 ..< ORDER_SWEEPS {
if sweep % 2 == 0 {
for r in 1 ..= int(outer_rank) {
reorder_rank_by_neighbors(
work,
neighbors,
rank_of,
&pos_in_rank,
u32(r),
u32(r) - 1,
)
}
} else {
for r := int(outer_rank) - 1; r >= 0; r -= 1 {
reorder_rank_by_neighbors(
work,
neighbors,
rank_of,
&pos_in_rank,
u32(r),
u32(r) + 1,
)
}
}
}
layers = make([dynamic][dynamic]GlobalTableIndex, len(work))
for r in 0 ..< len(work) {
row := make([dynamic]GlobalTableIndex, len(work[r]))
copy(row[:], work[r][:])
layers[r] = row
}
return
}
// Layered layout: every visible table is ranked by hop distance from the
// seed (one FK link = one hop, either direction, then relaxed by FK
// direction — see compute_layer_order) and ranks stack left-to-right, which
// is the orientation ImNodes' link curves want (see the tuning comment
// above LAYER_GUTTER_X). Within a rank, tables are ordered to minimise edge
// crossings against the ranks before and after, then packed top-to-bottom
// using real table sizes so nothing overlaps and FK links have a clear
// gutter to run through between ranks instead of across a table body. Runs
// on every view change — centring the seed's neighbourhood is the point —
// but is skipped when the seed and visible set are unchanged, so
// re-clicking the active table (or Show All twice) costs nothing and leaves
// drags alone.
layout_visible_tables :: proc(schema: ^Schema, state: ^DiagramState) -> (relaid_out: bool) {
visible_count := len(state.visible_tables)
if visible_count == 0 {
return false
}
if state.seed_table >= GlobalTableIndex(len(schema.tables)) {
return false
}
key_sum := u64(visible_count)
for t in state.visible_tables {
key_sum += u64(t)
}
if state.layout_key.seed == state.seed_table && state.layout_key.visible_sum == key_sum {
return false
}
state.layout_key.seed = state.seed_table
state.layout_key.visible_sum = key_sum
delete_layer_order(state.layer_order)
state.layer_order = compute_layer_order(schema, state)
pack_layer_positions(schema, state, state.layer_order)
// At least one visible table may have just been placed against an
// estimated size (never drawn before, so node_size has no entry yet).
// The estimate is only ever off for the one frame before ImNodes draws
// the node and reports its real size — request a repack for the frame
// right after that happens.
state.pending_size_refine = true
return true
}
linked_tables :: proc(
schema: ^Schema,
table_idx: GlobalTableIndex,
) -> (
tables: [dynamic]GlobalTableIndex,
) {
table := schema.tables[table_idx]
if table.has_foreign_keys {
fks := schema.foreign_keys[table.from_foreign_key:table.to_foreign_key]
for key in fks {
t := find_table_by_column(schema.tables[:], key.to)
if t >= 0 do append(&tables, GlobalTableIndex(u32(t)))
}
}
for key in schema.foreign_keys {
to_table := find_table_by_column(schema.tables[:], key.to)
if to_table >= 0 && GlobalTableIndex(u32(to_table)) == table_idx {
from_table := find_table_by_column(schema.tables[:], key.from)
if from_table >= 0 {
append(&tables, GlobalTableIndex(u32(from_table)))
}
}
}
return
}
init_file_dialog :: proc(fd: ^FileDialog) -> (err: os.Error) {
fd.show = true // Show on startup
fd.selected_file = -1
mem.dynamic_arena_init(&fd.arena)
alloc := mem.dynamic_arena_allocator(&fd.arena)
fd.items_in_folder = make([dynamic]DirectoryItem, alloc)
directory_path := os.get_working_directory(context.temp_allocator) or_return
copy(fd.path_buffer[:], directory_path)
fd.dirty = true
return nil
}
main :: proc() {
if len(os.args) != 2 {
make_imgui_app()
} else {
filename := os.args[1]
error := print_database_information(filename)
fmt.printfln("Return code: %v", error)
}
}
// Apply an ImGui theme and (re)apply the OS backdrop material it requests.
// enable_os_blur is idempotent, so this is safe on every theme switch.
apply_theme_to_window :: proc(window: ^sdl.Window, theme_data: ThemeData) {
apply_theme(theme_data)
enable_os_blur(window, theme_data.backdrop)
}
window_hit_test :: proc "c" (
win: ^sdl.Window,
area: ^sdl.Point,
data: rawptr,
) -> sdl.HitTestResult {
as := (^AppState)(data)
border := c.int(4)
pw, ph: c.int
sdl.GetWindowSizeInPixels(win, &pw, &ph)
lw, lh: c.int
sdl.GetWindowSize(win, &lw, &lh)
scale := f32(pw) / f32(max(lw, 1))
titlebar := i32(0)
controls := i32(WINDOW_CONTROLS_WIDTH / scale)
menu_end := i32(0)
if as != nil {
titlebar = i32(as.titlebar_height / scale)
menu_end = i32(as.titlebar_menu_end / scale)
}
x := area[0]
y := area[1]
if x < border && y < border {return .RESIZE_TOPLEFT}
if x >= lw - border && y < border {return .RESIZE_TOPRIGHT}
if x < border && y >= lh - border {return .RESIZE_BOTTOMLEFT}
if x >= lw - border && y >= lh - border {return .RESIZE_BOTTOMRIGHT}
if y < border {return .RESIZE_TOP}
if y >= lh - border {return .RESIZE_BOTTOM}
if x < border {return .RESIZE_LEFT}
if x >= lw - border {return .RESIZE_RIGHT}
// Interactive titlebar content (menus, window controls) must NOT be draggable
// — leave those to ImGui so clicks land on the widgets.
if y < titlebar && x < menu_end {
return .NORMAL
}
if y < titlebar && x < lw - controls {
return .DRAGGABLE
}
return .NORMAL
}
// Create the docking host window below the owner-drawn titlebar.
dock_space_below_titlebar :: proc(app_state: ^AppState) {
io := ig.GetIO()
h := app_state.titlebar_height
ig.SetNextWindowPos(ig.Vec2{0, h})
ig.SetNextWindowSize(ig.Vec2{io.DisplaySize.x, io.DisplaySize.y - h})
ig.PushStyleVar(.WindowRounding, 0.0)
ig.PushStyleVar(.WindowBorderSize, 0.0)
ig.PushStyleVarImVec2(.WindowPadding, ig.Vec2{0, 0})
defer ig.PopStyleVar(3)
if ig.Begin(
"##MainDockHost",
flags = {
.NoTitleBar,
.NoCollapse,
.NoResize,
.NoMove,
.NoDocking,
.NoBringToFrontOnFocus,
.NoNavFocus,
},
) {
ig.DockSpace(ig.GetID("MainDockSpace"), ig.GetContentRegionAvail())
}
ig.End()
}
TitleBarButtonAction :: enum {
Minimize,
Maximize,
Restore,
Close,
}
// One titlebar window-control button. Renders the icon texture when loaded,
// otherwise a plain text label (cross-platform fallback).
titlebar_button :: proc(
app_state: ^AppState,
id: cstring,
icon: ig.TextureRef,
text_label: cstring,
text_col: ig.Vec4,
action: TitleBarButtonAction,
) {
clicked := false
if icon._TexID != 0 {
clicked = ig.ImageButton(id, icon, ig.Vec2{20, 20}, tint_col = text_col)
} else {
clicked = ig.Button(id, {WINDOW_BUTTON_WIDTH, app_state.titlebar_height})
}
if !clicked {
return
}
switch action {
case .Minimize:
sdl.MinimizeWindow(app_state.window)
case .Maximize:
sdl.MaximizeWindow(app_state.window)
case .Restore:
sdl.RestoreWindow(app_state.window)
case .Close:
ev: sdl.Event
ev.type = .QUIT
_ = sdl.PushEvent(&ev)
}
}
// Draw the owner-drawn titlebar via the main menu bar (always on top, full
// width): title text + File/Theme menus on the left, minimize/
// maximize-restore/close buttons pinned to the right edge.
show_titlebar :: proc(app_state: ^AppState) {
io := ig.GetIO()
style := ig.GetStyle()
// Heighten the menu bar so it reads as a ~30px titlebar with the app's font.
ig.PushStyleVarY(.FramePadding, 9.0)
defer ig.PopStyleVar(1)
app_state.titlebar_height = ig.GetFrameHeight()
if ig.BeginMainMenuBar() {
ig.SetCursorPosX(8)
ig.TextUnformatted("Schema Spelunker")
ig.SameLine()
// Menus
if ig.BeginMenu("File") {
if ig.MenuItem("Open...") {app_state.file_dialog.show = true}
ig.EndMenu()
}
ig.SameLine()
if ig.BeginMenu("Theme") {
// Menu built from a live scan of assets/themes/*.ssTheme — the
// display name is each file's `name` tag, so dropping a new theme
// file in the folder is all it takes to extend the menu.
themes := discover_themes(context.temp_allocator)
for theme in themes {
if ig.MenuItem(theme.name) {
if theme_data, theme_ok := parse_ssTheme(theme.path, context.temp_allocator);
theme_ok {
apply_theme_to_window(app_state.window, theme_data)
}
}
}
ig.EndMenu()
}
app_state.titlebar_menu_end = ig.GetCursorPosX()
// Window controls pinned to the right edge.
text_col := style.Colors[ig.Col.Text]
icon_size := ig.Vec2{20, 20}