Queue handed-over paths for the main loop, and stop listening on any exit

A path handed over before SDL started its event queue was lost (its event
failed to push). Paths now wait in a queue the main loop takes from, and an
event only wakes it. A peer that connects and stays silent times out instead
of holding the listener (and quitting) forever. Forwarded paths are made
absolute first, a forwarded launch no longer opens (and prunes) session logs,
and an exception no longer leaves the listening thread joinable at exit.

Also: a failed audio device open is tried again on the next play, a voice
without a stream isn't kept, subprocess checks _WIN32, and a Process can't be
copied (closing its pipe twice).
This commit is contained in:
shweet committed 2026-11-22 19:43:33 -05:00
1 parent 48a6a386e3
commit 71b0ef683b
7 files changed
+87 -56

No files matched your search

+8 -3
View File
@@ -84,10 +84,12 @@ static AudioSound* sound_get(const AudioData& data)
return it->second.samples.empty() ? nullptr : &it->second; return it->second.samples.empty() ? nullptr : &it->second;
} }
// Opened on the first play. A failed open is tried again on the next, for a device that shows up later.
static SDL_AudioDeviceID device_get() static SDL_AudioDeviceID device_get()
{ {
static SDL_AudioDeviceID device = static SDL_AudioDeviceID device = 0;
SDL_InitSubSystem(SDL_INIT_AUDIO) ? SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &AUDIO_SPEC) : 0; if (!device && SDL_InitSubSystem(SDL_INIT_AUDIO))
device = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &AUDIO_SPEC);
return device; return device;
} }
@@ -141,9 +143,12 @@ void audio_play(const AudioData& data, AudioPlayMode mode)
voice = free->get(); voice = free->get();
else else
{ {
auto stream = SDL_CreateAudioStream(&AUDIO_SPEC, &AUDIO_SPEC);
if (!stream)
return;
voice = sound->voices.emplace_back(std::make_unique<AudioVoice>()).get(); voice = sound->voices.emplace_back(std::make_unique<AudioVoice>()).get();
voice->sound = sound; voice->sound = sound;
voice->stream = SDL_CreateAudioStream(&AUDIO_SPEC, &AUDIO_SPEC); voice->stream = stream;
SDL_SetAudioStreamGetCallback(voice->stream, voice_feed, voice); SDL_SetAudioStreamGetCallback(voice->stream, voice_feed, voice);
SDL_BindAudioStream(device_get(), voice->stream); SDL_BindAudioStream(device_get(), voice->stream);
} }
+34 -13
View File
@@ -2,7 +2,9 @@
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <atomic> #include <atomic>
#include <mutex>
#include <thread> #include <thread>
#include <utility>
#ifdef _WIN32 #ifdef _WIN32
#include <winsock2.h> #include <winsock2.h>
@@ -25,12 +27,15 @@ constexpr auto INSTANCE_ADDRESS = "127.0.0.1";
constexpr auto INSTANCE_PORT = 11414; constexpr auto INSTANCE_PORT = 11414;
// The listening editor's answer once it has every path, telling a later one it was heard. // The listening editor's answer once it has every path, telling a later one it was heard.
constexpr char INSTANCE_ANSWER[] = "anm2ed"; constexpr char INSTANCE_ANSWER[] = "anm2ed";
constexpr int ANSWER_TIMEOUT_MS = 1000; constexpr int RECEIVE_TIMEOUT_MS = 1000;
constexpr int BUFFER_SIZE = 4096; constexpr int BUFFER_SIZE = 4096;
constexpr std::size_t MESSAGE_SIZE_MAX = 1 << 20;
static Handle listener = HANDLE_INVALID; static Handle listener = HANDLE_INVALID;
static std::thread listenThread; static std::thread listenThread;
static std::atomic<bool> isListening = false; static std::atomic<bool> isListening = false;
static std::mutex pendingMutex;
static std::optional<std::vector<std::string>> pending;
static sockaddr_in address_get() static sockaddr_in address_get()
{ {
@@ -41,6 +46,17 @@ static sockaddr_in address_get()
return address; return address;
} }
// A silent peer can't hold a receive up for longer than RECEIVE_TIMEOUT_MS.
static void receive_timeout_set(Handle handle)
{
#ifdef _WIN32
DWORD timeout = RECEIVE_TIMEOUT_MS;
#else
timeval timeout = {RECEIVE_TIMEOUT_MS / 1000, RECEIVE_TIMEOUT_MS % 1000 * 1000};
#endif
setsockopt(handle, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
}
// Sends each path followed by a zero, then waits for the answer. // Sends each path followed by a zero, then waits for the answer.
static bool paths_send(const std::vector<std::string>& paths) static bool paths_send(const std::vector<std::string>& paths)
{ {
@@ -59,13 +75,11 @@ static bool paths_send(const std::vector<std::string>& paths)
message += path + '\0'; message += path + '\0';
auto isSent = send(handle, message.data(), (int)message.size(), 0) == (int)message.size(); auto isSent = send(handle, message.data(), (int)message.size(), 0) == (int)message.size();
#ifdef _WIN32 #ifdef _WIN32
DWORD timeout = ANSWER_TIMEOUT_MS;
shutdown(handle, SD_SEND); shutdown(handle, SD_SEND);
#else #else
timeval timeout = {ANSWER_TIMEOUT_MS / 1000, ANSWER_TIMEOUT_MS % 1000 * 1000};
shutdown(handle, SHUT_WR); shutdown(handle, SHUT_WR);
#endif #endif
setsockopt(handle, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); receive_timeout_set(handle);
char answer[sizeof(INSTANCE_ANSWER)] = {}; char answer[sizeof(INSTANCE_ANSWER)] = {};
auto isAnswered = isSent && recv(handle, answer, sizeof(answer), MSG_WAITALL) == sizeof(answer) && auto isAnswered = isSent && recv(handle, answer, sizeof(answer), MSG_WAITALL) == sizeof(answer) &&
std::string_view(answer, sizeof(answer)) == std::string_view(INSTANCE_ANSWER, sizeof(answer)); std::string_view(answer, sizeof(answer)) == std::string_view(INSTANCE_ANSWER, sizeof(answer));
@@ -73,24 +87,31 @@ static bool paths_send(const std::vector<std::string>& paths)
return isAnswered; return isAnswered;
} }
// Queues the paths for instance_paths_take before answering, and wakes the event loop if it is up yet.
static void paths_receive(Handle client) static void paths_receive(Handle client)
{ {
std::string message; std::string message;
char buffer[BUFFER_SIZE]; char buffer[BUFFER_SIZE];
for (int count = 0; (count = recv(client, buffer, sizeof(buffer), 0)) > 0;) receive_timeout_set(client);
for (int count = 0; message.size() < MESSAGE_SIZE_MAX && (count = recv(client, buffer, sizeof(buffer), 0)) > 0;)
message.append(buffer, count); message.append(buffer, count);
{
std::lock_guard lock(pendingMutex);
auto& paths = pending ? *pending : pending.emplace();
for (std::size_t start = 0, end = 0; (end = message.find('\0', start)) != std::string::npos; start = end + 1)
if (end != start)
paths.push_back(message.substr(start, end - start));
}
send(client, INSTANCE_ANSWER, sizeof(INSTANCE_ANSWER), 0); send(client, INSTANCE_ANSWER, sizeof(INSTANCE_ANSWER), 0);
closesocket(client); closesocket(client);
SDL_Event event = {.type = SDL_EVENT_USER};
for (std::size_t start = 0, end = 0; (end = message.find('\0', start)) != std::string::npos; start = end + 1)
{
if (end == start)
continue;
SDL_Event event = {};
event.type = SDL_EVENT_USER;
event.user.data1 = SDL_strdup(message.substr(start, end - start).c_str());
SDL_PushEvent(&event); SDL_PushEvent(&event);
} }
std::optional<std::vector<std::string>> instance_paths_take()
{
std::lock_guard lock(pendingMutex);
return std::exchange(pending, std::nullopt);
} }
InstanceRole instance_start(const std::vector<std::string>& paths) InstanceRole instance_start(const std::vector<std::string>& paths)
+6 -2
View File
@@ -1,5 +1,6 @@
#pragma once #pragma once
#include <optional>
#include <string> #include <string>
#include <vector> #include <vector>
@@ -10,7 +11,10 @@ enum InstanceRole
INSTANCE_ALONE INSTANCE_ALONE
}; };
// One editor at a time. The first listens on a local port and pushes an SDL_EVENT_USER (data1, an SDL_strdup'd path) // One editor at a time. The first listens on a local port for the paths a later one hands it, and that later one
// for each path a later one hands it, and that later one exits. When something else holds the port, it runs alone. // exits. Each hand-off pushes an SDL_EVENT_USER to wake the event loop. When something else holds the port, it runs
// alone.
InstanceRole instance_start(const std::vector<std::string>& paths); InstanceRole instance_start(const std::vector<std::string>& paths);
// The paths handed over since the last call (empty for a launch without any), or nothing without a hand-off.
std::optional<std::vector<std::string>> instance_paths_take();
void instance_stop(); void instance_stop();
+26 -25
View File
@@ -5,6 +5,7 @@
#include <imgui/backends/imgui_impl_opengl3.h> #include <imgui/backends/imgui_impl_opengl3.h>
#include <imgui/backends/imgui_impl_sdl3.h> #include <imgui/backends/imgui_impl_sdl3.h>
#include <imgui/imgui_internal.h> #include <imgui/imgui_internal.h>
#include <span>
#include "cli.h" #include "cli.h"
#include "gl.h" #include "gl.h"
@@ -243,18 +244,6 @@ static void events_poll(App& app, Editor& editor)
case SDL_EVENT_DROP_COMPLETE: case SDL_EVENT_DROP_COMPLETE:
file_drop_complete(app, editor); file_drop_complete(app, editor);
break; break;
// A path handed over by another instance (see instance.h).
case SDL_EVENT_USER:
{
auto path = path_from_utf8((const char*)event.user.data1);
SDL_free(event.user.data1);
if (is_path_extension(path, "anm2"))
{
editor.manager.open(path);
SDL_FlashWindow(app.window, SDL_FLASH_UNTIL_FOCUSED);
}
break;
}
case SDL_EVENT_QUIT: case SDL_EVENT_QUIT:
app.isQuitting = true; app.isQuitting = true;
break; break;
@@ -267,6 +256,15 @@ static void events_poll(App& app, Editor& editor)
break; break;
} }
} }
// Paths handed over by another instance (see instance.h).
if (auto paths = instance_paths_take())
{
for (auto& path : *paths)
if (is_path_extension(path_from_utf8(path), "anm2"))
editor.manager.open(path_from_utf8(path));
SDL_FlashWindow(app.window, SDL_FLASH_UNTIL_FOCUSED);
}
} }
// Ctrl+1 to Ctrl+0 switch to the first ten documents. // Ctrl+1 to Ctrl+0 switch to the first ten documents.
@@ -396,20 +394,23 @@ static void loop_step(App& app, Editor& editor)
app.isIdle = false; app.isIdle = false;
} }
// Paths are made absolute, so a running instance (with its own working directory) can open them.
static int editor_run(int argc, char* argv[]) static int editor_run(int argc, char* argv[])
{ {
std::vector<std::string> arguments(argv + 1, argv + argc); std::vector<std::string> arguments;
switch (instance_start(arguments)) for (auto argument : std::span(argv + 1, argv + argc))
{ {
case INSTANCE_FORWARDED: std::error_code error;
logger.info("Handed the arguments to the running instance."); auto path = std::filesystem::absolute(path_from_utf8(argument), error);
return EXIT_SUCCESS; arguments.push_back(error ? argument : path_to_utf8(path));
case INSTANCE_ALONE:
logger.warning("Another program holds the single-instance port. Running without it.");
break;
default:
break;
} }
auto role = instance_start(arguments);
if (role == INSTANCE_FORWARDED)
return EXIT_SUCCESS;
logger.session_open(preferences_directory_get());
if (role == INSTANCE_ALONE)
logger.warning("Another program holds the single-instance port. Running without it.");
App app; App app;
auto isOpen = window_open(app); auto isOpen = window_open(app);
@@ -423,7 +424,6 @@ static int editor_run(int argc, char* argv[])
while (!app.isQuit) while (!app.isQuit)
loop_step(app, editor); loop_step(app, editor);
} }
instance_stop();
window_close(app); window_close(app);
return isOpen ? EXIT_SUCCESS : EXIT_FAILURE; return isOpen ? EXIT_SUCCESS : EXIT_FAILURE;
} }
@@ -443,6 +443,7 @@ int main(int argc, char* argv[])
return cli_run(argc, (const char**)argv); return cli_run(argc, (const char**)argv);
} }
logger.session_open(preferences_directory_get()); auto result = log_exceptions([&] { return editor_run(argc, argv); });
return log_exceptions([&] { return editor_run(argc, argv); }); instance_stop();
return result;
} }
+4 -4
View File
@@ -1,11 +1,11 @@
#include "subprocess.h" #include "subprocess.h"
#ifdef WIN32 #ifdef _WIN32
#include <string> #include <string>
#include <windows.h> #include <windows.h>
#endif #endif
#ifdef WIN32 #ifdef _WIN32
std::wstring utf8_to_wstring(const char* text) std::wstring utf8_to_wstring(const char* text)
{ {
if (!text) if (!text)
@@ -33,7 +33,7 @@ bool Process::open(const char* command, const char* mode)
{ {
close(); close();
#ifdef WIN32 #ifdef _WIN32
auto wideCommand = utf8_to_wstring(command); auto wideCommand = utf8_to_wstring(command);
auto wideMode = utf8_to_wstring(mode); auto wideMode = utf8_to_wstring(mode);
pipe = _wpopen(wideCommand.c_str(), wideMode.c_str()); pipe = _wpopen(wideCommand.c_str(), wideMode.c_str());
@@ -47,7 +47,7 @@ int Process::close()
{ {
if (pipe) if (pipe)
{ {
#ifdef WIN32 #ifdef _WIN32
auto result = _pclose(pipe); auto result = _pclose(pipe);
#else #else
auto result = pclose(pipe); auto result = pclose(pipe);
+2
View File
@@ -7,6 +7,8 @@ class Process
public: public:
Process() = default; Process() = default;
Process(const char*, const char*); Process(const char*, const char*);
Process(const Process&) = delete;
Process& operator=(const Process&) = delete;
~Process(); ~Process();
bool open(const char*, const char*); bool open(const char*, const char*);
+7 -9
View File
@@ -365,7 +365,8 @@ TEST_CASE("audio decodes and mixes")
CHECK(mix[start + 2] == doctest::Approx(0.5f).epsilon(0.05)); CHECK(mix[start + 2] == doctest::Approx(0.5f).epsilon(0.05));
} }
// A second editor hands its paths to the first and is told it was heard. Skipped when the port is already taken. // A second editor hands its paths to the first, which has them queued once it answers, and wakes its event loop.
// Skipped when the port is already taken.
TEST_CASE("a second instance hands its paths to the first") TEST_CASE("a second instance hands its paths to the first")
{ {
if (!SDL_Init(SDL_INIT_EVENTS)) if (!SDL_Init(SDL_INIT_EVENTS))
@@ -373,14 +374,11 @@ TEST_CASE("a second instance hands its paths to the first")
if (instance_start({}) != INSTANCE_FIRST) if (instance_start({}) != INSTANCE_FIRST)
return; return;
CHECK(instance_start({"a.anm2", "b.anm2"}) == INSTANCE_FORWARDED); CHECK(instance_start({"a.anm2", "b.anm2"}) == INSTANCE_FORWARDED);
std::vector<std::string> paths; CHECK(instance_paths_take() == std::vector<std::string>{"a.anm2", "b.anm2"});
CHECK_FALSE(instance_paths_take());
SDL_Event event = {}; SDL_Event event = {};
for (int attempt = 0; attempt < 100 && paths.size() < 2; ++attempt) CHECK((SDL_WaitEventTimeout(&event, 1000) && event.type == SDL_EVENT_USER));
if (SDL_WaitEventTimeout(&event, 10) && event.type == SDL_EVENT_USER) CHECK(instance_start({}) == INSTANCE_FORWARDED);
{ CHECK(instance_paths_take() == std::vector<std::string>{});
paths.emplace_back((const char*)event.user.data1);
SDL_free(event.user.data1);
}
instance_stop(); instance_stop();
CHECK(paths == std::vector<std::string>{"a.anm2", "b.anm2"});
} }