feat(state): auto-save

This commit is contained in:
2026-08-29 12:00:50 +02:00
parent 9d300a69c1
commit 80add2ec67
7 changed files with 46 additions and 10 deletions
+23 -7
View File
@@ -12,6 +12,7 @@
#include "rand.h"
#include "state.h"
#include "tempo.h"
#include "timer.h"
static void safe_midi_write(MidiDevice midi, unsigned int code,
unsigned char value) {
@@ -179,10 +180,12 @@ static void load_from_index_file(Context *context, StateConfig state_config,
}
static void save_to_file(const Context *context, StateConfig state_config,
const char *state_file) {
const char *state_file, const bool log) {
StringArray lines;
log_info("Saving state to '%s'...", state_file);
if (log) {
log_info("Saving state to '%s'...", state_file);
}
lines.length = 0;
@@ -278,16 +281,16 @@ static void save_to_file(const Context *context, StateConfig state_config,
}
}
file_write(state_file, &lines);
file_write(state_file, &lines, log);
}
static void save_to_default_file(const Context *context,
StateConfig state_config) {
StateConfig state_config, const bool log) {
char state_file[STR_LEN];
snprintf(state_file, STR_LEN, "%s.txt", state_config.save_file_prefix);
save_to_file(context, state_config, state_file);
save_to_file(context, state_config, state_file, log);
}
static void save_to_index_file(const Context *context, StateConfig state_config,
@@ -297,7 +300,7 @@ static void save_to_index_file(const Context *context, StateConfig state_config,
snprintf(state_file, STR_LEN, "%s.%d.txt", state_config.save_file_prefix,
index);
save_to_file(context, state_config, state_file);
save_to_file(context, state_config, state_file, true);
}
void state_parse_config(StateConfig *state_config, const ConfigFile *config) {
@@ -756,16 +759,20 @@ void *state_background_write(void *args) {
Context *context = process_args->context;
StateConfig state_config = process_args->state_config;
MidiDevice *midi = process_args->midi;
bool auto_save = process_args->auto_save;
bool beat_active;
bool last_active;
bool change;
bool last_change;
bool do_auto_save;
bool last_auto_save;
log_info("(state) background writing started");
last_active = false;
last_change = false;
last_auto_save = false;
while (!context->stop) {
beat_active = tempo_progress(&context->tempo, 1.0) < 0.5;
@@ -791,6 +798,15 @@ void *state_background_write(void *args) {
}
last_change = change;
do_auto_save = fmod(context->time, STATE_AUTO_SAVE_SECONDS) <
STATE_AUTO_SAVE_SECONDS * 0.5;
if (auto_save && do_auto_save && !last_auto_save) {
save_to_default_file(context, state_config, false);
}
last_auto_save = do_auto_save;
}
log_info("(state) background writing stopped by main thread");
@@ -831,5 +847,5 @@ void state_init(Context *context, StateConfig state_config, bool demo,
}
void state_save(const Context *context, StateConfig state_config) {
save_to_default_file(context, state_config);
save_to_default_file(context, state_config, true);
}