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
|
#include "base/base_include.h"
#if PLATFORM_LINUX
#include <sys/prctl.h>
#include <sys/inotify.h>
#include <dlfcn.h>
#elif PLATFORM_APPLE
#include <dlfcn.h>
#include <sys/event.h>
#elif PLATFORM_WINDOWS
#include <timeapi.h>
#endif
#include "core_include.h"
#include "platform_include.h"
#include "render_include.h"
#include "diagram_include.h"
#include "app.h"
#include "app_settings.h"
#include "app_ui.h"
//- the manual
// NOTE: help.txt at the repo root, baked in (the help view, :help, --manual)
EMBED_FILE(design_help_text, "help.txt");
//- args and paths
internal b32 arg_value(const char *arg, const char *name, const char **value)
{
u64 length = strlen(name);
if(strncmp(arg, name, length) != 0) return false;
if(arg[length] == 0) { *value = NULL; return true; }
if(arg[length] == '=') { *value = arg + length + 1; return true; }
return false;
}
internal void app_parse_args(AppArgs *args, int argc, char **argv)
{
MemSetZero(args, sizeof(*args));
snprintf(args->anchor, sizeof(args->anchor), "center");
for(int index = 1; index < argc; ++index) {
const char *value = NULL;
const char *arg = argv[index];
if(arg_value(arg, "--layer", &value)) {
args->layer = true;
} else if(arg_value(arg, "--anchor", &value) && value) {
snprintf(args->anchor, sizeof(args->anchor), "%s", value);
args->layer = true;
} else if(arg_value(arg, "--screenshot", &value) && value) {
snprintf(args->screenshot, sizeof(args->screenshot), "%s", value);
} else if(arg_value(arg, "--open", &value) && value) {
snprintf(args->open_view, sizeof(args->open_view), "%s", value);
} else if(arg_value(arg, "--template", &value) && value) {
snprintf(args->template_name, sizeof(args->template_name), "%s", value);
} else if(arg_value(arg, "--scan", &value) && value) {
snprintf(args->scan_path, sizeof(args->scan_path), "%s", value);
} else if(arg_value(arg, "--export-svg", &value) && value) {
snprintf(args->export_svg, sizeof(args->export_svg), "%s", value);
} else if(arg_value(arg, "--export-style", &value) && value) {
snprintf(args->export_arg, sizeof(args->export_arg), "%s", value);
} else if(arg_value(arg, "--export", &value) && value) {
snprintf(args->export_any, sizeof(args->export_any), "%s", value);
} else if(arg_value(arg, "--set", &value) && value) {
if(args->set_count < ArrayCount(args->sets)) args->sets[args->set_count++] = (char *)value;
} else if(arg_value(arg, "--manual", &value)) {
fwrite(design_help_text, 1, (size_t)(design_help_text_end - design_help_text), stdout);
exit(0);
} else if(arg[0] != '-') {
snprintf(args->open_file, sizeof(args->open_file), "%s", arg);
} else {
printf("usage: design-it [file.dit|file.dit.txt] [options]\n"
" --template=<name> arch | ecs | microservices | compiler | uml | stress\n"
" --scan=<path> scan C/C++ headers into a live interactive UML diagram\n"
" --export-svg=<out> export diagram to themed vector SVG and exit\n"
" --export=<out> export by extension and exit: .svg .mmd .puml .dit.txt .dit\n"
" (.png renders in a window: it needs a display)\n"
" --export-style=<s> mermaid: class | flowchart | sequence, png: scale (2 = 2x)\n"
" --layer open as an overlay window (no frame, always on top)\n"
" --anchor=<edge> overlay anchor (implies --layer)\n"
" --open=<view> focus or open a view at startup (canvas, outline, inspector, frame, ...)\n"
" --set=\"name=value\" override any setting (e.g. --set=\"color scheme=nord\")\n"
" --screenshot=<ppm> render a frame to PPM and quit\n"
" --manual print the full user manual (also: F1 or :help in the app)\n"
"\n"
"drag a .dit / .dit.txt onto the window to open it, a folder to scan it.\n");
OSExit(0);
exit(0);
}
}
}
internal void make_directory(const char *path)
{
#if PLATFORM_WINDOWS
WCHAR wide[MAX_PATH * 2];
win32_utf8_to_wide(path, -1, wide, ArrayCount(wide));
CreateDirectoryW(wide, NULL);
#else
mkdir(path, 0755);
#endif
}
internal void make_directories(const char *path)
{
char tmp[1024];
snprintf(tmp, sizeof(tmp), "%s", path);
for(char *p = tmp + 1; *p; ++p) {
if(*p == '/' || *p == '\\') {
char separator = *p;
// NOTE: "C:" on its own is not a directory to create
if(p[-1] != ':') {
*p = 0;
make_directory(tmp);
*p = separator;
}
}
}
make_directory(tmp);
}
internal String8 app_data_dir(Arena *arena)
{
char buffer[1024];
#if PLATFORM_WINDOWS
// NOTE: %APPDATA%\design-it (roaming), the utf-16 variable so non ascii user names work
WCHAR wide[MAX_PATH * 2];
DWORD length = GetEnvironmentVariableW(L"APPDATA", wide, ArrayCount(wide));
char appdata[MAX_PATH * 4];
if(length > 0 && length < ArrayCount(wide)) win32_wide_to_utf8(wide, (s64)length, appdata, sizeof(appdata));
else snprintf(appdata, sizeof(appdata), ".");
for(char *at = appdata; *at; ++at) if(*at == '\\') *at = '/';
snprintf(buffer, sizeof(buffer), "%s/design-it", appdata);
#elif PLATFORM_APPLE
const char *home = getenv("HOME");
snprintf(buffer, sizeof(buffer), "%s/Library/Application Support/design-it", home ? home : "/tmp");
#else
const char *xdg = getenv("XDG_DATA_HOME");
const char *home = getenv("HOME");
if(xdg && xdg[0]) snprintf(buffer, sizeof(buffer), "%s/design-it", xdg);
else snprintf(buffer, sizeof(buffer), "%s/.local/share/design-it", home ? home : "/tmp");
#endif
make_directories(buffer);
String8 view = str8(buffer);
String8 copy = PushString8(arena, view.size + 1);
MemCpy(copy.data, view.data, view.size);
copy.size = view.size;
return copy;
}
#include "app_settings.cpp"
#include "app_ui.cpp"
//- heap profiling (malloc interposer in host binary only, identical to mp3_player)
// NOTE: glibc only. the ucrt has no __libc_* entry points to forward to, on windows the heap
// counters in the profiler just stay at zero.
#if !defined(DESIGN_UI_DLL) || !DESIGN_UI_DLL
#if PLATFORM_LINUX
extern "C" {
void *__libc_malloc(size_t size);
void *__libc_calloc(size_t count, size_t size);
void *__libc_realloc(void *pointer, size_t size);
void *__libc_memalign(size_t alignment, size_t size);
void __libc_free(void *pointer);
}
internal inline void profile_heap_alloc(void *pointer)
{
if(!pointer) return;
Profiler *profiler = &profiler_instance;
u64 size = malloc_usable_size(pointer);
AtomicAddRelaxed(&profiler->malloc_count, 1ull);
AtomicAddRelaxed(&profiler->heap_total, size);
s64 live = AtomicAddRelaxed(&profiler->heap_live, (s64)size);
if((u64)live > AtomicLoadRelaxed(&profiler->heap_peak)) AtomicStoreRelaxed(&profiler->heap_peak, (u64)live);
}
internal inline void profile_heap_free(void *pointer)
{
if(!pointer) return;
Profiler *profiler = &profiler_instance;
AtomicAddRelaxed(&profiler->free_count, 1ull);
AtomicAddRelaxed(&profiler->heap_live, -(s64)malloc_usable_size(pointer));
}
extern "C" void *malloc(size_t size) { void *p = __libc_malloc(size); profile_heap_alloc(p); return p; }
extern "C" void *calloc(size_t count, size_t size) { void *p = __libc_calloc(count, size); profile_heap_alloc(p); return p; }
extern "C" void free(void *pointer) { profile_heap_free(pointer); __libc_free(pointer); }
extern "C" void *realloc(void *pointer, size_t size)
{
profile_heap_free(pointer);
void *p = __libc_realloc(pointer, size);
if(p) profile_heap_alloc(p);
return p;
}
extern "C" void *memalign(size_t alignment, size_t size) { void *p = __libc_memalign(alignment, size); profile_heap_alloc(p); return p; }
extern "C" void *aligned_alloc(size_t alignment, size_t size) { void *p = __libc_memalign(alignment, size); profile_heap_alloc(p); return p; }
extern "C" int posix_memalign(void **out, size_t alignment, size_t size)
{
void *p = __libc_memalign(alignment, size);
if(!p) return ENOMEM;
profile_heap_alloc(p);
*out = p;
return 0;
}
#endif // PLATFORM_LINUX
//- state persistence (tagged chunks: settings + dockable layout)
#define STATE_MAGIC 0x54534944u // "DIST"
#define CHUNK_SETT 0x54544553u
#define CHUNK_LAYO 0x4F59414Cu
internal void app_save_state(App *app)
{
ScratchArena sc = ScratchGet();
char path[1024];
snprintf(path, sizeof(path), Str8Fmt "/state.bin", Str8Arg(app->data_dir));
FILE *f = fopen(path, "wb");
if(!f) { scratch_end(&sc); return; }
u32 magic = STATE_MAGIC;
fwrite(&magic, 4, 1, f);
String8 set_blob = settings_serialize(sc.arena, &app->settings);
u32 hdr[2] = {CHUNK_SETT, (u32)set_blob.size};
fwrite(hdr, 8, 1, f);
fwrite(set_blob.data, 1, set_blob.size, f);
u32 lhdr[2] = {CHUNK_LAYO, (u32)sizeof(Layout)};
fwrite(lhdr, 8, 1, f);
fwrite(&app->layout, sizeof(Layout), 1, f);
fclose(f);
scratch_end(&sc);
}
internal void app_load_state(App *app)
{
ScratchArena sc = ScratchGet();
char path[1024];
snprintf(path, sizeof(path), Str8Fmt "/state.bin", Str8Arg(app->data_dir));
String8 data = FileLoad(sc.arena, str8(path));
if(data.size < 4) { scratch_end(&sc); return; }
u32 magic = 0;
MemCpy(&magic, data.data, 4);
if(magic != STATE_MAGIC) { scratch_end(&sc); return; }
u64 at = 4;
while(at + 8 <= data.size) {
u32 tag = 0, size = 0;
MemCpy(&tag, data.data + at, 4);
MemCpy(&size, data.data + at + 4, 4);
at += 8;
if(at + size > data.size) break;
if(tag == CHUNK_SETT) {
settings_deserialize(&app->settings, ToString8Size(data.data + at, size));
} else if(tag == CHUNK_LAYO && size == sizeof(Layout)) {
Layout loaded;
MemCpy(&loaded, data.data + at, sizeof(Layout));
if(layout_valid(&loaded)) app->layout = loaded;
}
at += size;
}
scratch_end(&sc);
}
//- hot reload (linux: watches build/design_ui.so with inotify, windows: build/design_ui.dll
// with a directory change notification)
typedef struct UiCode UiCode;
struct UiCode {
void *handle;
DesignUiFrame *frame;
int watch_fd; // inotify fd, or the change notification HANDLE on windows
char so_path[512];
char so_dir[512];
char copy_path[512];
#if PLATFORM_WINDOWS
char loaded_copy[512]; // the live copy can't be deleted while it's mapped
FILETIME loaded_time;
#endif
};
#if defined(DESIGN_HOT_RELOAD) && DESIGN_HOT_RELOAD && PLATFORM_WINDOWS
internal b32 ui_code_file_time(const char *path, FILETIME *out)
{
WIN32_FILE_ATTRIBUTE_DATA data;
if(!GetFileAttributesExA(path, GetFileExInfoStandard, &data)) return false;
*out = data.ftLastWriteTime;
return true;
}
internal void ui_code_load(App *app, UiCode *code)
{
FILETIME written = {};
if(!ui_code_file_time(code->so_path, &written)) return;
// NOTE: load a copy, the original stays writable for the next build
char temp[MAX_PATH];
DWORD temp_length = GetTempPathA(sizeof(temp), temp);
if(temp_length == 0 || temp_length >= sizeof(temp)) snprintf(temp, sizeof(temp), "%s\\", code->so_dir);
snprintf(code->copy_path, sizeof(code->copy_path), "%sdesign_ui_live_%lu_%u.dll", temp, GetCurrentProcessId(), app->ui_generation + 1);
if(!CopyFileA(code->so_path, code->copy_path, FALSE)) return; // still being written, the next notification retries
HMODULE h = LoadLibraryA(code->copy_path);
if(!h) {
app_message(app, "reload failed: LoadLibrary error %lu", GetLastError());
DeleteFileA(code->copy_path);
return;
}
u64 *sig = (u64 *)(void *)GetProcAddress(h, DESIGN_UI_SIZE_SYMBOL);
DesignUiFrame *fn = (DesignUiFrame *)(void *)GetProcAddress(h, DESIGN_UI_FRAME_SYMBOL);
if(!sig || *sig != DESIGN_UI_SIGNATURE || !fn) {
FreeLibrary(h);
DeleteFileA(code->copy_path);
code->loaded_time = written; // don't retry this build
app_message(app, "struct layout changed — restart to apply");
return;
}
if(code->handle) {
FreeLibrary((HMODULE)code->handle);
if(code->loaded_copy[0]) DeleteFileA(code->loaded_copy);
}
code->handle = (void *)h;
code->frame = fn;
code->loaded_time = written;
snprintf(code->loaded_copy, sizeof(code->loaded_copy), "%s", code->copy_path);
++app->ui_generation;
app_message(app, "ui reloaded (#%u)", app->ui_generation);
}
internal void ui_code_init(App *app, UiCode *code)
{
char exe[512] = {};
DWORD len = GetModuleFileNameA(NULL, exe, sizeof(exe));
if(len == 0 || len >= sizeof(exe)) return;
char *slash = strrchr(exe, '\\');
if(!slash) return;
*slash = 0;
snprintf(code->so_dir, sizeof(code->so_dir), "%s", exe);
snprintf(code->so_path, sizeof(code->so_path), "%s\\design_ui.dll", exe);
HANDLE watch = FindFirstChangeNotificationA(code->so_dir, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_FILE_NAME);
code->watch_fd = (watch == INVALID_HANDLE_VALUE) ? -1 : (int)(smm)watch;
ui_code_load(app, code);
}
internal b32 ui_code_poll(App *app, UiCode *code)
{
if(code->watch_fd == -1) return false;
HANDLE watch = (HANDLE)(smm)code->watch_fd;
if(WaitForSingleObject(watch, 0) != WAIT_OBJECT_0) return false;
FindNextChangeNotification(watch);
FILETIME written = {};
if(!ui_code_file_time(code->so_path, &written) || CompareFileTime(&written, &code->loaded_time) == 0) return false;
u32 generation = app->ui_generation;
ui_code_load(app, code);
return app->ui_generation != generation;
}
internal void ui_code_shutdown(UiCode *code)
{
if(code->handle) FreeLibrary((HMODULE)code->handle);
if(code->loaded_copy[0]) DeleteFileA(code->loaded_copy);
if(code->watch_fd != -1) FindCloseChangeNotification((HANDLE)(smm)code->watch_fd);
code->handle = NULL;
code->watch_fd = -1;
}
#elif defined(DESIGN_HOT_RELOAD) && DESIGN_HOT_RELOAD && PLATFORM_APPLE
// NOTE: kqueue watching the build directory, its fd goes into the pump like inotify's does
internal void ui_code_load(App *app, UiCode *code)
{
if(access(code->so_path, R_OK) != 0) return;
const char *tmp_dir = getenv("TMPDIR");
if(!tmp_dir || !tmp_dir[0]) tmp_dir = "/tmp";
snprintf(code->copy_path, sizeof(code->copy_path), "%s/design_ui_live_%d_%u.dylib", tmp_dir, (int)getpid(), app->ui_generation + 1);
FILE *in = fopen(code->so_path, "rb");
FILE *out = in ? fopen(code->copy_path, "wb") : NULL;
if(!in || !out) {
if(in) fclose(in);
if(out) fclose(out);
return;
}
u8 buf[32768];
size_t n;
while((n = fread(buf, 1, sizeof(buf), in)) > 0) fwrite(buf, 1, n, out);
fclose(in);
fclose(out);
void *h = dlopen(code->copy_path, RTLD_NOW | RTLD_LOCAL);
unlink(code->copy_path);
if(!h) {
app_message(app, "reload failed: %s", dlerror());
return;
}
u64 *sig = (u64 *)dlsym(h, DESIGN_UI_SIZE_SYMBOL);
DesignUiFrame *fn = (DesignUiFrame *)dlsym(h, DESIGN_UI_FRAME_SYMBOL);
if(!sig || *sig != DESIGN_UI_SIGNATURE || !fn) {
dlclose(h);
app_message(app, "struct layout changed — restart to apply");
return;
}
if(code->handle) dlclose(code->handle);
code->handle = h;
code->frame = fn;
++app->ui_generation;
app_message(app, "ui reloaded (#%u)", app->ui_generation);
}
internal void ui_code_init(App *app, UiCode *code)
{
char exe[512] = {};
uint32_t size = sizeof(exe);
if(_NSGetExecutablePath(exe, &size) != 0) return;
char *slash = strrchr(exe, '/');
if(!slash) return;
*slash = 0;
snprintf(code->so_dir, sizeof(code->so_dir), "%s", exe);
snprintf(code->so_path, sizeof(code->so_path), "%s/design_ui.dylib", exe);
int queue = kqueue();
int dir = open(code->so_dir, O_EVTONLY);
if(queue >= 0 && dir >= 0) {
struct kevent change;
EV_SET(&change, (uintptr_t)dir, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB, 0, NULL);
kevent(queue, &change, 1, NULL, 0, NULL);
code->watch_fd = queue;
}
ui_code_load(app, code);
}
internal b32 ui_code_poll(App *app, UiCode *code)
{
if(code->watch_fd < 0) return false;
struct kevent events[8];
struct timespec zero = {};
int count = kevent(code->watch_fd, NULL, 0, events, 8, &zero);
if(count <= 0) return false;
u32 generation = app->ui_generation;
ui_code_load(app, code);
return app->ui_generation != generation;
}
internal void ui_code_shutdown(UiCode *code) {}
#elif defined(DESIGN_HOT_RELOAD) && DESIGN_HOT_RELOAD
internal void ui_code_load(App *app, UiCode *code)
{
if(access(code->so_path, R_OK) != 0) return;
// copy to unique user-writable path so dlopen always loads fresh code even when installed in /usr/local
const char *tmp_dir = getenv("XDG_RUNTIME_DIR");
if(!tmp_dir || !tmp_dir[0]) tmp_dir = "/tmp";
snprintf(code->copy_path, sizeof(code->copy_path), "%s/design_ui_live_%d_%u.so", tmp_dir, (int)getpid(), app->ui_generation + 1);
FILE *in = fopen(code->so_path, "rb");
FILE *out = in ? fopen(code->copy_path, "wb") : NULL;
if(!in || !out) {
if(in) fclose(in);
if(out) fclose(out);
return;
}
u8 buf[32768];
size_t n;
while((n = fread(buf, 1, sizeof(buf), in)) > 0) fwrite(buf, 1, n, out);
fclose(in);
fclose(out);
void *h = dlopen(code->copy_path, RTLD_NOW | RTLD_LOCAL);
unlink(code->copy_path);
if(!h) {
app_message(app, "reload failed: %s", dlerror());
return;
}
u64 *sig = (u64 *)dlsym(h, DESIGN_UI_SIZE_SYMBOL);
DesignUiFrame *fn = (DesignUiFrame *)dlsym(h, DESIGN_UI_FRAME_SYMBOL);
if(!sig || *sig != DESIGN_UI_SIGNATURE || !fn) {
dlclose(h);
app_message(app, "struct layout changed — restart to apply");
return;
}
if(code->handle) dlclose(code->handle);
code->handle = h;
code->frame = fn;
++app->ui_generation;
app_message(app, "ui reloaded (#%u)", app->ui_generation);
}
internal void ui_code_init(App *app, UiCode *code)
{
char exe[512] = {};
ssize_t len = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
if(len <= 0) return;
exe[len] = 0;
char *slash = strrchr(exe, '/');
if(!slash) return;
*slash = 0;
// Prefer sibling design_ui.so (local build/), else ../lib/design-it/design_ui.so (system install)
char local_so[512];
snprintf(local_so, sizeof(local_so), "%s/design_ui.so", exe);
if(access(local_so, R_OK) == 0) {
snprintf(code->so_dir, sizeof(code->so_dir), "%s", exe);
snprintf(code->so_path, sizeof(code->so_path), "%s", local_so);
} else {
snprintf(code->so_dir, sizeof(code->so_dir), "%s/../lib/design-it", exe);
snprintf(code->so_path, sizeof(code->so_path), "%s/../lib/design-it/design_ui.so", exe);
}
code->watch_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if(code->watch_fd >= 0) {
inotify_add_watch(code->watch_fd, code->so_dir, IN_MOVED_TO | IN_CLOSE_WRITE);
}
ui_code_load(app, code);
}
internal b32 ui_code_poll(App *app, UiCode *code)
{
if(code->watch_fd < 0) return false;
b32 changed = false;
alignas(8) u8 buf[4096];
for(;;) {
ssize_t n = read(code->watch_fd, buf, sizeof(buf));
if(n <= 0) break;
for(ssize_t at = 0; at < n;) {
struct inotify_event *ev = (struct inotify_event *)(buf + at);
if(ev->len && !strcmp(ev->name, "design_ui.so")) changed = true;
at += (ssize_t)(sizeof(*ev) + ev->len);
}
}
if(changed) ui_code_load(app, code);
return changed;
}
internal void ui_code_shutdown(UiCode *code) {}
#endif
//- anchor parser
internal u32 parse_anchor(const char *s)
{
u32 a = 0;
if(strstr(s, "top")) a |= PLATFORM_ANCHOR_TOP;
if(strstr(s, "bottom")) a |= PLATFORM_ANCHOR_BOTTOM;
if(strstr(s, "left")) a |= PLATFORM_ANCHOR_LEFT;
if(strstr(s, "right")) a |= PLATFORM_ANCHOR_RIGHT;
return a;
}
//- live resize
// NOTE: win32 / cocoa call this from inside their modal resize loop, while app_run is blocked in
// the pump. one frame at the new size with the input as it last was (held state, no events).
global_variable UiCode *app_host_ui_code;
global_variable PlatformInput app_host_last_input;
internal void app_live_refresh(void *user)
{
App *app = (App *)user;
if(app->quit || PlatformWindowSuspended(app->window)) return;
if(PlatformWindowTakeResized(app->window) || app->renderer.swapchain_dirty) {
PlatformWindowSize(app->window, &app->width, &app->height, &app->scale);
vk_resize(&app->renderer, app->width * app->scale, app->height * app->scale);
}
if(app->width == 0 || app->height == 0) return;
PlatformInput input = app_host_last_input;
for(u32 index = 0; index < ArrayCount(input.mouse); ++index) input.mouse[index].half_transition_count = 0;
input.key_count = 0;
input.text_size = 0;
input.scroll_x = 0;
input.scroll_y = 0;
input.drop_count = 0;
input.changed = true;
u64 now = time_now_ns();
app->dt = Min((f32)((f64)(now - app->last_frame_ns) / 1e9), 0.1f);
app->last_frame_ns = now;
app->time += app->dt;
app->ui_scale = PlatformWindowUiScale(app->window);
DrawInstance *mapped = vk_frame_begin(&app->renderer);
app->draw.instances = mapped ? mapped : app->draw.own;
if(app_host_ui_code && app_host_ui_code->frame) app_host_ui_code->frame(app, &input, wake_main_fd());
else ui_frame(app, &input);
u32 clear = PlatformWindowIsLayer(app->window) ? 0x0B0B0B00u : app->settings.colors[UI_COLOR_BG];
PlatformWindowRequestFrame(app->window);
if(!vk_render(&app->renderer, &app->draw, &app->fonts, clear)) PlatformWindowCancelFrame(app->window);
}
//- host main loop
internal int app_run(App *app)
{
Arena *arena = app->arena;
app->scratch = tls_scratch_arena;
app->profiler = global_profiler;
app->active_node = -1;
app->active_edge = -1;
app->drag_view = -1;
app->resize_panel = -1;
app->column_drag_view = -1;
app->column_resize_view = -1;
app->canvas_drag_view = -1;
app->canvas_drag_node = -1;
app->canvas_hover_node = -1;
app->canvas_hover_edge = -1;
app->canvas_hover_marker = -1;
app->canvas_drag_edge = -1;
settings_default(&app->settings);
ui_layout_default(&app->layout);
app_load_state(app);
for(u32 i = 0; i < app->args.set_count; ++i) {
settings_set(&app->settings, app->args.sets[i]);
}
app_apply_settings(app);
if(app->args.open_view[0]) {
ViewType vt;
if(view_resolve(app->args.open_view, &vt)) layout_open(&app->layout, (ViewKind)vt.kind, vt.group);
}
// Select first non-container node by default so Inspector is immediately populated
for(u32 i = 0; i < app->diagram->node_count; ++i) {
if(app->diagram->nodes[i].alive && app->diagram->nodes[i].kind != NODE_MODULE) {
app->active_node = (s32)i;
app->diagram->nodes[i].selected = true;
break;
}
}
// Reset canvas fit pending when loading a fresh diagram from CLI
for(u32 i = 0; i < UI_MAX_VIEWS; ++i) {
if(app->layout.views[i].kind == VIEW_CANVAS) app->layout.views[i].cam_fit_pending = true;
}
WindowParams params = {};
params.name = (char *)"design-it";
params.title = (char *)"design-it";
params.width = UI_WIDTH;
params.height = UI_HEIGHT;
params.min_width = UI_MIN_WIDTH;
params.min_height = UI_MIN_HEIGHT;
params.layer = app->args.layer;
params.anchor = parse_anchor(app->args.anchor);
params.margin = 16;
app->window = PlatformWindowOpen(arena, params);
if(!app->window) {
#if PLATFORM_LINUX
platform_show_error("design-it", "Could not open a window: no Wayland compositor and no X11 display found.");
#else
platform_show_error("design-it", "Could not open a window.");
#endif
return 1;
}
PlatformWindowSize(app->window, &app->width, &app->height, &app->scale);
app->ui_scale = PlatformWindowUiScale(app->window);
if(!font_init(arena, &app->fonts)) {
platform_show_error("design-it", "Font initialization failed (FreeType could not load the built in font).");
return 1;
}
draw_init(arena, &app->draw);
profile_arena_register("font run cache", app->fonts.run_arena);
if(!vk_init(&app->renderer, PlatformWindowSurfaceSource(app->window), app->width * app->scale, app->height * app->scale)) {
char message[768];
snprintf(message, sizeof(message), "design-it could not start Vulkan.\n\n%s", vk_loader_error[0] ? vk_loader_error : "vk_init failed");
platform_show_error("design-it", message);
PlatformWindowClose(app->window);
return 1;
}
UiCode ui_code = {};
ui_code.watch_fd = -1;
#if defined(DESIGN_HOT_RELOAD) && DESIGN_HOT_RELOAD
ui_code_init(app, &ui_code);
#endif
app_host_ui_code = &ui_code;
// NOTE: --export=x.png: draw the tiles, write the file, quit
b32 png_cli = app->args.export_any[0] && path_has_extension(app->args.export_any, ".png");
if(!app->message[0]) app_message(app, "F1: help · drop a .dit file onto the window to open it");
PlatformWindowSetRefresh(app->window, app_live_refresh, app);
app->last_frame_ns = time_now_ns();
b32 redraw = true;
u32 frame_count = 0;
u64 last_render_ns = 0;
u64 idle_ns = 0;
Profiler *profiler = app->profiler;
u64 next_frame_ns = 0;
#if PLATFORM_LINUX
prctl(PR_SET_TIMERSLACK, 1000ul, 0, 0, 0);
#elif PLATFORM_WINDOWS
timeBeginPeriod(1); // 1ms scheduler granularity for the ms fallback waits
#endif
u32 fps_count = 0;
u64 fps_window_ns = time_now_ns();
while(!app->quit) {
++frame_count;
if(png_cli && frame_count == 4) {
png_export_begin(app, app->args.export_any, app->args.export_arg[0] ? (f32)atof(app->args.export_arg) : 2.0f);
app->png.quit_after = true;
if(app->png.state == PNG_IDLE) { printf("%s\n", app->message); break; }
}
if(png_cli) redraw = true;
const char *shot_frame = getenv("DESIGN_IT_SHOT_FRAME");
if(app->args.screenshot[0] && frame_count == (shot_frame ? (u32)atoi(shot_frame) : 18u)) {
app->renderer.capture_path = app->args.screenshot;
}
if(app->renderer.captured) break;
if(app->args.screenshot[0]) redraw = true;
u64 now_ns = time_now_ns();
u32 cap = app->settings.fps_cap;
u64 interval = cap ? 1000000000ull / cap : 0;
b32 visible = !PlatformWindowSuspended(app->window);
b32 answered = PlatformWindowFrameReady(app->window);
b32 hidden = !answered && now_ns - PlatformWindowFrameRequested(app->window) > 250000000ull;
b32 ready = cap ? !hidden : answered;
s64 timeout = -1;
if(visible && ready) {
if(redraw || app->animating) {
timeout = (now_ns >= next_frame_ns) ? 0 : (s64)(next_frame_ns - now_ns);
} else if(app->ticking) {
u64 tick = 500000000ull; // 2Hz profiler refresh
u64 since = now_ns - last_render_ns;
timeout = (since >= tick) ? 0 : (s64)(tick - since);
}
}
int fds[2] = {wake_main_fd(), ui_code.watch_fd};
u32 ready_fds = 0;
PlatformInput input;
u64 idle_start = time_now_ns();
if(!PlatformWindowPump(app->window, &input, timeout, fds, 2, &ready_fds)) break;
idle_ns += time_now_ns() - idle_start;
profiler->sampling = layout_view_visible(&app->layout, VIEW_PROFILER);
if(profiler->sampling && time_now_ns() - profiler->sample_ns >= 500000000ull) {
profile_sample(profiler);
redraw = true;
}
if(time_now_ns() - fps_window_ns >= 1000000000ull) {
app->fps = (f32)fps_count * 1e9f / (f32)(time_now_ns() - fps_window_ns);
fps_count = 0;
fps_window_ns = time_now_ns();
}
b32 woke = wake_main_drain();
if(woke || input.changed) redraw = true;
#if defined(DESIGN_HOT_RELOAD) && DESIGN_HOT_RELOAD
if(ui_code_poll(app, &ui_code)) redraw = true;
#endif
if(PlatformWindowTakeResized(app->window) || app->renderer.swapchain_dirty) {
redraw = true;
PlatformWindowSize(app->window, &app->width, &app->height, &app->scale);
vk_resize(&app->renderer, app->width * app->scale, app->height * app->scale);
}
u64 now = time_now_ns();
app->dt = Min((f32)((f64)(now - app->last_frame_ns) / 1e9), 0.1f);
app->last_frame_ns = now;
app->time += app->dt;
b32 can_present = ready && visible && time_now_ns() >= next_frame_ns;
if(!((redraw || app->animating) && can_present) && !input.changed) continue;
app_host_last_input = input;
app->ui_scale = PlatformWindowUiScale(app->window);
u64 frame_start = time_now_ns();
DrawInstance *mapped = can_present ? vk_frame_begin(&app->renderer) : NULL;
app->draw.instances = mapped ? mapped : app->draw.own;
if(ui_code.frame) ui_code.frame(app, &input, wake_main_fd());
else ui_frame(app, &input);
u64 ui_end = time_now_ns();
redraw = redraw || app->animating;
if(redraw && can_present) {
u32 clear = PlatformWindowIsLayer(app->window) ? 0x0B0B0B00u : app->settings.colors[UI_COLOR_BG];
PlatformWindowRequestFrame(app->window);
redraw = false;
last_render_ns = time_now_ns();
next_frame_ns = (last_render_ns - next_frame_ns > interval) ? last_render_ns + interval : next_frame_ns + interval;
if(!vk_render(&app->renderer, &app->draw, &app->fonts, clear)) {
PlatformWindowCancelFrame(app->window);
redraw = true;
}
png_export_collect(app);
u64 frame_end = time_now_ns();
f32 ms = (f32)((f64)(frame_end - frame_start) / 1e6);
app->frame_ms = (app->frame_ms == 0) ? ms : app->frame_ms * 0.95f + ms * 0.05f;
profile_frame(profiler, ms, (f32)((f64)(ui_end - frame_start) / 1e6), (f32)((f64)(frame_end - ui_end) / 1e6), (f32)((f64)idle_ns / 1e6));
idle_ns = 0;
++fps_count;
}
}
app_save_state(app);
#if defined(DESIGN_HOT_RELOAD) && DESIGN_HOT_RELOAD
ui_code_shutdown(&ui_code);
#endif
vk_shutdown(&app->renderer);
PlatformWindowClose(app->window);
return 0;
}
#endif // !DESIGN_UI_DLL
#if defined(DESIGN_UI_DLL) && DESIGN_UI_DLL
#if PLATFORM_WINDOWS
#define DESIGN_UI_EXPORT __declspec(dllexport)
#else
#define DESIGN_UI_EXPORT __attribute__((visibility("default")))
#endif
extern "C" {
DESIGN_UI_EXPORT u64 design_ui_app_size = DESIGN_UI_SIGNATURE;
}
extern "C" DESIGN_UI_EXPORT void design_ui_frame(App *app, PlatformInput *input, int wake_fd)
{
global_wake_fd = wake_fd;
tls_scratch_arena = app->scratch;
ui_frame(app, input);
}
#else
ENTRYPOINT(argc, argv)
{
Arena *arena = ArenaCreate(MiB(64));
tls_scratch_arena = ArenaCreate(MiB(64));
profile_arena_register("main", arena);
profile_thread_register("main (ui)");
AppArgs args;
app_parse_args(&args, argc, argv);
wake_main_init();
String8 data_dir = app_data_dir(arena);
Diagram *diagram = PushStructAligned(arena, Diagram);
diagram_init(arena, diagram);
if(args.scan_path[0]) {
diagram_scan_cpp(diagram, args.scan_path);
} else if(args.open_file[0]) {
if(!diagram_load_file(diagram, args.open_file)) {
fprintf(stderr, "failed to load %s, starting with default template\n", args.open_file);
diagram_load_template(diagram, "arch");
}
} else if(args.template_name[0]) {
if(!diagram_load_template(diagram, args.template_name)) {
fprintf(stderr, "unknown template %s, using arch\n", args.template_name);
diagram_load_template(diagram, "arch");
}
} else {
diagram_load_template(diagram, "arch");
}
// Headless exports (no window needed), png renders through the window below
if(args.export_any[0] && !path_has_extension(args.export_any, ".png")) {
Settings s;
settings_default(&s);
for(u32 i = 0; i < args.set_count; ++i) settings_set(&s, args.sets[i]);
char message[256];
b32 ok = diagram_export_by_extension(diagram, args.export_any, args.export_arg, s.colors, message, sizeof(message));
printf("%s\n", message);
return ok ? 0 : 1;
}
if(args.export_svg[0]) {
Settings s;
settings_default(&s);
for(u32 i = 0; i < args.set_count; ++i) settings_set(&s, args.sets[i]);
b32 ok = diagram_export_svg(diagram, args.export_svg, s.colors);
printf("%s %s (%u nodes, %u edges)\n", ok ? "exported" : "failed to export", args.export_svg, diagram->live_nodes, diagram->live_edges);
return ok ? 0 : 1;
}
App *app = PushStructAligned(arena, App);
app->arena = arena;
app->args = args;
app->data_dir = data_dir;
app->diagram = diagram;
return app_run(app);
}
#endif
|