Files
Roman ChojnackiandClaude Opus 5.5 66e2d9a0ae Render: mask only frames that draw, one switch per command, SDL rects
The damage keys and the skip hash read the list before rounded fills
become masks; reaktor_damage_render masks once, after a frame proves to
draw and before any pass, the check pass included. command_read keys and
spans a command in one switch. Damage boxes are SDL_Rect, cut, joined and
tested through SDL's helpers; touches keeps its inclusive edge, and
nk_sdl_meets stays, as SDL_HasRectIntersectionFloat counts a shared edge.

The steppers of a property wash only where its field lights: one flag,
reaktor_property_live, for both. The manual says a new theme, icon or atlas
is redrawn where it changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:16:36 +01:00

2002 lines
59 KiB
C

#define SDL_MAIN_HANDLED 1
#include <SDL3/SDL_main.h>
#include "internal.h"
#include "declare.h"
#include "anim.h"
#include "locale.h"
#include "reaktor/launch.h"
#include "lifecycle.h"
#include "css.h"
#ifdef __EMSCRIPTEN__
#include "keyboard_web.h"
#endif
static int
effective_dark(const App *app)
{
if (app->theme_mode == REAKTOR_THEME_LIGHT) return 0;
if (app->theme_mode == REAKTOR_THEME_DARK) return 1;
return reaktor_prefers_dark();
}
size_t reaktor_rss[REAKTOR_RSS_STEPS];
size_t reaktor_priv[REAKTOR_RSS_STEPS];
void (*reaktor_test_hook)(App *app);
static reaktor_launch g_launch;
static App *g_app;
static int g_started, g_stopped;
static SDL_AtomicInt g_exit_code, g_hard_quit, g_running;
static char g_quit_tag;
static char **g_owned;
static int g_owned_n;
static const char *g_icon_name, *g_font, *g_font_bold, *g_cli_font,
*g_cli_font_bold;
static char *g_title, *g_pending_title;
static reaktor_asset g_css_last[REAKTOR_LAYER_MAX];
static int g_css_last_n = -1;
static const char *g_css[REAKTOR_LAYER_MAX], *g_cli_css[REAKTOR_LAYER_MAX];
static int g_css_n, g_cli_css_n, g_css_pending;
static const char *g_fallbacks[REAKTOR_LAYER_MAX];
static int g_fallback_n;
static const char *g_icon_dirs[REAKTOR_LAYER_MAX], *g_cli_icons[REAKTOR_LAYER_MAX];
static int g_inspect_flag;
static int g_motion_flag, g_contrast_flag, g_reduced, g_contrast, g_watch;
static int g_new_instance;
static SDL_IOStream *g_log;
static SDL_LogOutputFunction g_log_next;
static void *g_log_next_user;
static int g_icon_dir_n, g_cli_icon_n;
static const char *
own(const char *str)
{
char *d, **grown;
int i;
if (!str) return NULL;
for (i = 0; i < g_owned_n; i++)
if (SDL_strcmp(g_owned[i], str) == 0) return g_owned[i];
d = SDL_strdup(str);
if (!d) return NULL;
grown = (char **)SDL_realloc(g_owned,
(size_t)(g_owned_n + 1) * sizeof *g_owned);
if (!grown) {
SDL_free(d);
return NULL;
}
g_owned = grown;
g_owned[g_owned_n++] = d;
return d;
}
static void
forget_owned(void)
{
while (g_owned_n > 0) SDL_free(g_owned[--g_owned_n]);
SDL_free(g_owned);
g_owned = NULL;
}
const char *
reaktor_asset_name(const reaktor_asset *a, const char *fallback)
{
const char *name;
if (a->path) return own(a->path);
if (!a->data) return NULL;
name = own(a->name ? a->name : fallback);
if (name && !reaktor_asset_register(name, a->data, a->size))
SDL_Log("too many registered assets; %s is not one", name);
return name;
}
#ifdef __EMSCRIPTEN__
#define ON_WEB 1
#else
#define ON_WEB 0
#endif
#if defined(__EMSCRIPTEN__)
#define GPU_DRIVERS "opengles2"
#elif defined(__APPLE__)
#define GPU_DRIVERS "metal"
#elif defined(_WIN32)
#define GPU_DRIVERS "opengl,direct3d12,direct3d11"
#else
#define GPU_DRIVERS "opengl,opengles2"
#endif
SDL_Renderer *
reaktor_renderer_for(SDL_Window *win, const char *name, int hdr)
{
SDL_Renderer *ren = NULL;
if (hdr) {
SDL_PropertiesID p = SDL_CreateProperties();
SDL_SetPointerProperty(p, SDL_PROP_RENDERER_CREATE_WINDOW_POINTER, win);
if (name) SDL_SetStringProperty(p, SDL_PROP_RENDERER_CREATE_NAME_STRING, name);
SDL_SetNumberProperty(p, SDL_PROP_RENDERER_CREATE_OUTPUT_COLORSPACE_NUMBER,
SDL_COLORSPACE_SRGB_LINEAR);
ren = SDL_CreateRendererWithProperties(p);
SDL_DestroyProperties(p);
}
/* SDL's gpu renderer keeps a linear output on a swapchain that cannot show
one, and draws everything dark there. */
if (ren) {
SDL_GPUDevice *dev = (SDL_GPUDevice *)SDL_GetPointerProperty(
SDL_GetRendererProperties(ren), SDL_PROP_RENDERER_GPU_DEVICE_POINTER, NULL);
if (dev && !SDL_WindowSupportsGPUSwapchainComposition(
dev, win, SDL_GPU_SWAPCHAINCOMPOSITION_HDR_EXTENDED_LINEAR)) {
SDL_DestroyRenderer(ren);
ren = NULL;
}
}
return ren ? ren : SDL_CreateRenderer(win, name);
}
static const char *launch_title(void);
static bool
open_window(App *app, int w, int h, SDL_WindowFlags flags)
{
app->win = SDL_CreateWindow(launch_title(), w, h, flags | SDL_WINDOW_HIDDEN);
if (!app->win) return false;
app->ren = reaktor_renderer_for(app->win, NULL, g_launch.hdr);
if (!app->ren) {
SDL_DestroyWindow(app->win);
app->win = NULL;
return false;
}
if (!(flags & SDL_WINDOW_HIDDEN)) SDL_ShowWindow(app->win);
return true;
}
static int
capturing(const App *app)
{
return app->shot_path || app->dump_path;
}
static int
remembers(const App *app)
{
return !ON_WEB && g_launch.remember_window && !capturing(app);
}
static int
ms_x100(Uint64 from, Uint64 to)
{
return (int)(100000.0 * (double)(to - from) / (double)SDL_GetPerformanceFrequency());
}
int
reaktor_capturing(void)
{
return g_app && capturing(g_app);
}
reaktor_save
reaktor_save_mode(int *ms)
{
if (ms) *ms = g_launch.save_ms > 0 ? g_launch.save_ms : 1000;
return g_launch.save_settings;
}
int
reaktor_key_hook(App *app, const SDL_Event *event)
{
return g_launch.key && g_launch.key(app, event);
}
static int
starts_hidden(const App *app)
{
return !ON_WEB && g_launch.window.hidden && !capturing(app);
}
static int
placed(const App *app)
{
return !ON_WEB && (g_launch.window.centered || remembers(app));
}
const char *
reaktor_app_ident(void)
{
if (g_launch.id && *g_launch.id) return g_launch.id;
return g_launch.name && *g_launch.name ? g_launch.name : "Reaktor";
}
static const char *
launch_title(void)
{
if (g_title) return g_title;
if (g_launch.window.title) return g_launch.window.title;
return g_launch.name ? g_launch.name : "Reaktor";
}
void
reaktor_hint(const char *name, const char *value)
{
SDL_SetHintWithPriority(name, value, SDL_HINT_OVERRIDE);
}
static void
reaktor_rss_mark(int step)
{
reaktor_process_memory(&reaktor_rss[step], &reaktor_priv[step]);
}
static void
add_fallback(const char *path)
{
char *full = reaktor_path_from_cwd(path);
reaktor_text_add_fallback(full ? full : path);
SDL_free(full);
}
static const char *
own_here(const char *path)
{
char *full = reaktor_path_from_cwd(path);
const char *owned = own(full ? full : path);
SDL_free(full);
return owned;
}
static void SDLCALL
log_line(void *user, int category, SDL_LogPriority priority, const char *message)
{
static const char *const level[] = { "", "TRACE", "VERBOSE", "DEBUG", "INFO",
"WARN", "ERROR", "CRITICAL" };
static const char *const area[] = { "app", "error", "assert", "system", "audio",
"video", "render", "input", "test", "gpu" };
SDL_Time now = 0;
SDL_DateTime t;
char cat[16];
SDL_zero(t);
if (SDL_GetCurrentTime(&now)) SDL_TimeToDateTime(now, &t, true);
if (category >= 0 && category < (int)SDL_arraysize(area))
SDL_strlcpy(cat, area[category], sizeof cat);
else
SDL_snprintf(cat, sizeof cat, "%d", category);
SDL_IOprintf(g_log, "%04d-%02d-%02d %02d:%02d:%02d.%03d %-8s %-6s %s\n",
t.year, t.month, t.day, t.hour, t.minute, t.second,
t.nanosecond / 1000000,
(unsigned)priority < SDL_arraysize(level) ? level[priority] : "?",
cat, message);
SDL_FlushIO(g_log);
if (g_log_next) g_log_next(g_log_next_user, category, priority, message);
}
static void
log_open(const char *path)
{
if (g_log) return;
g_log = SDL_IOFromFile(path, "ab");
if (!g_log) {
SDL_Log("--log: %s", SDL_GetError());
return;
}
SDL_GetLogOutputFunction(&g_log_next, &g_log_next_user);
SDL_SetLogOutputFunction(log_line, NULL);
}
static void
log_close(void)
{
if (!g_log) return;
SDL_SetLogOutputFunction(g_log_next, g_log_next_user);
SDL_CloseIO(g_log);
g_log = NULL;
}
static int
pick(const char *v, const char *a, int va, const char *b, int vb, int other)
{
return SDL_strcmp(v, a) == 0 ? va : SDL_strcmp(v, b) == 0 ? vb : other;
}
static void
push_layer(const char **layers, int *n, const char *flag, const char *v)
{
if (*n < REAKTOR_LAYER_MAX) layers[(*n)++] = own_here(v);
else SDL_Log("%s: four at most; %s is not read", flag, v);
}
static int
take_flags(App *app, int argc, char **argv)
{
int i, n = 0;
g_cli_css_n = g_cli_icon_n = 0;
g_cli_font = g_cli_font_bold = NULL;
for (i = 0; i < argc; i++) {
const char *a = argv[i];
const char *v = (i + 1 < argc) ? argv[i + 1] : NULL;
if (v && SDL_strcmp(a, "--shot") == 0) { app->shot_path = v; i++; }
else if (v && SDL_strcmp(a, "--aa") == 0) {
g_launch.anti_aliasing = (reaktor_aa)pick(v, "on", REAKTOR_AA_ON, "off",
REAKTOR_AA_OFF, REAKTOR_AA_AUTO);
i++;
}
else if (v && SDL_strcmp(a, "--console") == 0) {
g_launch.console = (reaktor_console)pick(v, "debug", REAKTOR_CONSOLE_DEBUG, "parent",
REAKTOR_CONSOLE_PARENT, REAKTOR_CONSOLE_NONE);
i++;
}
else if (v && SDL_strcmp(a, "--css") == 0) { push_layer(g_cli_css, &g_cli_css_n, a, v); i++; }
else if (v && SDL_strcmp(a, "--icons") == 0) { push_layer(g_cli_icons, &g_cli_icon_n, a, v); i++; }
else if (v && SDL_strcmp(a, "--font") == 0) { g_cli_font = own_here(v); i++; }
else if (v && SDL_strcmp(a, "--font-bold") == 0) { g_cli_font_bold = own_here(v); i++; }
else if (v && SDL_strcmp(a, "--a11y-dump") == 0) { app->dump_path = v; i++; }
else if (v && SDL_strcmp(a, "--log") == 0) { log_open(v); i++; }
else if (SDL_strcmp(a, "--inspect") == 0) g_inspect_flag = 1;
else if (SDL_strcmp(a, "--no-inspector") == 0) g_inspect_flag = -1;
else if (SDL_strcmp(a, "--watch-css") == 0) g_watch = 1;
else if (v && SDL_strcmp(a, "--motion") == 0) { g_motion_flag = pick(v, "reduce", 1, "full", -1, 0); i++; }
else if (v && SDL_strcmp(a, "--contrast") == 0) { g_contrast_flag = pick(v, "more", 1, "normal", -1, 0); i++; }
else if (SDL_strcmp(a, "--new-instance") == 0) g_new_instance = 1;
else if (v && SDL_strcmp(a, "--renderer") == 0) { app->renderer_pref = v; i++; }
else if (v && SDL_strcmp(a, "--hdr") == 0) {
g_launch.hdr = pick(v, "on", 1, "off", 0, g_launch.hdr);
i++;
}
else if (v && SDL_strcmp(a, "--video") == 0) { app->video_pref = v; i++; }
else if (v && SDL_strcmp(a, "--popups") == 0) {
app->popups_inline = SDL_strcmp(v, "inline") == 0;
i++;
}
else if (v && SDL_strcmp(a, "--lang") == 0) { app->lang_pref = v; i++; }
else if (v && SDL_strcmp(a, "--font-fallback") == 0) { add_fallback(v); i++; }
else if (v && SDL_strcmp(a, "--theme") == 0) {
app->theme_mode = pick(v, "light", REAKTOR_THEME_LIGHT, "dark", REAKTOR_THEME_DARK,
REAKTOR_THEME_SYSTEM);
i++;
} else {
argv[n++] = argv[i];
}
}
if (n < argc) argv[n] = NULL;
return n;
}
static void
read_roles(App *app)
{
reaktor_style body, link;
reaktor_style_get("body", &body);
reaktor_style_get("a:link", &link);
app->page = body.matched && body.bg[3] ? nk_rgba_bv(body.bg)
: reaktor_token("--background-body", nk_rgb(247, 247, 247));
app->text = body.matched && body.fg[3] ? nk_rgba_bv(body.fg)
: reaktor_token("--text-main", nk_rgb(51, 51, 51));
app->accent = link.matched && link.fg[3] ? nk_rgba_bv(link.fg)
: reaktor_token("--links", app->text);
}
static int
roles_hold(const App *app)
{
const struct nk_color *c[3] = { &app->accent, &app->page, &app->text };
static const char *const name[3] = { "--links", "--background-body", "--text-main" };
unsigned char t[4];
int i;
for (i = 0; i < 3; i++)
if (!reaktor_style_token(name[i], t) || c[i]->a != 255 || t[3] != 255 ||
t[0] != c[i]->r || t[1] != c[i]->g || t[2] != c[i]->b)
return 0;
return 1;
}
static const char *
role_sheet(const App *app)
{
static char css[256];
const struct nk_color *c[3] = { &app->accent, &app->page, &app->text };
static const char *const name[3] = { "--links", "--background-body", "--text-main" };
int i, k = SDL_snprintf(css, sizeof(css), ":root {");
for (i = 0; i < 3 && k > 0 && k < (int)sizeof(css); i++)
k += SDL_snprintf(css + k, sizeof(css) - (size_t)k, " %s: rgba(%d, %d, %d, %.3f);",
name[i], c[i]->r, c[i]->g, c[i]->b, c[i]->a / 255.0);
if (k > 0 && k < (int)sizeof(css))
SDL_snprintf(css + k, sizeof(css) - (size_t)k, " }");
reaktor_asset_register(".reaktor-roles.css", css, SDL_strlen(css));
return ".reaktor-roles.css";
}
static const char *
theme_sheet(int dark)
{
return dark ? "external/watercss/src/variables-dark.css"
: "external/watercss/src/variables-light.css";
}
static int
read_prefs(void)
{
int r = 0, c = 0, changed;
if (!g_motion_flag || !g_contrast_flag) reaktor_prefers(&r, &c);
if (g_motion_flag) r = g_motion_flag > 0;
if (g_contrast_flag) c = g_contrast_flag > 0;
changed = r != g_reduced || c != g_contrast;
g_reduced = r;
g_contrast = c;
reaktor_css_media(r, c);
reaktor_anim_reduce(r);
return changed;
}
int reaktor_reduced_motion(void) { return g_reduced; }
int reaktor_high_contrast(void) { return g_contrast; }
#define WATCH_MAX 64
static struct {
SDL_Mutex *lock;
SDL_TimerID timer;
char *path[WATCH_MAX];
SDL_Time when[WATCH_MAX];
int n;
} g_watched;
static void
watch_reload(App *app, void *user)
{
(void)app; (void)user;
SDL_Log("css: a sheet changed on disk; restyling");
reaktor_restyle();
}
static Uint32 SDLCALL
watch_tick(void *user, SDL_TimerID id, Uint32 interval)
{
int i, changed = 0;
(void)user; (void)id;
SDL_LockMutex(g_watched.lock);
for (i = 0; i < g_watched.n; i++) {
SDL_PathInfo info;
if (SDL_GetPathInfo(g_watched.path[i], &info) && info.modify_time != g_watched.when[i]) {
g_watched.when[i] = info.modify_time;
changed = 1;
}
}
SDL_UnlockMutex(g_watched.lock);
if (changed && g_app) reaktor_post(g_app, watch_reload, NULL);
return interval;
}
static void
watch_seen(const char *name)
{
char full[1024];
SDL_PathInfo info;
int i;
if (reaktor_path_absolute(name)) SDL_strlcpy(full, name, sizeof full);
else if (!reaktor_path(full, sizeof full, name)) return;
if (!SDL_GetPathInfo(full, &info) || info.type != SDL_PATHTYPE_FILE) return;
SDL_LockMutex(g_watched.lock);
for (i = 0; i < g_watched.n && SDL_strcmp(g_watched.path[i], full) != 0; i++) {}
if (i == g_watched.n && g_watched.n < WATCH_MAX && (g_watched.path[i] = SDL_strdup(full))) {
g_watched.when[i] = info.modify_time;
g_watched.n++;
}
SDL_UnlockMutex(g_watched.lock);
}
static void
watch_begin(void)
{
if (!g_watched.lock && !(g_watched.lock = SDL_CreateMutex())) return;
SDL_LockMutex(g_watched.lock);
while (g_watched.n) SDL_free(g_watched.path[--g_watched.n]);
SDL_UnlockMutex(g_watched.lock);
reaktor_css_track(watch_seen);
if (!g_watched.timer) g_watched.timer = SDL_AddTimer(500, watch_tick, NULL);
}
static void
watch_stop(void)
{
if (g_watched.timer) SDL_RemoveTimer(g_watched.timer);
g_watched.timer = 0;
while (g_watched.n) SDL_free(g_watched.path[--g_watched.n]);
SDL_DestroyMutex(g_watched.lock);
g_watched.lock = NULL;
}
static void
load_theme(App *app)
{
const char *sheets[SHEET_MAX];
int n = 0, i, base;
unsigned char c[4];
Uint64 t0, t1;
app->dark = effective_dark(app);
if (g_watch) watch_begin();
sheets[n++] = theme_sheet(app->dark);
sheets[n++] = CORE_SHEET;
if (!g_launch.no_reaktor_css) sheets[n++] = APP_SHEET;
base = n;
for (i = 0; i < g_css_n && n < SHEET_MAX; i++) sheets[n++] = g_css[i];
for (i = 0; i < g_cli_css_n && n < SHEET_MAX; i++) sheets[n++] = g_cli_css[i];
if (reaktor_inspector_sheet() && n < SHEET_MAX) sheets[n++] = reaktor_inspector_sheet();
app->sheets = n;
app->why |= REAKTOR_WHY_STYLE;
t0 = SDL_GetPerformanceCounter();
if (!reaktor_style_init(sheets, n, app->dark ? "dark" : "light"))
SDL_Log("stylesheets failed to load; Nuklear defaults apply");
read_roles(app);
if (n > base && !roles_hold(app) && reaktor_style_add(role_sheet(app)))
read_roles(app);
t1 = SDL_GetPerformanceCounter();
app->style_ms_x100 = ms_x100(t0, t1);
app->card_bg = reaktor_style_token("--background", c)
? nk_rgba(c[0], c[1], c[2], c[3]) : nk_rgb(226, 226, 226);
app->icon_col = reaktor_style_token("--text-muted", c)
? nk_rgb(c[0], c[1], c[2]) : nk_rgb(0x6a, 0x6a, 0x6a);
reaktor_window_set_dark(app->win, app->dark);
img_cache_clear(app);
apply_widget_style(app);
app->clear = app->page;
app->dirty = 1;
reaktor_windows_restyle();
}
bool
reaktor_app_wake(const App *app)
{
SDL_Event e;
SDL_zero(e);
e.type = SDL_EVENT_USER;
if (app && app->secondary) e.user.windowID = app->win_id;
return SDL_PushEvent(&e);
}
#ifdef __EMSCRIPTEN__
static void
web_page_size(int *w, int *h)
{
int cw = EM_ASM_INT({ return window.innerWidth | 0; });
int ch = EM_ASM_INT({ return window.innerHeight | 0; });
if (cw > 64 && ch > 64) { *w = cw; *h = ch; }
}
static EM_BOOL
web_on_resize(int type, const EmscriptenUiEvent *ev, void *user)
{
App *app = (App *)user;
int w = WINDOW_WIDTH, h = WINDOW_HEIGHT;
(void)type; (void)ev;
web_page_size(&w, &h);
SDL_SetWindowSize(app->win, w, h);
app->dirty = 1;
return EM_TRUE;
}
#endif
#if defined(_WIN32) && !defined(__EMSCRIPTEN__)
#define COBJMACROS
#include <dxgi.h>
static int
renderer_is_software(SDL_Renderer *ren)
{
IUnknown *dev;
IDXGIDevice *dxgi = NULL;
IDXGIAdapter *ad = NULL;
DXGI_ADAPTER_DESC desc;
int software = 0;
dev = (IUnknown *)SDL_GetPointerProperty(
SDL_GetRendererProperties(ren),
SDL_PROP_RENDERER_D3D11_DEVICE_POINTER, NULL);
if (!dev) return 0;
if (SUCCEEDED(IUnknown_QueryInterface(dev, &IID_IDXGIDevice,
(void **)&dxgi)) && dxgi) {
if (SUCCEEDED(IDXGIDevice_GetAdapter(dxgi, &ad)) && ad) {
if (SUCCEEDED(IDXGIAdapter_GetDesc(ad, &desc))) {
software = desc.VendorId == 0x1414 ||
wcsstr(desc.Description, L"Basic Render") != NULL ||
wcsstr(desc.Description, L"WARP") != NULL;
}
IDXGIAdapter_Release(ad);
}
IDXGIDevice_Release(dxgi);
}
return software;
}
#else
static int renderer_is_software(SDL_Renderer *ren) { (void)ren; return 0; }
#endif
#define HOVER_GAP_MS 50
Uint64 g_hover_gap_ms = HOVER_GAP_MS;
#define CAL_SKIP 3
#define CAL_FRAMES 8
static void
calibrate_hover_gap(App *app)
{
double now;
if (app->cal_done) return;
if (app->cal_frames < CAL_SKIP) { app->cal_frames++; return; }
now = reaktor_process_cpu_ms();
if (app->cal_frames == CAL_SKIP) app->cal_cpu0 = now;
app->cal_frames++;
if (app->cal_frames < CAL_SKIP + CAL_FRAMES + 1) return;
app->cpu_ms_per_frame = (float)((now - app->cal_cpu0) / (double)CAL_FRAMES);
app->cal_done = 1;
g_hover_gap_ms = app->cpu_ms_per_frame > 40.0f ? 150
: app->cpu_ms_per_frame > 15.0f ? 100
: HOVER_GAP_MS;
}
static int
reaktor_hot_motion(App *app, float mx, float my)
{
struct nk_rect nr;
int i, over = -1, over_top = -1, had, has;
for (i = 0; i < app->hot_n; i++) {
struct nk_rect r = app->hot[i].r;
if (mx >= r.x && mx <= r.x + r.w && my >= r.y && my <= r.y + r.h) {
over = i;
if (app->hot[i].top) over_top = i;
}
}
if (over_top >= 0) over = over_top;
nr = over >= 0 ? app->hot[over].r : nk_rect(0, 0, 0, 0);
had = app->hot_last >= 0;
has = over >= 0;
if (had != has || (has && (nr.x != app->hot_last_r.x || nr.y != app->hot_last_r.y ||
nr.w != app->hot_last_r.w || nr.h != app->hot_last_r.h))) {
int was = had && app->hot_last_repaint;
app->hot_last = over;
app->hot_last_r = nr;
app->hot_last_repaint = has ? app->hot[over].repaint : 0;
app->want_cursor = has ? app->hot[over].cursor : 0;
return was || app->hot_last_repaint;
}
return has && app->hot[over].track;
}
static SDL_Cursor *g_cursor[REAKTOR_CURSORS];
SDL_Cursor *
reaktor_cursor(int kind)
{
static const SDL_SystemCursor sys[REAKTOR_CURSORS] = {
SDL_SYSTEM_CURSOR_DEFAULT, SDL_SYSTEM_CURSOR_POINTER,
SDL_SYSTEM_CURSOR_TEXT, SDL_SYSTEM_CURSOR_EW_RESIZE,
SDL_SYSTEM_CURSOR_NS_RESIZE
};
if (kind < 0 || kind >= REAKTOR_CURSORS) kind = REAKTOR_CURSOR_DEFAULT;
if (!g_cursor[kind]) g_cursor[kind] = SDL_CreateSystemCursor(sys[kind]);
return g_cursor[kind];
}
static void
reaktor_show_cursor(App *app)
{
SDL_Cursor *c;
if (app->want_cursor == app->cur_shown) return;
c = reaktor_cursor(app->want_cursor);
if (c) SDL_SetCursor(c);
app->cur_shown = app->want_cursor;
}
static void
reaktor_place_ime(App *app)
{
SDL_Window *keys = SDL_GetKeyboardFocus();
if (app->ime_valid && (!keys || keys == app->win))
SDL_SetTextInputArea(app->win, &app->ime_rect, app->ime_cursor);
app->ime_valid = 0;
}
static void
reaktor_hover_redraw(App *app)
{
if (app->dragging || SDL_GetTicks() - app->last_draw_ms >= g_hover_gap_ms) {
app->dirty = 1;
} else if (!app->hover_pending) {
app->hover_pending = 1;
reaktor_hint(SDL_HINT_MAIN_CALLBACK_RATE, "20");
}
}
static SDL_AppResult
fail(App *app, const char *what)
{
char msg[512];
SDL_Log("%s: %s", what, SDL_GetError());
if (capturing(app)) return SDL_APP_FAILURE;
SDL_snprintf(msg, sizeof(msg), "%s.\n\n%s", what, SDL_GetError());
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, launch_title(), msg, NULL);
return SDL_APP_FAILURE;
}
static void
push_quit(reaktor_quit_reason why)
{
SDL_Event e;
SDL_zero(e);
e.type = SDL_EVENT_USER;
e.user.code = (Sint32)why;
e.user.data1 = &g_quit_tag;
SDL_PushEvent(&e);
}
void
reaktor_console_quit(void)
{
push_quit(REAKTOR_QUIT_CONSOLE);
}
void
reaktor_hard_quit(int code)
{
SDL_SetAtomicInt(&g_exit_code, code);
SDL_SetAtomicInt(&g_hard_quit, 1);
reaktor_app_wake(NULL);
}
static void
run_stop(App *app)
{
if (g_started && !g_stopped) {
g_stopped = 1;
if (g_launch.stop) g_launch.stop(app);
}
reaktor_process_stopped();
}
void
reaktor_session_end(void)
{
if (!g_app) return;
if (g_started && !g_stopped && g_launch.closing)
g_launch.closing(g_app, REAKTOR_QUIT_SESSION);
run_stop(g_app);
reaktor_hard_quit(0);
}
static void
take_assets(App *app)
{
int i;
app->font_face = g_cli_font ? g_cli_font : g_font ? g_font : FONT_FILE;
app->font_face_bold = g_cli_font_bold ? g_cli_font_bold
: g_cli_font ? g_cli_font
: g_font_bold ? g_font_bold
: g_font ? g_font
: FONT_BOLD_FILE;
for (i = 0; i < g_fallback_n; i++) reaktor_text_add_fallback(g_fallbacks[i]);
app->icon_dir_count = 0;
for (i = 0; i < g_cli_icon_n; i++)
app->icon_dirs[app->icon_dir_count++] = g_cli_icons[i];
for (i = 0; i < g_icon_dir_n; i++)
app->icon_dirs[app->icon_dir_count++] = g_icon_dirs[i];
}
static void take_pending(App *app);
static SDL_AppResult
app_init(void **appstate, int argc, char *argv[])
{
App *app;
reaktor_rss_mark(REAKTOR_RSS_ENTRY);
app = (App *)SDL_calloc(1, sizeof(App));
if (!app) return SDL_APP_FAILURE;
app->started = SDL_GetPerformanceCounter();
*appstate = app;
g_app = app;
app->queue.moved_ok = 1;
app->theme_mode = (int)g_launch.theme;
reaktor_inspector_early();
argc = take_flags(app, argc, argv);
if (g_launch.log) log_open(g_launch.log);
reaktor_process_start((int)g_launch.console, launch_title());
if (g_launch.name || g_launch.version || g_launch.id)
SDL_SetAppMetadata(g_launch.name, g_launch.version, g_launch.id);
if (g_launch.single_instance && !g_new_instance && !capturing(app) &&
!reaktor_instance_claim(argc, argv))
return SDL_APP_SUCCESS;
reaktor_hint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER, "1");
reaktor_hint(SDL_HINT_TIMER_RESOLUTION, "0");
reaktor_hint(SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE, "0");
if (app->video_pref) reaktor_hint(SDL_HINT_VIDEO_DRIVER, app->video_pref);
#ifndef __APPLE__
/* SDL drops the click that activates a window; only macOS expects that. */
reaktor_hint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
#endif
if (!SDL_Init(SDL_INIT_VIDEO)) return fail(app, "SDL could not start");
SDL_RegisterEvents(1);
/* SDL makes every window a drop target while a drop event is enabled; on
Windows that is COM's drag-and-drop, three DLLs and three threads. */
if (!g_launch.file_opened) {
SDL_SetEventEnabled(SDL_EVENT_DROP_FILE, false);
SDL_SetEventEnabled(SDL_EVENT_DROP_TEXT, false);
}
reaktor_signal_watch();
if (g_launch.console == REAKTOR_CONSOLE_DEBUG)
SDL_SetLogPriorities(SDL_LOG_PRIORITY_DEBUG);
reaktor_rss_mark(REAKTOR_RSS_SDL);
take_assets(app);
if (!app->renderer_pref) app->renderer_pref = g_launch.renderer;
if (app->renderer_pref && SDL_strcmp(app->renderer_pref, "software") != 0) {
SDL_strlcpy(app->render_mode, app->renderer_pref,
sizeof(app->render_mode));
if (SDL_strcasecmp(app->renderer_pref, "directx") == 0)
reaktor_hint(SDL_HINT_RENDER_DRIVER, "direct3d12,direct3d11");
else if (SDL_strcasecmp(app->renderer_pref, "gpu") == 0)
reaktor_hint(SDL_HINT_RENDER_DRIVER, GPU_DRIVERS);
else if (SDL_strcasecmp(app->renderer_pref, "sdl-gpu") == 0)
reaktor_hint(SDL_HINT_RENDER_DRIVER, "gpu");
else if (SDL_strcmp(app->renderer_pref, "auto") != 0)
reaktor_hint(SDL_HINT_RENDER_DRIVER, app->renderer_pref);
} else {
SDL_strlcpy(app->render_mode, "auto: software",
sizeof(app->render_mode));
reaktor_hint(SDL_HINT_RENDER_DRIVER, "software");
}
#ifdef __EMSCRIPTEN__
app->borderless = 0;
#else
app->borderless = g_launch.window.borderless != 0;
#endif
{
float pre = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay());
int win_w, win_h;
if (pre <= 0.0f) pre = 1.0f;
win_w = (int)((g_launch.window.w > 0 ? g_launch.window.w : WINDOW_WIDTH) * pre + 0.5f);
win_h = (int)((g_launch.window.h > 0 ? g_launch.window.h : WINDOW_HEIGHT) * pre + 0.5f);
#ifdef __EMSCRIPTEN__
web_page_size(&win_w, &win_h);
#endif
SDL_WindowFlags flags = SDL_WINDOW_RESIZABLE |
SDL_WINDOW_HIGH_PIXEL_DENSITY |
(app->borderless ? SDL_WINDOW_BORDERLESS : 0) |
(g_launch.window.skip_taskbar ? SDL_WINDOW_UTILITY : 0) |
(placed(app) || starts_hidden(app) ? SDL_WINDOW_HIDDEN : 0);
Uint64 t0 = SDL_GetPerformanceCounter();
if (!open_window(app, win_w, win_h, flags)) {
SDL_Log("renderer '%s' would not start (%s); falling back",
app->render_mode, SDL_GetError());
reaktor_hint(SDL_HINT_RENDER_DRIVER, NULL);
SDL_strlcpy(app->render_mode, "auto", sizeof(app->render_mode));
if (!open_window(app, win_w, win_h, flags))
return fail(app, "The window could not be opened");
}
if (renderer_is_software(app->ren)) {
if (SDL_strcmp(app->render_mode, "auto") == 0) {
SDL_Renderer *sw;
SDL_DestroyRenderer(app->ren);
app->ren = NULL;
sw = SDL_CreateRenderer(app->win, "software");
if (!sw) sw = SDL_CreateRenderer(app->win, NULL);
if (!sw) return fail(app, "No renderer could draw the window");
app->ren = sw;
SDL_strlcpy(app->render_mode, "auto: software (no GPU)",
sizeof(app->render_mode));
} else {
SDL_strlcpy(app->render_mode + SDL_strlen(app->render_mode),
" (no GPU)",
sizeof(app->render_mode) -
SDL_strlen(app->render_mode));
}
}
app->renderer_is_sw =
SDL_strcmp(SDL_GetRendererName(app->ren), "software") == 0;
app->window_ms_x100 = ms_x100(t0, SDL_GetPerformanceCounter());
#ifndef __EMSCRIPTEN__
if (g_launch.window.min_w > 0 || g_launch.window.min_h > 0)
SDL_SetWindowMinimumSize(app->win,
(int)(g_launch.window.min_w * pre + 0.5f),
(int)(g_launch.window.min_h * pre + 0.5f));
#endif
if (placed(app)) {
if (g_launch.window.centered)
SDL_SetWindowPosition(app->win, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
if (remembers(app)) reaktor_window_restore(app);
if (!starts_hidden(app)) SDL_ShowWindow(app->win);
}
reaktor_session_watch(app->win);
}
#ifdef __EMSCRIPTEN__
emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, app, 0,
web_on_resize);
#endif
reaktor_a11y_platform_init(reader_activate, reader_focus, app);
app->vsync_on = SDL_SetRenderVSync(app->ren, 1) ? 1 : 0;
app->aa_mode = (int)g_launch.anti_aliasing;
SDL_strlcpy(app->frame_rate, "waitevent", sizeof(app->frame_rate));
{
const SDL_DisplayMode *m =
SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(app->win));
float hz = (m && m->refresh_rate > 1.0f) ? m->refresh_rate : 60.0f;
SDL_snprintf(app->drag_rate, sizeof(app->drag_rate), "%.2f", hz);
}
if (app->borderless && g_launch.window.hit_test)
SDL_SetWindowHitTest(app->win, g_launch.window.hit_test, app);
reaktor_rss_mark(REAKTOR_RSS_WINDOW);
reaktor_set_window_icon(app->win, reaktor_launch_icon());
reaktor_set_scale(reaktor_dpi_query_scale(app->win));
apply_render_scale(app);
reaktor_rss_mark(REAKTOR_RSS_ICON);
app->ctx = nk_sdl_init(app->win, app->ren, nk_sdl_allocator());
if (!app->ctx) return fail(app, "The interface could not start");
reaktor_rss_mark(REAKTOR_RSS_NUKLEAR);
reaktor_locale_start(app->lang_pref);
rebuild_font(app);
reaktor_rss_mark(REAKTOR_RSS_FONT);
if (g_launch.start) {
int rc = g_launch.start(app, argc, argv);
if (rc) {
SDL_SetAtomicInt(&g_exit_code, rc);
return SDL_APP_FAILURE;
}
}
reaktor_rss_mark(REAKTOR_RSS_START);
take_pending(app);
read_prefs();
load_theme(app);
reaktor_rss_mark(REAKTOR_RSS_STYLE);
if (g_launch.single_instance) reaktor_instance_listen(app, g_launch.file_opened);
app->dirty = 1;
#ifdef __EMSCRIPTEN__
reaktor_input_start();
#endif
nk_input_begin(app->ctx);
g_started = 1;
SDL_SetAtomicInt(&g_running, 1);
reaktor_inspector_start(app, &g_launch.inspector, g_inspect_flag);
return SDL_APP_CONTINUE;
}
static void
drag_end(App *app)
{
app->dragging = 0;
app->drag_in_field = 0;
app->restore_rate = 2;
}
void
reaktor_take_event(App *app, SDL_Event *event)
{
#ifdef __EMSCRIPTEN__
if (reaktor_input_page_key(app, event)) return;
#endif
if (app->secondary) reaktor_windows_take(app, event);
else if (reaktor_inspector_event(app, event)) return;
switch (event->type) {
case SDL_EVENT_MOUSE_BUTTON_DOWN:
case SDL_EVENT_MOUSE_BUTTON_UP:
case SDL_EVENT_MOUSE_WHEEL:
case SDL_EVENT_KEY_DOWN:
case SDL_EVENT_KEY_UP:
case SDL_EVENT_TEXT_INPUT:
case SDL_EVENT_TEXT_EDITING:
case SDL_EVENT_WINDOW_RESIZED:
case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
case SDL_EVENT_WINDOW_EXPOSED:
case SDL_EVENT_WINDOW_SHOWN:
case SDL_EVENT_WINDOW_FOCUS_GAINED:
case SDL_EVENT_WINDOW_FOCUS_LOST:
case SDL_EVENT_WINDOW_MOUSE_LEAVE:
case SDL_EVENT_SYSTEM_THEME_CHANGED:
case SDL_EVENT_LOCALE_CHANGED:
case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
case SDL_EVENT_WINDOW_HDR_STATE_CHANGED:
app->dirty = 1;
app->why |= REAKTOR_WHY_INPUT;
break;
default:
break;
}
switch (event->type) {
case SDL_EVENT_WINDOW_RESIZED:
case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
case SDL_EVENT_WINDOW_RESTORED:
case SDL_EVENT_WINDOW_MAXIMIZED:
case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
if (!app->dragging && app->restore_rate < 2) app->restore_rate = 2;
/* fall through */
case SDL_EVENT_WINDOW_EXPOSED:
case SDL_EVENT_WINDOW_SHOWN:
case SDL_EVENT_WINDOW_HDR_STATE_CHANGED:
case SDL_EVENT_RENDER_TARGETS_RESET:
case SDL_EVENT_RENDER_DEVICE_RESET:
app->must_draw = 1;
break;
default:
break;
}
switch (event->type) {
case SDL_EVENT_MOUSE_MOTION:
if (app->dragging) { app->drag_moved = 1; app->dirty = 1; }
if (reaktor_hot_motion(app, event->motion.x, event->motion.y))
reaktor_hover_redraw(app);
break;
case SDL_EVENT_MOUSE_BUTTON_DOWN:
app->focus_visible = 0;
app->dragging = 1;
app->drag_mouse = event->button.which != SDL_TOUCH_MOUSEID &&
event->button.which != SDL_PEN_MOUSEID;
app->restore_rate = 0;
if (app->field_rect_valid) {
struct nk_rect r = app->field_rect;
float bx = event->button.x, by = event->button.y;
app->drag_in_field = bx >= r.x && bx <= r.x + r.w &&
by >= r.y && by <= r.y + r.h;
}
reaktor_hint(SDL_HINT_MAIN_CALLBACK_RATE, app->drag_rate);
break;
case SDL_EVENT_WINDOW_FOCUS_GAINED:
if (!app->secondary && read_prefs()) load_theme(app);
break;
case SDL_EVENT_WINDOW_FOCUS_LOST:
if (app->dragging) {
drag_end(app);
}
break;
case SDL_EVENT_MOUSE_BUTTON_UP:
drag_end(app);
break;
case SDL_EVENT_MOUSE_WHEEL:
if (!app->dragging) app->restore_rate = 2;
break;
case SDL_EVENT_WINDOW_MOUSE_LEAVE:
app->hot_last = -1;
app->hot_last_repaint = 0;
app->want_cursor = 0;
break;
case SDL_EVENT_SYSTEM_THEME_CHANGED:
if (read_prefs() || app->theme_mode == REAKTOR_THEME_SYSTEM) load_theme(app);
break;
case SDL_EVENT_LOCALE_CHANGED:
if (!app->secondary && reaktor_locale_system() && reaktor_locale_set(NULL))
reaktor_windows_dirty();
break;
case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
if (app->secondary) break;
reaktor_set_scale(reaktor_dpi_query_scale(app->win));
apply_render_scale(app);
img_cache_clear(app);
rebuild_font(app);
reaktor_windows_rescale();
break;
case SDL_EVENT_KEY_DOWN:
app->queue.hook_ate = reaktor_key_hook(app, event);
if (app->queue.hook_ate) return;
if (focus_key(app, event)) return;
break;
case SDL_EVENT_KEY_UP:
app->queue.hook_ate = 0;
break;
case SDL_EVENT_TEXT_INPUT:
if (app->queue.hook_ate) {
app->queue.hook_ate = 0;
return;
}
break;
case SDL_EVENT_DROP_FILE:
if (g_launch.file_opened && event->drop.data)
g_launch.file_opened(app, event->drop.data);
app->dirty = 1;
break;
default:
if (event->type >= SDL_EVENT_USER) {
SDL_SetAtomicInt(&app->wake, 0);
app->dirty = 1;
}
break;
}
if (app->drag_in_field && event->type == SDL_EVENT_MOUSE_MOTION &&
app->field_rect_valid) {
struct nk_rect r = app->field_rect;
float lo_x = r.x + 2.0f, hi_x = r.x + r.w - 2.0f;
float lo_y = r.y + 2.0f, hi_y = r.y + r.h - 2.0f;
if (event->motion.x < lo_x) event->motion.x = lo_x;
if (event->motion.x > hi_x) event->motion.x = hi_x;
if (event->motion.y < lo_y) event->motion.y = lo_y;
if (event->motion.y > hi_y) event->motion.y = hi_y;
}
nk_sdl_handle_event(app->ctx, event);
}
static char *g_confirm;
static int g_confirm_id;
static void
confirm_answered(App *app, int button, void *user)
{
(void)user;
if (button == 1) reaktor_quit(app, 0);
}
static int
confirm_open(App *app)
{
static const char *const buttons[2] = { "Cancel", "Quit" };
SDL_WindowFlags flags;
if (!g_confirm) return 0;
flags = SDL_GetWindowFlags(app->win);
if (flags & SDL_WINDOW_HIDDEN) SDL_ShowWindow(app->win);
if (flags & SDL_WINDOW_MINIMIZED) SDL_RestoreWindow(app->win);
SDL_RaiseWindow(app->win);
if (reaktor_floater_is_open(app, g_confirm_id)) return 1;
g_confirm_id = reaktor_ask(app, &(reaktor_question){
.text = g_confirm, .buttons = buttons, .count = 2,
.answered = confirm_answered });
return g_confirm_id != 0;
}
static SDL_AppResult
quit_asked(App *app, reaktor_quit_reason why)
{
int refused = app && g_started && g_launch.closing &&
g_launch.closing(app, why);
if (why != REAKTOR_QUIT_WINDOW && why != REAKTOR_QUIT_APP &&
why != REAKTOR_QUIT_CONSOLE)
return SDL_APP_SUCCESS;
if (refused || (app && g_started && confirm_open(app)))
return SDL_APP_CONTINUE;
return SDL_APP_SUCCESS;
}
static SDL_AppResult
bare_quit(App *app)
{
int again, r = reaktor_signal_reason(&again);
if (again) {
reaktor_hard_quit(130);
return SDL_APP_SUCCESS;
}
if (r) return quit_asked(app, (reaktor_quit_reason)(r - 1));
#ifdef __APPLE__
return quit_asked(app, REAKTOR_QUIT_APP);
#else
return quit_asked(app, REAKTOR_QUIT_SIGNAL);
#endif
}
static SDL_AppResult
app_event(void *appstate, SDL_Event *event)
{
App *app = (App *)appstate, *to;
if (SDL_GetAtomicInt(&g_hard_quit)) return SDL_APP_SUCCESS;
if (!(to = reaktor_windows_app(event))) {
switch (event->type) {
case SDL_EVENT_TERMINATING:
if (app) run_stop(app);
return SDL_APP_SUCCESS;
case SDL_EVENT_QUIT:
return bare_quit(app);
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
return quit_asked(app, REAKTOR_QUIT_WINDOW);
case SDL_EVENT_USER:
if (event->user.data1 == &g_quit_tag)
return quit_asked(app, (reaktor_quit_reason)event->user.code);
break;
default:
break;
}
if (!(to = app)) return SDL_APP_CONTINUE;
}
if (!to->secondary) reaktor_tray_event(to, event);
reaktor_input_event(to, event);
return SDL_APP_CONTINUE;
}
static void
main_page(App *app, struct nk_context *ctx, int w, int h, void *user)
{
(void)user;
g_launch.page(app, ctx, w, h);
}
static void
take_pending(App *app)
{
char fallback[32];
const char *n;
int i;
if (g_css_pending) {
for (g_css_n = i = 0; i < g_css_last_n; i++) {
SDL_snprintf(fallback, sizeof(fallback), "app/set%d.css", i);
if ((n = reaktor_asset_name(&g_css_last[i], fallback))) g_css[g_css_n++] = n;
}
g_css_pending = 0;
}
if (app->theme_pending) {
app->theme_mode = app->theme_pending - 1;
app->theme_pending = 0;
}
}
void
reaktor_app_size(const App *app, int *w, int *h)
{
float s = reaktor_scale();
*w = *h = 0;
SDL_GetWindowSizeInPixels(app->win, w, h);
if (s > 0.0f) {
*w = (int)(*w / s + 0.5f);
*h = (int)(*h / s + 0.5f);
}
}
void
reaktor_app_due(App *app, int w, int h)
{
SDL_Window *over = SDL_GetMouseFocus();
if (w != app->laid_w || h != app->laid_h) {
app->dirty = 1;
app->why |= REAKTOR_WHY_RESIZE;
}
if (app->fling_v != 0.0f) {
app->dirty = 1;
app->why |= REAKTOR_WHY_MOTION;
}
if (app->hover_pending &&
SDL_GetTicks() - app->last_draw_ms >= g_hover_gap_ms) {
app->hover_pending = 0;
app->dirty = 1;
if (!app->dragging && app->restore_rate < 1) app->restore_rate = 1;
}
if (app->dragging && app->drag_mouse && !app->queue.n &&
!(SDL_GetGlobalMouseState(NULL, NULL) &
(SDL_BUTTON_LMASK | SDL_BUTTON_MMASK | SDL_BUTTON_RMASK |
SDL_BUTTON_X1MASK | SDL_BUTTON_X2MASK))) {
drag_end(app);
app->dirty = 1;
}
if (app->dragging) {
if (app->drag_moved || app->hot_last_repaint ||
SDL_GetTicks() - app->last_draw_ms >= g_hover_gap_ms)
app->dirty = 1;
}
if (over == app->win || (!over && !app->secondary)) reaktor_show_cursor(app);
}
static void
file_answer(App *app)
{
if (!SDL_GetAtomicInt(&app->file_ready)) return;
SDL_SetAtomicInt(&app->file_ready, 0);
app->file_pending = 0;
if (app->file_dialog.chosen)
app->file_dialog.chosen(app, (const char *const *)app->file_list,
app->file_count, app->file_dialog.user);
SDL_free(app->file_list);
app->file_list = NULL;
app->file_count = 0;
}
static int
same_frame(App *app, struct nk_context *ctx)
{
unsigned h;
int same;
if (g_launch.draw_every_frame) return 0;
h = reaktor_damage_collect(app, ctx);
h = reaktor_fnv_n(h, &app->laid_w, sizeof app->laid_w);
h = reaktor_fnv_n(h, &app->laid_h, sizeof app->laid_h);
h = reaktor_fnv_n(h, &app->clear, sizeof app->clear);
app->damage.forced = app->must_draw || app->want_capture || app->shot_path ||
!app->first_frame_done;
same = h == app->frame_hash && !app->damage.forced;
app->frame_hash = h;
app->must_draw = 0;
return same;
}
static int
take_shot(App *app)
{
static int done;
SDL_Surface *sh;
if (!app->shot_path || !*app->shot_path || done) return 0;
if (!reaktor_frame_settled(app)) {
app->dirty = 1;
reaktor_app_wake(app);
return 0;
}
done = 1;
sh = SDL_RenderReadPixels(app->ren, NULL);
if (!sh || !SDL_SaveBMP(sh, app->shot_path)) {
SDL_Log("screenshot: %s", SDL_GetError());
app->shot_failed = 1;
}
if (sh) SDL_DestroySurface(sh);
return 1;
}
static void
key_click(App *app)
{
struct nk_context *ctx = app->ctx;
int x, y;
if (app->key_click == KEY_CLICK_PRESS &&
(app->dragging || !app->focus_seen)) {
app->key_click = KEY_CLICK_NONE;
return;
}
if (app->key_click < KEY_CLICK_PRESS) return;
x = (int)(app->focus_rect.x + app->focus_rect.w * 0.5f);
y = (int)(app->focus_rect.y + app->focus_rect.h * 0.5f);
if (app->key_click == KEY_CLICK_PRESS) {
app->queue.pointer = SDL_GetMouseFocus() == app->win
? ctx->input.mouse.pos : nk_vec2(-1.0f, -1.0f);
nk_input_motion(ctx, x, y);
nk_input_button(ctx, NK_BUTTON_LEFT, x, y, nk_true);
app->key_click = KEY_CLICK_RELEASE;
reaktor_app_wake(app);
} else {
nk_input_button(ctx, NK_BUTTON_LEFT, x, y, nk_false);
app->key_click = app->key_click == KEY_CLICK_AGAIN
? KEY_CLICK_ASKED : KEY_CLICK_NONE;
app->queue.pointer_back = 1;
if (!app->dragging) app->restore_rate = 2;
}
app->dirty = 1;
}
int
reaktor_app_frame(App *app, int win_w, int win_h, const char *title,
reaktor_page_fn page, void *user)
{
struct nk_context *ctx = app->ctx;
struct nk_rect area = nk_rect(0, 0, (float)win_w, (float)win_h);
int is_main = !app->secondary, shot = 0, shown;
Uint64 now = SDL_GetTicks(), t_build0, t_render0, t_present0, t_end;
int busy;
app->laid_w = win_w;
app->laid_h = win_h;
app->hot_n = 0;
app->editing = 0;
app->surface_at = nk_rect(0, 0, 0, 0);
if (app->last_frame_ms) app->frame_gap_ms = (float)(now - app->last_frame_ms);
app->last_frame_ms = now;
nk_style_push_vec2(ctx, &ctx->style.window.padding, nk_vec2(0, 0));
nk_style_push_float(ctx, &ctx->style.window.border, 0.0f);
nk_style_push_style_item(ctx, &ctx->style.window.fixed_background,
nk_style_item_color(app->clear));
t_build0 = SDL_GetPerformanceCounter();
if (is_main) reaktor_a11y_platform_drain();
else reaktor_a11y_platform_window_drain(app->win);
key_click(app);
reaktor_fling_step(app);
nk_input_end(ctx);
ctx->style.text.color = app->text;
file_answer(app);
app->focus_seen = 0;
app->popup_open = 0;
app->popup_lo = app->popup_hi = app->trap_lo = app->trap_hi = -1;
if (!app->anim) app->anim = reaktor_anim_create();
if (app->anim) reaktor_anim_frame(app->anim, app->frame_gap_ms);
reaktor_a11y_begin(&app->a11y, title, area);
reaktor_frame_begin(app, ctx, area);
nk_style_push_style_item(ctx, &ctx->style.window.fixed_background,
nk_style_item_hide());
shown = reaktor_layer_begin(app, ctx, "page", area,
(nk_flags)NK_WINDOW_BACKGROUND |
(nk_flags)NK_WINDOW_NO_SCROLLBAR,
FOCUS_PAGE, 0,
is_main && reaktor_floaters_modal() ? HOLD_ALL
: HOLD_NONE,
&app->page_held);
nk_style_pop_style_item(ctx);
if (shown) {
nk_style_pop_vec2(ctx);
page(app, ctx, win_w, win_h, user);
nk_style_push_vec2(ctx, &ctx->style.window.padding, nk_vec2(0, 0));
}
reaktor_layer_end(app, ctx, shown);
if (is_main) {
struct nk_window *pw = nk_window_find(ctx, "page");
reaktor_floaters_draw(app, ctx, win_w, win_h);
reaktor_toasts_draw(app, ctx, win_w, win_h,
reaktor_floaters_modal() ||
(reaktor_popup_open(pw) && pw->popup.type == NK_PANEL_POPUP));
}
app->focus_step = 0;
if (!ctx->input.mouse.buttons[NK_BUTTON_LEFT].down) app->drag.armed = app->drag.active = 0;
{
int ring = app->focus_visible && app->focus_seen &&
app->focus_layer == FOCUS_POPUP;
if (ring || app->tip || (is_main && reaktor_inspector_marks(app)))
reaktor_overlay(app, ctx, ring);
}
app->stop_editing = 0;
if (app->activate_id && app->focus_seen && !app->focus_held &&
!reaktor_focus_covered(app))
reaktor_key_click_ask(app);
app->activate_id = 0;
if (app->key_click == KEY_CLICK_ASKED) {
if (app->focus_seen && (app->focus_held || reaktor_focus_covered(app))) {
app->key_click = KEY_CLICK_NONE;
} else {
app->key_click = KEY_CLICK_PRESS;
app->dirty = 1;
reaktor_app_wake(app);
}
}
reaktor_frame_end();
reaktor_a11y_end(&app->a11y);
focus_resolve(app);
if (is_main) {
reaktor_a11y_platform_push(&app->a11y, app->focus_id);
a11y_dump_once(app);
if (reaktor_test_hook) reaktor_test_hook(app);
reaktor_inspector_frame(app);
} else {
reaktor_a11y_platform_window_push(app->win, &app->a11y, app->focus_id,
reader_activate, reader_focus, app);
}
busy = app->anim && reaktor_anim_settle();
if (busy) {
app->dirty = 1;
reaktor_app_wake(app);
}
nk_sdl_update_TextInput(ctx);
#ifdef __EMSCRIPTEN__
reaktor_web_keys_wants(app->editing);
#endif
reaktor_place_ime(app);
nk_style_pop_style_item(ctx);
nk_style_pop_float(ctx);
nk_style_pop_vec2(ctx);
t_render0 = SDL_GetPerformanceCounter();
if (app->build_only || same_frame(app, ctx) || !reaktor_damage_render(app)) {
/* A drawn frame clears in nk_sdl_frame_done; kept, the next build's
popups and overlay never join the list. */
nk_clear(ctx);
t_present0 = t_end = t_render0;
app->frames_skipped++;
if (busy && !app->build_only) {
reaktor_hint(SDL_HINT_MAIN_CALLBACK_RATE, app->drag_rate);
if (!reaktor_windows_holding()) app->restore_rate = 2;
}
} else {
app->frames_drawn++;
nk_sdl_frame_done(ctx);
SDL_FlushRenderer(app->ren);
t_present0 = SDL_GetPerformanceCounter();
if (is_main) shot = take_shot(app);
if (app->want_capture) {
app->capture = SDL_RenderReadPixels(app->ren, NULL);
app->want_capture = 0;
}
SDL_RenderPresent(app->ren);
reaktor_damage_presented(app);
t_end = SDL_GetPerformanceCounter();
}
app->last_draw_ms = SDL_GetTicks();
if (is_main && app->first_frame_done) calibrate_hover_gap(app);
app->build_ms_x100 = ms_x100(t_build0, t_render0);
app->render_ms_x100 = ms_x100(t_render0, t_present0);
app->present_ms_x100 = ms_x100(t_present0, t_end);
nk_input_begin(ctx);
app->dirty = 0;
app->drag_moved = 0;
if (app->restore_rate > 0) {
if (--app->restore_rate > 0) {
app->dirty = 1;
reaktor_app_wake(app);
} else {
reaktor_hint(SDL_HINT_MAIN_CALLBACK_RATE, app->frame_rate);
}
}
reaktor_replay_held(app);
return shot;
}
static SDL_AppResult
app_iterate(void *appstate)
{
App *app = (App *)appstate;
int win_w, win_h;
if (SDL_GetAtomicInt(&g_hard_quit)) return SDL_APP_SUCCESS;
if (g_pending_title) {
SDL_free(g_title);
g_title = g_pending_title;
g_pending_title = NULL;
SDL_SetWindowTitle(app->win, g_title);
}
if (g_css_pending || app->theme_pending) {
take_pending(app);
read_prefs();
load_theme(app);
}
reaktor_windows_draw();
#ifdef __APPLE__
if (app->borderless_lock_frames > 0)
app->borderless_lock_frames--;
if (app->borderless_pending) {
int w = 0, h = 0;
app->borderless_pending = 0;
app->borderless = !app->borderless;
SDL_SetWindowBordered(app->win, app->borderless ? false : true);
SDL_SetWindowHitTest(app->win,
app->borderless ? g_launch.window.hit_test : NULL,
app->borderless ? app : NULL);
SDL_SyncWindow(app->win);
SDL_GetWindowSize(app->win, &w, &h);
SDL_SetWindowSize(app->win, w, h);
app->dirty = 1;
app->borderless_lock_frames = 3;
}
#endif
reaktor_app_size(app, &win_w, &win_h);
reaktor_app_due(app, win_w, win_h);
if (!app->dirty)
return SDL_APP_CONTINUE;
if (reaktor_app_frame(app, win_w, win_h, launch_title(), main_page, NULL))
return SDL_APP_SUCCESS;
if (!app->first_frame_done) {
app->first_frame_done = 1;
app->first_ms_x100 = ms_x100(app->started, SDL_GetPerformanceCounter());
reaktor_hint(SDL_HINT_MAIN_CALLBACK_RATE, app->frame_rate);
reaktor_release_free_memory();
}
return SDL_APP_CONTINUE;
}
static void
app_quit(void *appstate, SDL_AppResult result)
{
App *app = (App *)appstate;
(void)result;
SDL_SetAtomicInt(&g_running, 0);
reaktor_instance_stop();
if (!app) {
reaktor_process_end();
return;
}
reaktor_inspector_stop(app);
watch_stop();
run_stop(app);
if (remembers(app)) reaktor_window_remember(app);
reaktor_timers_drop(NULL);
if (g_launch.save_settings != REAKTOR_SAVE_NEVER) reaktor_settings_save();
reaktor_settings_free();
reaktor_undo_clear(app);
if (!SDL_GetAtomicInt(&g_exit_code) && (app->shot_failed || app->dump_failed))
SDL_SetAtomicInt(&g_exit_code, app->shot_failed && app->dump_failed ? 4
: app->shot_failed ? 2 : 3);
if (app->ctx) nk_input_end(app->ctx);
reaktor_app_input_free(app);
field_undo_clear(app);
reaktor_layout_free(&app->lay);
reaktor_toast_clear();
reaktor_floaters_clear(app);
reaktor_windows_close_all();
reaktor_tray_close(app);
reaktor_style_shutdown();
{
int k;
for (k = 0; k < REAKTOR_CURSORS; k++) {
if (g_cursor[k]) SDL_DestroyCursor(g_cursor[k]);
g_cursor[k] = NULL;
}
}
if (app->ren) img_cache_free(app);
reaktor_damage_free(app);
if (app->ctx) nk_sdl_shutdown(app->ctx);
reaktor_fontset_free(&app->fonts);
atlas_forget();
if (app->ren) SDL_DestroyRenderer(app->ren);
if (app->win) SDL_DestroyWindow(app->win);
reaktor_anim_destroy(app->anim);
app->anim = NULL;
reaktor_app_free(app);
g_app = NULL;
reaktor_signal_unwatch();
reaktor_process_end();
log_close();
}
static void
launch_copy(const reaktor_launch *l)
{
char fallback[32];
int i;
g_launch = *l;
g_launch.name = own(l->name);
g_launch.id = own(l->id);
g_launch.version = own(l->version);
g_launch.log = own(l->log);
g_launch.window.title = own(l->window.title);
g_confirm = l->confirm_close ? SDL_strdup(l->confirm_close) : NULL;
g_icon_name = reaktor_asset_name(&l->window.icon, "app/icon.svg");
g_font = reaktor_asset_name(&l->font, "app/font");
g_font_bold = reaktor_asset_name(&l->font_bold, "app/font-bold");
for (i = 0; i < REAKTOR_LAYER_MAX; i++) {
const char *n;
SDL_snprintf(fallback, sizeof(fallback), "app/%d.css", i);
if ((n = reaktor_asset_name(&l->css[i], fallback))) g_css[g_css_n++] = n;
SDL_snprintf(fallback, sizeof(fallback), "app/fallback%d", i);
if ((n = reaktor_asset_name(&l->font_fallbacks[i], fallback)))
g_fallbacks[g_fallback_n++] = n;
if (l->icon_dirs[i]) g_icon_dirs[g_icon_dir_n++] = own(l->icon_dirs[i]);
}
for (i = 0; i < l->asset_count; i++)
if (l->assets[i].data &&
!reaktor_asset_register(own(l->assets[i].name), l->assets[i].data,
l->assets[i].size))
SDL_Log("too many registered assets; %s is not one", l->assets[i].name);
}
int
reaktor_launch_app(int argc, char **argv, const reaktor_launch *l)
{
static int launched;
int rc, code;
if (!l || !l->page) {
SDL_Log("launchApp: a page is required");
return 1;
}
if (launched++) {
SDL_Log("launchApp: once per process");
return 1;
}
launch_copy(l);
rc = SDL_EnterAppMainCallbacks(argc, argv, app_init, app_iterate,
app_event, app_quit);
code = SDL_GetAtomicInt(&g_exit_code);
#ifndef __EMSCRIPTEN__
SDL_free(g_title);
SDL_free(g_pending_title);
SDL_free(g_confirm);
g_title = g_pending_title = g_confirm = NULL;
reaktor_asset_forget();
forget_owned();
#endif
return code ? code : rc;
}
void
reaktor_quit(App *app, int exit_code)
{
(void)app;
#ifdef __EMSCRIPTEN__
(void)exit_code;
SDL_Log("quit is ignored on the web");
#else
reaktor_hard_quit(exit_code);
#endif
}
void
reaktor_request_quit(App *app)
{
(void)app;
#ifdef __EMSCRIPTEN__
SDL_Log("quit is ignored on the web");
#else
push_quit(REAKTOR_QUIT_APP);
#endif
}
void
reaktor_wake(App *app)
{
App *to = app ? app : g_app;
if (!to || !SDL_GetAtomicInt(&g_running)) return;
if (SDL_CompareAndSwapAtomicInt(&to->wake, 0, 1) && !reaktor_app_wake(to))
SDL_SetAtomicInt(&to->wake, 0);
}
void
reaktor_set_theme(App *app, reaktor_theme theme)
{
App *m = g_app ? g_app : app;
if (m->theme_pending ? m->theme_pending == (int)theme + 1
: m->theme_mode == (int)theme)
return;
m->theme_pending = (int)theme + 1;
reaktor_wake(m);
}
static int
same_asset(const reaktor_asset *a, const reaktor_asset *b)
{
return SDL_strcmp(a->path ? a->path : "", b->path ? b->path : "") == 0 &&
SDL_strcmp(a->name ? a->name : "", b->name ? b->name : "") == 0 &&
a->data == b->data && a->size == b->size;
}
void
reaktor_set_css(App *app, const reaktor_asset *css, int count)
{
int i;
if (!css || count < 0) count = 0;
if (count > REAKTOR_LAYER_MAX) count = REAKTOR_LAYER_MAX;
if (count == g_css_last_n) {
for (i = 0; i < count && same_asset(&css[i], &g_css_last[i]); i++) {}
if (i == count) return;
}
g_css_last_n = count;
for (i = 0; i < count; i++) {
g_css_last[i] = css[i];
g_css_last[i].path = own(css[i].path);
g_css_last[i].name = own(css[i].name);
}
g_css_pending = 1;
reaktor_wake(app);
}
void
reaktor_restyle(void)
{
if (!g_app) return;
g_app->theme_pending = g_app->theme_mode + 1;
reaktor_wake(g_app);
}
void
reaktor_set_title(App *app, const char *title)
{
const char *now = g_pending_title ? g_pending_title : launch_title();
if (app && app->secondary) {
reaktor_windows_retitle(app, title);
return;
}
if (!title || SDL_strcmp(title, now) == 0) return;
SDL_free(g_pending_title);
g_pending_title = SDL_strdup(title);
reaktor_wake(app);
}
void
reaktor_set_confirm_close(App *app, const char *question)
{
char *q = question ? SDL_strdup(question) : NULL;
SDL_free(g_confirm);
g_confirm = q;
if (!q) reaktor_floater_close(g_app ? g_app : app, g_confirm_id);
}
App *
reaktor_main_app(void)
{
return g_app;
}
struct nka_context *
reaktor_anim(App *app)
{
if (app && !app->anim) app->anim = reaktor_anim_create();
return app ? app->anim : NULL;
}
const char *
reaktor_launch_icon(void)
{
return g_icon_name ? g_icon_name : REAKTOR_MARK;
}
void *
reaktor_user(App *app)
{
(void)app;
return g_launch.user;
}
SDL_Window *
reaktor_sdl_window(App *app)
{
return app ? app->win : NULL;
}
SDL_Renderer *
reaktor_sdl_renderer(App *app)
{
return app ? app->ren : NULL;
}
int
reaktor_dark(App *app)
{
return app && app->dark;
}
struct nk_color
reaktor_page_color(App *app)
{
return app ? app->page : nk_rgb(247, 247, 247);
}
struct nk_color
reaktor_accent_color(App *app)
{
return app ? app->accent : nk_rgb(0, 112, 224);
}
reaktor_theme
reaktor_get_theme(App *app)
{
return app ? (reaktor_theme)app->theme_mode : REAKTOR_THEME_SYSTEM;
}
const char *
reaktor_lang_pref(App *app)
{
App *m = reaktor_main_app();
return app && m ? m->lang_pref : NULL;
}
void
reaktor_set_borderless(App *app, int on)
{
if (!app || !app->win || app->secondary || !on == !app->borderless) return;
#ifdef __APPLE__
if (app->borderless_lock_frames == 0) {
app->borderless_pending = 1;
app->dirty = 1;
}
#else
app->borderless = on != 0;
SDL_SetWindowBordered(app->win, app->borderless ? false : true);
SDL_SetWindowHitTest(app->win,
app->borderless ? g_launch.window.hit_test : NULL,
app->borderless ? app : NULL);
app->dirty = 1;
#endif
}
int
reaktor_borderless(App *app)
{
return app && app->borderless;
}
void
reaktor_set_visible(App *app, int on)
{
if (!app || !app->win) return;
if (on) {
SDL_ShowWindow(app->win);
if (SDL_GetWindowFlags(app->win) & SDL_WINDOW_MINIMIZED)
SDL_RestoreWindow(app->win);
SDL_RaiseWindow(app->win);
} else {
SDL_HideWindow(app->win);
}
app->dirty = 1;
reaktor_wake(app);
}
const char *
reaktor_version(void)
{
return REAKTOR_VERSION_STRING;
}