//- small helpers internal b32 ui_hovered(PlatformInput *input, Rect rect) { return input->mouse_in_window && rect_contains(rect, input->mouse_x, input->mouse_y); } internal b32 ui_clicked(PlatformInput *input, Rect rect) { return ButtonPressed(input->mouse[0]) && ui_hovered(input, rect); } internal f32 ui_baseline(App *app, FontKind kind, f32 size, f32 y0, f32 height) { f32 line = font_line_height(&app->fonts, kind, size); f32 ascent = font_ascent(&app->fonts, kind, size); return floorf(y0 + (height - line) * 0.5f + ascent + 0.5f); } // NOTE: the integer cells (surah #, ayat, counts) are on every visible row every frame, and // vsnprintf is a few hundred cycles of format parsing for them. these just emit the digits. internal u32 ui_digits(u8 *out, u32 value) { u8 buffer[10]; u32 size = 0; do { buffer[size++] = (u8)('0' + value % 10); value /= 10; } while(value); for(u32 index = 0; index < size; ++index) out[index] = buffer[size - 1 - index]; return size; } internal String8 ui_u32(Arena *arena, u32 value) { u8 *out = PushArray(arena, u8, 10); return ToString8Size(out, ui_digits(out, value)); } // "ab", like "18/114" internal String8 ui_u32_pair(Arena *arena, u32 a, char separator, u32 b) { u8 *out = PushArray(arena, u8, 21); u32 size = ui_digits(out, a); out[size++] = (u8)separator; size += ui_digits(out + size, b); return ToString8Size(out, size); } internal String8 ui_format(Arena *arena, const char *format, ...) { va_list args; va_start(args, format); char buffer[256]; int length = vsnprintf(buffer, sizeof(buffer), format, args); va_end(args); length = Clamp(length, 0, (int)sizeof(buffer) - 1); u8 *out = PushArray(arena, u8, (u64)Max(length, 1)); MemCpy(out, buffer, (u64)length); return ToString8Size(out, (u64)length); } internal void format_duration(char *out, u32 size, f64 seconds) { u32 total = (u32)Max(seconds, 0.0); if(total >= 3600) { snprintf(out, size, "%u:%02u:%02u", total / 3600, (total / 60) % 60, total % 60); } else { snprintf(out, size, "%u:%02u", total / 60, total % 60); } } internal void app_message(App *app, const char *format, ...) { va_list args; va_start(args, format); vsnprintf(app->message, sizeof(app->message), format, args); va_end(args); app->message_ns = time_now_ns(); } internal b32 str8_contains_nocase(String8 haystack, const char *needle, u32 needle_size) { if(needle_size == 0) return true; for(u64 start = 0; start + needle_size <= haystack.size; ++start) { u32 index = 0; for(; index < needle_size; ++index) { u8 a = haystack.data[start + index], b = (u8)needle[index]; if(a >= 'A' && a <= 'Z') a += 32; if(b >= 'A' && b <= 'Z') b += 32; if(a != b) break; } if(index == needle_size) return true; } return false; } internal void scroll_update(ScrollList *scroll, f32 content, f32 view, f32 dt, b32 *animating) { f32 max_offset = Max(content - view, 0.0f); scroll->target = Clamp(scroll->target, 0.0f, max_offset); f32 speed = ui_theme.scroll_speed; scroll->offset += (scroll->target - scroll->offset) * (speed > 0 ? 1.0f - expf(-dt * speed) : 1.0f); if(fabsf(scroll->target - scroll->offset) < 0.25f) { scroll->offset = scroll->target; } scroll->offset = Clamp(scroll->offset, 0.0f, max_offset); if(scroll->offset != scroll->target) *animating = true; } //- playback queries internal u32 app_current_key(App *app) { if(app->position.flags & PLAYBACK_HAS_TRACK) { return app->position.track_key; } u32 status = AtomicLoadRelaxed(&app->decoder->status); if(status == DECODER_BUFFERING || status == DECODER_DECODING) { return app->requested_key; } return TRACK_NONE; } internal u64 app_track_total(App *app) { if(app->position.total_frames) { return app->position.total_frames; } if(AtomicLoadRelaxed(&app->decoder->status_key) == app_current_key(app)) { return AtomicLoadRelaxed(&app->decoder->published_total); } return 0; } internal u32 app_selected_key(App *app) { if(app->qari < 0 || (u32)app->qari >= app->catalog->qari_count) return TRACK_NONE; return TrackKey(app->qari, app->surah); } //- disk summary //- actions internal s32 queue_find(App *app, u32 key); internal void app_play_in_queue(App *app, u32 key); internal void app_play(App *app, u32 key, u64 frame) { if(!app->audio_ok || key == TRACK_NONE) { return; } app->requested_key = key; app->paused = false; app->resume_frame = 0; audio_output_set_paused(app->output, false); // NOTE: a plain single play ends any queue a multi selection started if(app->queue_count) { app->queue_count = 0; decoder_command(app->decoder, DECODER_QUEUE_CLEAR, 0, 0); } decoder_command(app->decoder, DECODER_SET_AUTOPLAY, 0, app->settings.autoplay); decoder_command(app->decoder, DECODER_PLAY, key, frame); TrackEntry *entry = store_entry(app->store, key); if(entry && AtomicLoadRelaxed(TrackStatePtr(app->store, entry)) != TRACK_DONE) { app_message(app, "streaming %u. " Str8Fmt, TrackSurah(key) + 1, Str8Arg(app->catalog->surahs[TrackSurah(key)].name)); } } internal void app_toggle_pause(App *app) { if(!app->audio_ok) { return; } if(app_current_key(app) == TRACK_NONE) { app_play(app, app_selected_key(app), app->resume_frame); return; } app->paused = !app->paused; if(app->paused) { app->paused_since_ns = time_now_ns(); } audio_output_set_paused(app->output, app->paused); } internal void app_step_track(App *app, s32 delta) { u32 key = app_current_key(app); if(key == TRACK_NONE) key = app_selected_key(app); if(key == TRACK_NONE) return; // NOTE: inside a queue, < and > move through the queue s32 at = queue_find(app, key); if(at >= 0) { s32 next = at + delta; if(next >= 0 && next < (s32)app->queue_count) app_play_in_queue(app, app->queue[next]); return; } s32 surah = (s32)TrackSurah(key); for(;;) { surah += delta; if(surah < 0 || surah >= SURAH_COUNT) return; // NOTE: when listening offline, skip what isn't on disk if(app->settings.autoplay != AUTOPLAY_NEXT_DOWNLOADED || store_on_disk(app->store, TrackKey(TrackQari(key), surah))) break; } app_play(app, TrackKey(TrackQari(key), surah), 0); } internal void app_seek_seconds(App *app, f64 delta) { if(app_current_key(app) == TRACK_NONE || app->position.rate == 0) { return; } s64 frame = (s64)app->position.frame + (s64)(delta * app->position.rate); decoder_command(app->decoder, DECODER_SEEK, 0, (u64)Max(frame, (s64)0)); } internal void app_apply_settings(App *app) { settings_clamp(&app->settings); if(app->audio_ok) { audio_output_set_volume(app->output, app->settings.volume); decoder_command(app->decoder, DECODER_SET_AUTOPLAY, 0, app->settings.autoplay); } // NOTE: extra download workers are started by the host (player.cpp), never from here: this // code may live in the hot reloaded .so, and a thread running in it would crash on unload } internal void app_set_volume(App *app, f32 volume) { app->settings.volume = Clamp(volume, 0.0f, 1.0f); app_apply_settings(app); } internal const char *autoplay_name(u32 mode) { switch(mode) { case AUTOPLAY_OFF: return "off"; case AUTOPLAY_NEXT: return "next surah"; case AUTOPLAY_NEXT_DOWNLOADED: return "next downloaded"; } return "?"; } internal void app_download(App *app, u32 key) { if(key == TRACK_NONE) return; if(store_on_disk(app->store, key)) { app_message(app, "already on disk"); return; } store_request(app->store, key, true); app_message(app, "downloading %u. " Str8Fmt, TrackSurah(key) + 1, Str8Arg(app->catalog->surahs[TrackSurah(key)].name)); } internal void app_delete(App *app, u32 key) { if(key == TRACK_NONE) return; if(key == app_current_key(app)) { decoder_command(app->decoder, DECODER_STOP, 0, 0); app->requested_key = TRACK_NONE; } if(store_delete(app->store, key)) { app_message(app, "deleted %u. " Str8Fmt " from disk", TrackSurah(key) + 1, Str8Arg(app->catalog->surahs[TrackSurah(key)].name)); } else { app_message(app, "busy downloading, try again when it's done"); } } internal void app_delete_qari(App *app, u32 qari) { u32 deleted = 0; for(u32 surah = 0; surah < SURAH_COUNT; ++surah) { u32 key = TrackKey(qari, surah); if(store_on_disk(app->store, key)) { if(key == app_current_key(app)) decoder_command(app->decoder, DECODER_STOP, 0, 0); deleted += store_delete(app->store, key); } } app_message(app, "deleted %u surahs of " Str8Fmt, deleted, Str8Arg(app->catalog->qaris[qari].name)); } internal UIPlace app_place(App *app) { UIPlace place = {}; if(app->qari >= 0) { place.qari_id = app->catalog->qaris[app->qari].id; place.surah = (u32)app->surah; } return place; } internal void app_goto_place(App *app, UIPlace place) { s32 qari = catalog_find_qari_by_id(app->catalog, place.qari_id); if(qari < 0) { app_message(app, "mark not set"); return; } app->jump_back = app_place(app); app->qari = qari; app->surah = (s32)Min(place.surah, (u32)SURAH_COUNT - 1); app->keep_selection_visible = true; } //- layout pool internal s32 layout_alloc_panel(Layout *layout) { for(s32 index = 0; index < UI_MAX_PANELS; ++index) { if(layout->panels[index].kind == PANEL_FREE) { MemSetZero(&layout->panels[index], sizeof(Panel)); layout->panels[index].kind = PANEL_LEAF; // reserved right away, callers retype it layout->panels[index].parent = -1; return index; } } return -1; } internal s32 layout_alloc_view(Layout *layout, ViewKind kind) { for(s32 index = 0; index < UI_MAX_VIEWS; ++index) { if(layout->views[index].kind == VIEW_NONE) { MemSetZero(&layout->views[index], sizeof(View)); layout->views[index].kind = (u32)kind; return index; } } return -1; } internal s32 layout_leaf(Layout *layout, s32 parent, ViewKind *kinds, u32 count) { s32 panel = layout_alloc_panel(layout); Panel *p = &layout->panels[panel]; p->kind = PANEL_LEAF; p->parent = parent; for(u32 index = 0; index < count && p->tab_count < UI_MAX_TABS; ++index) { s32 view = layout_alloc_view(layout, kinds[index]); if(view >= 0) p->tabs[p->tab_count++] = (u8)view; } return panel; } internal s32 layout_split(Layout *layout, s32 parent, u32 axis, f32 ratio) { s32 panel = layout_alloc_panel(layout); Panel *p = &layout->panels[panel]; p->kind = PANEL_SPLIT; p->parent = parent; p->axis = axis; p->ratio = ratio; return panel; } // NOTE: the footer: the whole tree goes above a one line bar holding the status view internal void layout_add_status_bar(Layout *layout) { u32 free_panels = 0, free_views = 0; for(u32 index = 0; index < UI_MAX_PANELS; ++index) free_panels += (layout->panels[index].kind == PANEL_FREE); for(u32 index = 0; index < UI_MAX_VIEWS; ++index) free_views += (layout->views[index].kind == VIEW_NONE); if(free_panels < 2 || free_views < 1) return; ViewKind kinds[] = {VIEW_STATUS}; s32 old_root = layout->root; s32 split = layout_split(layout, -1, 1, -1.0f); s32 bar = layout_leaf(layout, split, kinds, 1); layout->panels[split].children[0] = old_root; layout->panels[split].children[1] = bar; layout->panels[old_root].parent = split; layout->root = split; } // NOTE: version 2 layouts had the footer drawn outside the tree: keep the arrangement, add the bar internal void layout_migrate(Layout *layout) { if(layout->version != 2 || layout->root < 0 || layout->root >= UI_MAX_PANELS) return; layout->version = UI_LAYOUT_VERSION; layout_add_status_bar(layout); } internal void ui_layout_default(Layout *layout) { MemSetZero(layout, sizeof(*layout)); layout->version = UI_LAYOUT_VERSION; // [ reciters | offline ] | [ surahs ] / [ playing | downloads | settings ] ViewKind left_kinds[] = {VIEW_RECITERS, VIEW_OFFLINE}; ViewKind top_kinds[] = {VIEW_SURAHS}; ViewKind bottom_kinds[] = {VIEW_PLAYING, VIEW_QUEUE, VIEW_DOWNLOADS, VIEW_VIEWS}; s32 root = layout_split(layout, -1, 0, 0.32f); s32 left = layout_leaf(layout, root, left_kinds, ArrayCount(left_kinds)); s32 right = layout_split(layout, root, 1, 0.68f); s32 top = layout_leaf(layout, right, top_kinds, ArrayCount(top_kinds)); s32 bottom = layout_leaf(layout, right, bottom_kinds, ArrayCount(bottom_kinds)); layout->panels[root].children[0] = left; layout->panels[root].children[1] = right; layout->panels[right].children[0] = top; layout->panels[right].children[1] = bottom; layout->root = root; layout->focused = left; layout_add_status_bar(layout); } // NOTE: a saved layout is trusted only if every index it holds is in range and consistent internal b32 layout_valid(Layout *layout) { if(layout->version != UI_LAYOUT_VERSION || layout->root < 0 || layout->root >= UI_MAX_PANELS) return false; if(layout->panels[layout->root].kind == PANEL_FREE) return false; for(s32 index = 0; index < UI_MAX_PANELS; ++index) { Panel *p = &layout->panels[index]; if(p->kind == PANEL_SPLIT) { for(u32 c = 0; c < 2; ++c) { s32 child = p->children[c]; if(child < 0 || child >= UI_MAX_PANELS || layout->panels[child].kind == PANEL_FREE || layout->panels[child].parent != index) return false; } } else if(p->kind == PANEL_LEAF) { if(p->tab_count > UI_MAX_TABS) return false; for(u32 t = 0; t < p->tab_count; ++t) { if(p->tabs[t] >= UI_MAX_VIEWS || layout->views[p->tabs[t]].kind == VIEW_NONE || layout->views[p->tabs[t]].kind >= VIEW_KIND_COUNT) return false; } } else if(p->kind != PANEL_FREE) { return false; } } return layout->focused >= 0 && layout->focused < UI_MAX_PANELS && layout->panels[layout->focused].kind == PANEL_LEAF; } internal s32 layout_first_leaf(Layout *layout, s32 panel) { while(layout->panels[panel].kind == PANEL_SPLIT) panel = layout->panels[panel].children[0]; return panel; } internal s32 panel_active_view(Layout *layout, s32 panel) { Panel *p = &layout->panels[panel]; if(p->kind != PANEL_LEAF || p->tab_count == 0) return -1; return p->tabs[Min(p->active_tab, p->tab_count - 1)]; } // NOTE: an empty leaf disappears: its sibling takes the parent's place in the tree internal void layout_collapse(Layout *layout, s32 leaf) { Panel *p = &layout->panels[leaf]; if(p->kind != PANEL_LEAF || p->tab_count > 0 || p->parent < 0) { return; } s32 parent = p->parent; Panel *pp = &layout->panels[parent]; s32 sibling = (pp->children[0] == leaf) ? pp->children[1] : pp->children[0]; s32 grand = pp->parent; // move the sibling into the parent's slot so the grandparent's child index stays valid Panel moved = layout->panels[sibling]; moved.parent = grand; *pp = moved; if(pp->kind == PANEL_SPLIT) { layout->panels[pp->children[0]].parent = parent; layout->panels[pp->children[1]].parent = parent; } layout->panels[sibling].kind = PANEL_FREE; layout->panels[leaf].kind = PANEL_FREE; if(layout->focused == leaf || layout->focused == sibling || layout->panels[layout->focused].kind != PANEL_LEAF) { layout->focused = layout_first_leaf(layout, parent); } } internal void layout_remove_tab(Layout *layout, s32 panel, u32 tab) { Panel *p = &layout->panels[panel]; for(u32 index = tab; index + 1 < p->tab_count; ++index) p->tabs[index] = p->tabs[index + 1]; --p->tab_count; if(p->active_tab >= p->tab_count && p->active_tab > 0) --p->active_tab; } internal void layout_close_view(Layout *layout, s32 panel, u32 tab) { Panel *p = &layout->panels[panel]; if(tab >= p->tab_count) return; layout->views[p->tabs[tab]].kind = VIEW_NONE; layout_remove_tab(layout, panel, tab); layout_collapse(layout, panel); } typedef enum DropZone { DROP_NONE, DROP_CENTER, DROP_LEFT, DROP_RIGHT, DROP_TOP, DROP_BOTTOM, } DropZone; // NOTE: move a view into a panel. center joins its tabs, an edge splits the panel and puts the // view on that side. the source panel collapses if this was its last tab. internal void layout_move_view(Layout *layout, s32 from_panel, s32 view, s32 to_panel, DropZone zone) { Panel *source = &layout->panels[from_panel]; u32 tab = 0; for(; tab < source->tab_count && source->tabs[tab] != view; ++tab) {} if(tab == source->tab_count) return; if(from_panel == to_panel && (zone == DROP_CENTER || source->tab_count == 1)) return; if(zone == DROP_CENTER) { Panel *target = &layout->panels[to_panel]; if(target->tab_count >= UI_MAX_TABS) return; layout_remove_tab(layout, from_panel, tab); target->tabs[target->tab_count] = (u8)view; target->active_tab = target->tab_count++; layout->focused = to_panel; layout_collapse(layout, from_panel); return; } // NOTE: split: the target leaf's content moves into a new child, the target slot becomes the split s32 keep = layout_alloc_panel(layout); s32 fresh = (keep >= 0) ? layout_alloc_panel(layout) : -1; if(keep < 0 || fresh < 0) { if(keep >= 0) layout->panels[keep].kind = PANEL_FREE; return; } layout_remove_tab(layout, from_panel, tab); Panel *target = &layout->panels[to_panel]; layout->panels[keep] = *target; layout->panels[keep].parent = to_panel; Panel *fresh_panel = &layout->panels[fresh]; fresh_panel->kind = PANEL_LEAF; fresh_panel->parent = to_panel; fresh_panel->tabs[0] = (u8)view; fresh_panel->tab_count = 1; b32 fresh_first = (zone == DROP_LEFT || zone == DROP_TOP); target->kind = PANEL_SPLIT; target->axis = (zone == DROP_LEFT || zone == DROP_RIGHT) ? 0 : 1; target->ratio = 0.5f; target->children[0] = fresh_first ? fresh : keep; target->children[1] = fresh_first ? keep : fresh; target->tab_count = 0; // NOTE: the source may have been the target leaf, which now lives in `keep` s32 source_now = (from_panel == to_panel) ? keep : from_panel; layout->focused = fresh; layout_collapse(layout, source_now); // collapsing can move panels around, find the new view's leaf again for(s32 index = 0; index < UI_MAX_PANELS; ++index) { Panel *p = &layout->panels[index]; if(p->kind != PANEL_LEAF) continue; for(u32 t = 0; t < p->tab_count; ++t) { if(p->tabs[t] == view) { layout->focused = index; p->active_tab = t; } } } } internal void layout_compute(Layout *layout, s32 panel, Rect rect) { Panel *p = &layout->panels[panel]; p->rect = rect; if(p->kind != PANEL_SPLIT) return; f32 half = UI_GAP * 0.5f; if(p->axis == 0) { f32 split = rect.x0 + rect_w(rect) * p->ratio; layout_compute(layout, p->children[0], Rect{rect.x0, rect.y0, split - half, rect.y1}); layout_compute(layout, p->children[1], Rect{split + half, rect.y0, rect.x1, rect.y1}); } else { f32 split = (p->ratio < 0) ? Max(rect.y1 - half + p->ratio * UI_STATUS_H, rect.y0 + half) // bar: -ratio lines : rect.y0 + rect_h(rect) * p->ratio; layout_compute(layout, p->children[0], Rect{rect.x0, rect.y0, rect.x1, split - half}); layout_compute(layout, p->children[1], Rect{rect.x0, split + half, rect.x1, rect.y1}); } } internal s32 layout_find_kind(Layout *layout, ViewKind kind, s32 *out_panel, u32 group = 0) { for(s32 index = 0; index < UI_MAX_PANELS; ++index) { Panel *p = &layout->panels[index]; if(p->kind != PANEL_LEAF) continue; for(u32 t = 0; t < p->tab_count; ++t) { if(layout->views[p->tabs[t]].kind == (u32)kind && layout->views[p->tabs[t]].group == group) { if(out_panel) *out_panel = index; return p->tabs[t]; } } } return -1; } // NOTE: show a view of this kind: focus an existing tab, or open a new one in the focused panel internal void layout_open(Layout *layout, ViewKind kind, u32 group = 0) { s32 panel = -1; s32 view = layout_find_kind(layout, kind, &panel, group); if(view >= 0) { Panel *p = &layout->panels[panel]; for(u32 t = 0; t < p->tab_count; ++t) if(p->tabs[t] == view) p->active_tab = t; layout->focused = panel; return; } Panel *p = &layout->panels[layout->focused]; view = layout_alloc_view(layout, kind); if(view < 0) return; layout->views[view].group = group; if(p->tab_count >= UI_MAX_TABS) { layout->views[view].kind = VIEW_NONE; return; } p->tabs[p->tab_count] = (u8)view; p->active_tab = p->tab_count++; } internal void layout_split_with(Layout *layout, ViewKind kind, u32 axis, u32 group = 0) { s32 copy = layout_alloc_view(layout, kind); if(copy < 0) return; layout->views[copy].group = group; Panel *p = &layout->panels[layout->focused]; if(p->tab_count >= UI_MAX_TABS) { layout->views[copy].kind = VIEW_NONE; return; } p->tabs[p->tab_count++] = (u8)copy; layout_move_view(layout, layout->focused, copy, layout->focused, axis == 0 ? DROP_RIGHT : DROP_BOTTOM); } internal void layout_split_focused(Layout *layout, u32 axis) { s32 view = panel_active_view(layout, layout->focused); if(view < 0) return; layout_split_with(layout, (ViewKind)layout->views[view].kind, axis, layout->views[view].group); } // NOTE: ctrl-w h j k l: the nearest leaf on that side that overlaps us on the other axis // NOTE: a leaf drawn as a one line bar (the footer): shown, but keyboard focus passes over it internal b32 panel_is_bar(Layout *layout, s32 panel) { return rect_h(layout->panels[panel].rect) < UI_TAB_H + UI_COLUMN_H + UI_ROW_H; } internal void layout_focus_direction(Layout *layout, s32 dx, s32 dy) { Rect current = layout->panels[layout->focused].rect; s32 best = -1; f32 best_d = 1e9f; for(s32 index = 0; index < UI_MAX_PANELS; ++index) { Panel *p = &layout->panels[index]; if(p->kind != PANEL_LEAF || index == layout->focused || panel_is_bar(layout, index)) continue; Rect r = p->rect; f32 d = -1; if(dx > 0 && r.x0 >= current.x1 - 1 && r.y0 < current.y1 && r.y1 > current.y0) d = r.x0 - current.x1; if(dx < 0 && r.x1 <= current.x0 + 1 && r.y0 < current.y1 && r.y1 > current.y0) d = current.x0 - r.x1; if(dy > 0 && r.y0 >= current.y1 - 1 && r.x0 < current.x1 && r.x1 > current.x0) d = r.y0 - current.y1; if(dy < 0 && r.y1 <= current.y0 + 1 && r.x0 < current.x1 && r.x1 > current.x0) d = current.y0 - r.y1; if(d >= 0 && d < best_d) { best_d = d; best = index; } } if(best >= 0) layout->focused = best; } internal void layout_focus_next(Layout *layout) { for(s32 step = 1; step <= UI_MAX_PANELS; ++step) { s32 index = (layout->focused + step) % UI_MAX_PANELS; if(layout->panels[index].kind == PANEL_LEAF && !panel_is_bar(layout, index)) { layout->focused = index; return; } } } // NOTE: leaves in reading order: depth first, first child (left / top) before the second internal void layout_leaves(Layout *layout, s32 panel, s32 *out, u32 *count) { Panel *p = &layout->panels[panel]; if(p->kind == PANEL_SPLIT) { layout_leaves(layout, p->children[0], out, count); layout_leaves(layout, p->children[1], out, count); } else if(p->kind == PANEL_LEAF && *count < UI_MAX_PANELS) { out[(*count)++] = panel; } } // NOTE: ctrl-tab: every tab of every panel as one ring, in reading order. focuses the panel and // makes the tab active. bars are skipped, they aren't something to type into. internal void layout_cycle_views(Layout *layout, s32 direction) { s32 leaves[UI_MAX_PANELS]; u32 leaf_count = 0; layout_leaves(layout, layout->root, leaves, &leaf_count); // flatten to (panel, tab) and find where we are s32 panels[UI_MAX_PANELS * UI_MAX_TABS]; u32 tabs[UI_MAX_PANELS * UI_MAX_TABS]; u32 count = 0; s32 at = -1; for(u32 leaf = 0; leaf < leaf_count; ++leaf) { s32 panel = leaves[leaf]; Panel *p = &layout->panels[panel]; if(panel_is_bar(layout, panel)) continue; for(u32 t = 0; t < p->tab_count; ++t) { if(panel == layout->focused && t == p->active_tab) at = (s32)count; panels[count] = panel; tabs[count] = t; ++count; } } if(count == 0) return; s32 next = (at < 0) ? 0 : (at + direction + (s32)count) % (s32)count; layout->focused = panels[next]; layout->panels[panels[next]].active_tab = tabs[next]; } //- rows // NOTE: every view produces rows of small ids. cell text is only formatted for rows that are on // screen, so a 114 row table costs ~20 formatted rows per frame. typedef enum RowKind { ROW_QARI, ROW_SURAH, ROW_FIELD, ROW_SETTING, // a = index into the settings table } RowKind; typedef struct Row Row; struct Row { u32 a; // qari index / field id / setting id u32 b; // surah index u8 kind; // RowKind u8 depth; // tree indent u8 expandable; u8 expanded; }; #define UI_MAX_ROWS 4096 typedef enum PlayingField { FIELD_SURAH, FIELD_RECITER, FIELD_STATE, FIELD_POSITION, FIELD_VOLUME, FIELD_AUTOPLAY, FIELD_FORMAT, FIELD_COUNT, } PlayingField; //- profiler rows // NOTE: a fixed list of metrics in sections, two of them (arenas, threads) expand to one row per // registered entry. only the rows on screen get formatted, everything comes from counters and the // 2hz sample, nothing here touches the os. typedef enum ProfileMetric { PM_SECTION_FRAME, PM_FPS, PM_FRAME_CPU, PM_FRAME_SPLIT, PM_UI_SPLIT, PM_RENDER_SPLIT, PM_IDLE, PM_DRAW, PM_SECTION_MEMORY, PM_RSS, PM_RSS_KIND, PM_VIRTUAL, PM_STACK_MAIN, PM_SECTION_HEAP, PM_HEAP_LIVE, PM_HEAP_ALLOCS, PM_HEAP_FREES, PM_HEAP_BLOCKS, PM_HEAP_TOTAL, PM_HEAP_GLIBC, PM_SECTION_ARENAS, PM_ARENA, PM_SECTION_THREADS, PM_THREAD, PM_SECTION_PROCESS, PM_CPU, PM_FAULTS, PM_SWITCHES, PM_SECTION_AUDIO, PM_AUDIO_QUANTUM, PM_AUDIO_CALLBACK, PM_AUDIO_RING, PM_AUDIO_DECODER, PM_AUDIO_UNDERRUNS, PM_SECTION_GPU, PM_GPU_MEMORY, PM_GPU_SWAPCHAIN, PM_SECTION_FONTS, PM_FONT_GLYPHS, PM_FONT_RUNS, PM_FONT_ATLAS, PM_SECTION_DATA, PM_DATA_TRACKS, PM_DATA_NETWORK, PM_COUNT, } ProfileMetric; global_variable const char *profile_labels[PM_COUNT] = { "frame", "frame rate", "frame cpu", "frame split", "ui split", "render split", "between frames", "draw", "memory", "resident", "resident by kind", "virtual", "main thread stack", "heap (malloc, whole process)", "live", "allocations", "frees", "blocks alive", "handed out", "glibc arenas", "arenas", "", "threads and stacks", "", "process", "cpu", "page faults", "context switches", "audio", "pipewire quantum", "realtime callback", "ring", "decoder", "underruns", "gpu", "allocated by us", "swapchain", "fonts", "glyph cache", "shaped text cache", "atlas", "data", "track table", "network", }; // NOTE: the sections of the metric list are separate views (Frame, Memory, Heap, ...). the // section markers stay in the enum as the boundaries between groups. global_variable const char *profile_group_names[] = {"frame", "memory", "heap", "arenas", "threads", "process", "audio", "gpu", "fonts", "data"}; internal b32 profile_is_section(u32 metric) { return metric == PM_SECTION_FRAME || metric == PM_SECTION_MEMORY || metric == PM_SECTION_HEAP || metric == PM_SECTION_ARENAS || metric == PM_SECTION_THREADS || metric == PM_SECTION_PROCESS || metric == PM_SECTION_AUDIO || metric == PM_SECTION_GPU || metric == PM_SECTION_FONTS || metric == PM_SECTION_DATA; } //- the view registry // NOTE: everything that can be opened: the plain kinds, every settings group and every profiler // group. :view, its completion, --open, tab titles and the Views view all come from here. typedef struct ViewType ViewType; struct ViewType { u32 kind; u32 group; const char *name; }; #define UI_MAX_VIEW_TYPES 48 typedef struct BaseView BaseView; struct BaseView { u32 kind; const char *name; const char *title; }; global_variable const BaseView ui_base_views[] = { {VIEW_RECITERS, "reciters", "Reciters"}, {VIEW_SURAHS, "surahs", "Surahs"}, {VIEW_OFFLINE, "offline", "Offline"}, {VIEW_PLAYING, "playing", "Now Playing"}, {VIEW_QUEUE, "queue", "Queue"}, {VIEW_DOWNLOADS, "downloads", "Downloads"}, {VIEW_VIEWS, "views", "Views"}, {VIEW_STATUS, "status", "Status"}, }; internal u32 view_types(ViewType *out) { u32 count = 0; for(u32 index = 0; index < ArrayCount(ui_base_views); ++index) out[count++] = ViewType{ui_base_views[index].kind, 0, ui_base_views[index].name}; u32 group = 0; for(u32 index = 0; index < settings_desc_count() && count < UI_MAX_VIEW_TYPES; ++index) { if(settings_desc(index)->kind == SETTING_KIND_SECTION) out[count++] = ViewType{VIEW_SETTINGS, group++, settings_desc(index)->name}; } for(u32 index = 0; index < ArrayCount(profile_group_names) && count < UI_MAX_VIEW_TYPES; ++index) out[count++] = ViewType{VIEW_PROFILER, index, profile_group_names[index]}; return count; } internal const char *view_type_name(u32 kind, u32 group) { ViewType types[UI_MAX_VIEW_TYPES]; u32 count = view_types(types); for(u32 index = 0; index < count; ++index) if(types[index].kind == kind && types[index].group == group) return types[index].name; return "?"; } // NOTE: the tab title: the base views have their own, groups show their name capitalized internal String8 view_title(Arena *arena, View *view) { for(u32 index = 0; index < ArrayCount(ui_base_views); ++index) { if(ui_base_views[index].kind == view->kind) return str8((char *)ui_base_views[index].title); } String8 name = ui_format(arena, "%s", view_type_name(view->kind, view->group)); if(name.size && name.data[0] >= 'a' && name.data[0] <= 'z') name.data[0] -= 32; return name; } // NOTE: exact name first, then a unique prefix ("prof" is no view, "pro" is process) internal b32 view_resolve(const char *name, ViewType *out) { ViewType types[UI_MAX_VIEW_TYPES]; u32 count = view_types(types); u32 size = (u32)strlen(name), hits = 0; if(size == 0) return false; for(u32 index = 0; index < count; ++index) { if(!strcasecmp(types[index].name, name)) { *out = types[index]; return true; } if(!strncasecmp(types[index].name, name, size)) { *out = types[index]; ++hits; } } return hits == 1; } // NOTE: the host asks this to decide whether to sample at all internal b32 layout_view_visible(Layout *layout, ViewKind kind) { for(s32 index = 0; index < UI_MAX_PANELS; ++index) { s32 view = panel_active_view(layout, index); if(view >= 0 && layout->views[view].kind == (u32)kind) return true; } return false; } global_variable const char *field_labels[FIELD_COUNT] = {"surah", "reciter", "state", "position", "volume", "autoplay", "format"}; // NOTE: the status view's rows. as a bar: mode and message from the left, the rest from the right typedef enum StatusItem { STATUS_MODE, STATUS_MESSAGE, STATUS_PLAYING, STATUS_DOWNLOADS, STATUS_SELECTION, STATUS_KEYS, STATUS_COUNT, } StatusItem; global_variable const char *status_labels[STATUS_COUNT] = {"mode", "message", "playing", "downloads", "selection", "pending keys"}; typedef struct Column Column; struct Column { const char *title; f32 width; // fraction of the table b32 mono; }; internal u32 view_columns(ViewKind kind, Column *out) { switch(kind) { case VIEW_RECITERS: out[0] = {"Reciter", 0.58f, 0}; out[1] = {"Style", 0.20f, 0}; out[2] = {"On disk", 0.22f, 1}; return 3; case VIEW_SURAHS: out[0] = {"#", 0.07f, 1}; out[1] = {"Surah", 0.30f, 0}; out[2] = {"Meaning", 0.33f, 0}; out[3] = {"Ayat", 0.09f, 1}; out[4] = {"State", 0.21f, 1}; return 5; case VIEW_OFFLINE: out[0] = {"Name", 0.58f, 0}; out[1] = {"Size", 0.17f, 1}; out[2] = {"Files", 0.25f, 0}; return 3; case VIEW_PLAYING: out[0] = {"Field", 0.24f, 0}; out[1] = {"Value", 0.76f, 1}; return 2; case VIEW_DOWNLOADS: out[0] = {"Track", 0.55f, 0}; out[1] = {"Progress", 0.27f, 1}; out[2] = {"Size", 0.18f, 1}; return 3; case VIEW_SETTINGS: out[0] = {"Setting", 0.28f, 0}; out[1] = {"Value", 0.30f, 1}; out[2] = {"Note", 0.42f, 0}; return 3; case VIEW_QUEUE: out[0] = {"#", 0.07f, 1}; out[1] = {"Surah", 0.33f, 0}; out[2] = {"Reciter", 0.40f, 0}; out[3] = {"State", 0.20f, 1}; return 4; case VIEW_PROFILER: out[0] = {"Metric", 0.26f, 0}; out[1] = {"Value", 0.30f, 1}; out[2] = {"Detail", 0.44f, 1}; return 3; case VIEW_VIEWS: out[0] = {"View", 0.30f, 0}; out[1] = {"Command", 0.36f, 1}; out[2] = {"Shown", 0.34f, 0}; return 3; case VIEW_STATUS: out[0] = {"Item", 0.24f, 0}; out[1] = {"Value", 0.76f, 1}; return 2; default: return 0; } } internal b32 view_expanded(View *view, u32 qari) { return qari < VIEW_EXPANDED_WORDS * 64 && ((view->expanded[qari >> 6] >> (qari & 63)) & 1); } internal void view_set_expanded(View *view, u32 qari, b32 on) { if(qari >= VIEW_EXPANDED_WORDS * 64) return; if(on) view->expanded[qari >> 6] |= (1ull << (qari & 63)); else view->expanded[qari >> 6] &= ~(1ull << (qari & 63)); } internal u32 view_rows(App *app, View *view, Row *rows, u32 capacity) { u32 count = 0; switch(view->kind) { case VIEW_RECITERS: { for(u32 qari = 0; qari < app->catalog->qari_count && count < capacity; ++qari) { rows[count++] = Row{qari, 0, ROW_QARI, 0, 0, 0}; } } break; case VIEW_SURAHS: { if(app->qari < 0) break; for(u32 surah = 0; surah < SURAH_COUNT && count < capacity; ++surah) { rows[count++] = Row{(u32)app->qari, surah, ROW_SURAH, 0, 0, 0}; } } break; case VIEW_OFFLINE: { for(u32 qari = 0; qari < app->catalog->qari_count && count < capacity; ++qari) { if(store_disk_count(app->store, qari) == 0) continue; b32 open = view_expanded(view, qari); rows[count++] = Row{qari, 0, ROW_QARI, 0, 1, (u8)open}; if(!open) continue; for(u32 surah = 0; surah < SURAH_COUNT && count < capacity; ++surah) { if(store_on_disk(app->store, TrackKey(qari, surah))) rows[count++] = Row{qari, surah, ROW_SURAH, 1, 0, 0}; } } } break; case VIEW_PLAYING: { for(u32 field = 0; field < FIELD_COUNT && count < capacity; ++field) rows[count++] = Row{field, 0, ROW_FIELD, 0, 0, 0}; } break; case VIEW_DOWNLOADS: { for(u32 index = 0; index < app->store->worker_count && count < capacity; ++index) { u32 key = AtomicLoadRelaxed(&app->store->workers[index].current_key); if(key != TRACK_NONE) rows[count++] = Row{TrackQari(key), TrackSurah(key), ROW_SURAH, 0, 0, 0}; } // NOTE: peek at the queue, a few dozen is all that fits on screen anyway JobQueue *queue = &app->store->queue; spin_lock(&queue->lock); for(u32 index = 0; index < queue->count && index < 64 && count < capacity; ++index) { u32 key = queue->items[(queue->head + index) & queue->mask]; if(AtomicLoadRelaxed(&app->store->states[key]) == TRACK_QUEUED) rows[count++] = Row{TrackQari(key), TrackSurah(key), ROW_SURAH, 0, 0, 0}; } spin_unlock(&queue->lock); } break; case VIEW_PROFILER: { // NOTE: the metrics between this group's section marker and the next one Profiler *profiler = app->profiler; s32 group = -1; for(u32 metric = 0; metric < PM_COUNT && count < capacity; ++metric) { if(profile_is_section(metric)) { ++group; continue; } if(group != (s32)view->group) continue; if(metric == PM_ARENA) { for(u32 index = 0; index < profiler->arena_count && count < capacity; ++index) rows[count++] = Row{metric, index, ROW_FIELD, 0, 0, 0}; } else if(metric == PM_THREAD) { for(u32 index = 0; index < profiler->thread_count && count < capacity; ++index) rows[count++] = Row{metric, index, ROW_FIELD, 0, 0, 0}; } else { rows[count++] = Row{metric, 0, ROW_FIELD, 0, 0, 0}; } } } break; case VIEW_VIEWS: { ViewType types[UI_MAX_VIEW_TYPES]; u32 types_count = view_types(types); for(u32 index = 0; index < types_count && count < capacity; ++index) rows[count++] = Row{index, 0, ROW_FIELD, 0, 0, 0}; } break; case VIEW_STATUS: { for(u32 index = 0; index < STATUS_COUNT && count < capacity; ++index) rows[count++] = Row{index, 0, ROW_FIELD, 0, 0, 0}; } break; case VIEW_QUEUE: { for(u32 index = 0; index < app->queue_count && count < capacity; ++index) { u32 key = app->queue[index]; rows[count++] = Row{TrackQari(key), TrackSurah(key), ROW_SURAH, 0, 0, 0}; } } break; case VIEW_SETTINGS: { // NOTE: the settings between this group's section entry and the next one s32 group = -1; for(u32 index = 0; index < settings_desc_count() && count < capacity; ++index) { if(settings_desc(index)->kind == SETTING_KIND_SECTION) { ++group; continue; } if(group == (s32)view->group) rows[count++] = Row{index, 0, ROW_SETTING, 0, 0, 0}; } } break; } return count; } // NOTE: reciters and surahs show the shared selection (rad style: views follow the selected // entity), every other view keeps its own cursor internal s32 view_cursor(App *app, View *view, Row *rows, u32 count) { if(view->kind == VIEW_RECITERS) return app->qari; if(view->kind == VIEW_SURAHS) return app->surah; return (count == 0) ? 0 : Clamp(view->cursor, 0, (s32)count - 1); } internal void view_set_cursor(App *app, View *view, Row *rows, u32 count, s32 cursor) { if(count == 0) return; cursor = Clamp(cursor, 0, (s32)count - 1); view->cursor = cursor; Row *row = &rows[cursor]; if(view->kind == VIEW_RECITERS) { app->qari = (s32)row->a; } else if(view->kind == VIEW_SURAHS) { app->surah = (s32)row->b; } else if(view->kind == VIEW_OFFLINE) { app->qari = (s32)row->a; if(row->kind == ROW_SURAH) app->surah = (s32)row->b; } app->keep_selection_visible = true; } internal u32 row_track_key(Row *row) { return (row->kind == ROW_SURAH) ? TrackKey(row->a, row->b) : TRACK_NONE; } typedef struct Cells Cells; struct Cells { u32 swatch; // color settings: a sample square before the value b32 has_swatch; String8 text[5]; f32 progress; // >= 0 and an empty last column: draw a bar there b32 bright; // the playing track. in a bar: drawn as a highlighted block b32 dim; b32 right; // in a bar: placed from the right edge }; internal String8 track_state_text(App *app, u32 key, f32 *progress) { TrackEntry *entry = store_entry(app->store, key); u32 state = AtomicLoadRelaxed(TrackStatePtr(app->store, entry)); switch(state) { case TRACK_DONE: return str8("on disk"); case TRACK_QUEUED: return str8("queued"); case TRACK_DOWNLOADING: { u64 total = AtomicLoadRelaxed(&entry->bytes_total); *progress = total ? (f32)((f64)AtomicLoadRelaxed(&entry->bytes_done) / (f64)total) : 0.0f; return str8_zero(); } case TRACK_PARTIAL: return str8("partial"); case TRACK_FAILED: return str8(AtomicLoadRelaxed(&entry->http_status) == 0 ? "no connection" : "unavailable"); } return str8_zero(); } internal void view_cells(App *app, View *view, Row *row, Cells *cells, Arena *arena) { MemSetZero(cells, sizeof(*cells)); cells->progress = -1.0f; Catalog *catalog = app->catalog; u32 playing = app_current_key(app); char a[32], b[32]; switch(view->kind) { case VIEW_RECITERS: { Qari *qari = &catalog->qaris[row->a]; u32 on_disk = store_disk_count(app->store, row->a); cells->text[0] = qari->name; cells->text[1] = catalog_section_name(qari->section_id); cells->text[2] = on_disk ? ui_u32_pair(arena, on_disk, '/', SURAH_COUNT) : str8("-"); cells->bright = (playing != TRACK_NONE && TrackQari(playing) == row->a); } break; case VIEW_SURAHS: { Surah *surah = &catalog->surahs[row->b]; u32 key = row_track_key(row); cells->text[0] = ui_u32(arena, row->b + 1); cells->text[1] = surah->name; cells->text[2] = surah->english; cells->text[3] = ui_u32(arena, surah->ayah_count); cells->text[4] = track_state_text(app, key, &cells->progress); cells->bright = (key == playing); cells->dim = !store_on_disk(app->store, key) && cells->progress < 0; } break; case VIEW_DOWNLOADS: { Surah *surah = &catalog->surahs[row->b]; u32 key = row_track_key(row); TrackEntry *entry = store_entry(app->store, key); cells->text[0] = ui_format(arena, Str8Fmt " ยท %u. " Str8Fmt, Str8Arg(catalog->qaris[row->a].name), row->b + 1, Str8Arg(surah->name)); cells->text[1] = track_state_text(app, key, &cells->progress); if(cells->progress >= 0) cells->text[1] = ui_format(arena, "%3.0f%%", cells->progress * 100.0f); u64 total = AtomicLoadRelaxed(&entry->bytes_total); format_bytes(a, sizeof(a), (f64)total); cells->text[2] = total ? ui_format(arena, "%s", a) : str8("-"); cells->bright = (key == playing); } break; case VIEW_PROFILER: { Profiler *p = app->profiler; char x[32], y[32], z[32]; cells->text[0] = str8((char *)profile_labels[row->a]); switch(row->a) { case PM_FPS: { cells->text[1] = ui_format(arena, "%.0f fps", app->fps); cells->text[2] = app->settings.fps_cap ? ui_format(arena, "cap %u, renders only while something moves", app->settings.fps_cap) : str8("paced by the compositor"); } break; case PM_FRAME_CPU: { cells->text[1] = ui_format(arena, "%.3f ms", p->average); cells->text[2] = ui_format(arena, "p50 %.3f p99 %.3f worst %.3f (%u frames)", p->p50, p->p99, p->worst, p->frames_total); } break; case PM_FRAME_SPLIT: { cells->text[1] = ui_format(arena, "ui %.3f ms", p->ui_ms); cells->text[2] = ui_format(arena, "render %.3f ms (p99 ui %.3f render %.3f), ~%.0f fps of headroom", p->render_ms, p->ui_p99, p->render_p99, p->average > 0 ? 1000.0f / p->average : 0.0f); } break; case PM_UI_SPLIT: { f32 *us = p->ui_phase_us; cells->text[1] = ui_format(arena, "panels %.0f us", us[PROFILE_UI_PANELS]); cells->text[2] = ui_format(arena, "keys %.1f overlay %.1f us (averaged, panels include the status bar)", us[PROFILE_UI_KEYBOARD], us[PROFILE_UI_OVERLAY]); } break; case PM_RENDER_SPLIT: { VulkanRenderer *r = &app->renderer; cells->text[1] = ui_format(arena, "record %.3f ms", r->record_ms); cells->text[2] = ui_format(arena, "gpu wait %.3f acquire %.3f submit+present %.3f", r->wait_ms, r->acquire_ms, r->submit_ms); } break; case PM_IDLE: cells->text[1] = ui_format(arena, "%.2f ms", p->idle_ms); cells->text[2] = str8("asleep in poll() waiting for input or the next frame slot"); break; case PM_DRAW: { cells->text[1] = ui_format(arena, "%u quads", app->draw.count); cells->text[2] = ui_format(arena, "%u draw calls, peak %u of %u quads", app->renderer.batches, app->draw.peak, (u32)DRAW_MAX_INSTANCES); } break; case PM_RSS: { format_bytes(x, sizeof(x), (f64)p->rss); format_bytes(y, sizeof(y), (f64)p->rss_peak); cells->text[1] = ui_format(arena, "%s", x); cells->text[2] = ui_format(arena, "peak %s", y); } break; case PM_RSS_KIND: { format_bytes(x, sizeof(x), (f64)p->rss_anon); format_bytes(y, sizeof(y), (f64)p->rss_file); format_bytes(z, sizeof(z), (f64)p->rss_shmem); cells->text[1] = ui_format(arena, "anon %s", x); cells->text[2] = ui_format(arena, "file %s (library code, shared) shmem %s", y, z); } break; case PM_VIRTUAL: { format_bytes(x, sizeof(x), (f64)p->vm_size); format_bytes(y, sizeof(y), (f64)p->vm_data); format_bytes(z, sizeof(z), (f64)p->vm_lib); cells->text[1] = ui_format(arena, "%s", x); cells->text[2] = ui_format(arena, "data %s libraries %s (reserved, mostly untouched)", y, z); } break; case PM_STACK_MAIN: { format_bytes(x, sizeof(x), (f64)p->vm_stack); cells->text[1] = ui_format(arena, "%s", x); cells->text[2] = str8("touched so far (VmStk)"); } break; case PM_HEAP_LIVE: { format_bytes(x, sizeof(x), (f64)Max(AtomicLoadRelaxed(&p->heap_live), (s64)0)); format_bytes(y, sizeof(y), (f64)AtomicLoadRelaxed(&p->heap_peak)); cells->text[1] = ui_format(arena, "%s", x); cells->text[2] = ui_format(arena, "peak %s, counted at every malloc / free", y); } break; case PM_HEAP_ALLOCS: cells->text[1] = ui_format(arena, "%llu", (unsigned long long)AtomicLoadRelaxed(&p->malloc_count)); cells->text[2] = ui_format(arena, "%.0f / s", p->mallocs_per_s); break; case PM_HEAP_FREES: cells->text[1] = ui_format(arena, "%llu", (unsigned long long)AtomicLoadRelaxed(&p->free_count)); cells->text[2] = ui_format(arena, "%.0f / s", p->frees_per_s); break; case PM_HEAP_BLOCKS: cells->text[1] = ui_format(arena, "%lld", (long long)(AtomicLoadRelaxed(&p->malloc_count) - AtomicLoadRelaxed(&p->free_count))); cells->text[2] = str8("allocations not freed yet"); break; case PM_HEAP_TOTAL: format_bytes(x, sizeof(x), (f64)AtomicLoadRelaxed(&p->heap_total)); cells->text[1] = ui_format(arena, "%s", x); cells->text[2] = str8("every byte malloc ever returned"); break; case PM_HEAP_GLIBC: { format_bytes(x, sizeof(x), (f64)p->heap_arena); format_bytes(y, sizeof(y), (f64)p->heap_free); format_bytes(z, sizeof(z), (f64)p->heap_mmapped); cells->text[1] = ui_format(arena, "%s", x); cells->text[2] = ui_format(arena, "free in arenas %s mmapped chunks %s", y, z); } break; case PM_ARENA: { ProfileArena *entry = &p->arenas[row->b]; Arena *a = entry->arena; u64 used = arena_position(a), reserved = 0, blocks = 0; for(Arena *block = a->current; block; block = block->previous) { reserved += block->capacity; ++blocks; } format_bytes(x, sizeof(x), (f64)used); format_bytes(y, sizeof(y), (f64)a->peak_position); format_bytes(z, sizeof(z), (f64)reserved); cells->text[0] = ui_format(arena, "%s", entry->name); cells->text[1] = ui_format(arena, "%s", x); cells->text[2] = ui_format(arena, "peak %s of %s, %llu allocs (%.0f/s), %llu blocks", y, z, (unsigned long long)a->alloc_count, entry->allocs_per_s, (unsigned long long)blocks); } break; case PM_THREAD: { ProfileThread *t = &p->threads[row->b]; format_bytes(x, sizeof(x), (f64)t->stack_touched); format_bytes(y, sizeof(y), (f64)t->stack_size); cells->text[0] = ui_format(arena, "%s (%d)", t->name, t->tid); cells->text[1] = ui_format(arena, "cpu %5.1f%%", t->cpu * 100.0f); cells->text[2] = ui_format(arena, "stack %s / %s faults %.0f/s switches %.0f/s", x, t->stack_size ? y : "rlimit", t->minflt_per_s, t->csw_per_s); } break; case PM_CPU: cells->text[1] = ui_format(arena, "%.1f%%", p->cpu_process * 100.0f); cells->text[2] = str8("of one core, every thread together"); break; case PM_FAULTS: cells->text[1] = ui_format(arena, "%.0f / s", p->minflt_per_s); cells->text[2] = ui_format(arena, "major %.1f / s, %llu minor total", p->majflt_per_s, (unsigned long long)p->minflt); break; case PM_SWITCHES: cells->text[1] = ui_format(arena, "%.0f / s", p->csw_per_s); cells->text[2] = ui_format(arena, "%llu voluntary, %llu involuntary", (unsigned long long)p->vcsw, (unsigned long long)p->ivcsw); break; case PM_AUDIO_QUANTUM: { AudioOutput *o = app->output; u32 rate = Max(o->rate, 1u); cells->text[1] = ui_format(arena, "%u frames", o->callback_frames); cells->text[2] = ui_format(arena, "%.2f ms at %u hz, %llu callbacks", 1000.0 * o->callback_frames / rate, rate, (unsigned long long)o->callbacks); } break; case PM_AUDIO_CALLBACK: { AudioOutput *o = app->output; f64 average = o->callbacks ? (f64)o->callback_ns_total / (f64)o->callbacks / 1000.0 : 0.0; f64 budget = o->rate ? 1e6 * o->callback_frames / o->rate : 0.0; cells->text[1] = ui_format(arena, "%.1f us", average); cells->text[2] = ui_format(arena, "worst %.1f us, %.3f%% of its budget", (f64)o->callback_ns_max / 1000.0, budget > 0 ? 100.0 * average / budget : 0.0); } break; case PM_AUDIO_RING: { AudioRing *ring = app->ring; u64 fill = AtomicLoadRelaxed(&ring->write_frame) - AtomicLoadRelaxed(&ring->read_frame); format_bytes(x, sizeof(x), (f64)(ring->capacity_frames * AUDIO_CHANNELS * sizeof(f32))); cells->text[1] = ui_format(arena, "%3.0f%% full", 100.0 * (f64)fill / (f64)ring->capacity_frames); cells->text[2] = ui_format(arena, "%.2f s buffered of %.2f s, %s", (f64)fill / Max(app->output->rate, 1u), (f64)ring->capacity_frames / Max(app->output->rate, 1u), x); } break; case PM_AUDIO_DECODER: { Decoder *dec = app->decoder; u64 frames = AtomicLoadRelaxed(&dec->decoded_frames), ns = AtomicLoadRelaxed(&dec->decode_ns); f64 speed = ns ? ((f64)frames / Max(app->output->rate, 1u)) / ((f64)ns / 1e9) : 0.0; cells->text[1] = ui_format(arena, "%.0fx realtime", speed); cells->text[2] = ui_format(arena, "%.1f s of audio decoded in %.1f ms, mpg123 %s", (f64)frames / Max(app->output->rate, 1u), (f64)ns / 1e6, dec->decoder_name ? dec->decoder_name : "-"); } break; case PM_AUDIO_UNDERRUNS: cells->text[1] = ui_u32(arena, app->output->underruns); cells->text[2] = ui_format(arena, "audio missing mid track; %u waits for a new track's first samples", app->output->switch_gaps); break; case PM_GPU_MEMORY: { format_bytes(x, sizeof(x), (f64)app->renderer.gpu_bytes); cells->text[1] = ui_format(arena, "%s", x); cells->text[2] = str8("instance + staging buffers, glyph atlas (driver swapchain not included)"); } break; case PM_GPU_SWAPCHAIN: { VulkanRenderer *r = &app->renderer; cells->text[1] = ui_format(arena, "%ux%u", r->extent.width, r->extent.height); cells->text[2] = ui_format(arena, "%u images, %s", r->image_count, r->present_mode == VK_PRESENT_MODE_MAILBOX_KHR ? "mailbox" : "fifo"); } break; case PM_FONT_GLYPHS: { FontSystem *f = &app->fonts; cells->text[1] = ui_format(arena, "%u / %u", f->glyph_count, (u32)FONT_GLYPH_SLOTS); cells->text[2] = ui_format(arena, "%u faces loaded (font x size)", f->face_count); } break; case PM_FONT_RUNS: { FontSystem *f = &app->fonts; cells->text[1] = ui_format(arena, "%u / %u", f->run_count, (u32)FONT_RUN_SLOTS); cells->text[2] = str8("strings shaped once, then reused every frame"); } break; case PM_FONT_ATLAS: { FontSystem *f = &app->fonts; cells->text[1] = ui_format(arena, "%.0f%%", 100.0f * (f32)(f->shelf_y + f->shelf_h) / FONT_ATLAS_SIZE); cells->text[2] = ui_format(arena, "%ux%u single channel, rows filled", (u32)FONT_ATLAS_SIZE, (u32)FONT_ATLAS_SIZE); } break; case PM_DATA_TRACKS: { format_bytes(x, sizeof(x), (f64)(sizeof(TrackEntry) * app->store->entry_count)); cells->text[1] = ui_format(arena, "%s", x); cells->text[2] = ui_format(arena, "%u tracks x %u bytes, flat array", app->store->entry_count, (u32)sizeof(TrackEntry)); } break; case PM_DATA_NETWORK: { format_bytes(x, sizeof(x), (f64)AtomicLoadRelaxed(&app->store->bytes_downloaded)); format_bytes(y, sizeof(y), app->speed); cells->text[1] = ui_format(arena, "%s", x); cells->text[2] = ui_format(arena, "this session, %s/s now, %u active, %u queued", y, AtomicLoadRelaxed(&app->store->active), job_queue_count(&app->store->queue)); } break; } } break; case VIEW_STATUS: { cells->text[0] = str8((char *)status_labels[row->a]); cells->right = (row->a >= STATUS_PLAYING); switch(row->a) { case STATUS_MODE: { const char *mode = "NORMAL"; if(app->overlay == UI_OVERLAY_SEARCH) mode = "SEARCH"; if(app->overlay == UI_OVERLAY_COMMAND) mode = "COMMAND"; if(app->overlay == UI_OVERLAY_EDIT) mode = "EDIT"; if(app->drag_view >= 0 && app->drag_active) mode = "MOVE"; if(app->visual) mode = "VISUAL"; cells->text[1] = str8((char *)mode); cells->bright = true; } break; case STATUS_MESSAGE: { if(app->message[0] && time_now_ns() - app->message_ns < (u64)(ui_theme.message_seconds * 1e9f)) { cells->text[1] = str8(app->message); app->ticking = true; // so it disappears on time } } break; case STATUS_PLAYING: { u32 key = app_current_key(app); if(key == TRACK_NONE) break; char a[32], b[32]; u32 rate = Max(app->position.rate, 1u); u64 total = app_track_total(app); format_duration(a, sizeof(a), (f64)app->position.frame / rate); format_duration(b, sizeof(b), (f64)total / rate); cells->text[1] = ui_format(arena, "%s %u. " Str8Fmt " %s / %s", app->paused ? "paused" : "playing", TrackSurah(key) + 1, Str8Arg(app->catalog->surahs[TrackSurah(key)].name), a, total ? b : "--:--"); } break; case STATUS_DOWNLOADS: { u32 active = AtomicLoadRelaxed(&app->store->active); u32 queued = job_queue_count(&app->store->queue); if(active + queued == 0) break; char speed[32]; format_bytes(speed, sizeof(speed), app->speed); cells->text[1] = ui_format(arena, "dl %u+%u %s/s", active, queued, speed); cells->dim = true; app->ticking = true; } break; case STATUS_SELECTION: { if(app->visual) cells->text[1] = str8("selecting"); else if(app->selected_count) cells->text[1] = ui_format(arena, "%u selected", app->selected_count); } break; case STATUS_KEYS: { if(!app->count && !app->pending) break; char buffer[32]; int length = 0; if(app->count) length = snprintf(buffer, sizeof(buffer), "%u", app->count); if(app->pending == 'w') snprintf(buffer + length, sizeof(buffer) - (u32)length, "^W"); else if(app->pending) snprintf(buffer + length, sizeof(buffer) - (u32)length, "%c", (char)app->pending); cells->text[1] = ui_format(arena, "%s", buffer); } break; } } break; case VIEW_VIEWS: { ViewType types[UI_MAX_VIEW_TYPES]; view_types(types); ViewType *type = &types[row->a]; View probe = {}; probe.kind = type->kind; probe.group = type->group; s32 panel = -1; s32 shown = layout_find_kind(&app->layout, (ViewKind)type->kind, &panel, type->group); cells->text[0] = view_title(arena, &probe); cells->text[1] = ui_format(arena, ":view %s", type->name); cells->text[2] = (shown < 0) ? str8_zero() : str8(panel_active_view(&app->layout, panel) == shown ? "on screen" : "in a tab"); cells->dim = (shown < 0); } break; case VIEW_QUEUE: { u32 key = row_track_key(row); cells->text[0] = ui_u32(arena, row->b + 1); cells->text[1] = catalog->surahs[row->b].name; cells->text[2] = catalog->qaris[row->a].name; cells->text[3] = track_state_text(app, key, &cells->progress); cells->bright = (key == playing); } break; case VIEW_OFFLINE: { if(row->kind == ROW_QARI) { cells->text[0] = catalog->qaris[row->a].name; format_bytes(a, sizeof(a), (f64)AtomicLoadRelaxed(&app->store->qari_done_bytes[row->a])); cells->text[1] = ui_format(arena, "%s", a); cells->text[2] = ui_format(arena, "%u surahs", store_disk_count(app->store, row->a)); cells->bright = (playing != TRACK_NONE && TrackQari(playing) == row->a); } else { u32 key = row_track_key(row); cells->text[0] = ui_format(arena, "%u. " Str8Fmt, row->b + 1, Str8Arg(catalog->surahs[row->b].name)); format_bytes(a, sizeof(a), (f64)AtomicLoadRelaxed(&store_entry(app->store, key)->bytes_total)); cells->text[1] = ui_format(arena, "%s", a); cells->text[2] = catalog->surahs[row->b].english; cells->bright = (key == playing); } } break; case VIEW_PLAYING: { cells->text[0] = str8((char *)field_labels[row->a]); u32 key = (playing != TRACK_NONE) ? playing : app_selected_key(app); cells->dim = (playing == TRACK_NONE); if(key == TRACK_NONE) break; Surah *surah = &catalog->surahs[TrackSurah(key)]; u32 rate = Max(app->position.rate, 1u); switch(row->a) { case FIELD_SURAH: cells->text[1] = ui_format(arena, "%u. " Str8Fmt " (" Str8Fmt ")", surah->number, Str8Arg(surah->name), Str8Arg(surah->english)); break; case FIELD_RECITER: cells->text[1] = catalog->qaris[TrackQari(key)].name; break; case FIELD_STATE: { u32 status = AtomicLoadRelaxed(&app->decoder->status); const char *text = "stopped"; if(playing != TRACK_NONE) text = app->paused ? "paused" : "playing"; if(playing != TRACK_NONE && (status == DECODER_BUFFERING || (app->position.flags & PLAYBACK_STARVED))) text = "buffering"; if(status == DECODER_ERROR) { TrackEntry *entry = store_entry(app->store, app->requested_key); text = (entry && AtomicLoadRelaxed(TrackStatePtr(app->store, entry)) == TRACK_FAILED && entry->http_status == 0) ? "offline, and not downloaded" : "error, could not play"; } cells->text[1] = str8((char *)text); } break; case FIELD_POSITION: { u64 total = app_track_total(app); format_duration(a, sizeof(a), playing != TRACK_NONE ? (f64)app->position.frame / rate : 0.0); format_duration(b, sizeof(b), (f64)total / rate); cells->text[1] = ui_format(arena, "%s / %s", a, total ? b : "--:--"); cells->progress = (total && playing != TRACK_NONE) ? (f32)((f64)app->position.frame / (f64)total) : 0.0f; } break; case FIELD_VOLUME: cells->text[1] = ui_format(arena, "%.0f%%", app->settings.volume * 100.0f); break; case FIELD_AUTOPLAY: cells->text[1] = str8((char *)autoplay_name(app->settings.autoplay)); break; case FIELD_FORMAT: cells->text[1] = app->position.rate ? ui_format(arena, "%.1f kHz, f32 stereo, pipewire", app->position.rate / 1000.0f) : str8("-"); break; } } break; case VIEW_SETTINGS: { SettingDesc *desc = settings_desc(row->a); cells->text[0] = str8((char *)desc->name); cells->text[2] = desc->note ? str8((char *)desc->note) : str8_zero(); if(desc->kind == SETTING_KIND_COLOR) { cells->has_swatch = true; cells->swatch = *(u32 *)((u8 *)&app->settings + desc->offset); } if(desc->kind == SETTING_KIND_ACTION) { cells->text[1] = str8("run"); } else if(desc->kind == SETTING_KIND_INFO) { cells->dim = true; switch(desc->action) { case SETTING_INFO_FRAME: { cells->text[1] = ui_format(arena, "%.2f ms", app->frame_ms); cells->text[2] = ui_format(arena, "%.0f fps now, %u quads, ~%.0f fps possible", app->fps, app->draw.peak, app->frame_ms > 0 ? 1000.0f / app->frame_ms : 0.0f); } break; case SETTING_INFO_ON_DISK: { u64 bytes = 0; u32 files = 0; for(u32 qari = 0; qari < catalog->qari_count; ++qari) { bytes += AtomicLoadRelaxed(&app->store->qari_done_bytes[qari]); files += store_disk_count(app->store, qari); } format_bytes(a, sizeof(a), (f64)bytes); cells->text[1] = ui_format(arena, "%s", a); cells->text[2] = ui_format(arena, "%u surahs", files); } break; case SETTING_INFO_DATA_DIR: cells->text[1] = app->data_dir; break; case SETTING_INFO_RELOADS: cells->text[1] = ui_u32(arena, app->ui_generation); cells->text[2] = str8("hot reloaded ui builds this session"); break; } } else { cells->text[1] = settings_format(arena, &app->settings, desc); } } break; } } //- row actions internal void overlay_open(App *app, UIOverlay overlay); internal void view_adjust(App *app, View *view, Row *row, s32 direction) { if(view->kind == VIEW_PLAYING) { switch(row->a) { case FIELD_POSITION: app_seek_seconds(app, direction * (f64)app->settings.seek_seconds); break; case FIELD_VOLUME: app_set_volume(app, app->settings.volume + 0.05f * direction); break; case FIELD_AUTOPLAY: app->settings.autoplay = (app->settings.autoplay + 3 + direction) % 3; app_apply_settings(app); break; case FIELD_STATE: app_toggle_pause(app); break; } } else if(view->kind == VIEW_SETTINGS && row->kind == ROW_SETTING) { settings_adjust(&app->settings, settings_desc(row->a), direction); app_apply_settings(app); } } internal void edit_begin(App *app, View *view, u32 field) { app->edit_view = (u32)(view - app->layout.views); app->edit_field = field; overlay_open(app, UI_OVERLAY_EDIT); } internal void view_activate(App *app, View *view, Row *row) { switch(view->kind) { case VIEW_RECITERS: { app->qari = (s32)row->a; if(layout_find_kind(&app->layout, VIEW_SURAHS, NULL) >= 0) layout_open(&app->layout, VIEW_SURAHS); } break; case VIEW_VIEWS: { ViewType types[UI_MAX_VIEW_TYPES]; view_types(types); layout_open(&app->layout, (ViewKind)types[row->a].kind, types[row->a].group); } break; case VIEW_QUEUE: { u32 key = row_track_key(row); if(key == app_current_key(app)) app_toggle_pause(app); else app_play_in_queue(app, key); } break; case VIEW_SURAHS: case VIEW_DOWNLOADS: { u32 key = row_track_key(row); if(key == app_current_key(app)) app_toggle_pause(app); else app_play(app, key, 0); } break; case VIEW_OFFLINE: { if(row->kind == ROW_QARI) { view_set_expanded(view, row->a, !view_expanded(view, row->a)); } else { // NOTE: playing from the offline library keeps you offline if(app->settings.autoplay == AUTOPLAY_NEXT) app->settings.autoplay = AUTOPLAY_NEXT_DOWNLOADED; u32 key = row_track_key(row); if(key == app_current_key(app)) app_toggle_pause(app); else app_play(app, key, 0); } } break; case VIEW_PLAYING: { u32 key = app_current_key(app); if(row->a == FIELD_SURAH || row->a == FIELD_RECITER) { if(key != TRACK_NONE) { app->jump_back = app_place(app); app->qari = (s32)TrackQari(key); app->surah = (s32)TrackSurah(key); app->keep_selection_visible = true; } } else if(row->a == FIELD_STATE) { app_toggle_pause(app); } else if(row->a == FIELD_POSITION || row->a == FIELD_VOLUME) { edit_begin(app, view, row->a); } else { view_adjust(app, view, row, 1); } } break; case VIEW_SETTINGS: { SettingDesc *desc = settings_desc(row->a); if(desc->kind == SETTING_KIND_ACTION) { if(desc->action == SETTING_ACTION_RESET_LAYOUT) { ui_layout_default(&app->layout); app_message(app, "layout reset"); } else if(desc->action == SETTING_ACTION_RESET_COLORS) { settings_apply_scheme(&app->settings, app->settings.scheme == UI_SCHEME_CUSTOM ? 0 : app->settings.scheme); app_message(app, "colors reset"); } else if(desc->action == SETTING_ACTION_RESET_SETTINGS) { settings_default(&app->settings); app_apply_settings(app); app_message(app, "settings reset to defaults"); } } else if(desc->kind == SETTING_KIND_F32 || desc->kind == SETTING_KIND_U32 || desc->kind == SETTING_KIND_COLOR) { edit_begin(app, view, row->a); } else if(desc->kind != SETTING_KIND_INFO) { view_adjust(app, view, row, 1); } } break; } } //- table //- multi selection // NOTE: one bitset over every track key (177 * 114 bits = 2.5KB), so a selection survives // switching reciters and views and costs one bit test per drawn row. internal b32 track_selected(App *app, u32 key) { return key < app->store->entry_count && ((app->selected[key >> 6] >> (key & 63)) & 1); } internal void track_select(App *app, u32 key, b32 on) { if(key >= app->store->entry_count || track_selected(app, key) == on) return; app->selected[key >> 6] ^= (1ull << (key & 63)); app->selected_count += on ? 1 : (u32)-1; } internal void selection_clear(App *app) { MemSetZero(app->selected, sizeof(u64) * ((app->store->entry_count + 63) / 64)); app->selected_count = 0; app->visual = false; } // NOTE: rows between the visual anchor and the cursor count as selected while V is active internal b32 row_in_visual(App *app, View *view, s32 index, s32 cursor) { if(!app->visual || app->visual_view != (u32)(view - app->layout.views)) return false; s32 lo = Min(app->visual_anchor, cursor), hi = Max(app->visual_anchor, cursor); return index >= lo && index <= hi; } internal void visual_commit(App *app, View *view, Row *rows, u32 count) { if(!app->visual) return; s32 cursor = view_cursor(app, view, rows, count); s32 lo = Clamp(Min(app->visual_anchor, cursor), 0, (s32)count - 1), hi = Clamp(Max(app->visual_anchor, cursor), 0, (s32)count - 1); for(s32 index = lo; index <= hi && count; ++index) { u32 key = row_track_key(&rows[index]); if(key != TRACK_NONE) track_select(app, key, true); } app->visual = false; } // NOTE: selected keys in playing order: by reciter, then surah. 316 words, ctz per hit. internal u32 selection_keys(App *app, u32 *out, u32 capacity) { u32 count = 0; u32 words = (app->store->entry_count + 63) / 64; for(u32 word = 0; word < words && count < capacity; ++word) { u64 bits = app->selected[word]; while(bits && count < capacity) { u32 bit = (u32)__builtin_ctzll(bits); out[count++] = word * 64 + bit; bits &= bits - 1; } } return count; } //- queue internal void app_send_queue(App *app) { decoder_command(app->decoder, DECODER_QUEUE_CLEAR, 0, 0); for(u32 index = 0; index < app->queue_count; ++index) { decoder_command(app->decoder, DECODER_QUEUE_ADD, app->queue[index], 0); } } // NOTE: play these tracks as a queue, in order, gapless between them like autoplay internal void app_play_queue(App *app, const u32 *keys, u32 count) { count = Min(count, (u32)DECODER_QUEUE_CAPACITY); if(count == 0 || !app->audio_ok) return; if(keys != app->queue) MemMove(app->queue, keys, sizeof(u32) * count); app->queue_count = count; app_send_queue(app); app->requested_key = app->queue[0]; app->paused = false; audio_output_set_paused(app->output, false); decoder_command(app->decoder, DECODER_SET_AUTOPLAY, 0, app->settings.autoplay); decoder_command(app->decoder, DECODER_PLAY, app->queue[0], 0); } internal void app_play_selection(App *app, View *view, Row *rows, u32 count) { if(view) visual_commit(app, view, rows, count); u32 keys = selection_keys(app, app->queue, DECODER_QUEUE_CAPACITY); if(keys == 0) return; app_play_queue(app, app->queue, keys); app_message(app, "playing %u selected surahs", keys); selection_clear(app); } internal void app_play_in_queue(App *app, u32 key) { app->requested_key = key; app->paused = false; audio_output_set_paused(app->output, false); decoder_command(app->decoder, DECODER_PLAY, key, 0); } internal s32 queue_find(App *app, u32 key) { for(u32 index = 0; index < app->queue_count; ++index) if(app->queue[index] == key) return (s32)index; return -1; } internal void queue_remove(App *app, u32 key) { s32 at = queue_find(app, key); if(at < 0) return; for(u32 index = (u32)at; index + 1 < app->queue_count; ++index) app->queue[index] = app->queue[index + 1]; --app->queue_count; app_send_queue(app); } //- columns internal void view_columns_setup(View *view, Column *columns, u32 count) { if(view->column_count == count) return; view->column_count = count; view->column_hidden = 0; for(u32 index = 0; index < count; ++index) { view->column_order[index] = (u8)index; view->column_weight[index] = columns[index].width; } } typedef struct ColumnLayout ColumnLayout; struct ColumnLayout { u32 count; // visible columns u32 logical[UI_MAX_COLUMNS]; f32 x0[UI_MAX_COLUMNS]; f32 x1[UI_MAX_COLUMNS]; f32 total; // sum of visible weights }; internal ColumnLayout column_layout(View *view, Rect area) { ColumnLayout layout = {}; for(u32 index = 0; index < view->column_count; ++index) { u32 c = view->column_order[index]; if(!((view->column_hidden >> c) & 1)) { layout.logical[layout.count++] = c; layout.total += view->column_weight[c]; } } f32 x = area.x0, w = rect_w(area); for(u32 index = 0; index < layout.count; ++index) { layout.x0[index] = x; x += w * view->column_weight[layout.logical[index]] / Max(layout.total, 0.0001f); layout.x1[index] = (index + 1 == layout.count) ? area.x1 : x; } return layout; } // NOTE: column headers get the same gestures as tabs and panel gaps internal void draw_column_headers(App *app, PlatformInput *input, View *view, Column *columns, Rect header, ColumnLayout *layout) { DrawList *d = &app->draw; FontSystem *fonts = &app->fonts; s32 self = (s32)(view - app->layout.views); b32 free = app->drag_view < 0 && app->resize_panel < 0 && app->overlay == UI_OVERLAY_NONE; f32 base = ui_baseline(app, FONT_REGULAR, UI_FONT_SMALL, header.y0, rect_h(header)); draw_rect(d, header, COLOR_HEADER, 0); for(u32 index = 0; index < layout->count; ++index) { u32 c = layout->logical[index]; Rect cell = {layout->x0[index], header.y0, layout->x1[index], header.y1}; b32 over = free && ui_hovered(input, cell); if(app->column_drag_view == self && app->column_drag_active && app->column_drag_column == c) draw_rect(d, cell, COLOR_DROP, 0); else if(over) draw_rect(d, cell, COLOR_HOVER, 0); draw_text_fit(d, fonts, FONT_REGULAR, UI_FONT_SMALL, cell.x0 + 8, base, rect_w(cell) - 12, str8((char *)columns[c].title), COLOR_TEXT_FAINT); if(index > 0) draw_rect(d, Rect{cell.x0, header.y0 + 4, cell.x0 + 1, header.y1 - 4}, COLOR_PANEL_EDGE, 0); //- edge on the right: resize, like a panel gap Rect edge = {cell.x1 - 3, header.y0, cell.x1 + 3, header.y1}; b32 on_edge = free && index + 1 < layout->count && ui_hovered(input, edge); if(on_edge) app->table_cursor = PLATFORM_CURSOR_RESIZE_X; if(on_edge && ButtonPressed(input->mouse[0])) { app->column_resize_view = self; app->column_resize_index = index; input->mouse[0].half_transition_count = 0; continue; } //- body: drag to reorder, middle click hides, like a tab if(over && ButtonPressed(input->mouse[0])) { app->column_drag_view = self; app->column_drag_column = c; app->column_drag_active = false; app->column_drag_x = input->mouse_x; } if(over && ButtonPressed(input->mouse[2]) && layout->count > 1) { view->column_hidden |= (1u << c); app_message(app, "column %s hidden, :columns brings it back", columns[c].title); } } //- resizing: the two columns around the edge trade weight, the sum stays the same if(app->column_resize_view == self) { u32 index = app->column_resize_index; if(index + 1 < layout->count) { u32 a = layout->logical[index], b = layout->logical[index + 1]; f32 pair = view->column_weight[a] + view->column_weight[b]; f32 per_px = layout->total / Max(rect_w(header), 1.0f); f32 wa = (input->mouse_x - layout->x0[index]) * per_px; wa = Clamp(wa, pair * 0.08f, pair * 0.92f); view->column_weight[a] = wa; view->column_weight[b] = pair - wa; } app->table_cursor = PLATFORM_CURSOR_RESIZE_X; app->animating = true; if(!input->mouse[0].ended_down) app->column_resize_view = -1; } //- reordering: drop before the first column whose middle is right of the mouse if(app->column_drag_view == self) { if(fabsf(input->mouse_x - app->column_drag_x) > 6) app->column_drag_active = true; if(app->column_drag_active) { u32 slot = layout->count; for(u32 index = 0; index < layout->count; ++index) { if(input->mouse_x < (layout->x0[index] + layout->x1[index]) * 0.5f) { slot = index; break; } } f32 line_x = (slot < layout->count) ? layout->x0[slot] : layout->x1[layout->count - 1] - 2; draw_rect(d, Rect{line_x, header.y0, line_x + 2, header.y1}, COLOR_ACCENT, 0); app->table_cursor = PLATFORM_CURSOR_GRABBING; app->animating = true; if(!input->mouse[0].ended_down) { // rebuild the order: everything but the dragged column, with it inserted at the slot u32 target = (slot < layout->count) ? layout->logical[slot] : UINT32_MAX; u8 order[UI_MAX_COLUMNS]; u32 n = 0; for(u32 index = 0; index < view->column_count; ++index) { u8 c = view->column_order[index]; if(c == app->column_drag_column) continue; if(c == target) order[n++] = (u8)app->column_drag_column; order[n++] = c; } if(target == UINT32_MAX || target == app->column_drag_column) { if(n < view->column_count) order[n++] = (u8)app->column_drag_column; } if(n == view->column_count) MemCpy(view->column_order, order, n); } } if(!input->mouse[0].ended_down) app->column_drag_view = -1; } } internal void draw_table(App *app, PlatformInput *input, s32 panel, View *view, Rect area, b32 focused) { DrawList *d = &app->draw; FontSystem *fonts = &app->fonts; ScratchArena scratch = ScratchGet(); Row *rows = PushArray(scratch.arena, Row, UI_MAX_ROWS); u32 count = view_rows(app, view, rows, UI_MAX_ROWS); view->row_count = count; Column columns[UI_MAX_COLUMNS]; u32 column_count = view_columns((ViewKind)view->kind, columns); view_columns_setup(view, columns, column_count); ColumnLayout layout = column_layout(view, area); //- column header Rect header = {area.x0, area.y0, area.x1, area.y0 + UI_COLUMN_H}; if(UI_COLUMN_H > 0) draw_column_headers(app, input, view, columns, header, &layout); //- body Rect body = {area.x0, header.y1, area.x1, area.y1}; f32 row_h = UI_ROW_H; f32 view_h = rect_h(body); s32 cursor = view_cursor(app, view, rows, count); if(ui_hovered(input, body) && input->scroll_y != 0) { view->scroll.target += input->scroll_y * row_h * (f32)ui_theme.scroll_lines; } if(app->keep_selection_visible || (focused && input->key_count)) { // NOTE: keep a row of context around the cursor, like scrolloff=1 f32 y = (f32)cursor * row_h; if(y - row_h < view->scroll.target) view->scroll.target = y - row_h; if(y + 2 * row_h > view->scroll.target + view_h) view->scroll.target = y + 2 * row_h - view_h; } scroll_update(&view->scroll, (f32)count * row_h, view_h, app->dt, &app->animating); u32 first = (u32)(view->scroll.offset / row_h); u32 last = Min(count, first + (u32)(view_h / row_h) + 2); view->first_visible = first; view->visible_rows = (u32)(view_h / row_h); b32 busy = app->drag_view >= 0 || app->resize_panel >= 0 || app->column_drag_view >= 0 || app->column_resize_view >= 0 || app->overlay != UI_OVERLAY_NONE; draw_clip_push(d, body); Cells cells; for(u32 index = first; index < last; ++index) { Row *row = &rows[index]; f32 y = body.y0 + (f32)index * row_h - view->scroll.offset; Rect rect = {body.x0, y, body.x1, y + row_h}; b32 selected = ((s32)index == cursor); b32 hovered = ui_hovered(input, rect_intersect(rect, body)) && !busy; u32 key = row_track_key(row); b32 marked = (key != TRACK_NONE) && (track_selected(app, key) || row_in_visual(app, view, (s32)index, cursor)); view_cells(app, view, row, &cells, scratch.arena); if(ui_theme.zebra && (index & 1)) draw_rect(d, rect, COLOR_ZEBRA, 0); if(marked) draw_rect(d, rect, COLOR_MARKED, 0); if(selected) draw_rect(d, rect, focused ? COLOR_SELECTED : COLOR_HOVER, 0); else if(hovered) draw_rect(d, rect, COLOR_HOVER, 0); if(marked) draw_rect(d, Rect{rect.x1 - 4, rect.y0 + 3, rect.x1 - 2, rect.y1 - 3}, COLOR_TEXT_DIM, 0); if(cells.bright) draw_rect(d, Rect{rect.x0, rect.y0, rect.x0 + 2, rect.y1}, COLOR_ACCENT, 0); u32 color = cells.bright ? COLOR_ACCENT : (cells.dim ? COLOR_TEXT_FAINT : COLOR_TEXT); for(u32 slot = 0; slot < layout.count; ++slot) { u32 c = layout.logical[slot]; f32 cx = layout.x0[slot]; f32 w = layout.x1[slot] - layout.x0[slot]; f32 indent = 0; if(c == 0) { indent = (f32)row->depth * ui_theme.tree_indent; if(row->expandable) { draw_text(d, fonts, FONT_MONO, UI_FONT, cx + 8 + indent, ui_baseline(app, FONT_MONO, UI_FONT, y, row_h), str8(row->expanded ? "-" : "+"), COLOR_TEXT_DIM); indent += 14.0f; } } FontKind font = columns[c].mono ? FONT_MONO : ((cells.bright && ui_theme.bold_playing && c == 0) ? FONT_SEMIBOLD : FONT_REGULAR); if(c == 1 && cells.has_swatch) { // NOTE: color settings show a sample square, the hex value follows it f32 side = Min(row_h - 8, 14.0f); Rect sw = {cx + 8, y + (row_h - side) * 0.5f, cx + 8 + side, y + (row_h + side) * 0.5f}; draw_rect(d, sw, cells.swatch, 0); draw_border(d, sw, COLOR_PANEL_EDGE, 0, 1); indent = side + 8; } u32 tint = (c > 0 && !cells.bright) ? (cells.dim ? COLOR_TEXT_FAINT : COLOR_TEXT_DIM) : color; f32 tx = cx + 8 + indent; f32 base = ui_baseline(app, font, UI_FONT, y, row_h); if(c + 1 == column_count && cells.progress >= 0 && cells.text[c].size == 0) { Rect bar = {cx + 8, y + row_h * 0.5f - 2, cx + w - 10, y + row_h * 0.5f + 2}; draw_rect(d, bar, COLOR_TRACK, 0); draw_rect(d, Rect{bar.x0, bar.y0, bar.x0 + rect_w(bar) * cells.progress, bar.y1}, COLOR_TEXT_DIM, 0); } else if(view->kind == VIEW_PLAYING && row->a == FIELD_POSITION && c == 1) { // NOTE: the position value is text plus a seek bar you can click f32 tw = draw_text(d, fonts, font, UI_FONT, tx, base, cells.text[c], tint); Rect bar = {tx + tw + 12, y + row_h * 0.5f - 2, cx + w - 10, y + row_h * 0.5f + 2}; if(rect_w(bar) > 20) { draw_rect(d, bar, COLOR_TRACK, 0); draw_rect(d, Rect{bar.x0, bar.y0, bar.x0 + rect_w(bar) * Clamp(cells.progress, 0.0f, 1.0f), bar.y1}, COLOR_ACCENT, 0); u64 total = app_track_total(app); Rect hit = {bar.x0, rect.y0, bar.x1, rect.y1}; if(hovered && ui_clicked(input, hit) && total && app_current_key(app) != TRACK_NONE) { f32 t = Clamp((input->mouse_x - bar.x0) / rect_w(bar), 0.0f, 1.0f); decoder_command(app->decoder, DECODER_SEEK, 0, (u64)((f64)t * (f64)total)); input->mouse[0].half_transition_count = 0; } } } else { draw_text_fit(d, fonts, font, UI_FONT, tx, base, w - 14 - indent, cells.text[c], tint); } } //- mouse: click moves the cursor, double click (or the +) activates, // ctrl click toggles the row in the selection, shift click selects up to it if(hovered && ButtonPressed(input->mouse[0])) { app->layout.focused = panel; u64 now = time_now_ns(); b32 twice = (now - app->last_click_ns < (u64)ui_theme.double_click_ms * 1000000ull) && fabsf(input->mouse_x - app->last_click_x) < 4 && fabsf(input->mouse_y - app->last_click_y) < 4; b32 on_box = row->expandable && layout.count && layout.logical[0] == 0 && input->mouse_x < body.x0 + 8 + row->depth * ui_theme.tree_indent + 14.0f; if((input->mods & PLATFORM_MOD_CTRL) && key != TRACK_NONE) { track_select(app, key, !track_selected(app, key)); now = 0; } else if((input->mods & PLATFORM_MOD_SHIFT) && key != TRACK_NONE) { s32 lo = Min(cursor, (s32)index), hi = Max(cursor, (s32)index); for(s32 at = lo; at <= hi; ++at) if(row_track_key(&rows[at]) != TRACK_NONE) track_select(app, row_track_key(&rows[at]), true); now = 0; } else if(twice || on_box) { view_activate(app, view, row); now = 0; } view_set_cursor(app, view, rows, count, (s32)index); app->last_click_ns = now; app->last_click_x = input->mouse_x; app->last_click_y = input->mouse_y; } } draw_clip_pop(d); if(count == 0) { const char *empty = "nothing here"; if(view->kind == VIEW_OFFLINE) empty = "nothing downloaded yet: yy downloads a surah, Y a whole reciter"; if(view->kind == VIEW_DOWNLOADS) empty = "no downloads running"; if(view->kind == VIEW_QUEUE) empty = "empty: select surahs (v, V, ctrl click) and press enter"; draw_text_fit(d, fonts, FONT_REGULAR, UI_FONT, body.x0 + 10, body.y0 + 18, rect_w(body) - 20, str8((char *)empty), COLOR_TEXT_FAINT); } //- scrollbar f32 content = (f32)count * row_h; if(content > view_h && ui_theme.show_scrollbars) { f32 thumb_h = Max(view_h * view_h / content, 20.0f); f32 thumb_y = body.y0 + (view_h - thumb_h) * (view->scroll.offset / (content - view_h)); draw_rect(d, Rect{body.x1 - 4, thumb_y, body.x1 - 1, thumb_y + thumb_h}, COLOR_TRACK, 0); } scratch_end(&scratch); } //- panels internal DropZone drop_zone(Rect rect, f32 x, f32 y) { f32 u = (x - rect.x0) / Max(rect_w(rect), 1.0f); f32 v = (y - rect.y0) / Max(rect_h(rect), 1.0f); if(u < 0.25f) return DROP_LEFT; if(u > 0.75f) return DROP_RIGHT; if(v < 0.25f) return DROP_TOP; if(v > 0.75f) return DROP_BOTTOM; return DROP_CENTER; } internal Rect drop_preview(Rect rect, DropZone zone) { switch(zone) { case DROP_LEFT: return Rect{rect.x0, rect.y0, rect.x0 + rect_w(rect) * 0.5f, rect.y1}; case DROP_RIGHT: return Rect{rect.x0 + rect_w(rect) * 0.5f, rect.y0, rect.x1, rect.y1}; case DROP_TOP: return Rect{rect.x0, rect.y0, rect.x1, rect.y0 + rect_h(rect) * 0.5f}; case DROP_BOTTOM: return Rect{rect.x0, rect.y0 + rect_h(rect) * 0.5f, rect.x1, rect.y1}; default: return rect; } } // NOTE: a view as one line: each row's value side by side (the Value column, or the first one). // rows marked right are placed from the right edge first, the rest flow from the left into what's // left. drag it like a tab to move the view elsewhere, middle click closes it. internal b32 draw_bar(App *app, PlatformInput *input, s32 panel, s32 view_index, Rect rect, b32 modal) { DrawList *d = &app->draw; FontSystem *fonts = &app->fonts; View *view = &app->layout.views[view_index]; f32 size = UI_FONT_SMALL; ScratchArena scratch = ScratchGet(); draw_rect(d, rect, COLOR_BG, 0); if(!modal && ui_hovered(input, rect) && app->drag_view < 0) { if(ButtonPressed(input->mouse[0])) { app->drag_view = view_index; app->drag_panel = panel; app->drag_x = input->mouse_x; app->drag_y = input->mouse_y; app->drag_active = false; } if(ButtonPressed(input->mouse[2])) { Panel *p = &app->layout.panels[panel]; scratch_end(&scratch); layout_close_view(&app->layout, panel, p->active_tab); return true; } } Row *rows = PushArray(scratch.arena, Row, UI_MAX_ROWS); u32 count = view_rows(app, view, rows, UI_MAX_ROWS); // NOTE: field | value views show the value (an empty one is skipped), others their first column Column columns[UI_MAX_COLUMNS]; u32 shown = (view_columns((ViewKind)view->kind, columns) >= 2 && (view->kind == VIEW_STATUS || view->kind == VIEW_PLAYING || view->kind == VIEW_PROFILER || view->kind == VIEW_SETTINGS)) ? 1 : 0; Cells *all = PushArray(scratch.arena, Cells, count); f32 baseline = ui_baseline(app, FONT_MONO, size, rect.y0, Min(rect_h(rect), UI_STATUS_H)); f32 right = rect.x1 - 10; draw_clip_push(d, rect); for(u32 pass = 0; pass < 2; ++pass) { f32 left = rect.x0; for(u32 index = 0; index < count; ++index) { Cells *cells = &all[index]; if(pass == 0) { MemSetZero(cells, sizeof(*cells)); view_cells(app, view, &rows[index], cells, scratch.arena); } String8 text = cells->text[shown]; if(text.size == 0 || (b32)cells->right != (pass == 0)) continue; u32 color = cells->dim ? COLOR_TEXT_DIM : COLOR_TEXT; if(cells->right) { right -= font_measure(fonts, FONT_MONO, size, text); draw_text(d, fonts, FONT_MONO, size, right, baseline, text, color); right -= 18; } else if(cells->bright) { f32 w = font_measure(fonts, FONT_MONO, size, text) + 16; draw_rect(d, Rect{left, rect.y0, left + w, rect.y1}, COLOR_TAB_ACTIVE, 0); draw_text(d, fonts, FONT_MONO, size, left + 8, baseline, text, COLOR_TEXT); left += w + 10; } else if(right - left > 24) { left += draw_text_fit(d, fonts, FONT_REGULAR, size, left, baseline, right - left - 8, text, COLOR_TEXT_DIM) + 18; } } } draw_clip_pop(d); scratch_end(&scratch); return false; } internal void draw_panels(App *app, PlatformInput *input) { DrawList *d = &app->draw; FontSystem *fonts = &app->fonts; Layout *layout = &app->layout; u32 cursor = PLATFORM_CURSOR_DEFAULT; b32 modal = (app->overlay != UI_OVERLAY_NONE); f32 tab_font = UI_FONT_SMALL + 0.5f; //- split handles: drag the gap between two panels for(s32 index = 0; index < UI_MAX_PANELS && !modal; ++index) { Panel *p = &layout->panels[index]; if(p->kind != PANEL_SPLIT) continue; Rect a = layout->panels[p->children[0]].rect; Rect handle = (p->axis == 0) ? Rect{a.x1 - 1, p->rect.y0, a.x1 + UI_GAP + 1, p->rect.y1} : Rect{p->rect.x0, a.y1 - 1, p->rect.x1, a.y1 + UI_GAP + 1}; b32 over = ui_hovered(input, handle) && app->drag_view < 0; if(over && ButtonPressed(input->mouse[0])) app->resize_panel = index; if(over || app->resize_panel == index) cursor = (p->axis == 0) ? PLATFORM_CURSOR_RESIZE_X : PLATFORM_CURSOR_RESIZE_Y; } if(app->resize_panel >= 0) { Panel *p = &layout->panels[app->resize_panel]; if(p->kind == PANEL_SPLIT) { f32 t = (p->axis == 0) ? (input->mouse_x - p->rect.x0) / rect_w(p->rect) : (input->mouse_y - p->rect.y0) / rect_h(p->rect); p->ratio = Clamp(t, 0.1f, 0.9f); // NOTE: a bottom panel dragged down to a few lines snaps into a bar (whole status lines), // dragged back up it becomes a table again f32 lines = (p->rect.y1 - input->mouse_y) / UI_STATUS_H; if(p->axis == 1 && lines < 3.5f) p->ratio = -Max(roundf(lines), 1.0f); } if(!input->mouse[0].ended_down) app->resize_panel = -1; app->animating = true; } //- leaves for(s32 index = 0; index < UI_MAX_PANELS; ++index) { Panel *p = &layout->panels[index]; if(p->kind != PANEL_LEAF) continue; b32 focused = (layout->focused == index) && !modal; Rect rect = p->rect; // NOTE: too short for tabs + a header + a row: the active view becomes a bar if(panel_is_bar(layout, index)) { s32 view = panel_active_view(layout, index); if(view >= 0 && draw_bar(app, input, index, view, rect, modal)) return; // closed: layout changed continue; } draw_rect(d, rect, COLOR_PANEL, 0); //- tab bar // NOTE: tabs keep their natural width while they fit and shrink evenly when they don't, // so a panel can hold many views without spilling into its neighbour Rect bar = {rect.x0, rect.y0, rect.x1, rect.y0 + UI_TAB_H}; draw_rect(d, bar, COLOR_BG, 0); ScratchArena tab_scratch = ScratchGet(); String8 *titles = PushArray(tab_scratch.arena, String8, UI_MAX_TABS); f32 *widths = PushArray(tab_scratch.arena, f32, UI_MAX_TABS); f32 total = 0; for(u32 t = 0; t < p->tab_count; ++t) { titles[t] = view_title(tab_scratch.arena, &layout->views[p->tabs[t]]); widths[t] = font_measure(fonts, FONT_REGULAR, tab_font, titles[t]) + 24; total += widths[t] + 1; } f32 fit = (total > rect_w(bar) && total > 0) ? rect_w(bar) / total : 1.0f; draw_clip_push(d, bar); f32 tx = bar.x0; for(u32 t = 0; t < p->tab_count; ++t) { String8 title = titles[t]; f32 w = Max(widths[t] * fit, 28.0f); Rect tab = {tx, bar.y0, tx + w, bar.y1}; b32 active = (t == p->active_tab); b32 over = ui_hovered(input, rect_intersect(tab, bar)) && !modal; draw_rect(d, tab, active ? COLOR_TAB_ACTIVE : (over ? COLOR_TAB : COLOR_BG), 0); if(active && focused) draw_rect(d, Rect{tab.x0, tab.y0, tab.x1, tab.y0 + 2}, COLOR_ACCENT, 0); draw_text_fit(d, fonts, FONT_REGULAR, tab_font, tab.x0 + 12 * Min(fit, 1.0f), ui_baseline(app, FONT_REGULAR, tab_font, tab.y0, UI_TAB_H), w - 16, title, active ? (focused ? COLOR_ACCENT : COLOR_TEXT) : COLOR_TEXT_DIM); if(over && ButtonPressed(input->mouse[0])) { p->active_tab = t; layout->focused = index; app->drag_view = p->tabs[t]; app->drag_panel = index; app->drag_x = input->mouse_x; app->drag_y = input->mouse_y; app->drag_active = false; } if(over && ButtonPressed(input->mouse[2])) { draw_clip_pop(d); scratch_end(&tab_scratch); layout_close_view(layout, index, t); return; // the layout changed under us, it's drawn again next frame } tx += w + 1; } draw_clip_pop(d); scratch_end(&tab_scratch); //- empty tab bar space is the window's title bar: drag to move, double click to maximize Rect empty = {tx, bar.y0, bar.x1, bar.y1}; if(!modal && !PlatformWindowIsLayer(app->window) && ui_clicked(input, empty) && app->drag_view < 0) { u64 now = time_now_ns(); if(now - app->last_click_ns < (u64)ui_theme.double_click_ms * 1000000ull) { PlatformWindowToggleMaximized(app->window); app->last_click_ns = 0; } else { app->last_click_ns = now; PlatformWindowBeginMove(app->window); } } //- content Rect content = {rect.x0, bar.y1, rect.x1, rect.y1}; s32 view = panel_active_view(layout, index); if(view >= 0) { draw_clip_push(d, content); draw_table(app, input, index, &layout->views[view], content, focused); draw_clip_pop(d); } else { draw_text(d, fonts, FONT_MONO, UI_FONT_SMALL, content.x0 + 10, content.y0 + 20, str8(":view reciters | surahs | offline | playing | downloads | settings"), COLOR_TEXT_FAINT); } draw_border(d, rect, focused ? COLOR_FOCUS_EDGE : COLOR_PANEL_EDGE, 0, 1); } //- tab drag and drop if(app->drag_view >= 0) { f32 moved = fabsf(input->mouse_x - app->drag_x) + fabsf(input->mouse_y - app->drag_y); if(moved > 6) app->drag_active = true; if(app->drag_active) { cursor = PLATFORM_CURSOR_GRABBING; app->animating = true; for(s32 index = 0; index < UI_MAX_PANELS; ++index) { Panel *p = &layout->panels[index]; if(p->kind != PANEL_LEAF || !ui_hovered(input, p->rect)) continue; DropZone zone = drop_zone(p->rect, input->mouse_x, input->mouse_y); Rect preview = drop_preview(p->rect, zone); draw_rect(d, preview, COLOR_DROP, 0); draw_border(d, preview, COLOR_FOCUS_EDGE, 0, 1); if(!input->mouse[0].ended_down) { layout_move_view(layout, app->drag_panel, app->drag_view, index, zone); break; } } if(app->drag_view >= 0 && layout->views[app->drag_view].kind != VIEW_NONE) { ScratchArena ghost_scratch = ScratchGet(); String8 title = view_title(ghost_scratch.arena, &layout->views[app->drag_view]); f32 w = font_measure(fonts, FONT_REGULAR, tab_font, title) + 24; Rect ghost = {input->mouse_x + 10, input->mouse_y + 10, input->mouse_x + 10 + w, input->mouse_y + 10 + UI_TAB_H}; draw_rect(d, ghost, COLOR_TAB_ACTIVE, 0); draw_border(d, ghost, COLOR_FOCUS_EDGE, 0, 1); draw_text(d, fonts, FONT_REGULAR, tab_font, ghost.x0 + 12, ui_baseline(app, FONT_REGULAR, tab_font, ghost.y0, UI_TAB_H), title, COLOR_TEXT); scratch_end(&ghost_scratch); } } if(!input->mouse[0].ended_down) app->drag_view = -1; } if(cursor == PLATFORM_CURSOR_DEFAULT) cursor = app->table_cursor; if(app->cursor_shape != cursor) { app->cursor_shape = cursor; PlatformWindowSetCursor(app->window, (PlatformCursor)cursor); } } //- overlays internal void search_update(App *app) { app->result_count = 0; app->result_cursor = 0; if(app->input_size == 0) return; // NOTE: a number jumps straight to that surah u32 number = 0; b32 numeric = true; for(u32 index = 0; index < app->input_size; ++index) { char c = app->input[index]; if(c < '0' || c > '9') { numeric = false; break; } number = number * 10 + (u32)(c - '0'); } if(numeric && number >= 1 && number <= SURAH_COUNT) { app->results[app->result_count++] = SearchResult{UINT32_MAX, number - 1}; } for(u32 qari = 0; qari < app->catalog->qari_count && app->result_count < UI_MAX_RESULTS; ++qari) { if(str8_contains_nocase(app->catalog->qaris[qari].name, app->input, app->input_size)) { app->results[app->result_count++] = SearchResult{qari, 0}; } } for(u32 surah = 0; surah < SURAH_COUNT && app->result_count < UI_MAX_RESULTS; ++surah) { Surah *s = &app->catalog->surahs[surah]; if(numeric && surah == number - 1) continue; if(str8_contains_nocase(s->name, app->input, app->input_size) || str8_contains_nocase(s->english, app->input, app->input_size)) { app->results[app->result_count++] = SearchResult{UINT32_MAX, surah}; } } } internal void overlay_open(App *app, UIOverlay overlay) { app->overlay = overlay; app->overlay_opened = true; app->input_size = 0; app->result_count = 0; app->result_cursor = 0; if(overlay != UI_OVERLAY_EDIT) { return; } // NOTE: start from the current value, like editing a watch expression View *view = &app->layout.views[app->edit_view]; char text[64]; text[0] = 0; if(view->kind == VIEW_PLAYING && app->edit_field == FIELD_POSITION) format_duration(text, sizeof(text), app->position.rate ? (f64)app->position.frame / app->position.rate : 0.0); if(view->kind == VIEW_PLAYING && app->edit_field == FIELD_VOLUME) snprintf(text, sizeof(text), "%.0f", app->settings.volume * 100); if(view->kind == VIEW_SETTINGS) { ScratchArena scratch = ScratchGet(); String8 value = settings_format(scratch.arena, &app->settings, settings_desc(app->edit_field)); snprintf(text, sizeof(text), Str8Fmt, Str8Arg(value)); scratch_end(&scratch); } app->input_size = (u32)Min(strlen(text), sizeof(app->input) - 1); MemCpy(app->input, text, app->input_size); } // NOTE: pick a reciter / surah from anywhere: it moves the shared selection, so every view follows internal void search_accept(App *app, SearchResult result) { app->jump_back = app_place(app); if(result.qari != UINT32_MAX) { app->qari = (s32)result.qari; layout_open(&app->layout, VIEW_RECITERS); } else { app->surah = (s32)result.surah; layout_open(&app->layout, VIEW_SURAHS); } app->keep_selection_visible = true; } internal f64 parse_duration(const char *text) { f64 total = 0, part = 0; for(const char *at = text; *at; ++at) { if(*at == ':') { total = (total + part) * 60.0; part = 0; } else if(*at >= '0' && *at <= '9') { part = part * 10 + (*at - '0'); } } return total + part; } internal void edit_accept(App *app) { char text[65]; MemCpy(text, app->input, app->input_size); text[app->input_size] = 0; View *view = &app->layout.views[app->edit_view]; f64 value = atof(text); if(view->kind == VIEW_PLAYING) { if(app->edit_field == FIELD_POSITION && app->position.rate) decoder_command(app->decoder, DECODER_SEEK, 0, (u64)(parse_duration(text) * app->position.rate)); if(app->edit_field == FIELD_VOLUME) app->settings.volume = (f32)(value / 100.0); } else if(view->kind == VIEW_SETTINGS) { if(!settings_parse(&app->settings, settings_desc(app->edit_field), text)) app_message(app, "could not read \"%s\"", text); } app_apply_settings(app); } //- command completion // NOTE: computed from the typed text every time it's needed (a few dozen candidates, microseconds), // so the only state is the highlighted row (result_cursor). nothing new lives in App, which keeps // this hot reloadable. typedef struct CommandDesc CommandDesc; struct CommandDesc { const char *name; const char *args; const char *help; b32 takes_arg; }; global_variable const CommandDesc ui_commands[] = { {"view", "", "open or focus a view", 1}, {"vs", "", "open a view split to the right", 1}, {"sp", "", "open a view split below", 1}, {"set", "=", "change any setting", 1}, {"vol", "<0-100>", "volume", 1}, {"zoom", "<0.6-3>", "ui zoom", 1}, {"columns", "", "bring back the hidden columns of this view", 0}, {"reset", "", "back to the default panel layout", 0}, {"dl", "", "download every surah of the selected reciter", 0}, {"q", "", "quit", 0}, {"e", "", "same as view", 1}, {"open", "", "same as view", 1}, {"qa", "", "quit", 0}, {"wq", "", "quit (state is always saved)", 0}, }; typedef struct Completion Completion; struct Completion { String8 text; String8 detail; u32 from; // where in the input the completed token starts char suffix; // appended on accept: ' ' or '=' when an argument follows, 0 otherwise }; #define UI_MAX_COMPLETIONS 64 // NOTE: 2 = prefix, 1 = somewhere inside, 0 = no match. case insensitive. internal u32 completion_match(const char *candidate, const char *token, u32 token_size) { String8 c = str8((char *)candidate); if(token_size == 0) return 2; if(c.size >= token_size && strncasecmp(candidate, token, token_size) == 0) return 2; return str8_contains_nocase(c, token, token_size) ? 1 : 0; } typedef struct CompletionList CompletionList; struct CompletionList { Completion items[UI_MAX_COMPLETIONS]; u32 count; u32 from; const char *token; u32 token_size; u32 pass; // 2 = collecting prefix matches, 1 = substring matches }; internal void completion_add(CompletionList *list, const char *text, String8 detail, char suffix) { if(list->count >= UI_MAX_COMPLETIONS || completion_match(text, list->token, list->token_size) != list->pass) return; Completion *item = &list->items[list->count++]; item->text = str8((char *)text); item->detail = detail; item->from = list->from; item->suffix = suffix; } internal const CommandDesc *command_resolve(const char *word, u32 size) { const CommandDesc *found = NULL; u32 hits = 0; for(u32 index = 0; index < ArrayCount(ui_commands); ++index) { if(strlen(ui_commands[index].name) == size && !strncmp(ui_commands[index].name, word, size)) return &ui_commands[index]; if(!strncmp(ui_commands[index].name, word, size)) { found = &ui_commands[index]; ++hits; } } return (hits == 1) ? found : NULL; } internal SettingDesc *setting_resolve(const char *name, u32 size) { SettingDesc *found = NULL; u32 hits = 0; for(u32 index = 0; index < settings_desc_count(); ++index) { SettingDesc *desc = settings_desc(index); if(desc->kind == SETTING_KIND_SECTION || desc->kind == SETTING_KIND_ACTION || desc->kind == SETTING_KIND_INFO) continue; if(strlen(desc->name) == size && !strncasecmp(desc->name, name, size)) return desc; if(!strncasecmp(desc->name, name, size)) { found = desc; ++hits; } } return (hits == 1) ? found : NULL; } internal u32 command_completions(App *app, Arena *arena, CompletionList *list) { char text[65]; MemCpy(text, app->input, app->input_size); text[app->input_size] = 0; list->count = 0; const char *space = strchr(text, ' '); for(list->pass = 2; list->pass >= 1; --list->pass) { if(!space) { //- the command itself list->from = 0; list->token = text; list->token_size = app->input_size; for(u32 index = 0; index < ArrayCount(ui_commands); ++index) { const CommandDesc *command = &ui_commands[index]; completion_add(list, command->name, ui_format(arena, "%-15s %s", command->args, command->help), command->takes_arg ? ' ' : 0); } continue; } const CommandDesc *command = command_resolve(text, (u32)(space - text)); const char *rest = space + 1; if(!command) break; if(!strcmp(command->name, "view") || !strcmp(command->name, "e") || !strcmp(command->name, "open") || !strcmp(command->name, "vs") || !strcmp(command->name, "sp")) { list->from = (u32)(rest - text); list->token = rest; list->token_size = (u32)strlen(rest); ViewType types[UI_MAX_VIEW_TYPES]; u32 types_count = view_types(types); for(u32 index = 0; index < types_count; ++index) { View probe = {}; probe.kind = types[index].kind; probe.group = types[index].group; completion_add(list, types[index].name, view_title(arena, &probe), 0); } } else if(!strcmp(command->name, "set")) { const char *equals = strchr(rest, '='); if(!equals) { //- setting names, with their current value list->from = (u32)(rest - text); list->token = rest; list->token_size = (u32)strlen(rest); for(u32 index = 0; index < settings_desc_count(); ++index) { SettingDesc *desc = settings_desc(index); if(desc->kind == SETTING_KIND_SECTION || desc->kind == SETTING_KIND_ACTION || desc->kind == SETTING_KIND_INFO) continue; String8 value = settings_format(arena, &app->settings, desc); completion_add(list, desc->name, ui_format(arena, "%-20.*s %s", Str8Arg(value), desc->note ? desc->note : ""), '='); } } else { //- values for that setting SettingDesc *desc = setting_resolve(rest, (u32)(equals - rest)); if(!desc) break; list->from = (u32)(equals + 1 - text); list->token = equals + 1; list->token_size = (u32)strlen(equals + 1); switch(desc->kind) { case SETTING_KIND_BOOL: { completion_add(list, "on", str8_zero(), 0); completion_add(list, "off", str8_zero(), 0); } break; case SETTING_KIND_ENUM: case SETTING_KIND_CHOICE: { for(u32 index = 0; index < desc->count; ++index) completion_add(list, desc->names[index], str8_zero(), 0); } break; case SETTING_KIND_FONT: { for(u32 index = 0; index < UI_FONT_CHOICES; ++index) { if(index < ArrayCount(ui_fonts) && font_installed(index)) completion_add(list, ui_fonts[index].name, str8_zero(), 0); } } break; default: { // numbers and colors: offer the current value to edit from String8 value = settings_format(arena, &app->settings, desc); char *copy = PushArray(arena, char, value.size + 1); MemCpy(copy, value.data, value.size); copy[value.size] = 0; for(char *at = copy; *at; ++at) if(*at == '%') *at = 0; // "80%" -> "80" completion_add(list, copy, str8("current value"), 0); } break; } } } else if(!strcmp(command->name, "vol") || !strcmp(command->name, "zoom")) { list->from = (u32)(rest - text); list->token = rest; list->token_size = (u32)strlen(rest); char *value = PushArray(arena, char, 16); if(!strcmp(command->name, "vol")) snprintf(value, 16, "%.0f", app->settings.volume * 100.0f); else snprintf(value, 16, "%.2f", app->settings.zoom); completion_add(list, value, str8("current value"), 0); } } return list->count; } internal void command_accept_completion(App *app, Completion *item) { u32 size = Min(item->from, (u32)sizeof(app->input) - 1); u32 take = (u32)Min(item->text.size, (u64)(sizeof(app->input) - 1 - size)); MemCpy(app->input + size, item->text.data, take); size += take; if(item->suffix && size < sizeof(app->input) - 1) app->input[size++] = item->suffix; app->input_size = size; app->result_cursor = 0; } internal void command_run(App *app) { char text[65]; MemCpy(text, app->input, app->input_size); text[app->input_size] = 0; char *arg = strchr(text, ' '); if(arg) { *arg++ = 0; while(*arg == ' ') ++arg; } const CommandDesc *resolved = (text[0] && !(text[0] >= '0' && text[0] <= '9')) ? command_resolve(text, (u32)strlen(text)) : NULL; if(resolved) snprintf(text, sizeof(text), "%s", resolved->name); if(!strcmp(text, "q") || !strcmp(text, "q!") || !strcmp(text, "qa") || !strcmp(text, "wq") || !strcmp(text, "x")) { app->quit = true; } else if(text[0] >= '0' && text[0] <= '9') { u32 number = (u32)atoi(text); if(number >= 1 && number <= SURAH_COUNT) { app->jump_back = app_place(app); app->surah = (s32)number - 1; app->keep_selection_visible = true; layout_open(&app->layout, VIEW_SURAHS); } } else if((!strcmp(text, "view") || !strcmp(text, "e") || !strcmp(text, "open") || !strcmp(text, "vs") || !strcmp(text, "sp")) && arg && arg[0]) { ViewType type; if(view_resolve(arg, &type)) { if(!strcmp(text, "vs")) layout_split_with(&app->layout, (ViewKind)type.kind, 0, type.group); else if(!strcmp(text, "sp")) layout_split_with(&app->layout, (ViewKind)type.kind, 1, type.group); else layout_open(&app->layout, (ViewKind)type.kind, type.group); return; } app_message(app, "no view called %s (:view views lists them all)", arg); } else if(!strcmp(text, "vol") && arg) { app_set_volume(app, (f32)atof(arg) / 100.0f); } else if(!strcmp(text, "zoom") && arg) { app->settings.zoom = (f32)atof(arg); app_apply_settings(app); } else if(!strcmp(text, "set") && arg) { if(settings_set(&app->settings, arg)) app_apply_settings(app); else app_message(app, "unknown setting or value: %s", arg); } else if(!strcmp(text, "columns") || !strcmp(text, "cols")) { s32 view = panel_active_view(&app->layout, app->layout.focused); if(view >= 0) app->layout.views[view].column_count = 0; // set up again from the defaults } else if(!strcmp(text, "reset")) { ui_layout_default(&app->layout); } else if(!strcmp(text, "dl") || !strcmp(text, "download")) { if(app->qari >= 0) app_message(app, "queued %u surahs", store_request_qari(app->store, (u32)app->qari)); } else if(text[0]) { app_message(app, "not a command: %s", text); } } internal void draw_overlay(App *app, PlatformInput *input, Rect window) { if(app->overlay == UI_OVERLAY_NONE) return; DrawList *d = &app->draw; FontSystem *fonts = &app->fonts; ScratchArena scratch = ScratchGet(); CompletionList *completions = NULL; u32 shown = (app->overlay == UI_OVERLAY_SEARCH) ? Min(app->result_count, 12u) : 0; if(app->overlay == UI_OVERLAY_COMMAND) { completions = PushStruct(scratch.arena, CompletionList); u32 count = command_completions(app, scratch.arena, completions); app->result_cursor = (count == 0) ? 0 : Clamp(app->result_cursor, 0, (s32)count - 1); shown = Min(count, 12u); } f32 w = Min(560.0f, rect_w(window) - 40); f32 h = 40 + (f32)shown * UI_ROW_H + (shown ? 6 : 0); Rect box = {window.x0 + (rect_w(window) - w) * 0.5f, window.y0 + rect_h(window) * 0.18f, 0, 0}; box.x1 = box.x0 + w; box.y1 = box.y0 + h; draw_rect(d, window, 0x00000066u, 0); draw_shadow(d, box, 0x000000AAu, 0, 18); draw_rect(d, box, COLOR_TAB_ACTIVE, 0); draw_border(d, box, COLOR_FOCUS_EDGE, 0, 1); String8 label = str8(app->search_backward ? "?" : "/"); if(app->overlay == UI_OVERLAY_COMMAND) label = str8(":"); if(app->overlay == UI_OVERLAY_CONFIRM) { label = ui_format(scratch.arena, "delete every downloaded surah of " Str8Fmt "? y / n", Str8Arg(app->catalog->qaris[app->confirm_qari].name)); } else if(app->overlay == UI_OVERLAY_EDIT) { View *view = &app->layout.views[app->edit_view]; Row row = {app->edit_field, 0, (u8)(view->kind == VIEW_PLAYING ? ROW_FIELD : ROW_SETTING), 0, 0, 0}; Cells cells; view_cells(app, view, &row, &cells, scratch.arena); label = ui_format(scratch.arena, Str8Fmt " = ", Str8Arg(cells.text[0])); } f32 size = UI_FONT + 1; f32 baseline = ui_baseline(app, FONT_MONO, size, box.y0, 40); f32 lw = draw_text(d, fonts, FONT_MONO, size, box.x0 + 14, baseline, label, COLOR_TEXT_DIM); if(app->overlay != UI_OVERLAY_CONFIRM) { f32 tw = draw_text(d, fonts, FONT_MONO, size, box.x0 + 14 + lw, baseline, ToString8Size(app->input, app->input_size), COLOR_TEXT); if(fmodf(app->time, 1.0f) < 0.6f) draw_rect(d, Rect{box.x0 + 15 + lw + tw, box.y0 + 11, box.x0 + 23 + lw + tw, box.y0 + 29}, 0xFFFFFF99u, 0); app->animating = true; } f32 y = box.y0 + 40; if(completions) { // NOTE: keep the highlighted row inside the 12 we show u32 first = (app->result_cursor >= (s32)shown) ? (u32)app->result_cursor - shown + 1 : 0; for(u32 row = 0; row < shown; ++row) { u32 index = first + row; Completion *item = &completions->items[index]; Rect rect = {box.x0 + 4, y, box.x1 - 4, y + UI_ROW_H}; if((s32)index == app->result_cursor) draw_rect(d, rect, COLOR_SELECTED, 0); if(ui_clicked(input, rect)) command_accept_completion(app, item); f32 b = ui_baseline(app, FONT_MONO, UI_FONT, y, UI_ROW_H); f32 name = draw_text(d, fonts, FONT_MONO, UI_FONT, rect.x0 + 10, b, item->text, COLOR_TEXT); f32 dx = Max(name + 24, rect_w(rect) * 0.32f); draw_text_fit(d, fonts, FONT_MONO, UI_FONT_SMALL, rect.x0 + dx, b, rect_w(rect) - dx - 10, item->detail, COLOR_TEXT_DIM); y += UI_ROW_H; } shown = 0; // the search rows below don't apply } for(u32 index = 0; index < shown; ++index) { SearchResult *result = &app->results[index]; Rect rect = {box.x0 + 4, y, box.x1 - 4, y + UI_ROW_H}; if((s32)index == app->result_cursor) draw_rect(d, rect, COLOR_SELECTED, 0); if(ui_clicked(input, rect)) { search_accept(app, *result); app->overlay = UI_OVERLAY_NONE; } String8 kind, name; if(result->qari != UINT32_MAX) { kind = str8("reciter"); name = app->catalog->qaris[result->qari].name; } else { Surah *surah = &app->catalog->surahs[result->surah]; kind = str8("surah"); name = ui_format(scratch.arena, "%u. " Str8Fmt " (" Str8Fmt ")", result->surah + 1, Str8Arg(surah->name), Str8Arg(surah->english)); } f32 b = ui_baseline(app, FONT_REGULAR, UI_FONT, y, UI_ROW_H); draw_text(d, fonts, FONT_MONO, UI_FONT_SMALL, rect.x0 + 10, b, kind, COLOR_TEXT_FAINT); draw_text_fit(d, fonts, FONT_REGULAR, UI_FONT, rect.x0 + 80, b, rect_w(rect) - 90, name, COLOR_TEXT); y += UI_ROW_H; } scratch_end(&scratch); } //- keyboard internal View *focused_view(App *app) { s32 view = panel_active_view(&app->layout, app->layout.focused); return view >= 0 ? &app->layout.views[view] : NULL; } // NOTE: n / N: the next row in the focused view whose text matches the last search internal void search_repeat(App *app, b32 reverse) { View *view = focused_view(app); if(!view || app->last_search_size == 0) return; ScratchArena scratch = ScratchGet(); Row *rows = PushArray(scratch.arena, Row, UI_MAX_ROWS); u32 count = view_rows(app, view, rows, UI_MAX_ROWS); s32 start = view_cursor(app, view, rows, count); s32 step = (reverse != app->last_search_backward) ? -1 : 1; Cells cells; for(u32 n = 1; n <= count; ++n) { s32 index = (s32)((start + step * (s32)n + (s32)count * 2) % (s32)count); view_cells(app, view, &rows[index], &cells, scratch.arena); b32 hit = false; for(u32 c = 0; c < 3 && !hit; ++c) hit = str8_contains_nocase(cells.text[c], app->last_search, app->last_search_size); if(hit) { if((step > 0) != (index > start)) app_message(app, step > 0 ? "search hit BOTTOM, continuing at TOP" : "search hit TOP, continuing at BOTTOM"); view_set_cursor(app, view, rows, count, index); break; } } scratch_end(&scratch); } internal void ui_keyboard_overlay(App *app, PlatformInput *input) { for(u32 index = 0; index < input->key_count; ++index) { PlatformKeyEvent *event = &input->keys[index]; u32 sym = event->keysym; b32 ctrl = (event->mods & PLATFORM_MOD_CTRL) != 0; if(app->overlay == UI_OVERLAY_CONFIRM) { if(sym == XKB_KEY_y || sym == XKB_KEY_Y) app_delete_qari(app, app->confirm_qari); app->overlay = UI_OVERLAY_NONE; return; } if(sym == XKB_KEY_Escape || (ctrl && (sym == XKB_KEY_bracketleft || sym == XKB_KEY_c))) { app->overlay = UI_OVERLAY_NONE; return; } if(sym == XKB_KEY_Return || sym == XKB_KEY_KP_Enter) { UIOverlay overlay = app->overlay; app->overlay = UI_OVERLAY_NONE; if(overlay == UI_OVERLAY_SEARCH) { MemCpy(app->last_search, app->input, app->input_size); app->last_search_size = app->input_size; app->last_search_backward = app->search_backward; if(app->result_count > 0) search_accept(app, app->results[app->result_cursor]); } else if(overlay == UI_OVERLAY_COMMAND) { command_run(app); } else if(overlay == UI_OVERLAY_EDIT) { edit_accept(app); } return; } if(sym == XKB_KEY_BackSpace) { if(app->input_size == 0 && app->overlay != UI_OVERLAY_EDIT) { app->overlay = UI_OVERLAY_NONE; return; } while(app->input_size > 0) { u8 c = (u8)app->input[--app->input_size]; if((c & 0xC0) != 0x80) break; } } if(ctrl && sym == XKB_KEY_u) app->input_size = 0; if(ctrl && sym == XKB_KEY_w) { while(app->input_size > 0 && app->input[app->input_size - 1] == ' ') --app->input_size; while(app->input_size > 0 && app->input[app->input_size - 1] != ' ') --app->input_size; } if(app->overlay == UI_OVERLAY_COMMAND) { ScratchArena scratch = ScratchGet(); CompletionList *list = PushStruct(scratch.arena, CompletionList); u32 count = command_completions(app, scratch.arena, list); if(sym == XKB_KEY_Tab && count) { command_accept_completion(app, &list->items[Clamp(app->result_cursor, 0, (s32)count - 1)]); } s32 step = 0; if(sym == XKB_KEY_Down || (ctrl && (sym == XKB_KEY_n || sym == XKB_KEY_j))) step = 1; if(sym == XKB_KEY_Up || sym == XKB_KEY_ISO_Left_Tab || (ctrl && (sym == XKB_KEY_p || sym == XKB_KEY_k))) step = -1; if(step && count) app->result_cursor = (app->result_cursor + step + (s32)count) % (s32)count; if(sym == XKB_KEY_BackSpace || (ctrl && (sym == XKB_KEY_u || sym == XKB_KEY_w))) app->result_cursor = 0; scratch_end(&scratch); continue; } s32 move = 0; if(sym == XKB_KEY_Down || sym == XKB_KEY_Tab || (ctrl && (sym == XKB_KEY_n || sym == XKB_KEY_j))) move = 1; if(sym == XKB_KEY_Up || sym == XKB_KEY_ISO_Left_Tab || (ctrl && (sym == XKB_KEY_p || sym == XKB_KEY_k))) move = -1; if(move && app->result_count) app->result_cursor = (app->result_cursor + move + (s32)app->result_count) % (s32)app->result_count; } if(!app->overlay_opened && input->text_size > 0) { u32 take = Min((u32)sizeof(app->input) - 1 - app->input_size, input->text_size); MemCpy(app->input + app->input_size, input->text, take); app->input_size += take; if(app->overlay == UI_OVERLAY_COMMAND) app->result_cursor = 0; // typing narrows the list, start at the top } if(app->overlay == UI_OVERLAY_SEARCH) search_update(app); } internal void ui_keyboard(App *app, PlatformInput *input) { if(app->overlay != UI_OVERLAY_NONE) { ui_keyboard_overlay(app, input); app->overlay_opened = false; return; } // NOTE: most frames carry no keys: don't build the focused view's rows just to look at nothing if(input->key_count == 0) { return; } View *view = focused_view(app); ScratchArena scratch = ScratchGet(); Row *rows = PushArray(scratch.arena, Row, UI_MAX_ROWS); u32 count = view ? view_rows(app, view, rows, UI_MAX_ROWS) : 0; for(u32 index = 0; index < input->key_count && app->overlay == UI_OVERLAY_NONE; ++index) { PlatformKeyEvent *event = &input->keys[index]; u32 sym = event->keysym; b32 ctrl = (event->mods & PLATFORM_MOD_CTRL) != 0; u32 pending = app->pending; u32 n = app->count ? app->count : 1; s32 cursor = view ? view_cursor(app, view, rows, count) : 0; s32 page = view ? Max((s32)view->visible_rows, 1) : 10; Row *row = (view && count) ? &rows[Clamp(cursor, 0, (s32)count - 1)] : NULL; // NOTE: modifiers on their own are not keys if(sym == XKB_KEY_Shift_L || sym == XKB_KEY_Shift_R || sym == XKB_KEY_Control_L || sym == XKB_KEY_Control_R || sym == XKB_KEY_Alt_L || sym == XKB_KEY_Alt_R || sym == XKB_KEY_Super_L || sym == XKB_KEY_Super_R) { continue; } app->pending = 0; //- second key of a two key command if(pending) { Layout *layout = &app->layout; if(pending == 'g') { if(sym == XKB_KEY_g && view) { app->jump_back = app_place(app); view_set_cursor(app, view, rows, count, app->count ? (s32)app->count - 1 : 0); } if(sym == XKB_KEY_t || sym == XKB_KEY_T) { Panel *p = &layout->panels[layout->focused]; if(p->tab_count) p->active_tab = (p->active_tab + (sym == XKB_KEY_t ? 1 : p->tab_count - 1)) % p->tab_count; } } else if(pending == 'z' && view) { f32 y = (f32)cursor * UI_ROW_H, h = (f32)view->visible_rows * UI_ROW_H; if(sym == XKB_KEY_z) view->scroll.target = y - h * 0.5f; if(sym == XKB_KEY_t) view->scroll.target = y; if(sym == XKB_KEY_b) view->scroll.target = y - h + UI_ROW_H; } else if(pending == 'd' && sym == XKB_KEY_d && row && view->kind == VIEW_QUEUE) { queue_remove(app, row_track_key(row)); } else if(pending == 'd' && sym == XKB_KEY_d && row) { if(row_track_key(row) != TRACK_NONE) app_delete(app, row_track_key(row)); else app_message(app, "dd works on surahs, D removes a whole reciter"); } else if(pending == 'y' && sym == XKB_KEY_y && row) { if(row->kind == ROW_QARI) app_message(app, "queued %u surahs", store_request_qari(app->store, row->a)); else app_download(app, row_track_key(row) != TRACK_NONE ? row_track_key(row) : app_selected_key(app)); } else if(pending == 'm') { if(sym >= XKB_KEY_a && sym <= XKB_KEY_z) { app->marks[sym - XKB_KEY_a] = app_place(app); app_message(app, "mark %c set", (char)('a' + sym - XKB_KEY_a)); } } else if(pending == '\'' || pending == '`') { if(sym >= XKB_KEY_a && sym <= XKB_KEY_z) app_goto_place(app, app->marks[sym - XKB_KEY_a]); if(sym == XKB_KEY_apostrophe || sym == XKB_KEY_grave) app_goto_place(app, app->jump_back); } else if(pending == 'w') { switch(sym) { case XKB_KEY_h: case XKB_KEY_Left: layout_focus_direction(layout, -1, 0); break; case XKB_KEY_l: case XKB_KEY_Right: layout_focus_direction(layout, 1, 0); break; case XKB_KEY_k: case XKB_KEY_Up: layout_focus_direction(layout, 0, -1); break; case XKB_KEY_j: case XKB_KEY_Down: layout_focus_direction(layout, 0, 1); break; case XKB_KEY_w: case XKB_KEY_W: layout_focus_next(layout); break; case XKB_KEY_v: layout_split_focused(layout, 0); break; case XKB_KEY_s: layout_split_focused(layout, 1); break; case XKB_KEY_c: case XKB_KEY_q: { Panel *p = &layout->panels[layout->focused]; if(p->tab_count) layout_close_view(layout, layout->focused, p->active_tab); } break; case XKB_KEY_equal: { for(s32 i = 0; i < UI_MAX_PANELS; ++i) if(layout->panels[i].kind == PANEL_SPLIT) layout->panels[i].ratio = 0.5f; } break; } } app->count = 0; // NOTE: layout or selection may have changed, rebuild the row list for the next key view = focused_view(app); count = view ? view_rows(app, view, rows, UI_MAX_ROWS) : 0; continue; } //- count prefix if(!ctrl && ((sym >= XKB_KEY_1 && sym <= XKB_KEY_9) || (sym == XKB_KEY_0 && app->count))) { app->count = Min(app->count * 10 + (sym - XKB_KEY_0), 99999u); continue; } //- zoom if(ctrl && (sym == XKB_KEY_equal || sym == XKB_KEY_plus)) { app->settings.zoom += 0.1f; app_apply_settings(app); continue; } if(ctrl && sym == XKB_KEY_minus) { app->settings.zoom -= 0.1f; app_apply_settings(app); continue; } if(ctrl && sym == XKB_KEY_0) { app->settings.zoom = UI_ZOOM_DEFAULT; app_apply_settings(app); continue; } s32 motion = INT32_MIN; // new cursor row when this key is a motion if(ctrl) { switch(sym) { case XKB_KEY_d: motion = cursor + (s32)n * page / 2; break; case XKB_KEY_u: motion = cursor - (s32)n * page / 2; break; case XKB_KEY_f: motion = cursor + (s32)n * page; break; case XKB_KEY_b: motion = cursor - (s32)n * page; break; case XKB_KEY_n: motion = cursor + (s32)n; break; case XKB_KEY_p: motion = cursor - (s32)n; break; case XKB_KEY_e: { if(view) { view->scroll.target += UI_ROW_H * n; motion = Max(cursor, (s32)view->first_visible + (s32)n + 1); } } break; case XKB_KEY_y: { if(view) { view->scroll.target -= UI_ROW_H * n; motion = Min(cursor, (s32)(view->first_visible + view->visible_rows) - (s32)n - 2); } } break; case XKB_KEY_w: app->pending = 'w'; continue; // NOTE: panels directly, without the ^w prefix case XKB_KEY_h: case XKB_KEY_Left: layout_focus_direction(&app->layout, -1, 0); break; case XKB_KEY_l: case XKB_KEY_Right: layout_focus_direction(&app->layout, 1, 0); break; case XKB_KEY_k: case XKB_KEY_Up: layout_focus_direction(&app->layout, 0, -1); break; case XKB_KEY_j: case XKB_KEY_Down: layout_focus_direction(&app->layout, 0, 1); break; case XKB_KEY_Tab: layout_cycle_views(&app->layout, 1); break; case XKB_KEY_ISO_Left_Tab: layout_cycle_views(&app->layout, -1); break; // ctrl-shift-tab } } else { switch(sym) { case XKB_KEY_j: case XKB_KEY_Down: motion = cursor + (s32)n; break; case XKB_KEY_k: case XKB_KEY_Up: motion = cursor - (s32)n; break; case XKB_KEY_G: case XKB_KEY_End: { app->jump_back = app_place(app); motion = app->count ? (s32)app->count - 1 : (s32)count - 1; } break; case XKB_KEY_Home: motion = 0; break; case XKB_KEY_Page_Down: motion = cursor + page; break; case XKB_KEY_Page_Up: motion = cursor - page; break; case XKB_KEY_H: if(view) motion = (s32)view->first_visible + (s32)(app->count ? app->count - 1 : 0); break; case XKB_KEY_M: if(view) motion = (s32)view->first_visible + (s32)Min(view->visible_rows, count - view->first_visible) / 2; break; case XKB_KEY_L: if(view) motion = (s32)(view->first_visible + Min(view->visible_rows, count - view->first_visible)) - 1 - (s32)(app->count ? app->count - 1 : 0); break; case XKB_KEY_y: case XKB_KEY_d: { // NOTE: in visual mode y / d act on the selection right away, like vim operators if(app->visual || app->selected_count) { if(view) visual_commit(app, view, rows, count); u32 *keys = PushArray(scratch.arena, u32, app->selected_count + 1); u32 n = selection_keys(app, keys, app->selected_count); for(u32 i = 0; i < n; ++i) { if(sym == XKB_KEY_y) store_request(app->store, keys[i], false); else if(keys[i] != app_current_key(app)) store_delete(app->store, keys[i]); } app_message(app, sym == XKB_KEY_y ? "downloading %u surahs" : "deleted %u surahs from disk", n); selection_clear(app); break; } app->pending = (u32)('a' + (sym - XKB_KEY_a)); continue; } case XKB_KEY_g: case XKB_KEY_z: case XKB_KEY_m: { app->pending = (u32)('a' + (sym - XKB_KEY_a)); continue; } case XKB_KEY_v: { // NOTE: v toggles the row, V starts a range (V again keeps it, esc drops it) if(row && row_track_key(row) != TRACK_NONE) track_select(app, row_track_key(row), !track_selected(app, row_track_key(row))); } break; case XKB_KEY_V: { if(!view) break; if(app->visual) { visual_commit(app, view, rows, count); } else { app->visual = true; app->visual_anchor = cursor; app->visual_view = (u32)(view - app->layout.views); } } break; case XKB_KEY_apostrophe: app->pending = '\''; continue; case XKB_KEY_grave: app->pending = '`'; continue; case XKB_KEY_l: case XKB_KEY_Right: { if(row && row->expandable && !row->expanded) view_set_expanded(view, row->a, true); else if(view && row && (view->kind == VIEW_PLAYING || view->kind == VIEW_SETTINGS)) view_adjust(app, view, row, 1); else if(sym == XKB_KEY_Right) app_seek_seconds(app, app->settings.seek_seconds); } break; case XKB_KEY_h: case XKB_KEY_Left: { if(view && row && view->kind == VIEW_OFFLINE) { if(row->expandable && row->expanded) view_set_expanded(view, row->a, false); else if(row->depth > 0) { for(s32 i = cursor; i >= 0; --i) { if(rows[i].depth == 0) { motion = i; break; } } } } else if(view && row && (view->kind == VIEW_PLAYING || view->kind == VIEW_SETTINGS)) { view_adjust(app, view, row, -1); } else if(sym == XKB_KEY_Left) { app_seek_seconds(app, -(f64)app->settings.seek_seconds); } } break; case XKB_KEY_Return: case XKB_KEY_KP_Enter: case XKB_KEY_o: case XKB_KEY_space: { // NOTE: with a selection, enter and space play it as a queue if(app->visual || app->selected_count) app_play_selection(app, view, rows, count); else if(sym == XKB_KEY_space) app_toggle_pause(app); else if(view && row) view_activate(app, view, row); } break; case XKB_KEY_x: { if(app->audio_ok) { decoder_command(app->decoder, DECODER_STOP, 0, 0); app->requested_key = TRACK_NONE; } } break; case XKB_KEY_slash: case XKB_KEY_question: { app->search_backward = (sym == XKB_KEY_question); overlay_open(app, UI_OVERLAY_SEARCH); } break; case XKB_KEY_colon: overlay_open(app, UI_OVERLAY_COMMAND); break; case XKB_KEY_n: for(u32 i = 0; i < n; ++i) search_repeat(app, false); break; case XKB_KEY_N: for(u32 i = 0; i < n; ++i) search_repeat(app, true); break; case XKB_KEY_Y: { if(row && (row->kind == ROW_SURAH || row->kind == ROW_QARI)) app_message(app, "queued %u surahs", store_request_qari(app->store, row->a)); } break; case XKB_KEY_D: { u32 qari = (row && (row->kind == ROW_QARI || row->kind == ROW_SURAH)) ? row->a : (u32)Max(app->qari, 0); if(app->settings.confirm_delete) { app->confirm_qari = qari; overlay_open(app, UI_OVERLAY_CONFIRM); } else { app_delete_qari(app, qari); } } break; case XKB_KEY_less: case XKB_KEY_comma: app_step_track(app, -(s32)n); break; case XKB_KEY_greater: case XKB_KEY_period: app_step_track(app, (s32)n); break; case XKB_KEY_bracketleft: app_seek_seconds(app, -(f64)app->settings.seek_seconds * n); break; case XKB_KEY_bracketright: app_seek_seconds(app, (f64)app->settings.seek_seconds * n); break; case XKB_KEY_braceleft: app_seek_seconds(app, -(f64)app->settings.seek_seconds * app->settings.seek_big * n); break; case XKB_KEY_braceright: app_seek_seconds(app, (f64)app->settings.seek_seconds * app->settings.seek_big * n); break; case XKB_KEY_plus: case XKB_KEY_equal: case XKB_KEY_KP_Add: app_set_volume(app, app->settings.volume + 0.05f * n); break; case XKB_KEY_minus: case XKB_KEY_KP_Subtract: app_set_volume(app, app->settings.volume - 0.05f * n); break; case XKB_KEY_a: { app->settings.autoplay = (app->settings.autoplay + 1) % 3; app_apply_settings(app); app_message(app, "autoplay: %s", autoplay_name(app->settings.autoplay)); } break; case XKB_KEY_Tab: layout_focus_next(&app->layout); break; case XKB_KEY_q: app->quit = true; break; case XKB_KEY_Escape: { if(app->visual) app->visual = false; else if(app->selected_count) selection_clear(app); else app->message[0] = 0; } break; } } if(motion != INT32_MIN && view && count) { view_set_cursor(app, view, rows, count, Clamp(motion, 0, (s32)count - 1)); } app->count = 0; view = focused_view(app); count = view ? view_rows(app, view, rows, UI_MAX_ROWS) : 0; } scratch_end(&scratch); } //- frame // NOTE: fonts come from the settings. font files are loaded once into the host's arena (so they // survive a hot reload) and only swapped into the font system when the choice actually changes. internal String8 app_font_file(App *app, u32 choice) { if(choice >= UI_FONT_CHOICES) return str8_zero(); if(app->font_files[choice].size == 0 && access(font_choice(choice)->path, R_OK) == 0) { app->font_files[choice] = FileLoad(app->arena, str8((char *)font_choice(choice)->path)); } return app->font_files[choice]; } internal void ui_frame(App *app, PlatformInput *input_raw) { app->animating = false; app->ticking = false; app->table_cursor = PLATFORM_CURSOR_DEFAULT; ui_settings = &app->settings; ui_theme = app->settings; font_set_data(&app->fonts, FONT_REGULAR, app_font_file(app, app->settings.font_ui)); font_set_data(&app->fonts, FONT_SEMIBOLD, app_font_file(app, app->settings.font_bold)); font_set_data(&app->fonts, FONT_MONO, app_font_file(app, app->settings.font_mono)); // NOTE: zoom: the ui works in "ui units" = logical pixels / zoom. the draw list scales by // buffer scale * zoom, the font system rasterizes at that size, and mouse input is divided. f32 zoom = (app->settings.zoom > 0) ? app->settings.zoom : 1.0f; font_set_scale(&app->fonts, (f32)app->scale * zoom); PlatformInput input = *input_raw; input.mouse_x /= zoom; input.mouse_y /= zoom; if(!layout_valid(&app->layout)) ui_layout_default(&app->layout); // NOTE: per phase timing for the profiler. a clock read is a register read (cntvct), ~free u64 t_keys = time_now_ns(); ui_keyboard(app, &input); if(app->quit) return; u64 t_keys_end = time_now_ns(); f32 w = (f32)app->width / zoom; f32 h = (f32)app->height / zoom; Rect window = {0, 0, w, h}; draw_begin(&app->draw, app->renderer.extent.width, app->renderer.extent.height, (f32)app->scale * zoom); app->draw.rounding = 0.0f; app->draw.text_gamma = app->settings.text_gamma; // NOTE: a normal window is cleared to the background by the render pass already. the layer // surface clears transparent, so there the background is a real quad if(PlatformWindowIsLayer(app->window)) draw_rect(&app->draw, window, COLOR_BG, 0); Rect panels = {UI_GAP, UI_GAP, w - UI_GAP, h - UI_GAP}; layout_compute(&app->layout, app->layout.root, panels); u64 t_panels = time_now_ns(); draw_panels(app, &input); u64 t_status = time_now_ns(); u64 t_overlay = t_status; // the footer is a view now, drawn with the panels draw_overlay(app, &input, window); u64 t_end = time_now_ns(); if(app->profiler) { u64 spans[PROFILE_UI_PHASES] = {t_keys_end - t_keys, t_status - t_panels, t_overlay - t_status, t_end - t_overlay}; for(u32 phase = 0; phase < PROFILE_UI_PHASES; ++phase) { f32 *us = &app->profiler->ui_phase_us[phase]; *us += ((f32)spans[phase] / 1000.0f - *us) * 0.05f; } } app->keep_selection_visible = false; if(app_current_key(app) != TRACK_NONE && !app->paused) app->ticking = true; if(app->profiler && app->profiler->sampling) app->ticking = true; }