Files

267 lines
11 KiB
C++

/* Portable text boards: Life 1.06 coordinates plus size/generation metadata. */
static const char *exampleNames[] = {
"Sierpinski triangle", "Acorn kaleidoscope", "Pulsar garden", "Glider pinwheel",
"Gosper glider gun", "Pentadecathlon garden", "Diehard", "R-pentomino", "Spaceship fleet", "Cross bloom", "Sierpinski carpet", "Blinker weave",
"Glider gun compass", "Oscillator sampler", "Pulsar phase wave", "Diehard constellation", "Glider rain", "Acorn orbit", "Sierpinski diamond", "Symmetric nebula"
};
static const char *exampleFiles[] = {
"examples/sierpinski.life", "examples/acorn-kaleidoscope.life", "examples/pulsar-garden.life", "examples/glider-pinwheel.life",
"examples/gosper-glider-gun.life", "examples/pentadecathlon-garden.life", "examples/diehard.life", "examples/r-pentomino.life", "examples/spaceship-fleet.life", "examples/cross-bloom.life", "examples/sierpinski-carpet.life", "examples/blinker-weave.life",
"examples/glider-gun-compass.life", "examples/oscillator-sampler.life", "examples/pulsar-phase-wave.life", "examples/diehard-constellation.life", "examples/glider-rain.life", "examples/acorn-orbit.life", "examples/sierpinski-diamond.life", "examples/symmetric-nebula.life"
};
#define EXAMPLE_COUNT ((int)(sizeof(exampleFiles) / sizeof(exampleFiles[0])))
static char boardMessage[160];
static double boardMessageStarted;
static double notificationTime(void) {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return now.tv_sec * 1000.0 + now.tv_nsec / 1000000.0;
}
static void notifyBoard(const char *message) {
snprintf(boardMessage, sizeof(boardMessage), "%s", message);
boardMessageStarted = notificationTime();
}
/* 250 ms entrance, 3 seconds readable, 250 ms exit; no blocking waits. */
static float boardNotificationVisibility(double now) {
double age = now - boardMessageStarted;
if (!boardMessage[0]) return 0;
if (age >= 3500) { boardMessage[0] = '\0'; return 0; }
float t = age < 250 ? (float)(age / 250) : age > 3250 ? (float)((3500 - age) / 250) : 1;
if (t < 0) t = 0;
return t * t * (3 - 2 * t);
}
static bool boardBusy;
static pthread_t boardThread;
static pthread_mutex_t boardMutex = PTHREAD_MUTEX_INITIALIZER;
static bool boardDone;
static struct {
EditSnapshot board;
char path[PATH_MAX], message[160];
bool save, dialog, success, replace;
} boardJob;
static bool boardNumbers(const char *line, unsigned long long *a, unsigned long long *b) {
unsigned long long *outputs[] = {a, b};
for (int i = 0; i < 2; ++i) {
while (isspace((unsigned char)*line)) ++line;
if (!isdigit((unsigned char)*line)) return false;
char *end;
errno = 0;
*outputs[i] = strtoull(line, &end, 10);
if (errno || (*end && !isspace((unsigned char)*end))) return false;
line = end;
}
while (isspace((unsigned char)*line)) ++line;
return *line == '\0';
}
static bool readBoardFile(const char *path, EditSnapshot *board, char message[160]) {
FILE *file = fopen(path, "rb");
if (!file) { snprintf(message, 160, "Cannot open board file."); return false; }
char line[128];
bool valid = fgets(line, sizeof(line), file) &&
(strcmp(line, "#Life 1.06\n") == 0 || strcmp(line, "#Life 1.06\r\n") == 0);
bool metadata = false;
size_t bytes = 0;
memset(board, 0, sizeof(*board));
while (valid && fgets(line, sizeof(line), file)) {
bytes += strlen(line);
if (strlen(line) >= sizeof(line) - 1 || bytes > 4 * 1024 * 1024) { valid = false; break; }
unsigned long long a, b;
if (strncmp(line, "#BOARD ", 7) == 0) {
valid = !metadata && boardNumbers(line + 7, &a, &b)
&& a >= MIN_RESOLUTION && a <= MAX_RESOLUTION && a % RESOLUTION_STEP == 0;
if (valid) { board->resolution = (int)a; board->generation = b; metadata = true; }
} else if (line[0] != '#') {
const char *p = line;
while (isspace((unsigned char)*p)) ++p;
if (!*p) continue;
valid = metadata && boardNumbers(p, &a, &b)
&& a < (unsigned)board->resolution && b < (unsigned)board->resolution;
if (valid) {
size_t index = (size_t)b * board->resolution + (size_t)a;
if (board->cells[index]) valid = false;
else { board->cells[index] = 1; ++board->population; }
}
}
}
valid = valid && metadata && !ferror(file);
fclose(file);
if (!valid) snprintf(message, 160, "Invalid board file; current board unchanged.");
return valid;
}
static bool writeBoardFileMode(const char *path, const EditSnapshot *board, char message[160], bool replace) {
char temporary[PATH_MAX + 16];
snprintf(temporary, sizeof(temporary), "%s.tmp.XXXXXX", path);
int fd = mkstemp(temporary);
if (fd < 0) goto failed;
FILE *file = fdopen(fd, "w");
if (!file) { close(fd); unlink(temporary); goto failed; }
bool ok = fprintf(file, "#Life 1.06\n#BOARD %d %llu\n", board->resolution, board->generation) >= 0;
for (int row = 0; row < board->resolution; ++row)
for (int col = 0; col < board->resolution; ++col)
if (board->cells[row * board->resolution + col]
&& fprintf(file, "%d %d\n", col, row) < 0) ok = false;
if (fflush(file) != 0 || fsync(fd) != 0) ok = false;
if (fclose(file) != 0) ok = false;
if (!ok || (replace ? rename(temporary, path) : link(temporary, path)) != 0) {
int savedError = errno;
unlink(temporary);
if (!replace && savedError == EEXIST) {
snprintf(message, 160, "Name already exists. Choose another or confirm replacement.");
return false;
}
goto failed;
}
if (!replace) unlink(temporary);
return true;
failed:
snprintf(message, 160, "Cannot save board; check the folder and free space.");
return false;
}
static bool writeBoardFile(const char *path, const EditSnapshot *board, char message[160]) {
return writeBoardFileMode(path, board, message, true);
}
static void boardPath(char path[PATH_MAX], const char *name) {
#if !APP_PORTABLE
int length;
if (strncmp(name, "examples/", 9) == 0)
length = snprintf(path, PATH_MAX, "%s/%s", APP_DATA_DIR, name);
else length = snprintf(path, PATH_MAX, "%s/%s", userBoardsDirectory, name);
if (length < 0 || length >= PATH_MAX) path[0] = '\0';
#else
const char *slash = strrchr(settingsPath, '/');
size_t prefix = slash ? (size_t)(slash - settingsPath + 1) : 0;
if (prefix + strlen("boards/") + strlen(name) + 1 > PATH_MAX) { path[0] = '\0'; return; }
memcpy(path, settingsPath, prefix);
snprintf(path + prefix, PATH_MAX - prefix, "boards/%s", name);
#endif
}
/* Native KDE dialogs run outside the GLUT thread, with explicit argv (no shell). */
static bool chooseBoardFile(bool save, char path[PATH_MAX], char message[160]) {
int output[2];
if (pipe(output) != 0) return false;
posix_spawn_file_actions_t actions;
posix_spawn_file_actions_init(&actions);
posix_spawn_file_actions_adddup2(&actions, output[1], STDOUT_FILENO);
posix_spawn_file_actions_addclose(&actions, output[0]);
posix_spawn_file_actions_addclose(&actions, output[1]);
char *argv[] = {"kdialog", save ? "--getsavefilename" : "--getopenfilename",
path, "*.life|Life boards (*.life)", "--title", save ? "Save board" : "Open board", NULL};
pid_t child;
extern char **environ;
int result = posix_spawnp(&child, "kdialog", &actions, NULL, argv, environ);
posix_spawn_file_actions_destroy(&actions);
close(output[1]);
if (result != 0) {
close(output[0]);
snprintf(message, 160, "File dialogs require kdialog. Example buttons still work.");
return false;
}
size_t used = 0;
char buffer[512];
ssize_t count;
bool tooLong = false;
while ((count = read(output[0], buffer, sizeof(buffer))) != 0) {
if (count < 0) { if (errno == EINTR) continue; break; }
if (used + (size_t)count >= PATH_MAX) tooLong = true;
else { memcpy(path + used, buffer, (size_t)count); used += (size_t)count; }
}
close(output[0]);
int status;
while (waitpid(child, &status, 0) < 0) if (errno != EINTR) return false;
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) return false;
if (tooLong) { snprintf(message, 160, "Board filename is too long."); return false; }
if (used && path[used - 1] == '\n') --used;
path[used] = '\0';
return used > 0;
}
static void *boardWorker(void *unused) {
(void)unused;
bool ready = !boardJob.dialog || chooseBoardFile(boardJob.save, boardJob.path, boardJob.message);
if (ready && boardJob.save) {
char directory[PATH_MAX];
boardPath(directory, "");
if (mkdir(directory, 0700) != 0 && errno != EEXIST) {
snprintf(boardJob.message, sizeof(boardJob.message), "Cannot create boards folder.");
ready = false;
}
}
if (ready) {
boardJob.success = boardJob.save
? (boardJob.replace ? writeBoardFile(boardJob.path, &boardJob.board, boardJob.message)
: writeBoardFileMode(boardJob.path, &boardJob.board, boardJob.message, false))
: readBoardFile(boardJob.path, &boardJob.board, boardJob.message);
}
pthread_mutex_lock(&boardMutex);
boardDone = true;
pthread_mutex_unlock(&boardMutex);
return NULL;
}
static void applyBoard(const EditSnapshot *board) {
beginEdit();
commitEdit();
clearHistory();
resolution = board->resolution;
generation = board->generation;
population = board->population;
memcpy(grid, board->cells, (size_t)resolution * resolution);
paused = true;
reversePlayback = drawing = editPending = hasSelection = false;
activeSlider = -1;
capturePlaybackStart();
saveSettingsIfChanged();
}
static void startBoardPath(bool save, const char *path, bool dialog, bool replace) {
if (boardBusy) return;
finishLoopInput();
paused = true;
drawing = editPending = false;
memset(&boardJob, 0, sizeof(boardJob));
boardJob.save = save;
boardJob.dialog = dialog;
boardJob.replace = replace;
snprintf(boardJob.path, sizeof(boardJob.path), "%s", path);
if (save) {
memcpy(boardJob.board.cells, grid, (size_t)resolution * resolution);
boardJob.board.resolution = resolution;
boardJob.board.population = population;
boardJob.board.generation = generation;
}
boardDone = false;
notifyBoard(dialog ? "Choose a board file in the file dialog." : save ? "Saving board..." : "Opening board...");
if (pthread_create(&boardThread, NULL, boardWorker, NULL) == 0) boardBusy = true;
else notifyBoard("Cannot start board file operation.");
}
static void startBoardJob(bool save, int example) {
char path[PATH_MAX];
boardPath(path, example >= 0 ? exampleFiles[example] : save ? "my-board.life" : "");
startBoardPath(save, path, example < 0, true);
}
static void pollBoardJob(void) {
if (!boardBusy) return;
pthread_mutex_lock(&boardMutex);
bool done = boardDone;
pthread_mutex_unlock(&boardMutex);
if (!done) return;
pthread_join(boardThread, NULL);
boardBusy = false;
if (boardJob.success) {
if (!boardJob.save) applyBoard(&boardJob.board);
if (sidebarPage != PAGE_CONTROLS) changeSidebarPage(PAGE_CONTROLS);
notifyBoard(boardJob.save ? "Board saved." : "Board opened. Click Play to evolve it.");
} else notifyBoard(boardJob.message[0] ? boardJob.message : "File operation canceled.");
}