Files
RetroArch/menu/menu_dirwalk.c
LibretroAdminandLibretroAdmin ff050a1ee5 menu: non-blocking directory walks and playlist first-touch for interactive list building (#19409)
* dir_list: expose the sort comparators

dir_list_sort() and dir_list_sort_ignore_ext() each pick one of four
static qsort comparators.  dir_list_sort_cmp() now hands the chosen
comparator to callers that need the identical ordering through a
different sorting strategy - concretely, a menu-side incremental
sort that must produce the same listing order as today's blocking
qsort while doing bounded work per invocation.  The two sort entry
points route through the selector, so there is exactly one source
of the ordering and no behaviour change.

Two listings sorted with the same comparator agree everywhere
except among entries that compare equal (case-insensitive twins in
one directory), whose relative order qsort never specified in the
first place; the header says so.

Verified: strict C89 syntax pass; full Linux build links; the
dirwalk oracle added alongside the first consumer asserts listing
parity against dir_list_sort() across every flag combination the
menu uses.

* menu: add menu_dirwalk, a budgeted cancellable directory walk

Every interactive displaylist that lists a directory - the file
browser's three dir_list_initialize variants plus its sort, and the
four playlist-directory walks - performs the enumeration and the
sort synchronously on the thread that drives the UI, a stall
proportional to directory size.  menu_dirwalk is the mechanism the
follow-up commits route those sites through; this commit adds the
module, its build wiring, and its oracle, with no callers yet.

A request first runs the walk synchronously under the shared
per-frame I/O window (tasks/task_nbio_slice.c): dir_list_iter
consults the budget between entries with a one-entry floor, so small
and medium directories - the overwhelming case - complete on the
spot with the identical single enumeration and single sort as today,
merely capped.  A directory too large for the window continues on a
silent retro_task and, when Threaded Tasks is on, leaves the main
thread entirely; completion fires a registered refresh callback (the
task_menu_explore hand-off pattern), and the repopulation that
callback triggers re-issues the identical request and consumes the
finished listing.  Nothing is enumerated or sorted twice.  One walk
is pending at a time, identity is the full parameter set plus a
consumer tag, a superseding request or menu_dirwalk_cancel() ends
the previous walk, and a generation counter makes late completions
of cancelled walks no-ops.

Sorting turned out to be the larger half of the stall: qsort of a
40k-entry listing costs ~15ms of main-thread time, measured as an
18.5ms worst gather when the sort ran whole in the handler.  Above
a synchronous threshold the sort is therefore resumable too - fixed
runs qsorted one or more per window, then bottom-up merge passes
with the budget consulted every batch of copied elements, ordered
by the exact comparator dir_list_sort_cmp() exposes.  A walk that
fits the window but produces an oversized listing defers just the
sort.  Scratch allocation failure falls back to the one-shot qsort:
a stall is a lesser evil than a lost listing.

The oracle (samples/menu/dirwalk, wired into Linux-samples-tasks)
compiles the shipping TU with shrunken sort constants and provides
the clock itself: real time for the pacing and bench lanes, a fixed
virtual step for deterministic window exhaustion in the deferral,
cancel and threaded lanes.  Parity asserts a consumed listing equals
dir_list_new() plus the same sort across the seven flag/sort
combinations the displaylist callers use, on a flat 40k-file fixture
(the walk is non-recursive; flat is what a large ROM directory looks
like).  Pacing: worst main-thread stall 4.17-4.25ms across three
runs against a 16ms gate, versus 18.5ms before the resumable sort.
Bench: best-of-three wall clock to consumed listing 34.2-35.6ms
versus 28.6-29.0ms blocking (ratio 1.18-1.24, gate 1.35) - the
honest price of per-entry budget checks and the merge's copy
traffic, paid only on the deferred path; a regression to a second
enumeration or a quadratic measures 2x and up.  The cancel lane
supersedes and cancels mid-walk and drains stale completions with
LeakSanitizer judging teardown; the threaded lane is the TSan
target for the worker-handler to main-callback hand-off.

Verified: strict C89 syntax pass on the new TU; full Linux build
links; oracle three consecutive plain passes plus
ASan+UBSan+LSan and TSan runs with zero reports, CI step literal-
replayed locally.

* menu_displaylist: drive the file browser through menu_dirwalk

filebrowser_parse walked and sorted its directory synchronously on
the thread that drives the UI - three dir_list_initialize variants
(subsystem extensions, MANUAL_SCAN_DAT/SIDELOAD without compressed
files, and the default) plus a dir_list_sort - so opening a large
content directory froze the menu for as long as the walk took.  The
three variants now route through menu_dirwalk_request with the
dirs-first sort, and the outcomes map exactly onto the existing
control flow:

DONE moves the completed heap listing into the local string_list
the append loop reads (the loop itself is untouched), with the
module's sort making the local dir_list_sort call redundant for
that path; the archive branch keeps its own listing and its own
sort, unchanged - an in-memory enumeration after the archive read
is a different cost class.  PENDING appends a single inert
"Loading" placeholder and jumps to the parent-directory prepend, so
backing out stays possible while the walk continues in the
background - off the main thread entirely when Threaded Tasks is
on.  FAILED falls into the same directory-not-found entry a failed
dir_list_initialize produced before.

The hand-off back is the explore-task pattern: the registered
refresh callback marks ENTRIES_NEED_REFRESH | PREVENT_POPULATE on
the main thread, the repopulation re-issues the identical request,
and menu_dirwalk hands over the finished sorted listing - one
enumeration, one sort, ever.  The list's contents change exactly
once, at that refresh, so cursor and scroll state are never
invalidated mid-fill.  Navigating to a different directory
supersedes the pending walk through request identity;
RARCH_MENU_CTL_DEINIT cancels outright, and the generation guard
makes any late completion a no-op.

Small and medium directories complete inside the synchronous
budgeted pass and never see any of this: same single walk, same
single sort, same single tick, no placeholder, no refresh.

Verified: full Linux build links; strict declaration-placement gate
clean on both touched TUs; dirwalk oracle re-swept after the tag
enum addition - plain, ASan+UBSan+LSan and TSan all pass with zero
reports.  Manual smoke on Ozone/XMB/RGUI (large directory open,
placeholder, refresh-to-full-list, navigate-away mid-walk) still
owed on real hardware before the series goes upstream.

* menu_displaylist: budget the playlist-directory walks

The four remaining directory walks in interactive displaylists all
enumerate the playlist directory synchronously: the Playlists tab
(menu_displaylist_parse_playlists, dir_list_initialize + a
sort-ignore-ext), and the three DIR_LIST_COLLECTIONS listings
behind add-to-playlist, the playlist manager and the thumbnail
downloader (dir_list_new_special + a dirs-first sort each).  A
playlist directory is rarely huge, but every one of these runs on
the thread that drives the UI on every visit, and after the file
browser's conversion they were the last unbounded dir_list_new*
calls on any interactive menu path except the core list, which is
converted separately.

Each site now issues the equivalent menu_dirwalk request - the tab
keeps its NULL-extension, directories-included walk with the
ignore-extension sort; the three COLLECTIONS sites request exactly
what DIR_LIST_COLLECTIONS resolved to, "lpl" with no directories
and no compressed files, dirs-first sort - under its own consumer
tag.  DONE hands the module-sorted listing to the untouched
consumption loop (the in-loop sort calls are gone with the walks
that needed them); PENDING appends the same inert "Loading"
placeholder the file browser shows and returns, with the refresh
callback rebuilding the list on completion; a failed walk leaves
the same early-out or NULL-list path each site already had.  All
five converted consumers share the single pending slot by design -
the menu shows one list at a time, and a request from a different
list supersedes whatever was in flight.

Verified: full Linux build links; strict declaration-placement
gate clean on the TU; anchored replacements verified unique before
application.  Manual smoke of the four lists rides with the
file-browser smoke already owed on real hardware.

* menu_displaylist: budget the core-list directory walk

menu_displaylist_parse_cores slipped through the first inventory
because it builds its listing with dir_list_append rather than
dir_list_new - same unbounded synchronous walk of the cores
directory plus a dirs-first sort on the thread that drives the UI,
behind "Load Core".  A cores directory is usually a few hundred
entries, so this is the fast path almost always; the conversion
buys the bound, not a visible change.

The common path now issues the equivalent menu_dirwalk request
(extension filter from the displaylist info, directories included,
no compressed files, dirs-first sort) under its own tag, with the
usual outcome mapping: DONE hands the module-sorted listing to the
untouched loop and skips the local sort; PENDING shows the inert
placeholder after the parent-directory entry so backing out works;
a failed walk lands in the same directory-not-found entry a failed
append produced.  UWP keeps its one-shot construction and local
sort unchanged - it folds the optional core packages into the same
listing, a platform special case of a handful of directories that
menu_dirwalk's single-directory contract does not cover.

Verified: full Linux build links (object and binary mtimes checked
against the source); strict declaration-placement gate clean on the
TU; anchored replacements verified unique before application.

* materialui: document why the icon-list walk stays synchronous

The Phase 2 plan flagged materialui's playlist-directory
enumeration for conversion pending investigation of how hot the
path is.  Investigated: it runs at driver init and on
RESET_HORIZONTAL_LIST only - not per navigation - over the playlist
directory, and both call sites expect the icon list populated on
return (RESET_HORIZONTAL_LIST destroys, refreshes and re-uploads
textures in one synchronous sequence).  Deferring it would also
put an init-time walk into menu_dirwalk's single pending slot,
where the first displaylist build would supersede it and the icon
list would silently never fill, since the driver has no refresh
channel to re-enter through.

A cold path over a small directory, with a correctness hazard and
a driver rework as the price of conversion: it stays blocking, and
the comment at the site says so for the next audit that greps
dir_list_new_special.

* menu/qt: playlist first-touch through the cache

Audit of every interactive playlist_init call in the menu and the
Qt UI, per the Phase 2 plan.  One menu site and four Qt sites
parsed a playlist from disk synchronously on the thread that
drives the UI; three convert to cached-first, one converts with
mutation through the cached instance, and one stays with its
reason recorded at the site.

The menu site (menu_displaylist_parse_database_entry) reads the
database playlist for CRC matching and is reached from that very
playlist, so the cached instance is the common case: reuse it when
playlist_get_conf_path matches, parse otherwise, free only what
was parsed.

Qt's PlaylistModel::getPlaylistItems is the first-touch hitch the
plan targets - the grid view parsed the whole file on the UI
thread at every open.  It now borrows the cached playlist when the
paths match; every field the loop reads deep-copies into QStrings,
so nothing outlives the borrow.  The single-entry update and
delete-index handlers adopt the cached-mutate template the file
already uses for core association (mutate the object the menu
reads, write to disk, free only if loaded), replacing a full parse
per one-entry edit.  The bulk add-files dialog stays on a private
parse: its cancel path discards the half-modified playlist by
freeing it unwritten, which a borrowed cached instance cannot
offer - the comment at the site says so.

The remaining first-ever-open of a huge playlist with a cold cache
still parses whole; a resumable rjson playlist parse is Phase 2.5
scope, per the plan, and the cached path covers the in-session
requirement.  The nine menu_displaylist_build_list calls under
ui_qt_widgets.cpp were re-checked during this audit: all settings
enumerations, no directory or playlist I/O behind any of them, so
no Qt displaylist conversion is needed - the CoA's Qt exposure was
the playlist parses handled here.

Verified: full Linux build links with HAVE_QT=1 (ui_qt_widgets.cpp
compiled clean) and with the menu TU under the strict declaration-
placement gate; anchored replacements verified unique before
application.

* menu_displaylist: flag over-budget builds in debug builds

The watchdog the Phase 2 plan closes with: with Threaded Tasks
off, every displaylist build runs on the thread that drives the
UI, so any build past frame scale is a user-visible hitch of
exactly the kind the preceding commits converted away.  Debug
builds now time menu_displaylist_ctl end to end - the driver
list_push runs inside a declaration initializer, so the existing
entry point became a thin wrapper around the renamed internal -
and log a warning with the displaylist type and the measured time
when a build on a non-threaded queue exceeds 16 ms.  A newly
added blocking walk, a cold-cache playlist parse, or a large
archive listing identifies itself in the log instead of surviving
as an anonymous stutter.

Threaded queues are exempt: their heavy lifting is off-thread by
construction, and the main-thread callback cost is already bounded
by the same window the tasks step under.  Release builds compile
to the plain internal call.

Verified: full Linux build links (object mtime checked against the
source); strict declaration-placement gate clean both with and
without DEBUG defined.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-08-15 04:45:30 +02:00

612 lines
19 KiB
C

/* RetroArch - A frontend for libretro.
* Copyright (C) 2011-2021 - Daniel De Matteis
*
* RetroArch is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <string.h>
#include <compat/strl.h>
#include <lists/dir_list.h>
#include <lists/string_list.h>
#include <queues/task_queue.h>
#include <string/stdstring.h>
#include "menu_dirwalk.h"
#include "../tasks/tasks_internal.h"
/* Sorting a large completed listing is itself a stall: qsort of a
* 40k-entry directory costs ~15ms of main-thread time, well past the
* shared window. Above the synchronous threshold the sort runs as a
* resumable bottom-up mergesort on the task: fixed-size runs are
* qsorted one or more per window, then merge passes proceed with the
* budget consulted every batch of copied elements. The comparator
* comes from dir_list_sort_cmp(), so the ordering is exactly the one
* dir_list_sort() produces (equal-comparing entries excepted, whose
* relative order qsort never specified).
*
* The constants are compile-overridable so the oracle can drive the
* machinery deterministically with tiny values; production defaults
* below. */
#ifndef MENU_DIRWALK_SORT_SYNC_MAX
#define MENU_DIRWALK_SORT_SYNC_MAX 8192 /* fast path sorts inline up to this */
#endif
#ifndef MENU_DIRWALK_SORT_RUN
#define MENU_DIRWALK_SORT_RUN 2048 /* qsorted run length */
#endif
#ifndef MENU_DIRWALK_SORT_BATCH
#define MENU_DIRWALK_SORT_BATCH 1024 /* merged elements between budget checks */
#endif
enum
{
MENU_DIRWALK_PHASE_WALK = 0,
MENU_DIRWALK_PHASE_SORT_RUNS,
MENU_DIRWALK_PHASE_SORT_MERGE
};
/* Identity of a request. Strings are owned copies. */
typedef struct
{
char *dir;
char *ext; /* NULL when the request had none */
unsigned sort_mode;
unsigned tag;
bool include_dirs;
bool include_hidden;
bool include_compressed;
} menu_dirwalk_ident_t;
/* State a background walk task owns exclusively while it runs. The
* handler (worker thread under a threaded queue) touches only this;
* hand-off back to the module happens in the completion callback,
* which the task queue always runs on the main thread. */
typedef struct
{
dir_list_iter_t *iter; /* NULL for a sort-only task */
struct string_list *list;
dir_list_sort_cmp_t cmp; /* NULL when sort_mode is NONE */
struct string_list_elem *scratch;
size_t run_pos; /* SORT_RUNS: next run start */
size_t width; /* SORT_MERGE: current run width */
size_t pair_base; /* SORT_MERGE: pair being merged */
size_t a_pos; /* SORT_MERGE: intra-merge cursors */
size_t b_pos;
size_t o_pos;
unsigned phase;
unsigned sort_mode;
unsigned tag;
unsigned generation;
bool src_is_scratch; /* which buffer holds the runs */
bool ok;
} menu_dirwalk_task_state_t;
/* The single slot. Main-thread only. */
static struct
{
menu_dirwalk_ident_t ident;
retro_task_t *task; /* in-flight walk, if any */
struct string_list *done_list; /* completed, awaiting pickup */
void (*refresh_cb)(unsigned tag);
unsigned generation; /* stale-completion guard */
bool have_ident;
bool ready;
} dirwalk_st;
static void menu_dirwalk_ident_clear(menu_dirwalk_ident_t *ident)
{
if (ident->dir)
free(ident->dir);
if (ident->ext)
free(ident->ext);
memset(ident, 0, sizeof(*ident));
}
static bool menu_dirwalk_ident_matches(const menu_dirwalk_ident_t *ident,
const char *dir, const char *ext,
bool include_dirs, bool include_hidden, bool include_compressed,
unsigned sort_mode, unsigned tag)
{
if ( !string_is_equal(ident->dir, dir)
|| (ident->include_dirs != include_dirs)
|| (ident->include_hidden != include_hidden)
|| (ident->include_compressed != include_compressed)
|| (ident->sort_mode != sort_mode)
|| (ident->tag != tag))
return false;
if (!ident->ext)
return (!ext || !*ext);
if (!ext)
return false;
return string_is_equal(ident->ext, ext);
}
static void menu_dirwalk_sort(struct string_list *list, unsigned sort_mode)
{
switch (sort_mode)
{
case MENU_DIRWALK_SORT_DIR_FIRST:
dir_list_sort(list, true);
break;
case MENU_DIRWALK_SORT_IGNORE_EXT:
dir_list_sort_ignore_ext(list, true);
break;
default:
break;
}
}
static dir_list_sort_cmp_t menu_dirwalk_cmp(unsigned sort_mode)
{
switch (sort_mode)
{
case MENU_DIRWALK_SORT_DIR_FIRST:
return dir_list_sort_cmp(true, false);
case MENU_DIRWALK_SORT_IGNORE_EXT:
return dir_list_sort_cmp(true, true);
default:
break;
}
return NULL;
}
static bool menu_dirwalk_within_budget(void *ud)
{
return task_nbio_slice_within_budget(ud, 0, 0);
}
/* Enter the budgeted sort. Allocation failure falls back to the
* one-shot qsort - a stall is a lesser evil than a lost listing -
* and reports the phase complete. */
static bool menu_dirwalk_sort_begin(menu_dirwalk_task_state_t *state)
{
size_t n = state->list->size;
if (!state->cmp || n <= 1)
return true; /* nothing to do */
if (!(state->scratch = (struct string_list_elem*)malloc(
n * sizeof(*state->scratch))))
{
menu_dirwalk_sort(state->list, state->sort_mode);
return true;
}
state->phase = MENU_DIRWALK_PHASE_SORT_RUNS;
state->run_pos = 0;
state->width = 0;
state->src_is_scratch = false;
return false; /* phases remain */
}
/* One budgeted slice of the sort. Returns true when the listing is
* fully ordered. @b NULL removes the budget (threaded queue). */
static bool menu_dirwalk_sort_step(menu_dirwalk_task_state_t *state,
nbio_budget_t *b)
{
struct string_list_elem *elems = state->list->elems;
size_t n = state->list->size;
if (state->phase == MENU_DIRWALK_PHASE_SORT_RUNS)
{
/* qsort fixed-length runs in place; each run is bounded work */
while (state->run_pos < n)
{
size_t run = n - state->run_pos;
if (run > MENU_DIRWALK_SORT_RUN)
run = MENU_DIRWALK_SORT_RUN;
qsort(elems + state->run_pos, run, sizeof(*elems), state->cmp);
state->run_pos += run;
if (state->run_pos < n && b && !menu_dirwalk_within_budget(b))
return false;
}
if (n <= MENU_DIRWALK_SORT_RUN)
return true; /* single run: already fully ordered */
state->phase = MENU_DIRWALK_PHASE_SORT_MERGE;
state->width = MENU_DIRWALK_SORT_RUN;
state->pair_base = 0;
state->a_pos = 0;
state->b_pos = 0;
state->o_pos = 0;
}
/* Bottom-up merge passes, resumable at element granularity. */
for (;;)
{
struct string_list_elem *src = state->src_is_scratch
? state->scratch : elems;
struct string_list_elem *dst = state->src_is_scratch
? elems : state->scratch;
while (state->pair_base < n)
{
size_t a_end = state->pair_base + state->width;
size_t b_end = state->pair_base + (state->width << 1);
size_t batch = 0;
if (a_end > n)
a_end = n;
if (b_end > n)
b_end = n;
/* Fresh pair: initialise cursors */
if (state->o_pos == 0 && state->a_pos == 0 && state->b_pos == 0)
{
state->a_pos = state->pair_base;
state->b_pos = a_end;
state->o_pos = state->pair_base;
}
while (state->o_pos < b_end)
{
if ( state->a_pos < a_end
&& ( state->b_pos >= b_end
|| state->cmp(&src[state->a_pos],
&src[state->b_pos]) <= 0))
dst[state->o_pos++] = src[state->a_pos++];
else
dst[state->o_pos++] = src[state->b_pos++];
if (++batch >= MENU_DIRWALK_SORT_BATCH)
{
batch = 0;
if (b && !menu_dirwalk_within_budget(b))
return false;
}
}
state->pair_base = b_end;
state->a_pos = 0;
state->b_pos = 0;
state->o_pos = 0;
if (state->pair_base < n && b && !menu_dirwalk_within_budget(b))
return false;
}
state->src_is_scratch = !state->src_is_scratch;
state->width <<= 1;
state->pair_base = 0;
if (state->width >= n)
{
if (state->src_is_scratch)
memcpy(elems, state->scratch, n * sizeof(*elems));
return true;
}
if (b && !menu_dirwalk_within_budget(b))
return false;
}
}
/* ------------------------------------------------------------------ */
/* Background walk task */
/* ------------------------------------------------------------------ */
static void menu_dirwalk_task_handler(retro_task_t *task)
{
menu_dirwalk_task_state_t *state = NULL;
int r;
if (!task)
return;
if (!(state = (menu_dirwalk_task_state_t*)task->state))
return;
if ((task_get_flags(task) & RETRO_TASK_FLG_CANCELLED) > 0)
{
task_set_flags(task, RETRO_TASK_FLG_FINISHED, true);
return;
}
if (task_queue_is_threaded())
{
/* Off the main thread: the shared window exists to protect
* frame pacing, which a worker cannot hurt. Run to the end,
* one-shot sort included. */
r = state->iter ? dir_list_iter_step(state->iter, NULL, NULL) : 1;
if (r > 0)
{
menu_dirwalk_sort(state->list, state->sort_mode);
state->ok = true;
}
task_set_flags(task, RETRO_TASK_FLG_FINISHED, true);
return;
}
{
nbio_budget_t b;
task_nbio_slice_open(&b);
if (state->phase == MENU_DIRWALK_PHASE_WALK)
{
r = state->iter
? dir_list_iter_step(state->iter, menu_dirwalk_within_budget, &b)
: 1;
if (r == 0)
{
task_nbio_slice_close(&b);
return; /* yielded; the queue calls the handler again */
}
if (r < 0)
{
task_nbio_slice_close(&b);
task_set_flags(task, RETRO_TASK_FLG_FINISHED, true);
return; /* ok stays false */
}
/* Walk complete: the sort may span further invocations. */
if (menu_dirwalk_sort_begin(state))
{
state->ok = true;
task_nbio_slice_close(&b);
task_set_flags(task, RETRO_TASK_FLG_FINISHED, true);
return;
}
}
if (menu_dirwalk_sort_step(state, &b))
{
state->ok = true;
task_nbio_slice_close(&b);
task_set_flags(task, RETRO_TASK_FLG_FINISHED, true);
return;
}
task_nbio_slice_close(&b);
}
}
/* Main thread (task_queue_check runs callbacks there for both queue
* implementations). */
static void menu_dirwalk_task_callback(retro_task_t *task,
void *task_data, void *user_data, const char *err)
{
menu_dirwalk_task_state_t *state = NULL;
(void)task_data;
(void)user_data;
(void)err;
if (!task)
return;
if (!(state = (menu_dirwalk_task_state_t*)task->state))
return;
/* A cancelled or superseded walk: the cleanup that follows this
* callback releases everything; the slot moved on. */
if (state->generation != dirwalk_st.generation)
return;
dirwalk_st.task = NULL;
if (state->ok)
{
dirwalk_st.done_list = state->list; /* hand-off */
state->list = NULL;
dirwalk_st.ready = true;
}
else
/* The walk failed mid-flight. Drop the identity so the
* refresh-triggered re-request starts over (and can fail fast
* into the caller's error path). */
menu_dirwalk_ident_clear(&dirwalk_st.ident);
if (dirwalk_st.refresh_cb)
dirwalk_st.refresh_cb(state->tag);
}
static void menu_dirwalk_task_free(retro_task_t *task)
{
menu_dirwalk_task_state_t *state = NULL;
if (!task)
return;
if (!(state = (menu_dirwalk_task_state_t*)task->state))
return;
dir_list_iter_free(state->iter);
if (state->list)
string_list_free(state->list);
if (state->scratch)
free(state->scratch);
free(state);
}
static bool menu_dirwalk_task_push(dir_list_iter_t *iter,
struct string_list *list, unsigned sort_mode, unsigned tag)
{
retro_task_t *task = NULL;
menu_dirwalk_task_state_t *state = NULL;
task = task_init();
state = (menu_dirwalk_task_state_t*)calloc(1, sizeof(*state));
if (!task || !state)
{
if (task)
free(task);
if (state)
free(state);
return false;
}
state->iter = iter; /* NULL: sort-only task */
state->list = list;
state->cmp = menu_dirwalk_cmp(sort_mode);
state->phase = MENU_DIRWALK_PHASE_WALK;
state->sort_mode = sort_mode;
state->tag = tag;
state->generation = dirwalk_st.generation;
/* Silent task: no title, no notifications. */
task->handler = menu_dirwalk_task_handler;
task->state = state;
task->title = NULL;
task->callback = menu_dirwalk_task_callback;
task->cleanup = menu_dirwalk_task_free;
task_queue_push(task);
dirwalk_st.task = task;
return true;
}
/* ------------------------------------------------------------------ */
/* Public API (main thread) */
/* ------------------------------------------------------------------ */
void menu_dirwalk_cancel(void)
{
/* New generation: a completion already in flight becomes stale
* and its callback leaves the slot alone. */
dirwalk_st.generation++;
if (dirwalk_st.task)
{
/* Thread-safe under the threaded queue; the handler notices on
* its next invocation and finishes, and the task's own cleanup
* releases the iterator and partial list. */
task_set_flags(dirwalk_st.task, RETRO_TASK_FLG_CANCELLED, true);
dirwalk_st.task = NULL;
}
if (dirwalk_st.done_list)
{
string_list_free(dirwalk_st.done_list);
dirwalk_st.done_list = NULL;
}
dirwalk_st.ready = false;
menu_dirwalk_ident_clear(&dirwalk_st.ident);
dirwalk_st.have_ident = false;
}
bool menu_dirwalk_pending(void)
{
return (dirwalk_st.task != NULL) || dirwalk_st.ready;
}
void menu_dirwalk_set_refresh_cb(void (*cb)(unsigned tag))
{
dirwalk_st.refresh_cb = cb;
}
enum menu_dirwalk_status menu_dirwalk_request(
const char *dir, const char *ext,
bool include_dirs, bool include_hidden, bool include_compressed,
enum menu_dirwalk_sort sort_mode, unsigned tag,
struct string_list **out_list)
{
dir_list_iter_t *iter = NULL;
struct string_list *list = NULL;
nbio_budget_t b;
int r;
if (!dir || !*dir || !out_list)
return MENU_DIRWALK_FAILED;
if ( dirwalk_st.have_ident
&& menu_dirwalk_ident_matches(&dirwalk_st.ident, dir, ext,
include_dirs, include_hidden, include_compressed,
(unsigned)sort_mode, tag))
{
if (dirwalk_st.ready)
{
/* Consume: the identity is spent, so a later visit to the
* same directory enumerates afresh, exactly as every visit
* does today. */
*out_list = dirwalk_st.done_list;
dirwalk_st.done_list = NULL;
dirwalk_st.ready = false;
menu_dirwalk_ident_clear(&dirwalk_st.ident);
dirwalk_st.have_ident = false;
return MENU_DIRWALK_DONE;
}
if (dirwalk_st.task)
return MENU_DIRWALK_PENDING;
/* Identity recorded but neither pending nor ready: the task
* push failed last time. Fall through and start over. */
}
/* Different request (or restart): supersede whatever is there. */
menu_dirwalk_cancel();
if (!(list = string_list_new()))
return MENU_DIRWALK_FAILED;
/* NULL under the same condition dir_list_new() returns NULL:
* unreadable directory (or allocation failure). The caller's
* existing error entry covers it. */
if (!(iter = dir_list_iter_new(dir, ext, include_dirs,
include_hidden, include_compressed, false, list)))
{
string_list_free(list);
return MENU_DIRWALK_FAILED;
}
/* Fast path: one budgeted pass, synchronously. The iterator
* consults the window between entries with a one-entry floor, so
* this single call walks as much as the shared window allows -
* for small and medium directories, all of it. */
task_nbio_slice_open(&b);
r = dir_list_iter_step(iter, menu_dirwalk_within_budget, &b);
task_nbio_slice_close(&b);
if (r > 0)
{
dir_list_iter_free(iter);
iter = NULL;
if ( sort_mode == MENU_DIRWALK_SORT_NONE
|| list->size <= MENU_DIRWALK_SORT_SYNC_MAX)
{
menu_dirwalk_sort(list, (unsigned)sort_mode);
*out_list = list;
return MENU_DIRWALK_DONE;
}
/* The walk fit the window but the listing is too large to
* sort inside it: defer just the sort. Falls through to the
* task push below with no iterator. */
}
else if (r < 0)
{
dir_list_iter_free(iter);
string_list_free(list);
return MENU_DIRWALK_FAILED;
}
/* Too large for the window: record the identity and hand the
* remaining work (walk and/or sort) to a task. */
dirwalk_st.ident.dir = strldup(dir, strlen(dir) + 1);
dirwalk_st.ident.ext = (ext && *ext)
? strldup(ext, strlen(ext) + 1) : NULL;
dirwalk_st.ident.include_dirs = include_dirs;
dirwalk_st.ident.include_hidden = include_hidden;
dirwalk_st.ident.include_compressed = include_compressed;
dirwalk_st.ident.sort_mode = (unsigned)sort_mode;
dirwalk_st.ident.tag = tag;
dirwalk_st.have_ident = true;
if ( !dirwalk_st.ident.dir
|| !menu_dirwalk_task_push(iter, list, (unsigned)sort_mode, tag))
{
dir_list_iter_free(iter);
string_list_free(list);
menu_dirwalk_ident_clear(&dirwalk_st.ident);
dirwalk_st.have_ident = false;
return MENU_DIRWALK_FAILED;
}
return MENU_DIRWALK_PENDING;
}