diff --git a/src/audio.cpp b/src/audio.cpp index 1eb8611..2a37686 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -84,10 +84,12 @@ static AudioSound* sound_get(const AudioData& data) 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 = - SDL_InitSubSystem(SDL_INIT_AUDIO) ? SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &AUDIO_SPEC) : 0; + static SDL_AudioDeviceID device = 0; + if (!device && SDL_InitSubSystem(SDL_INIT_AUDIO)) + device = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &AUDIO_SPEC); return device; } @@ -141,9 +143,12 @@ void audio_play(const AudioData& data, AudioPlayMode mode) voice = free->get(); else { + auto stream = SDL_CreateAudioStream(&AUDIO_SPEC, &AUDIO_SPEC); + if (!stream) + return; voice = sound->voices.emplace_back(std::make_unique()).get(); voice->sound = sound; - voice->stream = SDL_CreateAudioStream(&AUDIO_SPEC, &AUDIO_SPEC); + voice->stream = stream; SDL_SetAudioStreamGetCallback(voice->stream, voice_feed, voice); SDL_BindAudioStream(device_get(), voice->stream); } diff --git a/src/instance.cpp b/src/instance.cpp index 4fcd3c0..31ecc23 100644 --- a/src/instance.cpp +++ b/src/instance.cpp @@ -2,7 +2,9 @@ #include #include +#include #include +#include #ifdef _WIN32 #include @@ -25,12 +27,15 @@ constexpr auto INSTANCE_ADDRESS = "127.0.0.1"; constexpr auto INSTANCE_PORT = 11414; // The listening editor's answer once it has every path, telling a later one it was heard. constexpr char INSTANCE_ANSWER[] = "anm2ed"; -constexpr int ANSWER_TIMEOUT_MS = 1000; +constexpr int RECEIVE_TIMEOUT_MS = 1000; constexpr int BUFFER_SIZE = 4096; +constexpr std::size_t MESSAGE_SIZE_MAX = 1 << 20; static Handle listener = HANDLE_INVALID; static std::thread listenThread; static std::atomic isListening = false; +static std::mutex pendingMutex; +static std::optional> pending; static sockaddr_in address_get() { @@ -41,6 +46,17 @@ static sockaddr_in address_get() 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. static bool paths_send(const std::vector& paths) { @@ -59,13 +75,11 @@ static bool paths_send(const std::vector& paths) message += path + '\0'; auto isSent = send(handle, message.data(), (int)message.size(), 0) == (int)message.size(); #ifdef _WIN32 - DWORD timeout = ANSWER_TIMEOUT_MS; shutdown(handle, SD_SEND); #else - timeval timeout = {ANSWER_TIMEOUT_MS / 1000, ANSWER_TIMEOUT_MS % 1000 * 1000}; shutdown(handle, SHUT_WR); #endif - setsockopt(handle, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); + receive_timeout_set(handle); char answer[sizeof(INSTANCE_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)); @@ -73,24 +87,31 @@ static bool paths_send(const std::vector& paths) 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) { std::string message; 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); + { + 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); closesocket(client); + SDL_Event event = {.type = SDL_EVENT_USER}; + SDL_PushEvent(&event); +} - 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); - } +std::optional> instance_paths_take() +{ + std::lock_guard lock(pendingMutex); + return std::exchange(pending, std::nullopt); } InstanceRole instance_start(const std::vector& paths) diff --git a/src/instance.h b/src/instance.h index ece9696..40e4048 100644 --- a/src/instance.h +++ b/src/instance.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -10,7 +11,10 @@ enum InstanceRole 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) -// for each path a later one hands it, and that later one exits. When something else holds the port, it runs alone. +// One editor at a time. The first listens on a local port for the paths a later one hands it, and that later one +// 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& paths); +// The paths handed over since the last call (empty for a launch without any), or nothing without a hand-off. +std::optional> instance_paths_take(); void instance_stop(); diff --git a/src/main.cpp b/src/main.cpp index 9a6ebb4..02bccb2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include "cli.h" #include "gl.h" @@ -243,18 +244,6 @@ static void events_poll(App& app, Editor& editor) case SDL_EVENT_DROP_COMPLETE: file_drop_complete(app, editor); 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: app.isQuitting = true; break; @@ -267,6 +256,15 @@ static void events_poll(App& app, Editor& editor) 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. @@ -396,20 +394,23 @@ static void loop_step(App& app, Editor& editor) 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[]) { - std::vector arguments(argv + 1, argv + argc); - switch (instance_start(arguments)) + std::vector arguments; + for (auto argument : std::span(argv + 1, argv + argc)) { - case INSTANCE_FORWARDED: - logger.info("Handed the arguments to the running instance."); - return EXIT_SUCCESS; - case INSTANCE_ALONE: - logger.warning("Another program holds the single-instance port. Running without it."); - break; - default: - break; + std::error_code error; + auto path = std::filesystem::absolute(path_from_utf8(argument), error); + arguments.push_back(error ? argument : path_to_utf8(path)); } + 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; auto isOpen = window_open(app); @@ -423,7 +424,6 @@ static int editor_run(int argc, char* argv[]) while (!app.isQuit) loop_step(app, editor); } - instance_stop(); window_close(app); return isOpen ? EXIT_SUCCESS : EXIT_FAILURE; } @@ -443,6 +443,7 @@ int main(int argc, char* argv[]) return cli_run(argc, (const char**)argv); } - logger.session_open(preferences_directory_get()); - return log_exceptions([&] { return editor_run(argc, argv); }); + auto result = log_exceptions([&] { return editor_run(argc, argv); }); + instance_stop(); + return result; } diff --git a/src/subprocess.cpp b/src/subprocess.cpp index bca84fa..e532092 100644 --- a/src/subprocess.cpp +++ b/src/subprocess.cpp @@ -1,11 +1,11 @@ #include "subprocess.h" -#ifdef WIN32 +#ifdef _WIN32 #include #include #endif -#ifdef WIN32 +#ifdef _WIN32 std::wstring utf8_to_wstring(const char* text) { if (!text) @@ -33,7 +33,7 @@ bool Process::open(const char* command, const char* mode) { close(); -#ifdef WIN32 +#ifdef _WIN32 auto wideCommand = utf8_to_wstring(command); auto wideMode = utf8_to_wstring(mode); pipe = _wpopen(wideCommand.c_str(), wideMode.c_str()); @@ -47,7 +47,7 @@ int Process::close() { if (pipe) { -#ifdef WIN32 +#ifdef _WIN32 auto result = _pclose(pipe); #else auto result = pclose(pipe); diff --git a/src/subprocess.h b/src/subprocess.h index f9b974f..e6e89b4 100644 --- a/src/subprocess.h +++ b/src/subprocess.h @@ -7,6 +7,8 @@ class Process public: Process() = default; Process(const char*, const char*); + Process(const Process&) = delete; + Process& operator=(const Process&) = delete; ~Process(); bool open(const char*, const char*); diff --git a/tests/render/render.cpp b/tests/render/render.cpp index 7337ed0..a69f331 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -365,7 +365,8 @@ TEST_CASE("audio decodes and mixes") 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") { 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) return; CHECK(instance_start({"a.anm2", "b.anm2"}) == INSTANCE_FORWARDED); - std::vector paths; + CHECK(instance_paths_take() == std::vector{"a.anm2", "b.anm2"}); + CHECK_FALSE(instance_paths_take()); SDL_Event event = {}; - for (int attempt = 0; attempt < 100 && paths.size() < 2; ++attempt) - if (SDL_WaitEventTimeout(&event, 10) && event.type == SDL_EVENT_USER) - { - paths.emplace_back((const char*)event.user.data1); - SDL_free(event.user.data1); - } + CHECK((SDL_WaitEventTimeout(&event, 1000) && event.type == SDL_EVENT_USER)); + CHECK(instance_start({}) == INSTANCE_FORWARDED); + CHECK(instance_paths_take() == std::vector{}); instance_stop(); - CHECK(paths == std::vector{"a.anm2", "b.anm2"}); }