#include "base/base_include.h" #if PLATFORM_LINUX #include #include #include #elif PLATFORM_APPLE #include #include #elif PLATFORM_WINDOWS #include #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, "--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= arch | ecs | microservices | compiler | uml | stress\n" " --scan= scan C/C++ headers into a live interactive UML diagram\n" " --export-svg= export diagram to themed vector SVG and exit\n" " --layer open as an overlay window (no frame, always on top)\n" " --anchor= overlay anchor (implies --layer)\n" " --open= 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= 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; 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; 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; 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; } 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 SVG export mode (no window needed!) 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