1#ifndef FRAY_MANAGER_HPP
2#define FRAY_MANAGER_HPP
15#include <system_error>
16#include <unordered_map>
17#include <unordered_set>
88 std::shared_ptr<threads::TaskQueue>
queue = std::make_shared<threads::TaskQueue>();
121 std::shared_ptr<threads::TaskQueue>
queue;
149 inline static std::atomic<bool>
_active{
false};
157 std::unique_ptr<files::FileManager>
_files = std::make_unique<files::FileManager>();
159 std::unordered_map<std::string, std::unique_ptr<state::StateManager>>
_states;
179 std::shared_ptr<threads::TaskQueue>
_consoleQueue = std::make_shared<threads::TaskQueue>();
187 std::shared_ptr<threads::TaskQueue>
_logQueue = std::make_shared<threads::TaskQueue>();
215 std::function<void(
const std::string&
id,
const std::string& path,
const std::string& name)>
_renameNotifier;
225 std::function<void(
const std::string& name,
const std::string&
id,
F_err result,
bool packaged,
230 using Projects = std::unordered_map<std::string, Entry>;
272 std::unordered_map<ProjectManager*, std::string>
_logIds;
281 ProjectClosingStatuses statuses;
289 const auto id =
_logIds.find(entry.second.project.get());
292 std::fprintf(stderr,
"Cannot report closing project: project identity is unavailable.\n");
295 auto* status = statuses.add_projects();
296 status->set_id(id->second);
297 status->set_path(entry.first);
298 status->set_name(std::filesystem::path(entry.first).filename().string());
302 const auto& entry = item.second.entry;
303 auto* status = statuses.add_projects();
304 status->set_id(entry.id.empty() ?
openingTag(item.first) : entry.id);
305 status->set_path(entry.path);
306 status->set_name(std::filesystem::path(entry.path).filename().string());
356 const std::string& path,
357 std::error_code& error)
359 if (path.empty() || path.find(
'\0') != std::string::npos)
361 error = std::make_error_code(std::errc::invalid_argument);
364 auto resolved = std::filesystem::weakly_canonical(path, error);
367 if (resolved.filename().empty() && resolved != resolved.root_path())
368 resolved = resolved.parent_path();
369 if (resolved.extension() ==
".fry")
370 resolved.replace_extension();
371 return resolved.string();
380 const std::string& target)
390 return path->second->identity;
393 const std::filesystem::path input(target);
395 if (input.is_absolute() || input.has_parent_path())
397 std::error_code error;
401 std::fprintf(stderr,
"Cannot resolve project log target %s: %s.\n",
402 target.c_str(), error.message().c_str());
408 bool ambiguous =
false;
413 if ((!key.empty() && item.first != key) ||
414 (key.empty() && std::filesystem::path(item.first).filename() != input))
424 if (!
identity.empty() && !ambiguous)
426 std::fprintf(stderr,
"Cannot resolve project log target %s%s; using the application log.\n",
427 target.c_str(), ambiguous ?
" (ambiguous)" :
"");
439 const std::string& target,
441 bool includeClosed =
false)
443 error = errors::PROJECT_NOT_FOUND;
444 const std::filesystem::path input(target);
445 if (input.is_absolute() || input.has_parent_path())
447 std::error_code pathError;
448 const std::string key =
projectKey(target, pathError);
451 log::engineError(
"Cannot resolve project path: %s", pathError.message().c_str());
456 (includeClosed || found->second.project->isOpen() || found->second.project->isOpening()))
458 error = errors::NONE;
466 if (std::filesystem::path(it->first).filename() != input ||
467 (!includeClosed && !it->second.project->isOpen() && !it->second.project->isOpening()))
471 error = errors::PROJECT_AMBIGUOUS;
472 log::engineError(
"Multiple projects are named %s; use the full path.", target.c_str());
478 error = errors::NONE;
490 const std::string& name,
492 bool includeClosed =
false)
494 std::lock_guard<std::mutex> lock(
_mutex);
495 const auto found =
lookup(name, error, includeClosed);
496 return found ==
_projects.end() ? std::nullopt : std::optional<Entry>(found->second);
508 const std::string& name,
511 bool shutdownAction =
false)
513 std::lock_guard<std::mutex> lock(
_mutex);
517 log::engineError(
"Cannot change a database choice: the Engine is shutting down.");
518 return errors::FAILED_OPEN_PROJECT;
521 const auto found =
lookup(name, error);
522 if (found ==
_projects.end() || !found->second.project->isOpening())
524 log::engineError(
"No project is waiting for a database choice: %s", name.c_str());
525 return error == errors::PROJECT_AMBIGUOUS ? error : errors::FAILED_OPEN_PROJECT;
527 const std::string key = found->first;
531 log::engineError(
"A database-choice action is already queued: %s", name.c_str());
532 return errors::FAILED_OPEN_PROJECT;
534 const auto project = found->second.project;
535 const auto queue = found->second.queue;
537 if (!queue->post([
this, key,
project, queue, action, choice]
539 F_err result = errors::FAILED_OPEN_PROJECT;
540 const std::string tag = openingTag(project.get());
543 const log::ProjectScope scope(tag);
544 if (action == OpeningDecision::resolve)
546 result = project->resolveDatabase(choice);
547 if (result == errors::NONE)
548 result = registerOpenedProject(project.get());
549 if (result != errors::NONE && !project->isOpen() && project->databaseCandidates().empty())
551 _logs.discardOpening(tag);
557 result = project->cancelOpen();
558 if (result == errors::NONE)
560 _logs.discardOpening(tag);
561 std::lock_guard<std::mutex> lock(_mutex);
562 const auto found = _projects.find(key);
563 if (found == _projects.end() || found->second.project != project)
565 log::engineError(
"Cannot remove project: it is no longer registered.");
566 result = errors::FAILED_OPEN_PROJECT;
570 forgetProject(project.get());
571 retainRetiredLocked(std::move(found->second));
572 _projects.erase(found);
577 catch (
const std::exception& exception)
580 result = errors::FAILED_OPEN_PROJECT;
582 if (result != errors::NONE)
584 key.c_str(),
static_cast<long long>(result));
585 std::lock_guard<std::mutex> lock(
_mutex);
590 log::engineError(
"Cannot change a database choice: the project queue is stopped.");
591 return errors::FAILED_OPEN_PROJECT;
604 entry.
queue->shutdown();
634 entry.
queue->shutdown();
646 std::vector<Entry> readyEntries;
648 std::lock_guard<std::mutex> lock(
_mutex);
651 if (
_threads->running(it->thread) ||
652 (it->logWorker &&
_threads->running(it->logWorker->thread)))
657 readyEntries.push_back(std::move(*it));
661 for (
auto& entry : readyEntries)
677 _logs.closeProject(logged->second);
704 const auto found =
_states.find(
"Fray");
705 if (!
_files->isOpen() || found ==
_states.end() || !found->second->isOpen())
706 return errors::FAILED_SAVE_STATE;
708 return found->second->set(
"application.session.lastOpenProjects",
727 [
project](
const auto& entry) { return entry.second.project.get() == project; });
728 if (found ==
_projects.end() || found->second.id.empty())
731 saved->set_id(found->second.id);
732 saved->set_path(found->second.path);
745 const std::string&
id,
746 const std::string& path)
748 std::lock_guard<std::mutex> lock(
_mutex);
769 return "opening:" + std::to_string(
reinterpret_cast<std::uintptr_t
>(
project));
777 const std::string&
id)
779 std::function<void(
const std::string&)> notifier;
781 std::lock_guard<std::mutex> lock(
_mutex);
798 const std::string&
id,
799 const std::shared_ptr<ProjectLogWorker>& worker,
800 const std::shared_ptr<threads::TaskQueue>& queue,
801 const std::shared_ptr<ProjectManager>&
project,
802 const std::filesystem::path& folder,
805 bool resumed =
false;
808 resumed =
_logs.moveProject(
id, folder);
810 catch (
const std::exception& error)
812 std::fprintf(stderr,
"Cannot resume project log after rename: %s\n", error.what());
815 result = errors::FAILED_RENAME_PROJECT;
816 for (
const auto& entry : worker->duringRename)
820 _logs.persist(entry);
822 _logs.persistApplication(entry);
824 catch (
const std::exception& error)
826 std::fprintf(stderr,
"Cannot store log entry after rename: %s\n", error.what());
827 result = errors::FAILED_RENAME_PROJECT;
829 worker->duringRename.clear();
830 worker->renaming =
false;
832 if (result != errors::NONE)
834 if (!queue->post([
project] { project->replayRenameChanges(); }))
835 std::fprintf(stderr,
"Cannot replay rename changes: project queue is stopped.\n");
836 auto close = std::move(worker->deferredClose);
850 std::shared_ptr<ProjectLogWorker> worker;
851 std::shared_ptr<threads::TaskQueue> queue;
852 std::weak_ptr<ProjectManager> owned;
854 std::lock_guard<std::mutex> lock(
_mutex);
856 [
project](
const auto& entry) { return entry.second.project.get() == project; });
857 if (found ==
_projects.end() || !found->second.logWorker)
859 std::fprintf(stderr,
"Cannot attach project log: project worker is unavailable.\n");
862 worker = found->second.logWorker;
863 queue = found->second.queue;
864 owned = found->second.project;
866 std::lock_guard<std::recursive_mutex> projectLock(
project->_mutex);
869 const auto project = owned.lock();
875 return worker->queue->post([
this,
id, worker, queue,
project, request = std::move(request)]
877 worker->renaming =
true;
878 bool suspended =
false;
881 suspended =
_logs.suspendProject(
id);
883 catch (
const std::exception& error)
885 std::fprintf(stderr,
"Cannot suspend project log: %s\n", error.what());
889 worker->renaming =
false;
890 project->finishRename(errors::FAILED_RENAME_PROJECT);
892 std::fprintf(stderr,
"Cannot suspend project log for rename.\n");
893 if (!queue->post([
project] { project->replayRenameChanges(); }))
894 std::fprintf(stderr,
"Cannot replay rename changes: project queue is stopped.\n");
897 if (!queue->post([
this,
id, worker, queue,
project, request]
899 F_err result = errors::FAILED_RENAME_PROJECT;
900 std::filesystem::path folder;
902 std::lock_guard<std::recursive_mutex> lock(project->_mutex);
903 const log::ProjectScope tag(project->_projectId);
906 const auto current = project->refreshRenameRequest(request);
907 result = project->applyName(current.name, current.workspace,
908 current.renameFolder, current.databaseStem);
910 catch (const std::exception& error)
912 log::engineError(
"Cannot rename project: %s", error.what());
914 folder = project->_files.workingDirectory();
916 if (!worker->queue->post([
this,
id, worker, queue,
project, folder, result]
918 finishLogRename(id, worker, queue, project, folder, result);
921 project->finishRename(errors::FAILED_RENAME_PROJECT);
922 notifyRenameFailure(id);
923 std::fprintf(stderr,
"Cannot resume project log: log worker is stopped.\n");
928 errors::FAILED_RENAME_PROJECT);
929 std::fprintf(stderr,
"Cannot finish project rename: project queue is stopped.\n");
944 const std::string original =
project->id();
945 if (original.empty())
948 return errors::FAILED_OPEN_PROJECT;
950 std::string reserved;
954 std::lock_guard<std::mutex> lock(
_mutex);
956 [
project](
const auto& entry) { return entry.second.project.get() == project; });
960 return errors::FAILED_OPEN_PROJECT;
962 const auto used = [
this,
project](
const std::string& id)
965 [
project, &
id](
const auto& entry)
966 { return entry.second.project.get() != project && entry.second.project->isOpen() &&
967 entry.second.id == id; });
971 else if (!used(candidate))
972 reserved = candidate;
975 found->second.id = reserved;
978 if (reserved == original)
980 const F_err result =
project->reassignProjectId(reserved);
981 if (result != errors::NONE)
983 std::lock_guard<std::mutex> lock(
_mutex);
985 [
project](
const auto& entry) { return entry.second.project.get() == project; });
986 if (found !=
_projects.end() && found->second.id == reserved)
987 found->second.id.clear();
991 log::engineWarn(
"A copied project had a duplicate identity; a new identity was assigned.");
1004 if (result != errors::NONE)
1006 project->setLogCloseBarrier(
nullptr);
1007 if (
project->closeNow(
false,
nullptr,
true) != errors::NONE)
1008 log::engineError(
"Cannot release a project after its identity could not be registered.");
1014 return errors::NONE;
1027 const std::string
id =
project->isOpen() ?
project->id() : std::string();
1028 const auto folder =
project->fileManager().workingDirectory();
1029 std::function<void(
const std::string&,
const std::string&)> resolved;
1030 std::shared_ptr<ProjectLogWorker> worker;
1032 std::lock_guard<std::mutex> lock(
_mutex);
1034 [
project](
const auto& entry) { return entry.second.project.get() == project; });
1038 if (found->second.restoreOrder)
1043 const auto entry = std::find_if(_projects.begin(), _projects.end(),
1044 [other](const auto& item) { return item.second.project.get() == other; });
1045 return entry ==
_projects.end() || !entry->second.restoreOrder ||
1046 *entry->second.restoreOrder > *found->second.restoreOrder;
1052 found->second.id = id;
1056 worker = found->second.logWorker;
1057 if (!worker->queue->post([worker] { worker->opening = true; }))
1059 throw std::runtime_error(
"Cannot queue project log opening: project log worker is shutting down.");
1062 worker->identity = id;
1071 _logs.openProject(
id, folder, openingTag(project));
1075 if (!worker->queue->post([
this, worker,
id, tag = openingTag(project)]
1079 _logs.discardOpening(tag);
1081 catch (
const std::exception& error)
1083 std::fprintf(stderr,
"Cannot discard opening logs: %s\n", error.what());
1085 for (
const auto& entry : worker->duringOpening)
1089 auto fallback = entry;
1090 if (fallback.project == tag)
1091 fallback.project = id;
1092 _logs.persistApplication(fallback);
1094 catch (
const std::exception& error)
1096 std::fprintf(stderr,
"Cannot store buffered project log: %s\n", error.what());
1099 worker->duringOpening.clear();
1100 worker->opening =
false;
1102 std::fprintf(stderr,
"Cannot release buffered project logs: project log worker is shutting down.\n");
1105 if (!worker->queue->post([
this, worker]
1107 for (const auto& entry : worker->duringOpening)
1111 _logs.persist(entry);
1113 catch (const std::exception& error)
1115 std::fprintf(stderr,
"Cannot store buffered project log: %s\n", error.what());
1118 worker->duringOpening.clear();
1119 worker->opening =
false;
1121 std::fprintf(stderr,
"Cannot release buffered project logs: project log worker is shutting down.\n");
1124 resolved(openingTag(project),
id);
1135 const std::filesystem::path& path)
1137 std::error_code error;
1138 const std::string key =
projectKey(path.string(), error);
1141 log::engineError(
"Cannot update renamed project path: %s", error.message().c_str());
1145 std::lock_guard<std::mutex> lock(
_mutex);
1147 [
project](
const auto& entry) { return entry.second.project.get() == project; });
1148 if (found ==
_projects.end() || found->first == key)
1150 const auto collision =
_projects.find(key);
1153 if (collision->second.project->isOpen() || collision->second.project->isOpening())
1155 log::engineError(
"Cannot register renamed project: %s is already open.", key.c_str());
1168 node.mapped().path = key;
1171 std::function<void(
const std::string&,
const std::string&,
const std::string&)> notify;
1173 std::lock_guard<std::mutex> lock(
_mutex);
1188 F_err result = errors::NONE;
1189 const auto apply = [&](
const std::string& key,
const auto& value)
1191 if (result != errors::NONE)
1194 result =
state.contains(key, exists);
1195 if (result == errors::NONE && !exists)
1196 result =
state.set(key, value);
1198 apply(
"application.preferences.defaultSaveLocation", std::string());
1199 apply(
"application.preferences.reopenProjectsOnLaunch",
false);
1200 apply(
"application.preferences.packageOnClose",
false);
1201 apply(
"application.info.stateKind",
"application");
1214 const F_err result =
state.get(
"application.info.stateKind", kind);
1215 if (result != errors::NONE || kind !=
"application")
1217 log::engineError(
"Cannot open application state: database is not an application database.");
1218 return errors::FAILED_OPEN_STORE;
1220 return errors::NONE;
1232 bool reopen =
false;
1233 bool package = false;
1234 const auto check = [&](
const std::string& key,
auto& value)
1237 const F_err result =
state.contains(key, exists);
1238 return result != errors::NONE || !exists ? result :
state.get(key, value);
1240 F_err result = check(
"application.preferences.defaultSaveLocation", folder);
1241 if (result == errors::NONE)
1242 result = check(
"application.preferences.reopenProjectsOnLaunch", reopen);
1243 if (result == errors::NONE)
1244 result = check(
"application.preferences.packageOnClose", package);
1245 if (result != errors::NONE)
1246 log::engineError(
"Cannot open application state: a preference has an invalid value.");
1256 bool expected =
false;
1257 if (!
_active.compare_exchange_strong(expected,
true))
1258 throw std::logic_error(
"Only one FrayManager may exist in an engine process.");
1269 catch (
const std::system_error&)
1278 catch (
const std::bad_alloc&)
1301 void forwardLogEntry(
1304 bool includeLoading);
1315 bool includeLoading =
true)
1317 if (!
_consoleQueue->post([
this, entry, &
ipc, includeLoading] { forwardLogEntry(entry, ipc, includeLoading); }))
1318 std::fprintf(stderr,
"Cannot queue Console entry: Console worker is shutting down.\n");
1355 void handleNotification(
1372 void addNotification(
1374 NotificationSeverity severity,
1375 const std::string& title,
1376 const std::string& description,
1377 const std::string& project,
1378 std::uint32_t flags,
1380 const std::string& uid =
"",
1381 ProcessKind destination = PROCESS_KIND_ENGINE);
1388 ConsoleEntry describeCommand(
1397 static void sendConsoleEntry(
1399 const ConsoleEntry& entry,
1438 const auto worker = found->second;
1439 if (!worker->queue->post([
this, entry, worker]
1441 if (worker->opening)
1442 worker->duringOpening.push_back(entry);
1443 else if (worker->renaming)
1444 worker->duringRename.push_back(entry);
1446 _logs.persist(entry);
1448 std::fprintf(stderr,
"Cannot queue project log entry: project log worker is shutting down.\n");
1452 if (!
_logQueue->post([
this, entry] { _logs.persistApplication(entry); }))
1453 std::fprintf(stderr,
"Cannot queue log entry: application log worker is shutting down.\n");
1466 bool includeLoading =
true)
1468 const auto prepared =
_logs.prepare(std::move(entry));
1471 if (prepared->project.empty())
1475 if (!prepared->project.empty())
1495 std::uint64_t arrivedUs = 0,
1496 bool consoleVisible =
true)
1500 entry.
process =
static_cast<int>(PROCESS_KIND_ENGINE);
1501 entry.
level = level;
1502 entry.
thread =
static_cast<std::uint32_t
>(thread);
1506 if (std::string(level) ==
"SES")
1507 entry.
kind = LOG_ENTRY_KIND_SESSION;
1564 const std::filesystem::path& directory)
1566 std::lock_guard<std::mutex> lock(
_mutex);
1569 log::engineError(
"Cannot open application state: already open or shutting down.");
1570 return errors::FAILED_OPEN_STORE;
1572 std::error_code directoryError;
1573 const auto resolvedDirectory = std::filesystem::canonical(directory, directoryError);
1574 if (directoryError || !std::filesystem::is_directory(resolvedDirectory, directoryError) || directoryError)
1576 log::engineError(
"Cannot open application state: invalid Engine directory.");
1577 return errors::FAILED_OPEN_STORE;
1580 std::filesystem::path selected;
1582 if (result != errors::NONE)
1584 if (!selected.empty())
1587 if (result != errors::NONE)
1589 const auto database =
_files->workingDirectory() /
_files->databaseFileName();
1590 std::error_code error;
1591 const bool existing = std::filesystem::exists(database, error);
1594 log::engineError(
"Cannot inspect application database: %s", error.message().c_str());
1595 if (
_files->close() != errors::NONE)
1596 log::engineError(
"Cannot close application files after inspection failed.");
1597 return errors::FAILED_OPEN_STORE;
1599 auto manager = std::make_unique<state::StateManager>();
1601 if (result == errors::NONE && existing)
1603 if (result == errors::NONE)
1605 if (result == errors::NONE)
1607 if (result != errors::NONE)
1609 if (manager->isOpen() && manager->close() != errors::NONE)
1610 log::engineError(
"Cannot close application state after initialization failed.");
1611 if (
_files->close() != errors::NONE)
1612 log::engineError(
"Cannot close application files after state initialization failed.");
1615 _states.emplace(
"Fray", std::move(manager));
1616 return errors::NONE;
1626 const std::string& defaults,
1629 std::lock_guard<std::mutex> lock(
_mutex);
1639 const std::string& css)
1641 std::lock_guard<std::mutex> lock(
_mutex);
1654 const std::filesystem::path& path,
1659 log::engineError(
"Cannot switch application state: Engine directory is unavailable or shutting down.");
1660 return errors::FAILED_OPEN_STORE;
1662 std::error_code error;
1663 const auto status = std::filesystem::symlink_status(path, error);
1664 if (error || !std::filesystem::is_regular_file(status))
1666 log::engineError(
"Cannot switch application state: file is not an existing regular file.");
1667 return errors::FAILED_OPEN_STORE;
1671 const auto current =
_files->workingDirectory() /
_files->databaseFileName();
1672 if (std::filesystem::equivalent(current, path, error) && !error)
1676 log::engineError(
"Cannot compare application database paths: %s", error.message().c_str());
1677 return errors::FAILED_OPEN_STORE;
1680 auto files = std::make_unique<files::FileManager>();
1682 if (result != errors::NONE)
1684 auto manager = std::make_unique<state::StateManager>();
1686 if (result == errors::NONE)
1688 if (result == errors::NONE)
1690 if (result == errors::NONE)
1692 if (result != errors::NONE)
1694 std::unordered_map<std::string, std::unique_ptr<state::StateManager>> states;
1695 states.emplace(
"Fray", std::move(manager));
1696 for (
const auto& entry :
_states)
1698 if (entry.first ==
"Fray" || !entry.second->isOpen())
1700 auto extra = std::make_unique<state::StateManager>();
1702 if (result != errors::NONE)
1704 states.emplace(entry.first, std::move(extra));
1706 const auto selected =
files->workingDirectory() /
files->databaseFileName();
1710 if (result != errors::NONE)
1713 auto previousFiles = std::move(
_files);
1714 auto previousStates = std::move(
_states);
1717 for (
auto& entry : previousStates)
1718 if (entry.second->isOpen() && entry.second->close() != errors::NONE)
1719 log::engineError(
"Cannot close previous application state: %s", entry.first.c_str());
1720 previousStates.clear();
1721 if (previousFiles->isOpen() && previousFiles->close() != errors::NONE)
1722 log::engineError(
"Cannot close previous application files after switching.");
1723 return errors::NONE;
1734 const std::filesystem::path& path)
1736 if (!path.is_absolute() || path.string().find(
'\0') != std::string::npos)
1738 log::engineError(
"Cannot switch application state: database path must be absolute.");
1739 return errors::FAILED_OPEN_STORE;
1741 std::lock_guard<std::mutex> lock(
_mutex);
1751 std::lock_guard<std::mutex> lock(
_mutex);
1753 : std::filesystem::path();
1762 ApplicationPreferences& output)
1764 std::lock_guard<std::mutex> lock(
_mutex);
1765 const auto found =
_states.find(
"Fray");
1766 if (!
_files->isOpen() || found ==
_states.end() || !found->second->isOpen())
1768 log::engineError(
"Cannot read application preferences: store is not open.");
1769 return errors::FAILED_LOAD_STATE;
1772 bool reopen =
false;
1773 bool package = false;
1774 F_err result = found->second->get(
"application.preferences.defaultSaveLocation", folder);
1775 if (result == errors::NONE)
1776 result = found->second->get(
"application.preferences.reopenProjectsOnLaunch", reopen);
1777 if (result == errors::NONE)
1778 result = found->second->get(
"application.preferences.packageOnClose", package);
1779 if (result != errors::NONE)
1782 output.set_default_save_location(folder);
1783 output.set_reopen_projects_on_launch(reopen);
1784 output.set_package_on_close(package);
1785 output.set_database_path((
_files->workingDirectory() /
_files->databaseFileName()).string());
1786 return errors::NONE;
1795 std::lock_guard<std::mutex> lock(
_mutex);
1796 const auto found =
_states.find(
"Fray");
1797 if (found ==
_states.end() || !found->second->isOpen())
1799 log::engineError(
"Cannot reset application preferences: store is not open.");
1800 return errors::FAILED_SAVE_STATE;
1802 auto&
state = *found->second;
1803 return state.withDatabase([&](sqlite3* db)
1805 if (sqlite3_exec(db,
"BEGIN IMMEDIATE",
nullptr,
nullptr,
nullptr) != SQLITE_OK)
1807 log::engineError(
"Cannot start preferences reset: %s", sqlite3_errmsg(db));
1808 return errors::FAILED_SAVE_STATE;
1810 F_err result =
state.set(
"application.preferences.defaultSaveLocation",
"");
1811 if (result == errors::NONE)
1812 result =
state.set(
"application.preferences.reopenProjectsOnLaunch",
false);
1813 if (result == errors::NONE)
1814 result =
state.set(
"application.preferences.packageOnClose",
false);
1815 if (result == errors::NONE && sqlite3_exec(db,
"COMMIT",
nullptr,
nullptr,
nullptr) == SQLITE_OK)
1816 return errors::NONE;
1817 log::engineError(
"Cannot reset application preferences: %s", sqlite3_errmsg(db));
1818 if (sqlite3_exec(db,
"ROLLBACK",
nullptr,
nullptr,
nullptr) != SQLITE_OK)
1819 log::engineError(
"Cannot roll back preferences reset: %s", sqlite3_errmsg(db));
1820 return errors::FAILED_SAVE_STATE;
1830 const std::string& name)
1832 std::lock_guard<std::mutex> lock(
_mutex);
1835 log::engineError(
"Cannot open application state: files are closed or shutting down.");
1836 return errors::FAILED_OPEN_STORE;
1838 const auto found =
_states.find(name);
1839 if (found !=
_states.end() && found->second->isOpen())
1840 return errors::NONE;
1841 auto manager = std::make_unique<state::StateManager>();
1843 if (result != errors::NONE)
1845 _states[name] = std::move(manager);
1846 return errors::NONE;
1856 const std::string& name)
1858 std::lock_guard<std::mutex> lock(
_mutex);
1859 const auto found =
_states.find(name);
1860 if (found ==
_states.end() || !found->second->isOpen())
1861 throw std::out_of_range(
"Application state manager is not open: " + name);
1862 return *found->second;
1872 template<
typename T>
1874 const std::string& key,
1877 std::lock_guard<std::mutex> lock(
_mutex);
1878 const auto found =
_states.find(
"Fray");
1879 if (found ==
_states.end() || !found->second->isOpen())
1882 return errors::FAILED_SAVE_STATE;
1884 return found->second->set(key, value);
1894 template<
typename T>
1896 const std::string& key,
1899 std::lock_guard<std::mutex> lock(
_mutex);
1900 const auto found =
_states.find(
"Fray");
1901 if (found ==
_states.end() || !found->second->isOpen())
1904 return errors::FAILED_LOAD_STATE;
1906 return found->second->get(key, value);
1916 std::lock_guard<std::mutex> lock(
_mutex);
1929 item.second.closeAttempted =
false;
1930 item.second.cancelAttempted =
false;
1951 std::vector<std::string> cancellations;
1952 bool changed =
false;
1954 std::lock_guard<std::mutex> lock(
_mutex);
1960 const auto track = [&](
const Entry& entry)
1962 const bool active = entry.project->isOpen() || entry.project->isOpening() ||
1964 (entry.logWorker &&
_threads->running(entry.logWorker->thread));
1968 if (inserted.second)
1970 else if (inserted.first->second.entry.path != entry.path ||
1971 inserted.first->second.entry.id != entry.id)
1973 inserted.first->second.entry.path = entry.path;
1974 inserted.first->second.entry.id = entry.id;
1979 track(entry.second);
1985 auto& tracked = it->second;
1986 const auto& entry = tracked.entry;
1988 const auto registered =
_projects.find(entry.path);
1989 const bool present = registered !=
_projects.end() && registered->second.project == entry.project;
1992 const bool openingPending = opening !=
_openingStatuses.end() && !opening->second.result;
1993 const bool decisionPending = decision !=
_openingDecisions.end() && !decision->second.result;
1995 tracked.closeAttempted =
true;
1996 else if (applicationDrained && present && !openingPending && !decisionPending &&
project->isOpening())
1998 if (!tracked.cancelAttempted)
2000 tracked.cancelAttempted =
true;
2001 cancellations.push_back(entry.path);
2004 else if (applicationDrained && present && !openingPending && !decisionPending &&
project->isOpen())
2006 if (!tracked.closeAttempted)
2008 tracked.closeAttempted =
true;
2010 [
this, path = entry.path](
ProjectManager& target,
const std::shared_ptr<threads::TaskQueue>& queue)
2012 CloseTaskGuard guard{*this, target, queue, true};
2014 const std::string projectName = target.
name();
2015 const std::string projectId = target.
id();
2019 bool packaged =
false;
2021 std::function<void(
const std::string&,
const std::string&,
F_err,
bool,
const std::string&)> notify;
2023 std::lock_guard<std::mutex> notifyLock(
_mutex);
2028 notify(projectName, projectId, result, packaged, packaged ? archivePath : workingPath);
2029 guard.finish(result);
2030 if (result != errors::NONE)
2031 log::engineError(
"Shutdown close failed for %s (error %lld); retry shutdown after resolving it.",
2032 path.c_str(),
static_cast<long long>(result));
2034 if (result != errors::NONE)
2036 entry.path.c_str(),
static_cast<long long>(result));
2039 else if (!
project->isOpen() && !
project->isOpening() && !openingPending &&
2042 if (!tracked.threadsStopRequested)
2044 project->requestStopThreads();
2045 tracked.threadsStopRequested =
true;
2047 entry.queue->shutdown();
2048 if (!
_threads->running(entry.thread) && entry.logWorker && !tracked.logStopping)
2051 entry.logWorker->closing =
true;
2052 entry.logWorker->queue->shutdown();
2053 tracked.logStopping =
true;
2055 if (!
_threads->running(entry.thread) &&
2056 (!entry.logWorker || !
_threads->running(entry.logWorker->thread)))
2067 if (cancellations.empty() &&
_shutdownEntries.empty() && applicationDrained)
2070 for (
const auto& path : cancellations)
2071 if (queueOpeningDecision(path, OpeningDecision::cancel,
DatabaseChoice{},
true) != errors::NONE)
2072 log::engineError(
"Cannot cancel project opening during shutdown: %s", path.c_str());
2073 return shutdownPhase();
2082 std::lock_guard<std::mutex> lock(
_mutex);
2095 std::lock_guard<std::mutex> lock(
_mutex);
2101 std::lock_guard<std::mutex> lock(
_mutex);
2113 std::lock_guard<std::mutex> lock(
_mutex);
2116 if (
close() != errors::NONE)
2117 log::engineError(
"Some project closes could not be queued during final cleanup.");
2118 std::vector<Entry> projects;
2120 std::lock_guard<std::mutex> lock(
_mutex);
2123 projects.push_back(entry.second);
2124 const auto owned = entry.second.project;
2125 const auto queue = entry.second.queue;
2126 if (!queue->post([
this, owned, queue]
2128 if (owned->isOpening())
2130 if (owned->cancelOpen() != errors::NONE)
2131 log::engineError(
"Could not cancel project opening during final cleanup.");
2133 _logs.discardOpening(openingTag(owned.get()));
2139 std::lock_guard<std::mutex> lock(_mutex);
2140 closing = _closingProjects.count(owned.get()) != 0;
2144 if (owned->isOpen())
2146 const F_err result = queueProjectClose(
"", [](ProjectManager& target, bool& packaged)
2148 return target.closeNow(false, &packaged);
2149 }, {}, owned.get());
2150 if (result == errors::NONE)
2157 if (
_threads->running(entry.second.thread))
2158 log::engineWarn(
"Project queue was already stopped during final cleanup.");
2161 projects.insert(projects.end(), _retiredProjects.begin(), _retiredProjects.end());
2164 for (
auto& entry : projects)
2165 _threads->join(entry.thread);
2166 const auto closed = closeAllStatus();
2167 if (closed && closed->result && *closed->result != errors::NONE)
2168 log::engineError(
"Some projects could not be closed; check their archives and working folders.");
2169 for (
auto& entry : projects)
2170 if (entry.logWorker)
2171 entry.logWorker->queue->shutdown();
2172 for (
auto& entry : projects)
2173 if (entry.logWorker)
2174 _threads->join(entry.logWorker->thread);
2175 for (
auto& entry : _retiredProjects)
2177 _retiredProjects.clear();
2179 std::lock_guard<std::mutex> lock(_projectLogsMutex);
2180 _projectLogRoutes.clear();
2181 _projectLogPaths.clear();
2184 _shutdownEntries.clear();
2186 _closingProjects.clear();
2187 _closeAllProjects.clear();
2189 std::lock_guard<std::mutex> lock(_mutex);
2190 for (
auto& entry : _states)
2191 if (entry.second->isOpen() && entry.second->close() != errors::NONE)
2192 log::engineError(
"Cannot close application state: %s", entry.first.c_str());
2194 if (_files->isOpen() && _files->close() != errors::NONE)
2195 log::engineError(
"Cannot close application files.");
2197 _logQueue->shutdown();
2198 _threads->join(_logThread);
2207 const std::string& reason,
2208 bool closing =
false)
2215 if (entry.second.completed)
2217 entry.second.response.set_request_id(entry.first);
2218 entry.second.response.set_dismissed(
true);
2219 entry.second.response.set_error(reason);
2220 entry.second.completed =
true;
2232 PromptResponse& response)
2238 response = std::move(found->second.response);
2254 std::function<
void()> task)
2256 std::lock_guard<std::mutex> lock(
_mutex);
2259 log::engineError(
"Cannot queue application work: shutdown is in progress.");
2281 void handleApplicationMessage(
2294 const PromptRequest& request,
2295 uint64_t& requestId);
2309 const std::string& path,
2311 bool cancelOnDatabaseConflict =
false,
2313 std::optional<OpeningOrigin> origin = std::nullopt,
2314 std::optional<std::size_t> restoreOrder = std::nullopt,
2315 const std::string& expectedId =
"")
2320 std::lock_guard<std::mutex> lock(
_mutex);
2326 return errors::FAILED_OPEN_PROJECT;
2331 return errors::FAILED_OPEN_PROJECT;
2333 std::error_code error;
2334 const std::string key =
projectKey(path, error);
2337 log::engineError(
"Cannot resolve project path: %s", error.message().c_str());
2338 return errors::FAILED_OPEN_PROJECT;
2340 bool alreadyOpen =
false;
2342 std::shared_ptr<threads::TaskQueue> queue;
2343 std::optional<bool> newProjectPackageDefault;
2344 bool posted =
false;
2346 std::lock_guard<std::mutex> lock(
_mutex);
2350 return errors::FAILED_OPEN_PROJECT;
2362 if (!alreadyOpen && found !=
_projects.end())
2364 if (found->second.project->isOpen() || found->second.project->isOpening() ||
2378 if (mayCreate &&
_files->isOpen())
2383 log::engineError(
"Cannot create project: application state is unavailable.");
2384 return errors::FAILED_LOAD_STATE;
2387 const F_err result =
state->second->get(
"application.preferences.packageOnClose", value);
2388 if (result != errors::NONE)
2390 log::engineError(
"Cannot create project: application packaging default is invalid.");
2393 newProjectPackageDefault = value;
2400 entry.
project = std::make_shared<ProjectManager>();
2401 entry.
queue = std::make_shared<threads::TaskQueue>();
2402 entry.
logWorker = std::make_shared<ProjectLogWorker>();
2404 queue = entry.
queue;
2406 [worker = entry.
logWorker] { return worker->closeReady.load(); });
2408 _logs.beginOpening(tag);
2424 return target.
closeNow(package, &packaged);
2428 project->setRenameCallback([
this,
project](
const std::filesystem::path& renamed)
2442 posted = queue->post([
this, owned = entry.
project, queue, key, path, choice,
2443 cancelOnDatabaseConflict, mode, newProjectPackageDefault, expectedId]
2445 ProjectManager* project = owned.get();
2446 F_err result = errors::FAILED_OPEN_PROJECT;
2450 const log::ProjectScope tag(openingTag(project));
2451 result = project->open(path, _applicationId, choice, _threads, queue, mode,
2452 newProjectPackageDefault);
2454 if (result == errors::NONE && !expectedId.empty() && project->id() != expectedId)
2456 log::engineError(
"Cannot restore project: saved identity does not match %s.", path.c_str());
2457 project->setLogCloseBarrier(nullptr);
2458 if (project->closeNow(false, nullptr, true) != errors::NONE)
2460 log::engineError(
"Cannot release a project with an unexpected identity.");
2461 if (registerOpenedProject(project) != errors::NONE)
2462 log::engineError(
"Cannot register the unreleased project.");
2464 result = errors::FAILED_OPEN_PROJECT;
2466 if (result == errors::NONE)
2467 result = registerOpenedProject(project);
2468 if (result != errors::NONE && result != errors::DATABASE_CONFLICT && !project->isOpen())
2469 _logs.discardOpening(openingTag(project));
2470 if (result == errors::DATABASE_CONFLICT && cancelOnDatabaseConflict)
2472 if (project->cancelOpen() != errors::NONE)
2473 log::engineError(
"Could not cancel the pending database choice.");
2476 _logs.discardOpening(openingTag(project));
2480 if (result != errors::NONE && result != errors::DATABASE_CONFLICT && !project->isOpen())
2483 catch (
const std::exception& exception)
2486 result = errors::FAILED_OPEN_PROJECT;
2490 std::lock_guard<std::recursive_mutex> lock(
project->_mutex);
2500 std::lock_guard<std::mutex> lock(
_mutex);
2502 current.result = result;
2503 current.remainsOpen =
project->isOpen();
2513 _logs.discardOpening(tag);
2519 catch (
const std::exception&)
2521 const auto registered =
_projects.find(key);
2522 if (registered !=
_projects.end() && registered->second.project == entry.project)
2530 _logs.discardOpening(tag);
2531 entry.queue->shutdown();
2532 entry.logWorker->queue->shutdown();
2534 _threads->join(entry.logWorker->thread);
2542 return errors::PROJECT_ALREADY_OPEN;
2546 log::engineError(
"Cannot open project: project queue is stopped.");
2547 return errors::FAILED_OPEN_PROJECT;
2549 return errors::NONE;
2558 const std::string& path)
2560 std::error_code error;
2561 const std::string key =
projectKey(path, error);
2564 log::engineError(
"Cannot resolve project path: %s", error.message().c_str());
2565 return std::nullopt;
2567 std::lock_guard<std::mutex> lock(
_mutex);
2569 return found ==
_openingStatuses.end() ? std::nullopt : std::optional<OpeningStatus>(found->second);
2579 std::lock_guard<std::mutex> lock(
_mutex);
2590 const std::string& name)
2593 auto entry =
find(name, error);
2594 if (!entry && error == errors::PROJECT_NOT_FOUND)
2595 log::engineError(
"No project is waiting for a database choice: %s", name.c_str());
2596 return entry ? entry->project->databaseCandidates() : std::vector<std::string>();
2607 const std::string& name,
2620 const std::string& name)
2632 const std::string& path)
2634 std::error_code error;
2635 const std::string key =
projectKey(path, error);
2638 log::engineError(
"Cannot resolve project path: %s", error.message().c_str());
2639 return std::nullopt;
2641 std::lock_guard<std::mutex> lock(
_mutex);
2644 : std::optional<OpeningDecisionStatus>(found->second);
2656 const std::string& name)
2658 std::lock_guard<std::mutex> lock(
_mutex);
2660 const auto found =
lookup(name, error);
2661 if (error == errors::PROJECT_AMBIGUOUS)
2662 throw std::invalid_argument(
"Multiple projects have this name; use the full path: " + name);
2663 if (found ==
_projects.end() || !found->second.project->isOpen())
2664 throw std::out_of_range(
"Project is not open: " + name);
2665 return *found->second.project;
2678 const std::shared_ptr<ProjectManager>&
project,
2679 const std::shared_ptr<threads::TaskQueue>& queue,
2680 const std::shared_ptr<ProjectLogWorker>& worker,
2681 const std::string&
id,
2682 std::function<
void(
ProjectManager&,
const std::shared_ptr<threads::TaskQueue>&)> task)
2684 worker->closeReady =
false;
2688 std::lock_guard<std::recursive_mutex> projectLock(
project->_mutex);
2690 worker->closing =
true;
2693 bool closed =
false;
2696 closed =
_logs.closeProject(
id);
2698 catch (
const std::exception& error)
2700 std::fprintf(stderr,
"Cannot close project log: %s\n", error.what());
2705 worker->closing =
false;
2707 worker->closeReady = closed;
2708 if (!queue->post([
project, queue, task] { task(*project, queue); }))
2709 std::fprintf(stderr,
"Cannot finish project close: project queue is stopped.\n");
2711 posted = worker->queue->post([worker,
close = std::move(
close)]
2713 if (worker->renaming)
2714 worker->deferredClose =
close;
2719 worker->closing =
false;
2723 std::fprintf(stderr,
"Cannot close project log: project log worker is stopped.\n");
2738 const std::string& target,
2741 std::function<
void(
ProjectManager&,
const std::shared_ptr<threads::TaskQueue>&)> task,
2744 std::lock_guard<std::mutex> lock(
_mutex);
2758 const std::string& target,
2761 std::function<
void(
ProjectManager&,
const std::shared_ptr<threads::TaskQueue>&)> task,
2766 log::engineError(
"Cannot dispatch project work: shutdown is in progress.");
2767 return errors::FAILED_CLOSE_PROJECT;
2771 std::shared_ptr<ProjectManager>
project;
2772 std::shared_ptr<threads::TaskQueue> queue;
2773 std::shared_ptr<ProjectLogWorker> logWorker;
2774 F_err lookupError = errors::PROJECT_NOT_FOUND;
2778 if (entry.second.project.get() == exact && exact->
isOpen())
2780 project = entry.second.project;
2781 queue = entry.second.queue;
2782 logWorker = entry.second.logWorker;
2786 else if (target.empty() && allowLatest)
2790 if (entry.second.project.get() ==
_openOrder.back())
2792 project = entry.second.project;
2793 queue = entry.second.queue;
2794 logWorker = entry.second.logWorker;
2798 else if (!target.empty())
2800 const auto found =
lookup(target, lookupError);
2801 if (found !=
_projects.end() && found->second.project->isOpen())
2803 project = found->second.project;
2804 queue = found->second.queue;
2805 logWorker = found->second.logWorker;
2807 else if (lookupError == errors::NONE)
2808 lookupError = errors::PROJECT_NOT_FOUND;
2813 lookupError == errors::PROJECT_AMBIGUOUS
2814 ?
"multiple projects have this name; use the full path."
2815 :
"no matching project is open.");
2820 log::engineError(
"Cannot dispatch project task: project is already closing.");
2821 return errors::FAILED_CLOSE_PROJECT;
2827 if (!logWorker ||
id ==
_logIds.end())
2830 return errors::FAILED_CLOSE_PROJECT;
2834 [&
project](
const auto& entry) { return entry.second.project == project; });
2838 return errors::FAILED_CLOSE_PROJECT;
2844 project->_closePending =
true;
2846 std::lock_guard<std::mutex> closeLock(
project->_closeDispatchMutex);
2850 if (!queue->post([
this,
project, queue, logWorker, logId, closing, task = std::move(task)]
2853 queueLogClose(project, queue, logWorker, logId, task);
2855 task(*project, queue);
2861 project->_closePending =
false;
2865 std::lock_guard<std::mutex> closeLock(
project->_closeDispatchMutex);
2869 return errors::FAILED_CLOSE_PROJECT;
2873 return errors::NONE;
2887 if (result != errors::NONE)
2891 false,
_closeAllFailed ? errors::FAILED_CLOSE_PROJECT : errors::NONE};
2904 const std::shared_ptr<threads::TaskQueue>& queue,
2906 bool removeOnSuccess =
false)
2909 std::lock_guard<std::mutex> lock(
_mutex);
2911 project._closePending =
false;
2918 if (result == errors::NONE)
2922 if (removeOnSuccess)
2925 [&
project](
const auto& entry) { return entry.second.project.get() == &project; });
2932 std::fprintf(stderr,
"Cannot retire closed project: it is no longer registered.\n");
2941 std::lock_guard<std::mutex> closeLock(
project._closeDispatchMutex);
2963 const std::shared_ptr<threads::TaskQueue>&
queue;
3007 const std::string& target,
3009 std::function<
void(
const std::string&,
F_err,
bool)> completion,
3011 bool removeOnSuccess =
false)
3015 const std::shared_ptr<threads::TaskQueue>& queue)
3018 const std::string name =
project.name();
3019 bool packaged =
false;
3023 completion(name, result, packaged);
3025 if (result != errors::NONE && completion)
3026 completion(target, result,
false);
3035 void handleProjectMessage(
3044 void announceActiveProject(
3051 void watchProjectOpenings(
3064 out.set_uid(entry.
uid);
3065 out.set_process(
static_cast<ProcessKind
>(entry.
process));
3066 out.set_level(entry.
level);
3067 out.set_thread(entry.
thread);
3068 out.set_project(entry.
project);
3069 out.set_text(entry.
text);
3070 out.set_kind(
static_cast<LogEntryKind
>(entry.
kind));
3071 out.set_destination(
static_cast<ProcessKind
>(entry.
destination));
3073 out.set_ref_uid(entry.
refUid);
3081 void handleLogMessage(
3099 F_err restoreProjects(
3107 std::function<
void(
const ProjectClosingStatuses&)> notifier)
3109 std::lock_guard<std::mutex> lock(
_mutex);
3121 using RenameNotifier = std::function<void(
const std::string&
id,
const std::string& path,
3122 const std::string& name)>;
3131 std::lock_guard<std::mutex> lock(
_mutex);
3141 std::function<
void(
const std::string&)> notifier)
3143 std::lock_guard<std::mutex> lock(
_mutex);
3153 std::function<
void(
const std::string& name,
const std::string&
id,
F_err result,
bool packaged,
3154 const std::string& path)> notifier)
3156 std::lock_guard<std::mutex> lock(
_mutex);
3166 std::function<
void(
const std::string&
openingTag,
const std::string&
id)> notifier)
3168 std::lock_guard<std::mutex> lock(
_mutex);
3180 const std::string& target,
3182 std::function<
void(
const std::string&,
F_err,
bool)> completion)
3186 return project.closeNow(package, &packaged);
3187 }, std::move(completion));
3197 const std::string& name)
3200 std::shared_ptr<ProjectManager>
project;
3202 std::lock_guard<std::mutex> lock(
_mutex);
3204 auto found =
lookup(name, error);
3205 if (found ==
_projects.end() && error == errors::PROJECT_NOT_FOUND)
3206 found =
lookup(name, error,
true);
3209 log::engineError(
"Cannot close project: project is not open: %s", name.c_str());
3210 return error == errors::PROJECT_AMBIGUOUS ? error : errors::FAILED_CLOSE_PROJECT;
3212 project = found->second.project;
3215 log::engineError(
"Cannot close project: project is already closing or opening.");
3216 return errors::FAILED_CLOSE_PROJECT;
3225 return errors::NONE;
3230 return target.
closeNow(
false, &packaged);
3240 const std::string& name)
3242 if (name.empty() || name.find(
'\0') != std::string::npos)
3244 log::engineError(
"Cannot read project close status: invalid project name.");
3245 return std::nullopt;
3247 std::filesystem::path input(name);
3248 std::lock_guard<std::mutex> lock(
_mutex);
3249 if (input.is_absolute() || input.has_parent_path())
3251 std::error_code error;
3255 log::engineError(
"Cannot resolve project path: %s", error.message().c_str());
3256 return std::nullopt;
3260 : std::optional<ProjectManager::CloseStatus>(found->second);
3262 if (input.extension() ==
".fry")
3263 input.replace_extension();
3267 if (std::filesystem::path(entry.first).filename() != input)
3271 log::engineError(
"Multiple close statuses match %s; use the full path.", name.c_str());
3272 return std::nullopt;
3274 match = &entry.second;
3276 return match ? std::optional<ProjectManager::CloseStatus>(*match) : std::nullopt;
3287 std::lock_guard<std::mutex> lock(
_mutex);
3294 if (entry.second.project->isOpen() ||
_closingProjects.count(entry.second.project.get()))
3299 return errors::NONE;
3302 bool rejected =
false;
3305 auto project = entry.second.project;
3309 [
this](
ProjectManager& target,
const std::shared_ptr<threads::TaskQueue>& queue)
3315 if (queued != errors::NONE)
3321 return rejected ? errors::FAILED_CLOSE_PROJECT : errors::NONE;
3330 std::lock_guard<std::mutex> lock(
_mutex);
F_err set(const std::string &key, const T &value)
Writes a value in the default application state namespace.
bool postApplication(std::function< void()> task)
Posts work to the application thread without waiting for it.
void queueConsoleEntry(const logs::Entry &entry, ipc::IPCManager &ipc, bool includeLoading=true)
Queues a prepared entry for Console delivery independently of persistence.
Projects _projects
Project entries keyed by canonical working path; guarded by _mutex.
std::optional< ProjectManager::CloseStatus > _closeAllStatus
Latest aggregate close state; guarded by _mutex.
F_err enqueueProjectTask(const std::string &target, bool allowLatest, bool closing, std::function< void(ProjectManager &, const std::shared_ptr< threads::TaskQueue > &)> task, ProjectManager *exact=nullptr)
Finds an open project and posts work to its queue under _mutex.
void finishCloseAllMemberLocked(ProjectManager *project, F_err result)
Records an aggregate member's result while holding _mutex.
void attachLog(ProjectManager *project)
Registers queued project-log rename coordination after opening. Call without holding _mutex because t...
F_err openApplicationState(const std::filesystem::path &directory)
Opens the application directory and its default state namespace.
std::unordered_map< std::string, std::unique_ptr< state::StateManager > > _states
Open application state namespaces, guarded by _mutex.
void notifyRenameFailure(const std::string &id)
Reports an asynchronous rename failure without holding the manager mutex.
F_err closeProject(const std::string &name)
Queues a project close and removes its registry entry on success. Retired workers are joined later,...
void cancelPrompts(const std::string &reason, bool closing=false)
Completes outstanding prompts as dismissed with an error under _promptMutex.
static std::string openingTag(const ProjectManager *project)
Creates the temporary log tag used while a project opens.
void captureShutdownSessionLocked()
Captures open project identities and paths before shutdown starts closing them. Caller holds _mutex a...
void shutdown()
Requests shutdown without waiting for project work or worker termination.
static FrayManager * _acceptedApplicationTask
Identifies application work accepted before shutdown on its worker thread.
F_err reserveProjectIdentity(ProjectManager *project)
Reserves a unique identity and updates a copied project's persisted identity if necessary....
F_err queueOpeningDecision(const std::string &name, OpeningDecision action, const DatabaseChoice &choice, bool shutdownAction=false)
Queues a database-choice action and records its result locally.
threads::ThreadManager * _threads
Non-owning pointer to the owned or externally supplied thread manager.
std::vector< std::string > databaseCandidates(const std::string &name)
Lists candidate databases for an opening project.
bool consoleStopped() const
Returns whether the Console delivery worker has finished its local queue.
std::filesystem::path applicationStatePath()
Returns the currently open application database path.
std::atomic< bool > _consoleStopping
Whether new Console deliveries are disabled during final local teardown.
bool isActiveProjectLocked(const ProjectManager *project) const
Tests whether a project is the currently active eligible project. Caller holds _mutex.
void updateShutdownSessionPath(const std::string &id, const std::string &path)
Updates the shutdown snapshot after a queued rename has finished.
void init()
Claims the process-wide manager slot and starts application, log, and Console workers.
F_err close()
Queues all open project closes independently; entries remain registered. Already queued closes are in...
std::shared_ptr< threads::TaskQueue > _applicationQueue
Queue for application-level work, separate from project queues.
F_err switchApplicationStateLocked(const std::filesystem::path &path, bool persist)
Switches to an existing application database while retaining the current one on failure....
std::string logProjectIdentity(const std::string &target)
Resolves a message's project target to its log identity without changing dispatch.
F_err applyApplicationDefaults(state::StateManager &state)
Adds missing application preference defaults without replacing saved values.
std::filesystem::path _applicationDirectory
Engine directory containing the selected-database location file.
std::unordered_map< std::string, OpeningStatus > _openingStatuses
Latest project open for each canonical path, guarded by _mutex.
F_err switchApplicationState(const std::filesystem::path &path)
Selects and persists an existing application database without replacing active state on failure....
void finishProjectClose(ProjectManager &project, const std::shared_ptr< threads::TaskQueue > &queue, F_err result, bool removeOnSuccess=false)
Clears the closing marker and, on success, forgets the project and stops its queue....
std::mutex _mutex
Protects the project registry, ordering, closing state, shutdown state, and notifiers.
std::unordered_map< std::string, std::shared_ptr< ProjectLogWorker > > _projectLogRoutes
Routes project IDs and temporary opening tags to their dedicated workers.
std::shared_ptr< threads::TaskQueue > _logQueue
Serializes application log writes and asynchronous history reads.
void rekey(ProjectManager *project, const std::filesystem::path &path)
Updates the registry and notifies listeners after a project rename. Takes _mutex, retains a colliding...
threads::ThreadManager::Id _logThread
Worker for application log writes and history reads.
F_err resolveDatabase(const std::string &name, const DatabaseChoice &choice)
Queues a database choice on the project thread. Inspect openingDecisionStatus() for its eventual resu...
ProjectClosingStatuses closingStatusesLocked()
Builds the pending-close snapshot without taking a project lock. Caller holds _mutex,...
std::function< void(const std::string &id, const std::string &path, const std::string &name)> _renameNotifier
Rename callback receiving project ID, canonical path key, and name; guarded by _mutex.
std::optional< ProjectManager::CloseStatus > closeStatus(const std::string &name)
Reads the latest project close state, including after registry removal.
static std::string projectKey(const std::string &path, std::error_code &error)
Canonicalizes a project path, removing a .fry extension.
F_err validateApplicationState(state::StateManager &state)
Verifies that an existing state table is an application database.
FrayManager(threads::ThreadManager &threads, const std::string &applicationId="Fray")
Constructs a manager using an externally owned thread manager.
void setOpeningNotifier(std::function< void(const OpeningStatus &)> notifier)
Installs a publisher for completed project-open states.
logs::LogStore & logStore()
Returns the manager-owned log store by reference.
std::unordered_map< ProjectManager *, ShutdownEntry > _shutdownEntries
void requestShutdown()
Starts or retries Engine-owned shutdown without joining any worker. Previously accepted application w...
void retainRetiredLocked(Entry entry)
Stops an entry's queues and retains it until its workers can safely be joined. Caller holds _mutex; n...
ProjectSession _shutdownSession
Shutdown snapshot and capture state; guarded by _mutex.
ShutdownPhase
Progress of an Engine-owned shutdown request.
std::uint64_t _closingRevision
Revision of the pending-close snapshot, guarded by _mutex.
std::unordered_set< ProjectManager * > _closeAllProjects
Projects still included in the active aggregate close; guarded by _mutex.
void recordLogEntry(logs::Entry entry, ipc::IPCManager *ipc, bool includeLoading=true)
Identifies a log entry and submits it independently to Console and persistence. Application writes ar...
console::EntryList _consoleEntries
Console entries the Engine owns; only the Console worker changes them.
logs::LogStore _logs
Store for engine and project log entries.
F_err validateApplicationPreferences(state::StateManager &state)
Validates the types of saved application preferences that are present.
std::optional< Entry > find(const std::string &name, F_err &error, bool includeClosed=false)
Looks up and copies an entry under _mutex.
void requestCloseProject(const std::string &target, bool package, std::function< void(const std::string &, F_err, bool)> completion)
Queues a project close without waiting for completion.
F_err resetApplicationPreferences()
Resets only application preference values in one database transaction.
void recordEngineLog(const char *level, F_long thread, const std::string &project, const char *text, ipc::IPCManager *ipc, std::uint64_t arrivedUs=0, bool consoleVisible=true)
Prepares an Engine log line and independently queues Console delivery and persistence.
std::optional< OpeningDecisionStatus > openingDecisionStatus(const std::string &path)
Reads the latest queued database-choice action for a project path. The result remains available after...
F_err openProject(const std::string &path, files::ConflictChoice choice=files::ConflictChoice::Ask, bool cancelOnDatabaseConflict=false, files::OpenMode mode=files::OpenMode::OpenOrCreate, std::optional< OpeningOrigin > origin=std::nullopt, std::optional< std::size_t > restoreOrder=std::nullopt, const std::string &expectedId="")
Queues a project open on its own worker.
void forgetProject(ProjectManager *project)
Removes a project from open order and closes its tracked log. Caller holds _mutex; this does not remo...
OpeningDecision
The queued action applied to a project's database choice.
F_err registerOpenedProject(ProjectManager *project)
Reserves identity and registers a successfully opened project.
void publishClosingLocked()
Publishes the current pending-close snapshot while holding _mutex.
bool _closeAllFailed
Whether an aggregate close member failed; guarded by _mutex.
std::unordered_map< std::string, ProjectManager::CloseStatus > _closeStatuses
Latest close state by project path, retained after removal; guarded by _mutex.
std::unordered_map< std::string, Entry > Projects
Registry mapping canonical project path keys to owned project entries.
void finishLogRename(const std::string &id, const std::shared_ptr< ProjectLogWorker > &worker, const std::shared_ptr< threads::TaskQueue > &queue, const std::shared_ptr< ProjectManager > &project, const std::filesystem::path &folder, F_err result)
Resumes logging and releases any close deferred behind a rename on the log worker.
threads::ThreadManager::Id _applicationThread
Identifier of the application queue worker.
bool _promptClosing
Rejects new prompts after closing begins; guarded by _promptMutex.
std::vector< Entry > _retiredProjects
Closed project workers retained until they have both stopped; guarded by _mutex.
std::mutex _promptMutex
Protects pending prompts and prompt shutdown state.
ShutdownPhase _shutdownPhase
Shutdown state and project ownership; guarded by _mutex.
F_err loadButtonStyle(const std::string &defaults, std::string &css)
Loads the Engine-owned application button stylesheet.
std::optional< ProjectManager::CloseStatus > closeAllStatus()
Reads the latest aggregate close state.
void recordOpen(ProjectManager *project)
Records an open project, opens its log, and resolves its opening tag. Opens and flushes the project l...
void setLogResolvedNotifier(std::function< void(const std::string &openingTag, const std::string &id)> notifier)
Installs the opening-log resolution callback under _mutex unless the manager is marked shut down.
std::unordered_map< ProjectManager *, std::string > _logIds
Maps non-owning project pointers to their open log IDs; guarded by _mutex.
void queueLogClose(const std::shared_ptr< ProjectManager > &project, const std::shared_ptr< threads::TaskQueue > &queue, const std::shared_ptr< ProjectLogWorker > &worker, const std::string &id, std::function< void(ProjectManager &, const std::shared_ptr< threads::TaskQueue > &)> task)
Closes the project log on its worker, then returns close work to the project queue.
bool _shutdownSessionCaptured
std::unordered_set< ProjectManager * > _closingProjects
Non-owning projects with a queued close in progress; guarded by _mutex.
std::function< void(const OpeningStatus &)> _openingNotifier
Publisher for opening state changes, guarded by _mutex.
std::function< void(const std::string &name, const std::string &id, F_err result, bool packaged, const std::string &path)> _shutdownCloseNotifier
Callback reporting a project closed by shutdown: name, ID, result, whether it was packaged,...
void persistLogEntry(const logs::Entry &entry)
Queues persistence on the project's worker or the application worker.
void setClosingNotifier(std::function< void(const ProjectClosingStatuses &)> notifier)
Installs a nonblocking pending-close snapshot notifier and sends its initial snapshot.
std::function< void(const std::string &id, const std::string &path, const std::string &name)> RenameNotifier
Callback receiving a renamed project's ID, new path key, and name.
static void toProto(const logs::Entry &entry, LogEntry &out)
Copies a stored log entry into its protobuf representation.
void reapRetired()
Joins already-finished retired workers without waiting for active projects. Call outside _mutex and o...
std::uint64_t _activeAnnouncementRevision
Monotonic ordering for active-project announcements; guarded by _mutex.
std::shared_ptr< threads::TaskQueue > _consoleQueue
Queue of Console deliveries; it does not wait for log persistence.
const std::string & applicationId() const
Returns the application identifier by reference.
FrayManager & operator=(const FrayManager &)=delete
Copy assignment is disabled because the manager owns running work.
void stopConsoleDelivery()
Stops and drains Console delivery before its IPC manager is destroyed. Call from the controlling thre...
FrayManager(const std::string &applicationId="Fray")
Constructs a manager with its own thread manager and application worker.
void beginConsoleShutdown()
Stops accepting Console deliveries while allowing its queued work to drain.
std::function< void(const std::string &openingTag, const std::string &id)> _logResolvedNotifier
Callback mapping an opening log tag to a project ID; guarded by _mutex.
void setRenameNotifier(RenameNotifier notifier)
Installs the rename callback under _mutex unless the manager is marked shut down.
std::function< void(const std::string &id)> _renameFailureNotifier
Reports asynchronously failed project renames; guarded by _mutex.
void setShutdownCloseNotifier(std::function< void(const std::string &name, const std::string &id, F_err result, bool packaged, const std::string &path)> notifier)
Installs the callback reporting projects closed by shutdown, under _mutex unless the manager is marke...
std::optional< OpeningStatus > openingStatus(const std::string &path)
Reads the latest project-open state for a folder or archive path.
bool _shutdown
Whether shutdown has progressed past application queue termination; guarded by _mutex.
std::string _applicationId
Application identifier supplied when opening projects.
std::vector< ProjectManager * > _openOrder
Non-owning projects in opening order; guarded by _mutex.
void finishShutdown()
Releases local workers after shutdown is ready. The normal Engine path calls this only after advanceS...
F_err cancelProject(const std::string &name)
Queues cancellation of a pending open and retires it after cancellation. Inspect openingDecisionStatu...
std::unique_ptr< files::FileManager > _files
Application directory and database ownership; state managers detach before this is destroyed.
std::mutex _projectLogsMutex
Protects the opening-tag and project-ID log routes.
void setRenameFailureNotifier(std::function< void(const std::string &)> notifier)
Installs a notifier for asynchronously failed project renames.
Projects::iterator lookup(const std::string &target, F_err &error, bool includeClosed=false)
Looks up a project by path or unique bare name; caller must hold _mutex.
F_err queueProjectClose(const std::string &target, std::function< F_err(ProjectManager &, bool &)> operation, std::function< void(const std::string &, F_err, bool)> completion, ProjectManager *exact=nullptr, bool removeOnSuccess=false)
Queues a close operation; an empty target selects the latest open project. If supplied,...
threads::ThreadManager::Id _consoleThread
Independent worker for forwarding prepared Console entries.
state::StateManager & state(const std::string &name)
Returns a borrowed reference to an open application state namespace.
bool takePromptResponse(uint64_t requestId, PromptResponse &response)
Consumes a completed prompt response under _promptMutex.
static std::atomic< bool > _active
Process-wide guard against multiple live managers.
std::unordered_map< ProjectManager *, std::string > _closeStatusKeys
Original path for each active close, guarded by _mutex.
std::unordered_map< std::string, OpeningDecisionStatus > _openingDecisions
Latest queued database-choice action for each canonical project path, guarded by _mutex.
std::unordered_map< uint64_t, PendingPrompt > _pendingPrompts
Pending prompts indexed by request message ID; guarded by _promptMutex.
void retire(Entry &entry)
Shuts down a project queue and joins its worker. Call outside _mutex and not on the worker being join...
~FrayManager()
Shuts down owned work and releases the process-wide manager slot.
F_err readApplicationPreferences(ApplicationPreferences &output)
Reads an authoritative application preferences snapshot.
F_err saveShutdownSessionLocked()
Writes the captured project session to application state. Caller holds _mutex.
F_err openState(const std::string &name)
Opens an additional application state namespace.
ShutdownPhase advanceShutdown()
Advances shutdown using only local state and nonblocking queue operations. Pending opens,...
std::unique_ptr< threads::ThreadManager > _ownedThreads
Optional owned thread manager used by the standalone constructor.
FrayManager(const FrayManager &)=delete
Copy construction is disabled because the manager owns running work.
ProjectManager & project(const std::string &name)
Returns a non-owning reference to an open project under registry lookup. The reference is valid only ...
F_err saveButtonStyle(const std::string &css)
Saves the Engine-owned application button stylesheet.
std::function< void(const ProjectClosingStatuses &)> _closingNotifier
Queues a snapshot notification; invoked under _mutex and must not block.
F_err enqueueProjectTaskLocked(const std::string &target, bool allowLatest, bool closing, std::function< void(ProjectManager &, const std::shared_ptr< threads::TaskQueue > &)> task, ProjectManager *exact)
Selects and queues project work while the caller holds _mutex.
std::unordered_map< std::string, std::shared_ptr< ProjectLogWorker > > _projectLogPaths
Resolves registered project paths to log workers; guarded by _projectLogsMutex.
ShutdownPhase shutdownPhase()
Reads shutdown progress without advancing it.
F_err get(const std::string &key, T &value)
Reads a value from the default application state namespace.
Owns a project’s files, state stores, watcher and registered threads. Public operations synchronize t...
F_err closeNow(bool forcePackage=false, bool *packaged=nullptr, bool leaveWorkingFolder=false)
Stops watching, closes stores and releases or packages the project under _mutex. Intended for the pro...
std::string id() const
Returns a copy of the persistent project ID under _mutex.
files::FileManager & fileManager()
Returns a borrowed file manager reference; callers must coordinate access and lifetime.
bool isOpen() const
Returns whether the atomic open flag is set.
std::string name() const
Returns a copy of the current project name under _mutex.
static std::string newProjectId()
Generates a hexadecimal project identifier from random-device values.
The Console entries the Engine owns and the Renderer shows, keyed by UID. The UID is the one stamped ...
const std::filesystem::path & archivePath() const
Returns a borrowed reference to the archive path.
const std::filesystem::path & workingDirectory() const
Returns a borrowed reference to the working folder path.
Owns the TCP servers and the threads around them.
Temporarily tag log lines on the calling thread, then restore its previous tag. Construct and destroy...
Persist and query application and project logs across session SQLite files. Project logs use their wo...
Owns a SQLite connection and a typed key/value state table. Database operations serialize on a recurs...
std::vector< std::uint8_t > Binary
Byte sequence stored as a SQLite blob.
Cooperative cancellation shared by every copy of a token. Copies share one state guarded by an intern...
Registry of the engine's threads: starts them, names them, asks them to stop and joins them....
std::uint64_t Id
Handle for a spawned thread; ids start at 1 and are never reused.
F_long F_err
Error return type used across the Engine; the value is a fray::errors::code (0 / NONE means success).
ConflictChoice
Selects how an archive/folder name conflict is resolved. Ask reports a conflict; Archive selects the ...
OpenMode
Selects existence and conflict requirements when opening a project. OpenOrCreate opens or creates; Cr...
std::string & threadProject()
Return the calling thread's project tag; an empty tag denotes the application.
F_void engineError(const F_char *fmt,...)
Log error for Engine.
F_void engineWarn(const F_char *fmt,...)
Log warning for Engine.
F_void engineSession(const std::string &name)
Marks the start of a log session under the calling thread's project tag. The Engine records it as a s...
F_err readApplicationLocation(const std::filesystem::path &directory, std::filesystem::path &result)
Reads the selected application database path, if one has been recorded.
F_err writeApplicationLocation(const std::filesystem::path &directory, const std::filesystem::path &database)
Atomically records the selected application database path.
F_err loadButtonStyle(const std::filesystem::path &engineDirectory, const std::string &defaults, std::string &css)
Reads the application button stylesheet, creating it from packaged defaults if absent.
F_err saveButtonStyle(const std::filesystem::path &engineDirectory, const std::string &css)
Writes the application button stylesheet atomically.
Chooses an existing candidate database or a new database when opening is ambiguous.
Ensures a queued close clears its closing marker even on early exit.
bool active
Whether close completion still needs to be recorded.
~CloseTaskGuard()
Finishes an active close according to whether the project remains open.
void finish(F_err result)
Records the close result once and disarms the guard.
FrayManager & manager
Non-owning manager that tracks the close.
ProjectManager & project
Non-owning project being closed.
bool removeOnSuccess
Whether successful completion removes the registered project.
const std::shared_ptr< threads::TaskQueue > & queue
Non-owning reference to the shared project queue handle.
Associates a project and its queue with its managed worker thread.
std::string path
Most recently registered project path.
std::shared_ptr< threads::TaskQueue > queue
Shared queue serviced by the project thread.
std::shared_ptr< ProjectManager > project
Shared ownership of the project, including while queued tasks run.
std::optional< std::size_t > restoreOrder
Saved opening order for startup restoration, or empty for a user-opened project.
std::string id
Project identity once known.
threads::ThreadManager::Id thread
Identifier of the project worker in the thread manager.
std::shared_ptr< ProjectLogWorker > logWorker
Separate worker for the project's log writes.
Latest database-choice action and its result, once it finishes.
std::optional< F_err > result
Address of the process that requested a project open.
A queued project open and its result, once finished.
std::optional< F_err > result
std::optional< OpeningOrigin > origin
Retains a prompt request and its eventual response until consumed.
bool completed
Whether a response is ready to consume.
PromptRequest request
Original request used to validate the response.
PromptResponse response
Renderer response or locally generated cancellation.
Dedicated queue and worker for one project's log writes.
std::shared_ptr< threads::TaskQueue > queue
Queue draining this project's log writes.
std::function< void()> deferredClose
A close held until the rename has resumed its log session; worker thread only.
threads::ThreadManager::Id thread
Worker identifier in the shared thread manager.
std::string identity
Opening tag or stable ID, guarded by _projectLogsMutex.
bool closing
True once the project session is being closed.
bool renaming
True while log entries are held during a folder rename; worker thread only.
std::vector< logs::Entry > duringOpening
Entries received while the project log session opens; worker thread only.
bool opening
Holds log entries until the project log session is ready; worker thread only.
std::vector< logs::Entry > duringRename
Entries captured while the log connection is suspended; worker thread only.
std::atomic< bool > closeReady
Result of the queued log-close operation.
Project resources retained while shutdown progresses.
bool threadsStopRequested
The latest queued close and its result, once finished.
Rename arguments captured before the log worker suspends its session.
One log line from a process. This store instance assigns arrivedUs as an increasing microsecond times...
std::string project
Project identifier; empty denotes the application.
std::uint64_t operation
Command id of a command or receipt; zero for lines.
std::string text
Log message text.
std::uint64_t arrivedUs
Store-assigned arrival timestamp in microseconds since the Unix epoch.
int destination
Destination process of a command or receipt; zero for lines.
bool consoleVisible
Whether this entry may be delivered to the Console or loading window.
std::string level
Log severity label.
int process
Source process identifier.
int kind
What the row records: 0 line, 1 command, 2 receipt, 3 notification, 4 session start (LogEntryKind).
std::string refUid
For a receipt, the UID of the command it confirms; empty otherwise.
std::string uid
Globally unique lowercase hexadecimal entry identity.
std::uint32_t thread
Source thread identifier.
A parsed incoming message. The payload is a view into the frame, which this keeps alive via shared ow...
int32_t F_long
Signed 32-bit integer (also the base of F_err).
uint32_t F_ulong
Unsigned 32-bit integer.
bool F_bool
Alias for bool.