summaryrefslogtreecommitdiffstats
path: root/source/app/app_features.cpp
blob: 1fdaf72f0cc93ea219cb215d9ef3acc514373639 (plain) (blame)
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
//- documentation, source links, clipboard, png export
// NOTE: the ui side of the features that live in diagram_links / diagram_interop / diagram_png.

//- launching urls and files

#if PLATFORM_WINDOWS
internal void app_spawn_command(const char *command)
{
	WCHAR wide[4096];
	win32_utf8_to_wide(command, -1, wide, ArrayCount(wide));
	STARTUPINFOW        si = {sizeof(si)};
	PROCESS_INFORMATION pi = {};
	if(CreateProcessW(NULL, wide, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi)) {
		CloseHandle(pi.hThread);
		CloseHandle(pi.hProcess);
	}
}

internal void app_shell_open(const char *target)
{
	WCHAR wide[4096];
	win32_utf8_to_wide(target, -1, wide, ArrayCount(wide));
	ShellExecuteW(NULL, L"open", wide, NULL, NULL, SW_SHOWNORMAL);
}
#else
// NOTE: double fork: the opener is reparented to init, we never collect a zombie
internal void app_spawn_argv(const char *const *argv)
{
	pid_t pid = fork();
	if(pid == 0) {
		setsid();
		pid_t again = fork();
		if(again == 0) {
			int devnull = open("/dev/null", O_RDWR);
			if(devnull >= 0) { dup2(devnull, 0); dup2(devnull, 1); dup2(devnull, 2); }
			execvp(argv[0], (char *const *)argv);
			_exit(127);
		}
		_exit(0);
	}
	if(pid > 0) waitpid(pid, NULL, 0);
}

internal void app_spawn_command(const char *command)
{
	const char *argv[] = {"/bin/sh", "-c", command, NULL};
	app_spawn_argv(argv);
}

internal void app_shell_open(const char *target)
{
#if PLATFORM_APPLE
	const char *argv[] = {"open", target, NULL};
#else
	const char *argv[] = {"xdg-open", target, NULL};
#endif
	app_spawn_argv(argv);
}
#endif

// NOTE: DESIGN_IT_EDITOR="code -g {file}:{line}" (or "zed {file}:{line}", "kitty nvim +{line} {file}")
// opens files at the line, without it the system opener shows the file
internal void app_open_file_at(App *app, const char *path, u32 line)
{
	const char *editor = getenv("DESIGN_IT_EDITOR");
	if(editor && editor[0]) {
		char quoted[1200], line_s[16], a[2048], b[2048];
#if PLATFORM_WINDOWS
		snprintf(quoted, sizeof(quoted), "\"%s\"", path);
#else
		// single quotes for the shell, a ' in the path becomes '\''
		u32 n = 0;
		quoted[n++] = '\'';
		for(const char *c = path; *c && n + 5 < sizeof(quoted); ++c) {
			if(*c == '\'') { quoted[n++] = '\''; quoted[n++] = '\\'; quoted[n++] = '\''; quoted[n++] = '\''; }
			else quoted[n++] = *c;
		}
		quoted[n++] = '\'';
		quoted[n]   = 0;
#endif
		snprintf(line_s, sizeof(line_s), "%u", line ? line : 1);
		str_replace_all(a, sizeof(a), editor, "{file}", quoted);
		str_replace_all(b, sizeof(b), a, "{line}", line_s);
		if(!strstr(editor, "{file}")) snprintf(b, sizeof(b), "%s %s", editor, quoted);
		app_spawn_command(b);
		app_message(app, "opened %s:%u in $DESIGN_IT_EDITOR", path, line);
		return;
	}
	app_shell_open(path);
	app_message(app, "opened %s%s", path, line ? "  (set DESIGN_IT_EDITOR=\"code -g {file}:{line}\" to jump to the line)" : "");
}

// NOTE: online = the repo url in a browser (falls back to the local file without a repo),
// otherwise the local file in the editor (falls back to the url when there is no file)
internal void app_open_link(App *app, s32 node, b32 online)
{
	Diagram *dia = app->diagram;
	if(node < 0 || node >= (s32)dia->node_count || !dia->nodes[node].alive) {
		app_message(app, "select a node first");
		return;
	}
	const char *link = dia->nodes[node].link;
	if(!link[0]) {
		app_message(app, "%s has no source link: set one in the inspector or :link path/file.c:42", dia->nodes[node].name);
		return;
	}
	char url[1024], path[1024];
	u32  line     = 0;
	b32  has_url  = diagram_link_url(dia, link, url, sizeof(url));
	b32  has_path = diagram_link_local(dia, link, path, sizeof(path), &line) && file_exists(path);
	if((online && has_url) || (!has_path && has_url)) {
		app_shell_open(url);
		app_message(app, "opened %s", url);
	} else if(has_path) {
		app_open_file_at(app, path, line);
	} else if(path[0]) {
		app_message(app, "no file at %s, and no repo url to open (:repo <url> or :repo detect)", path);
	} else {
		app_message(app, "can't open %s", link);
	}
}

//- clipboard

internal u64 hash_bytes(String8 s)
{
	u64 h = 1469598103934665603ull;
	for(u64 i = 0; i < s.size; ++i) h = (h ^ s.data[i]) * 1099511628211ull;
	return h ^ s.size;
}

// NOTE: the yank register always gets it, the system clipboard only for real copies (dd yanks
// without clobbering what you copied elsewhere, like vim)
internal void app_clip_store(App *app, String8 text, b32 system)
{
	free(app->clip);
	app->clip      = (char *)malloc(text.size + 1);
	app->clip_size = app->clip ? text.size : 0;
	if(app->clip) { MemCpy(app->clip, text.data, text.size); app->clip[text.size] = 0; }
	if(system && app->window) {
		PlatformClipboardSet(app->window, (const char *)text.data, text.size);
		app->clip_system_hash = hash_bytes(text);
	}
}

internal u32 app_copy_selection(App *app, b32 system)
{
	Diagram     *dia     = app->diagram;
	ScratchArena scratch = ScratchGet();
	u32          count   = 0;
	String8      text    = diagram_selection_to_dsl(scratch.arena, dia, app->active_node, &count);
	if(count) app_clip_store(app, text, system);
	scratch_end(&scratch);
	return count;
}

// NOTE: paste: the system clipboard when something else put text there since our last copy,
// otherwise the yank register. design-it text goes straight in, mermaid / plantuml is imported
// into a scratch diagram first (that lays it out) and comes in through its DSL
internal void app_paste(App *app, b32 at_mouse, f32 wx, f32 wy)
{
	Diagram     *dia     = app->diagram;
	ScratchArena scratch = ScratchGet();
	String8      text    = str8_zero();
	if(app->window) {
		String8 sys = PlatformClipboardGet(app->window, scratch.arena);
		if(sys.size && hash_bytes(sys) != app->clip_system_hash) text = sys;
	}
	if(!text.size && app->clip_size) text = ToString8Size((u8 *)app->clip, app->clip_size);
	if(!text.size) { app_message(app, "nothing to paste (yy copies the selection)"); scratch_end(&scratch); return; }

	TextFormat format = diagram_detect_format(text, NULL);
	if(format == TEXT_FORMAT_MERMAID || format == TEXT_FORMAT_PLANTUML) {
		if(!app->clip_diagram) {
			app->clip_diagram = PushStructZero(app->arena, Diagram);
			diagram_init_scratch(app->arena, app->clip_diagram);
		}
		b32 ok = (format == TEXT_FORMAT_MERMAID) ? diagram_import_mermaid(app->clip_diagram, text) : diagram_import_plantuml(app->clip_diagram, text);
		if(!ok) { app_message(app, "couldn't read the %s on the clipboard", format == TEXT_FORMAT_MERMAID ? "mermaid" : "plantuml"); scratch_end(&scratch); return; }
		text = diagram_to_dsl(scratch.arena, app->clip_diagram);
	} else if(format == TEXT_FORMAT_UNKNOWN) {
		app_message(app, "the clipboard holds text, not a diagram (design-it, mermaid or plantuml)");
		scratch_end(&scratch);
		return;
	}

	b8 *was_node = PushArrayZero(scratch.arena, b8, DIAGRAM_MAX_NODES);
	b8 *was_edge = PushArrayZero(scratch.arena, b8, DIAGRAM_MAX_EDGES);
	for(u32 i = 0; i < dia->node_count; ++i) was_node[i] = (b8)dia->nodes[i].alive;
	for(u32 i = 0; i < dia->edge_count; ++i) was_edge[i] = (b8)dia->edges[i].alive;
	diagram_push_undo(dia);
	if(!diagram_append_dsl(dia, text)) { app_message(app, "nothing pasted"); scratch_end(&scratch); return; }

	// NOTE: centre the pasted nodes on the mouse (p), or leave them where they were (P)
	f32 x0 = 1e9f, y0 = 1e9f, x1 = -1e9f, y1 = -1e9f;
	u32 count = 0;
	for(u32 i = 0; i < dia->node_count; ++i) {
		DiagramNode *n = &dia->nodes[i];
		if(!n->alive || was_node[i]) continue;
		x0 = Min(x0, n->x); y0 = Min(y0, n->y); x1 = Max(x1, n->x + n->w); y1 = Max(y1, n->y + n->h);
		++count;
	}
	f32 dx = at_mouse ? roundf(wx - (x0 + x1) * 0.5f) : 0.0f;
	f32 dy = at_mouse ? roundf(wy - (y0 + y1) * 0.5f) : 0.0f;
	diagram_clear_selection(dia);
	app->active_node = -1;
	app->active_edge = -1;
	for(u32 i = 0; i < dia->node_count; ++i) {
		DiagramNode *n = &dia->nodes[i];
		if(!n->alive || was_node[i]) continue;
		n->x += dx;
		n->y += dy;
		n->selected = true;
		if(app->active_node < 0 && n->parent < 0) app->active_node = (s32)i;
	}
	for(u32 i = 0; i < dia->edge_count; ++i) {
		DiagramEdge *e = &dia->edges[i];
		if(!e->alive || was_edge[i]) continue;
		e->msg_y += dy;
		for(u32 w = 0; w < e->waypoint_count; ++w) { e->waypoints[w].x += dx; e->waypoints[w].y += dy; }
	}
	diagram_fit_containers(dia);
	diagram_fit_lifelines(dia);
	++dia->version;
	app_message(app, "pasted %u node(s)%s", count, format == TEXT_FORMAT_MERMAID ? " from mermaid" : (format == TEXT_FORMAT_PLANTUML ? " from plantuml" : ""));
	scratch_end(&scratch);
}

//- documentation editor

internal String8 doc_target_text(App *app, u32 kind, s32 index)
{
	Diagram *dia = app->diagram;
	if(kind == DOC_TARGET_NODE && index >= 0 && index < (s32)dia->node_count && dia->nodes[index].alive) return diagram_doc(dia, dia->nodes[index].doc_off, dia->nodes[index].doc_len);
	if(kind == DOC_TARGET_EDGE && index >= 0 && index < (s32)dia->edge_count && dia->edges[index].alive) return diagram_doc(dia, dia->edges[index].doc_off, dia->edges[index].doc_len);
	if(kind == DOC_TARGET_DIAGRAM) return diagram_doc(dia, dia->doc_off, dia->doc_len);
	return str8_zero();
}

internal String8 doc_target_name(App *app, Arena *arena, u32 kind, s32 index)
{
	Diagram *dia = app->diagram;
	if(kind == DOC_TARGET_NODE && index >= 0 && dia->nodes[index].alive) return ui_format(arena, "%s  [%s]", dia->nodes[index].name, node_kind_name(dia->nodes[index].kind));
	if(kind == DOC_TARGET_EDGE && index >= 0 && dia->edges[index].alive) {
		DiagramEdge *e = &dia->edges[index];
		return ui_format(arena, "%s %s %s%s%s", dia->nodes[e->src].name, edge_kind_symbol(e->kind), dia->nodes[e->dst].name, e->label[0] ? " : " : "", e->label);
	}
	return ui_format(arena, "diagram: %s", dia->title);
}

internal void doc_edit_open(App *app, DocTargetKind kind, s32 index)
{
	Diagram   *dia = app->diagram;
	DocEditor *ed  = &app->doc;
	if(!ed->text) ed->text = PushArray(app->arena, char, DOC_EDIT_CAP);
	String8 doc = doc_target_text(app, kind, index);
	u32 n = (u32)Min(doc.size, (u64)DOC_EDIT_CAP - 1);
	MemCpy(ed->text, doc.data, n);
	ed->text[n]       = 0;
	ed->size          = n;
	ed->cursor        = n;
	ed->kind          = kind;
	ed->index         = index;
	ed->target_id     = (kind == DOC_TARGET_NODE) ? dia->nodes[index].id : ((kind == DOC_TARGET_EDGE) ? dia->edges[index].id : 0);
	ed->scroll        = 0;
	ed->changed       = false;
	ed->discard_armed = false;
	ed->want_x        = -1.0f;
	app->overlay        = UI_OVERLAY_DOC;
	app->overlay_opened = true;
}

internal b32 doc_target_valid(App *app)
{
	Diagram   *dia = app->diagram;
	DocEditor *ed  = &app->doc;
	if(ed->kind == DOC_TARGET_NODE) return ed->index >= 0 && ed->index < (s32)dia->node_count && dia->nodes[ed->index].alive && dia->nodes[ed->index].id == ed->target_id;
	if(ed->kind == DOC_TARGET_EDGE) return ed->index >= 0 && ed->index < (s32)dia->edge_count && dia->edges[ed->index].alive && dia->edges[ed->index].id == ed->target_id;
	return true;
}

internal void doc_edit_save(App *app)
{
	Diagram   *dia = app->diagram;
	DocEditor *ed  = &app->doc;
	app->overlay = UI_OVERLAY_NONE;
	if(!ed->changed) return;
	if(!doc_target_valid(app)) { app_message(app, "the documented element is gone (undo?), text not saved"); return; }
	diagram_push_undo(dia);
	u32 *off = &dia->doc_off, *len = &dia->doc_len;
	if(ed->kind == DOC_TARGET_NODE) { off = &dia->nodes[ed->index].doc_off; len = &dia->nodes[ed->index].doc_len; }
	if(ed->kind == DOC_TARGET_EDGE) { off = &dia->edges[ed->index].doc_off; len = &dia->edges[ed->index].doc_len; }
	if(diagram_set_doc(dia, off, len, ed->text, ed->size)) app_message(app, ed->size ? "documentation saved (%u bytes)" : "documentation cleared", ed->size);
	else app_message(app, "documentation is full (%u MiB per diagram), not saved", (u32)(DIAGRAM_TEXT_CAP >> 20));
}

// NOTE: soft wrapped visual lines: starts[i] .. starts[i] + lengths[i], at most cols characters
typedef struct DocLines DocLines;
struct DocLines {
	u32 *start;
	u32 *length;
	u32  count;
};

internal u32 utf8_char_count(const char *s, u32 n)
{
	u32 count = 0;
	for(u32 i = 0; i < n; ++i) if(((u8)s[i] & 0xC0) != 0x80) ++count;
	return count;
}

internal void doc_wrap(Arena *arena, const char *text, u32 size, u32 cols, DocLines *out)
{
	cols = Max(cols, 8u);
	u32 cap = size / 4 + 2;
	for(u32 i = 0; i < size; ++i) cap += (text[i] == '\n');
	cap += size / cols + 1;
	out->start  = PushArray(arena, u32, cap);
	out->length = PushArray(arena, u32, cap);
	out->count  = 0;
	u32 line = 0;
	while(line <= size && out->count < cap) {
		u32 end = line;
		while(end < size && text[end] != '\n') ++end;
		// break the paragraph [line, end) into rows of cols chars, at a space when there is one
		u32 at = line;
		do {
			u32 take = at, chars = 0, last_space = 0;
			while(take < end && chars < cols) {
				if(text[take] == ' ') last_space = take + 1;
				++take;
				while(take < end && ((u8)text[take] & 0xC0) == 0x80) ++take;
				++chars;
			}
			if(take < end && last_space > at) take = last_space;
			out->start[out->count]  = at;
			out->length[out->count] = take - at;
			++out->count;
			at = take;
		} while(at < end && out->count < cap);
		line = end + 1;
		if(end >= size) break;
	}
	if(out->count == 0) { out->start[0] = 0; out->length[0] = 0; out->count = 1; }
}

internal u32 doc_line_of(DocLines *lines, u32 cursor)
{
	u32 best = 0;
	for(u32 i = 0; i < lines->count; ++i) {
		if(lines->start[i] <= cursor) best = i;
		else break;
	}
	return best;
}

internal u32 doc_offset_at_col(const char *text, DocLines *lines, u32 line, u32 col)
{
	u32 at = lines->start[line], end = at + lines->length[line];
	// a wrapped row ends at its last char, the cursor may sit after it only on the final row
	b32 hard_end = (line + 1 >= lines->count) || (end < 0xFFFFFFFF && text[end] == '\n');
	for(u32 c = 0; c < col && at < end; ++c) {
		++at;
		while(at < end && ((u8)text[at] & 0xC0) == 0x80) ++at;
	}
	if(!hard_end && at == end && end > lines->start[line]) {
		--at;
		while(at > lines->start[line] && ((u8)text[at] & 0xC0) == 0x80) --at;
	}
	return at;
}

internal void doc_insert(DocEditor *ed, const char *s, u32 n)
{
	if(ed->size + n >= DOC_EDIT_CAP) n = DOC_EDIT_CAP - 1 - ed->size;
	if(!n) return;
	memmove(ed->text + ed->cursor + n, ed->text + ed->cursor, ed->size - ed->cursor);
	MemCpy(ed->text + ed->cursor, s, n);
	ed->size   += n;
	ed->cursor += n;
	ed->text[ed->size] = 0;
	ed->changed = true;
	ed->discard_armed = false;
}

internal void doc_delete_range(DocEditor *ed, u32 from, u32 to)
{
	if(to <= from) return;
	memmove(ed->text + from, ed->text + to, ed->size - to);
	ed->size -= (to - from);
	ed->text[ed->size] = 0;
	ed->cursor = from;
	ed->changed = true;
	ed->discard_armed = false;
}

internal u32 doc_prev_char(DocEditor *ed, u32 at)
{
	if(at == 0) return 0;
	--at;
	while(at > 0 && ((u8)ed->text[at] & 0xC0) == 0x80) --at;
	return at;
}

internal u32 doc_next_char(DocEditor *ed, u32 at)
{
	if(at >= ed->size) return ed->size;
	++at;
	while(at < ed->size && ((u8)ed->text[at] & 0xC0) == 0x80) ++at;
	return at;
}

global_variable u32 doc_edit_cols = 72; // last frame's wrap width, the keys move by visual rows

internal void doc_edit_keys(App *app, PlatformInput *input)
{
	DocEditor   *ed      = &app->doc;
	ScratchArena scratch = ScratchGet();
	DocLines     lines;
	doc_wrap(scratch.arena, ed->text, ed->size, doc_edit_cols, &lines);
	for(u32 index = 0; index < input->key_count && app->overlay == UI_OVERLAY_DOC; ++index) {
		PlatformKeyEvent *event = &input->keys[index];
		u32 sym   = event->keysym;
		b32 ctrl  = (event->mods & PLATFORM_MOD_CTRL) != 0;
		b32 moved_vertically = false;
		if(sym == XKB_KEY_Escape) {
			if(ed->changed && !ed->discard_armed) {
				ed->discard_armed = true;
				app_message(app, "unsaved documentation: Esc again throws it away, Ctrl+S saves");
			} else {
				app->overlay = UI_OVERLAY_NONE;
				if(ed->changed) app_message(app, "documentation edit discarded");
			}
			continue;
		}
		if((ctrl && sym == XKB_KEY_s) || (ctrl && (sym == XKB_KEY_Return || sym == XKB_KEY_KP_Enter))) { doc_edit_save(app); continue; }
		if(ctrl && sym == XKB_KEY_v && app->window) {
			String8 paste = PlatformClipboardGet(app->window, scratch.arena);
			// NOTE: \r\n from other tools becomes \n
			for(u64 i = 0; i < paste.size; ++i) if(paste.data[i] != '\r') doc_insert(ed, (const char *)paste.data + i, 1);
		} else if(ctrl && sym == XKB_KEY_c && app->window) {
			PlatformClipboardSet(app->window, ed->text, ed->size);
			app_message(app, "copied the documentation text");
		} else if(sym == XKB_KEY_Return || sym == XKB_KEY_KP_Enter) {
			doc_insert(ed, "\n", 1);
		} else if(sym == XKB_KEY_Tab) {
			doc_insert(ed, "  ", 2);
		} else if(sym == XKB_KEY_BackSpace) {
			if(ctrl) {
				u32 at = ed->cursor;
				while(at > 0 && ed->text[at - 1] == ' ') --at;
				while(at > 0 && ed->text[at - 1] != ' ' && ed->text[at - 1] != '\n') --at;
				doc_delete_range(ed, at, ed->cursor);
			} else {
				doc_delete_range(ed, doc_prev_char(ed, ed->cursor), ed->cursor);
			}
		} else if(sym == XKB_KEY_Delete) {
			doc_delete_range(ed, ed->cursor, doc_next_char(ed, ed->cursor));
		} else if(sym == XKB_KEY_Left) {
			ed->cursor = doc_prev_char(ed, ed->cursor);
		} else if(sym == XKB_KEY_Right) {
			ed->cursor = doc_next_char(ed, ed->cursor);
		} else if(sym == XKB_KEY_Home) {
			ed->cursor = ctrl ? 0 : lines.start[doc_line_of(&lines, ed->cursor)];
		} else if(sym == XKB_KEY_End) {
			if(ctrl) ed->cursor = ed->size;
			else { u32 l = doc_line_of(&lines, ed->cursor); ed->cursor = doc_offset_at_col(ed->text, &lines, l, 0xFFFF); }
		} else if(sym == XKB_KEY_Up || sym == XKB_KEY_Down || sym == XKB_KEY_Page_Up || sym == XKB_KEY_Page_Down) {
			u32 l   = doc_line_of(&lines, ed->cursor);
			u32 col = utf8_char_count(ed->text + lines.start[l], ed->cursor - lines.start[l]);
			if(ed->want_x < 0) ed->want_x = (f32)col;
			s32 step = (sym == XKB_KEY_Up) ? -1 : (sym == XKB_KEY_Down ? 1 : (sym == XKB_KEY_Page_Up ? -12 : 12));
			s32 target = Clamp((s32)l + step, 0, (s32)lines.count - 1);
			ed->cursor = doc_offset_at_col(ed->text, &lines, (u32)target, (u32)ed->want_x);
			moved_vertically = true;
		}
		if(!moved_vertically) ed->want_x = -1.0f;
		doc_wrap(scratch.arena, ed->text, ed->size, doc_edit_cols, &lines);
	}
	if(app->overlay == UI_OVERLAY_DOC && !app->overlay_opened && input->text_size > 0) {
		b32 ctrl = (input->mods & PLATFORM_MOD_CTRL) != 0;
		if(!ctrl) doc_insert(ed, (const char *)input->text, input->text_size);
	}
	scratch_end(&scratch);
}

internal void doc_edit_draw(App *app, PlatformInput *input, Rect window)
{
	DrawList    *d       = &app->draw;
	FontSystem  *fonts   = &app->fonts;
	DocEditor   *ed      = &app->doc;
	ScratchArena scratch = ScratchGet();

	f32  w   = Min(Max(rect_w(window) * 0.62f, 420.0f), rect_w(window) - 40.0f);
	f32  h   = Min(Max(rect_h(window) * 0.66f, 260.0f), rect_h(window) - 40.0f);
	Rect box = {window.x0 + (rect_w(window) - w) * 0.5f, window.y0 + (rect_h(window) - h) * 0.42f, 0, 0};
	box.x1 = box.x0 + w;
	box.y1 = box.y0 + h;
	draw_rect(d, window, 0x00000066u, 0);
	draw_shadow(d, box, 0x000000AAu, 0, 18);
	draw_rect(d, box, COLOR_TAB_ACTIVE, 0);
	draw_border(d, box, COLOR_FOCUS_EDGE, 0, 1);

	// title row
	f32 th = 34.0f;
	Rect title = {box.x0, box.y0, box.x1, box.y0 + th};
	draw_rect(d, title, COLOR_HEADER, 0);
	String8 name = doc_target_name(app, scratch.arena, ed->kind, ed->index);
	f32 tb = ui_baseline(app, FONT_SEMIBOLD, UI_FONT, title.y0, th);
	f32 lw = draw_text(d, fonts, FONT_MONO, UI_FONT_SMALL, title.x0 + 12, tb, str8("doc "), COLOR_TEXT_DIM);
	draw_text_fit(d, fonts, FONT_SEMIBOLD, UI_FONT, title.x0 + 12 + lw, tb, rect_w(title) - lw - 260, name, COLOR_TEXT);
	String8 keys = str8((char *)"Ctrl+S save   Esc cancel   Ctrl+V paste");
	f32 kw = font_measure(fonts, FONT_MONO, UI_FONT_SMALL, keys);
	draw_text(d, fonts, FONT_MONO, UI_FONT_SMALL, title.x1 - kw - 12, tb, keys, ed->changed ? COLOR_ACCENT : COLOR_TEXT_FAINT);

	// text, soft wrapped at the box width (mono font: every char is as wide as an 'M')
	Rect body  = {box.x0 + 14, title.y1 + 10, box.x1 - 14, box.y1 - 10};
	f32  fsize = UI_FONT;
	f32  cw    = Max(font_measure(fonts, FONT_MONO, fsize, str8((char *)"M")), 1.0f);
	f32  lh    = Max(UI_ROW_H, fsize * 1.5f);
	doc_edit_cols = (u32)Max(rect_w(body) / cw, 8.0f);
	DocLines lines;
	doc_wrap(scratch.arena, ed->text, ed->size, doc_edit_cols, &lines);
	u32 visible = (u32)Max(rect_h(body) / lh, 1.0f);
	u32 cur_line = doc_line_of(&lines, ed->cursor);
	if((f32)cur_line < ed->scroll) ed->scroll = (f32)cur_line;
	if((f32)cur_line >= ed->scroll + (f32)visible) ed->scroll = (f32)(cur_line - visible + 1);
	if(ui_hovered(input, body) && input->scroll_y != 0.0f) ed->scroll = Clamp(ed->scroll + input->scroll_y * 3.0f, 0.0f, (f32)Max((s32)lines.count - (s32)visible, 0));
	u32 first = (u32)ed->scroll;

	draw_clip_push(d, body);
	if(ed->size == 0) {
		draw_text(d, fonts, FONT_REGULAR, UI_FONT_SMALL, body.x0, ui_baseline(app, FONT_REGULAR, UI_FONT_SMALL, body.y0 + lh, lh),
		          str8((char *)"What is it, why does it exist, what must stay true? Plain text, as many lines as you like."), COLOR_TEXT_FAINT);
	}
	for(u32 i = first; i < lines.count && i < first + visible + 1; ++i) {
		f32 y = body.y0 + (f32)(i - first) * lh;
		draw_text(d, fonts, FONT_MONO, fsize, body.x0, ui_baseline(app, FONT_MONO, fsize, y, lh), ToString8Size((u8 *)ed->text + lines.start[i], lines.length[i]), COLOR_TEXT);
		if(i == cur_line) {
			u32 col = utf8_char_count(ed->text + lines.start[i], ed->cursor - lines.start[i]);
			f32 cx  = body.x0 + (f32)col * cw;
			draw_rect(d, Rect{cx, y + 3, cx + 2, y + lh - 3}, COLOR_ACCENT, 0);
		}
	}
	draw_clip_pop(d);

	// click: put the cursor there
	if(ButtonPressed(input->mouse[0]) && ui_hovered(input, body)) {
		u32 line = first + (u32)Max((input->mouse_y - body.y0) / lh, 0.0f);
		line = Min(line, lines.count - 1);
		u32 col = (u32)Max((input->mouse_x - body.x0) / cw + 0.5f, 0.0f);
		ed->cursor = doc_offset_at_col(ed->text, &lines, line, col);
	}
	f32 sb = ui_baseline(app, FONT_MONO, UI_FONT_SMALL, box.y1 - 22, 20);
	String8 info = ui_format(scratch.arena, "%u lines  %u bytes%s", lines.count, ed->size, ed->changed ? "  modified" : "");
	f32 iw = font_measure(fonts, FONT_MONO, UI_FONT_SMALL, info);
	draw_text(d, fonts, FONT_MONO, UI_FONT_SMALL, box.x1 - iw - 14, sb, info, COLOR_TEXT_FAINT);
	scratch_end(&scratch);
}

//- docs view (a table: the target's name, link, repo, then its doc text wrapped to the panel)

internal void docs_target(App *app, u32 *kind, s32 *index)
{
	Diagram *dia = app->diagram;
	if(app->active_node >= 0 && app->active_node < (s32)dia->node_count && dia->nodes[app->active_node].alive) { *kind = DOC_TARGET_NODE; *index = app->active_node; return; }
	if(app->active_edge >= 0 && app->active_edge < (s32)dia->edge_count && dia->edges[app->active_edge].alive) { *kind = DOC_TARGET_EDGE; *index = app->active_edge; return; }
	*kind  = DOC_TARGET_DIAGRAM;
	*index = -1;
}

internal f32 view_panel_width(App *app, View *view)
{
	s32 vi = (s32)(view - app->layout.views);
	for(s32 i = 0; i < UI_MAX_PANELS; ++i) {
		Panel *p = &app->layout.panels[i];
		if(p->kind == PANEL_LEAF && panel_active_view(&app->layout, i) == vi) return rect_w(p->rect);
	}
	return 480.0f;
}

//- png export: the diagram drawn in window sized tiles, read back and stitched

internal Rect diagram_export_bounds(Diagram *d)
{
	Rect b = diagram_bounds(d);
	EdgePath ep;
	for(u32 i = 0; i < d->edge_count; ++i) {
		if(!d->edges[i].alive || diagram_edge_hidden(d, (s32)i) || !diagram_edge_route(d, (s32)i, &ep)) continue;
		b.x0 = Min(b.x0, ep.bounds.x0 + 16.0f); b.y0 = Min(b.y0, ep.bounds.y0 + 16.0f);
		b.x1 = Max(b.x1, ep.bounds.x1 - 16.0f); b.y1 = Max(b.y1, ep.bounds.y1 - 16.0f);
		// labels reach past the path
		if(d->edges[i].label[0]) {
			f32 lw = (f32)strlen(d->edges[i].label) * 4.5f + 12.0f;
			b.x0 = Min(b.x0, ep.label_pos.x - lw); b.x1 = Max(b.x1, ep.label_pos.x + lw);
			b.y0 = Min(b.y0, ep.label_pos.y - 14.0f); b.y1 = Max(b.y1, ep.label_pos.y + 14.0f);
		}
	}
	f32 pad = 40.0f;
	return Rect{floorf(b.x0 - pad), floorf(b.y0 - pad), ceilf(b.x1 + pad), ceilf(b.y1 + pad)};
}

internal void png_export_begin(App *app, const char *path, f32 scale)
{
	PngExport *png = &app->png;
	if(png->state != PNG_IDLE) { app_message(app, "a png export is already running"); return; }
	if(!app->renderer.can_capture) { app_message(app, "this gpu / compositor can't read frames back, png export unavailable (try :export x.svg)"); return; }
	if(scale <= 0.0f) scale = 2.0f;
	Rect world = diagram_export_bounds(app->diagram);
	f32  ww = rect_w(world), wh = rect_h(world);
	// NOTE: 16k pixels a side keeps the buffer under 800 MB and every viewer happy
	f32 max_side = 16384.0f;
	if(ww * scale > max_side) scale = max_side / ww;
	if(wh * scale > max_side) scale = max_side / wh;
	scale = Max(scale, 0.05f);
	u32 width  = (u32)ceilf(ww * scale);
	u32 height = (u32)ceilf(wh * scale);
	u32 tw = app->renderer.extent.width, th = app->renderer.extent.height;
	if(!width || !height || tw < 64 || th < 64) { app_message(app, "nothing to export"); return; }
	png->rgb = (u8 *)malloc((u64)width * height * 3);
	if(!png->rgb) { app_message(app, "png too large (%ux%u)", width, height); return; }
	snprintf(png->path, sizeof(png->path), "%s", path);
	png->scale   = scale;
	png->world   = world;
	png->width   = width;
	png->height  = height;
	png->tile_w  = tw;
	png->tile_h  = th;
	png->tiles_x = (width + tw - 1) / tw;
	png->tiles_y = (height + th - 1) / th;
	png->tile    = 0;
	png->drawn   = false;
	png->state   = PNG_TILES;
	app_message(app, "exporting %s: %ux%u px in %u tile(s)...", path, width, height, png->tiles_x * png->tiles_y);
}

internal void png_export_finish(App *app, b32 ok, const char *why)
{
	PngExport *png = &app->png;
	if(ok) ok = png_write_rgb(png->path, png->rgb, png->width, png->height, (u32)(96.0f * png->scale + 0.5f));
	if(ok) snprintf(png->result, sizeof(png->result), "exported PNG -> %s (%ux%u)", png->path, png->width, png->height);
	else   snprintf(png->result, sizeof(png->result), "failed to export %s%s%s", png->path, why ? ": " : "", why ? why : "");
	app_message(app, "%s", png->result);
	free(png->rgb);
	png->rgb   = NULL;
	png->state = PNG_IDLE;
	if(png->quit_after) {
		printf("%s\n", png->result);
		app->quit = true;
	}
}

internal void draw_canvas_layers(App *app, View *view, Rect rect);

// NOTE: called by ui_frame instead of the normal ui while an export runs
internal void png_export_frame(App *app)
{
	PngExport *png = &app->png;
	u32 tx = png->tile % png->tiles_x, ty = png->tile / png->tiles_x;
	f32 s  = png->scale;
	if(app->renderer.extent.width != png->tile_w || app->renderer.extent.height != png->tile_h) {
		png_export_finish(app, false, "the window was resized during the export");
		return;
	}
	f32 lw = (f32)png->tile_w / s, lh = (f32)png->tile_h / s; // the tile in world units
	View view = {};
	view.kind      = VIEW_CANVAS;
	view.cam_zoom  = view.cam_target_zoom = 1.0f;
	view.cam_x     = view.cam_target_x = png->world.x0 + (f32)tx * lw + lw * 0.5f;
	view.cam_y     = view.cam_target_y = png->world.y0 + (f32)ty * lh + lh * 0.5f;
	view.cam_init  = true;
	Rect rect = {0, 0, lw, lh};

	font_set_scale(&app->fonts, s);
	draw_begin(&app->draw, app->renderer.extent.width, app->renderer.extent.height, s);
	app->draw.rounding   = 1.0f;
	app->draw.text_gamma = app->settings.text_gamma;
	draw_rect(&app->draw, rect, COLOR_BG, 0);
	app->exporting = true;
	draw_canvas_layers(app, &view, rect);
	app->exporting = false;
	png->drawn = true;
	app->renderer.capture_request = true;
	app->animating = true;
}

internal void png_export_collect(App *app)
{
	PngExport      *png = &app->png;
	VulkanRenderer *r   = &app->renderer;
	if(png->state != PNG_TILES || !png->drawn) return;
	if(!r->capture_ready) return; // not presented this frame: the tile gets drawn again
	r->capture_ready = false;
	png->drawn       = false;
	u32 tx = png->tile % png->tiles_x, ty = png->tile / png->tiles_x;
	u32 x0 = tx * png->tile_w, y0 = ty * png->tile_h;
	u32 cw = Min(png->tile_w, png->width - x0), ch = Min(png->tile_h, png->height - y0);
	const u8 *src = (const u8 *)r->readback_mapped;
	for(u32 y = 0; y < ch && y < r->capture_height; ++y) {
		const u8 *row = src + (u64)y * r->capture_width * 4;
		u8       *dst = png->rgb + ((u64)(y0 + y) * png->width + x0) * 3;
		for(u32 x = 0; x < cw && x < r->capture_width; ++x) {
			const u8 *p = row + (u64)x * 4;
			dst[x * 3 + 0] = r->capture_bgra ? p[2] : p[0];
			dst[x * 3 + 1] = p[1];
			dst[x * 3 + 2] = r->capture_bgra ? p[0] : p[2];
		}
	}
	if(++png->tile >= png->tiles_x * png->tiles_y) png_export_finish(app, true, NULL);
}