Fray Engine
Loading...
Searching...
No Matches
fray_manager.hpp
Go to the documentation of this file.
1#ifndef FRAY_MANAGER_HPP
2#define FRAY_MANAGER_HPP
3
4#include <atomic>
5#include <algorithm>
6#include <cstdio>
7#include <filesystem>
8#include <functional>
9#include <memory>
10#include <mutex>
11#include <new>
12#include <optional>
13#include <stdexcept>
14#include <string>
15#include <system_error>
16#include <unordered_map>
17#include <unordered_set>
18#include <vector>
19
20#include "console_list.hpp"
22#include "application_style.hpp"
23#include "log_store.hpp"
24#include "project_manager.hpp"
25#include "thread_manager.hpp"
26#include "fray.pb.h"
27
28namespace fray
29{
30 namespace ipc { class IPCManager; }
31 namespace message { struct InData; }
32
38 {
39 public:
41 enum class OpeningDecision
42 {
45 };
46
49 {
51 std::optional<F_err> result;
52 };
53
56 {
57 ProcessKind sender;
59 std::uint64_t requestId;
61 };
62
65 {
66 std::string path;
67 std::optional<F_err> result;
68 std::optional<OpeningOrigin> origin;
69 bool restoring = false;
70 bool remainsOpen = false;
71 };
72
80
81 private:
86 {
88 std::shared_ptr<threads::TaskQueue> queue = std::make_shared<threads::TaskQueue>();
92 bool closing = false;
94 std::string identity;
96 std::atomic<bool> closeReady{false};
98 bool opening = false;
100 std::vector<logs::Entry> duringOpening;
102 bool renaming = false;
104 std::vector<logs::Entry> duringRename;
106 std::function<void()> deferredClose;
107 };
108
112 struct Entry
113 {
117 std::shared_ptr<ProjectManager> project;
121 std::shared_ptr<threads::TaskQueue> queue;
127 std::shared_ptr<ProjectLogWorker> logWorker;
129 std::string path;
131 std::string id;
133 std::optional<std::size_t> restoreOrder;
134 };
135
138 {
140 bool closeAttempted = false;
141 bool cancelAttempted = false;
143 bool logStopping = false;
144 };
145
149 inline static std::atomic<bool> _active{false};
153 std::string _applicationId;
155 std::filesystem::path _applicationDirectory;
157 std::unique_ptr<files::FileManager> _files = std::make_unique<files::FileManager>();
159 std::unordered_map<std::string, std::unique_ptr<state::StateManager>> _states;
163 std::unique_ptr<threads::ThreadManager> _ownedThreads;
175 std::shared_ptr<threads::TaskQueue> _applicationQueue = std::make_shared<threads::TaskQueue>();
179 std::shared_ptr<threads::TaskQueue> _consoleQueue = std::make_shared<threads::TaskQueue>();
183 std::atomic<bool> _consoleStopping{false};
187 std::shared_ptr<threads::TaskQueue> _logQueue = std::make_shared<threads::TaskQueue>();
191 std::unordered_map<std::string, std::shared_ptr<ProjectLogWorker>> _projectLogRoutes;
193 std::unordered_map<std::string, std::shared_ptr<ProjectLogWorker>> _projectLogPaths;
197 bool _shutdown = false; // guarded by _mutex
200 std::unordered_map<ProjectManager*, ShutdownEntry> _shutdownEntries;
202 ProjectSession _shutdownSession;
207 inline static thread_local FrayManager* _acceptedApplicationTask = nullptr;
211 std::mutex _mutex;
215 std::function<void(const std::string& id, const std::string& path, const std::string& name)> _renameNotifier;
217 std::function<void(const std::string& id)> _renameFailureNotifier;
221 std::function<void(const std::string& openingTag, const std::string& id)> _logResolvedNotifier;
225 std::function<void(const std::string& name, const std::string& id, F_err result, bool packaged,
226 const std::string& path)> _shutdownCloseNotifier;
230 using Projects = std::unordered_map<std::string, Entry>;
236 std::unordered_map<std::string, OpeningDecisionStatus> _openingDecisions;
238 std::unordered_map<std::string, OpeningStatus> _openingStatuses;
240 std::function<void(const OpeningStatus&)> _openingNotifier;
242 std::vector<Entry> _retiredProjects;
246 std::vector<ProjectManager*> _openOrder;
250 std::unordered_set<ProjectManager*> _closingProjects;
252 std::unordered_map<std::string, ProjectManager::CloseStatus> _closeStatuses;
254 std::unordered_map<ProjectManager*, std::string> _closeStatusKeys;
256 std::optional<ProjectManager::CloseStatus> _closeAllStatus;
258 std::unordered_set<ProjectManager*> _closeAllProjects;
260 bool _closeAllFailed = false;
262 std::uint64_t _closingRevision = 0;
264 std::function<void(const ProjectClosingStatuses&)> _closingNotifier;
272 std::unordered_map<ProjectManager*, std::string> _logIds;
273
279 ProjectClosingStatuses closingStatusesLocked()
280 {
281 ProjectClosingStatuses statuses;
282 statuses.set_revision(_closingRevision);
283 for (const auto& entry : _projects)
284 {
285 if (!_closingProjects.count(entry.second.project.get()))
286 continue;
287 if (_shutdownEntries.count(entry.second.project.get()))
288 continue;
289 const auto id = _logIds.find(entry.second.project.get());
290 if (id == _logIds.end())
291 {
292 std::fprintf(stderr, "Cannot report closing project: project identity is unavailable.\n");
293 continue;
294 }
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());
299 }
300 for (const auto& item : _shutdownEntries)
301 {
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());
307 }
308 return statuses;
309 }
310
318
322 {
326 PromptRequest request;
330 PromptResponse response;
334 bool completed = false;
335 };
336
339 std::mutex _promptMutex;
343 std::unordered_map<uint64_t, PendingPrompt> _pendingPrompts;
347 bool _promptClosing = false;
348
355 static std::string projectKey(
356 const std::string& path,
357 std::error_code& error)
358 {
359 if (path.empty() || path.find('\0') != std::string::npos)
360 {
361 error = std::make_error_code(std::errc::invalid_argument);
362 return {};
363 }
364 auto resolved = std::filesystem::weakly_canonical(path, error);
365 if (error)
366 return {};
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();
372 }
373
380 const std::string& target)
381 {
382 if (target.empty())
383 return target;
384 {
385 std::lock_guard<std::mutex> lock(_projectLogsMutex);
386 if (_projectLogRoutes.count(target))
387 return target;
388 const auto path = _projectLogPaths.find(target);
389 if (path != _projectLogPaths.end())
390 return path->second->identity;
391 }
392
393 const std::filesystem::path input(target);
394 std::string key;
395 if (input.is_absolute() || input.has_parent_path())
396 {
397 std::error_code error;
398 key = projectKey(target, error);
399 if (error)
400 {
401 std::fprintf(stderr, "Cannot resolve project log target %s: %s.\n",
402 target.c_str(), error.message().c_str());
403 return target;
404 }
405 }
406
407 std::string identity;
408 bool ambiguous = false;
409 {
410 std::lock_guard<std::mutex> lock(_projectLogsMutex);
411 for (const auto& item : _projectLogPaths)
412 {
413 if ((!key.empty() && item.first != key) ||
414 (key.empty() && std::filesystem::path(item.first).filename() != input))
415 continue;
416 if (!identity.empty())
417 {
418 ambiguous = true;
419 break;
420 }
421 identity = item.second->identity;
422 }
423 }
424 if (!identity.empty() && !ambiguous)
425 return identity;
426 std::fprintf(stderr, "Cannot resolve project log target %s%s; using the application log.\n",
427 target.c_str(), ambiguous ? " (ambiguous)" : "");
428 return target;
429 }
430
438 Projects::iterator lookup(
439 const std::string& target,
440 F_err& error,
441 bool includeClosed = false)
442 {
443 error = errors::PROJECT_NOT_FOUND;
444 const std::filesystem::path input(target);
445 if (input.is_absolute() || input.has_parent_path())
446 {
447 std::error_code pathError;
448 const std::string key = projectKey(target, pathError);
449 if (pathError)
450 {
451 log::engineError("Cannot resolve project path: %s", pathError.message().c_str());
452 return _projects.end();
453 }
454 auto found = _projects.find(key);
455 if (found != _projects.end() &&
456 (includeClosed || found->second.project->isOpen() || found->second.project->isOpening()))
457 {
458 error = errors::NONE;
459 return found;
460 }
461 return _projects.end();
462 }
463 auto match = _projects.end();
464 for (auto it = _projects.begin(); it != _projects.end(); ++it)
465 {
466 if (std::filesystem::path(it->first).filename() != input ||
467 (!includeClosed && !it->second.project->isOpen() && !it->second.project->isOpening()))
468 continue;
469 if (match != _projects.end())
470 {
471 error = errors::PROJECT_AMBIGUOUS;
472 log::engineError("Multiple projects are named %s; use the full path.", target.c_str());
473 return _projects.end();
474 }
475 match = it;
476 }
477 if (match != _projects.end())
478 error = errors::NONE;
479 return match;
480 }
481
489 std::optional<Entry> find(
490 const std::string& name,
491 F_err& error,
492 bool includeClosed = false)
493 {
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);
497 }
498
508 const std::string& name,
509 OpeningDecision action,
510 const DatabaseChoice& choice,
511 bool shutdownAction = false)
512 {
513 std::lock_guard<std::mutex> lock(_mutex);
514 if (_shutdown || (_shutdownPhase != ShutdownPhase::running && !shutdownAction &&
516 {
517 log::engineError("Cannot change a database choice: the Engine is shutting down.");
518 return errors::FAILED_OPEN_PROJECT;
519 }
520 F_err error;
521 const auto found = lookup(name, error);
522 if (found == _projects.end() || !found->second.project->isOpening())
523 {
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;
526 }
527 const std::string key = found->first;
528 const auto previous = _openingDecisions.find(key);
529 if (previous != _openingDecisions.end() && !previous->second.result)
530 {
531 log::engineError("A database-choice action is already queued: %s", name.c_str());
532 return errors::FAILED_OPEN_PROJECT;
533 }
534 const auto project = found->second.project;
535 const auto queue = found->second.queue;
536 _openingDecisions.insert_or_assign(key, OpeningDecisionStatus{action, std::nullopt});
537 if (!queue->post([this, key, project, queue, action, choice]
538 {
539 F_err result = errors::FAILED_OPEN_PROJECT;
540 const std::string tag = openingTag(project.get());
541 try
542 {
543 const log::ProjectScope scope(tag);
544 if (action == OpeningDecision::resolve)
545 {
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())
550 {
551 _logs.discardOpening(tag);
552 queue->shutdown();
553 }
554 }
555 else
556 {
557 result = project->cancelOpen();
558 if (result == errors::NONE)
559 {
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)
564 {
565 log::engineError("Cannot remove project: it is no longer registered.");
566 result = errors::FAILED_OPEN_PROJECT;
567 }
568 else
569 {
570 forgetProject(project.get());
571 retainRetiredLocked(std::move(found->second));
572 _projects.erase(found);
573 }
574 }
575 }
576 }
577 catch (const std::exception& exception)
578 {
579 log::engineError("Database-choice action failed: %s", exception.what());
580 result = errors::FAILED_OPEN_PROJECT;
581 }
582 if (result != errors::NONE)
583 log::engineError("Database-choice action failed for %s (error %lld).",
584 key.c_str(), static_cast<long long>(result));
585 std::lock_guard<std::mutex> lock(_mutex);
586 _openingDecisions.at(key).result = result;
587 }))
588 {
589 _openingDecisions.at(key).result = errors::FAILED_OPEN_PROJECT;
590 log::engineError("Cannot change a database choice: the project queue is stopped.");
591 return errors::FAILED_OPEN_PROJECT;
592 }
593 return errors::NONE;
594 }
595
601 void retire(
602 Entry& entry)
603 {
604 entry.queue->shutdown();
605 _threads->join(entry.thread);
606 if (entry.logWorker)
607 {
608 {
609 std::lock_guard<std::mutex> lock(_projectLogsMutex);
610 for (auto it = _projectLogRoutes.begin(); it != _projectLogRoutes.end();)
611 if (it->second == entry.logWorker)
612 it = _projectLogRoutes.erase(it);
613 else
614 ++it;
615 for (auto it = _projectLogPaths.begin(); it != _projectLogPaths.end();)
616 if (it->second == entry.logWorker)
617 it = _projectLogPaths.erase(it);
618 else
619 ++it;
620 }
621 entry.logWorker->queue->shutdown();
622 _threads->join(entry.logWorker->thread);
623 }
624 }
625
632 Entry entry)
633 {
634 entry.queue->shutdown();
635 if (entry.logWorker)
636 entry.logWorker->queue->shutdown();
637 _retiredProjects.push_back(std::move(entry));
638 }
639
645 {
646 std::vector<Entry> readyEntries;
647 {
648 std::lock_guard<std::mutex> lock(_mutex);
649 for (auto it = _retiredProjects.begin(); it != _retiredProjects.end();)
650 {
651 if (_threads->running(it->thread) ||
652 (it->logWorker && _threads->running(it->logWorker->thread)))
653 {
654 ++it;
655 continue;
656 }
657 readyEntries.push_back(std::move(*it));
658 it = _retiredProjects.erase(it);
659 }
660 }
661 for (auto& entry : readyEntries)
662 retire(entry);
663 }
664
672 {
673 _openOrder.erase(std::remove(_openOrder.begin(), _openOrder.end(), project), _openOrder.end());
674 const auto logged = _logIds.find(project);
675 if (logged != _logIds.end())
676 {
677 _logs.closeProject(logged->second);
678 _logIds.erase(logged);
679 }
680 }
681
689 const ProjectManager* project) const
690 {
691 for (auto active = _openOrder.rbegin(); active != _openOrder.rend(); ++active)
692 if ((*active)->isOpen() && !_closingProjects.count(*active))
693 return *active == project;
694 return false;
695 }
696
703 {
704 const auto found = _states.find("Fray");
705 if (!_files->isOpen() || found == _states.end() || !found->second->isOpen())
706 return errors::FAILED_SAVE_STATE;
707 const std::string bytes = _shutdownSession.SerializeAsString();
708 return found->second->set("application.session.lastOpenProjects",
709 state::StateManager::Binary(bytes.begin(), bytes.end()));
710 }
711
717 {
719 if (!_files->isOpen())
720 return;
721 _shutdownSession.Clear();
722 for (auto* project : _openOrder)
723 {
724 if (!project->isOpen() || _closingProjects.count(project))
725 continue;
726 const auto found = std::find_if(_projects.begin(), _projects.end(),
727 [project](const auto& entry) { return entry.second.project.get() == project; });
728 if (found == _projects.end() || found->second.id.empty())
729 continue;
730 auto* saved = _shutdownSession.add_projects();
731 saved->set_id(found->second.id);
732 saved->set_path(found->second.path);
733 _shutdownSession.set_active_id(found->second.id);
734 }
735 if (saveShutdownSessionLocked() != errors::NONE)
736 log::engineError("Cannot save the open-project session.");
737 }
738
745 const std::string& id,
746 const std::string& path)
747 {
748 std::lock_guard<std::mutex> lock(_mutex);
749 if (!_shutdownSessionCaptured || !_files->isOpen())
750 return;
751 for (auto& project : *_shutdownSession.mutable_projects())
752 if (project.id() == id && project.path() != path)
753 {
754 project.set_path(path);
755 if (saveShutdownSessionLocked() != errors::NONE)
756 log::engineError("Cannot update the open-project session after a rename.");
757 return;
758 }
759 }
760
766 static std::string openingTag(
767 const ProjectManager* project)
768 {
769 return "opening:" + std::to_string(reinterpret_cast<std::uintptr_t>(project));
770 }
771
777 const std::string& id)
778 {
779 std::function<void(const std::string&)> notifier;
780 {
781 std::lock_guard<std::mutex> lock(_mutex);
782 notifier = _renameFailureNotifier;
783 }
784 if (notifier)
785 notifier(id);
786 }
787
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,
803 F_err result)
804 {
805 bool resumed = false;
806 try
807 {
808 resumed = _logs.moveProject(id, folder);
809 }
810 catch (const std::exception& error)
811 {
812 std::fprintf(stderr, "Cannot resume project log after rename: %s\n", error.what());
813 }
814 if (!resumed)
815 result = errors::FAILED_RENAME_PROJECT;
816 for (const auto& entry : worker->duringRename)
817 try
818 {
819 if (resumed)
820 _logs.persist(entry);
821 else
822 _logs.persistApplication(entry);
823 }
824 catch (const std::exception& error)
825 {
826 std::fprintf(stderr, "Cannot store log entry after rename: %s\n", error.what());
827 result = errors::FAILED_RENAME_PROJECT;
828 }
829 worker->duringRename.clear();
830 worker->renaming = false;
831 project->finishRename(result);
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);
837 if (close)
838 close();
839 }
840
848 {
849 const auto id = project->id();
850 std::shared_ptr<ProjectLogWorker> worker;
851 std::shared_ptr<threads::TaskQueue> queue;
852 std::weak_ptr<ProjectManager> owned;
853 {
854 std::lock_guard<std::mutex> lock(_mutex);
855 const auto found = std::find_if(_projects.begin(), _projects.end(),
856 [project](const auto& entry) { return entry.second.project.get() == project; });
857 if (found == _projects.end() || !found->second.logWorker)
858 {
859 std::fprintf(stderr, "Cannot attach project log: project worker is unavailable.\n");
860 return;
861 }
862 worker = found->second.logWorker;
863 queue = found->second.queue;
864 owned = found->second.project;
865 }
866 std::lock_guard<std::recursive_mutex> projectLock(project->_mutex);
867 project->_renameDispatcher = [this, id, worker, queue, owned](ProjectManager::RenameRequest request)
868 {
869 const auto project = owned.lock();
870 if (!project)
871 return false;
872 std::lock_guard<std::mutex> lock(_projectLogsMutex);
873 if (worker->closing)
874 return false;
875 return worker->queue->post([this, id, worker, queue, project, request = std::move(request)]
876 {
877 worker->renaming = true;
878 bool suspended = false;
879 try
880 {
881 suspended = _logs.suspendProject(id);
882 }
883 catch (const std::exception& error)
884 {
885 std::fprintf(stderr, "Cannot suspend project log: %s\n", error.what());
886 }
887 if (!suspended)
888 {
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");
895 return;
896 }
897 if (!queue->post([this, id, worker, queue, project, request]
898 {
899 F_err result = errors::FAILED_RENAME_PROJECT;
900 std::filesystem::path folder;
901 {
902 std::lock_guard<std::recursive_mutex> lock(project->_mutex);
903 const log::ProjectScope tag(project->_projectId);
904 try
905 {
906 const auto current = project->refreshRenameRequest(request);
907 result = project->applyName(current.name, current.workspace,
908 current.renameFolder, current.databaseStem);
909 }
910 catch (const std::exception& error)
911 {
912 log::engineError("Cannot rename project: %s", error.what());
913 }
914 folder = project->_files.workingDirectory();
915 }
916 if (!worker->queue->post([this, id, worker, queue, project, folder, result]
917 {
918 finishLogRename(id, worker, queue, project, folder, result);
919 }))
920 {
921 project->finishRename(errors::FAILED_RENAME_PROJECT);
922 notifyRenameFailure(id);
923 std::fprintf(stderr, "Cannot resume project log: log worker is stopped.\n");
924 }
925 }))
926 {
927 finishLogRename(id, worker, queue, project, request.workspace,
928 errors::FAILED_RENAME_PROJECT);
929 std::fprintf(stderr, "Cannot finish project rename: project queue is stopped.\n");
930 }
931 });
932 };
933 }
934
943 {
944 const std::string original = project->id();
945 if (original.empty())
946 {
947 log::engineError("Cannot register a project with an empty identity.");
948 return errors::FAILED_OPEN_PROJECT;
949 }
950 std::string reserved;
951 for (;;)
952 {
953 const std::string candidate = ProjectManager::newProjectId();
954 std::lock_guard<std::mutex> lock(_mutex);
955 const auto found = std::find_if(_projects.begin(), _projects.end(),
956 [project](const auto& entry) { return entry.second.project.get() == project; });
957 if (found == _projects.end() || !project->isOpen())
958 {
959 log::engineError("Cannot reserve identity for an unregistered project.");
960 return errors::FAILED_OPEN_PROJECT;
961 }
962 const auto used = [this, project](const std::string& id)
963 {
964 return std::any_of(_projects.begin(), _projects.end(),
965 [project, &id](const auto& entry)
966 { return entry.second.project.get() != project && entry.second.project->isOpen() &&
967 entry.second.id == id; });
968 };
969 if (!used(original))
970 reserved = original;
971 else if (!used(candidate))
972 reserved = candidate;
973 else
974 continue;
975 found->second.id = reserved;
976 break;
977 }
978 if (reserved == original)
979 return errors::NONE;
980 const F_err result = project->reassignProjectId(reserved);
981 if (result != errors::NONE)
982 {
983 std::lock_guard<std::mutex> lock(_mutex);
984 const auto found = std::find_if(_projects.begin(), _projects.end(),
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();
988 log::engineError("Cannot assign a unique identity to a copied project.");
989 return result;
990 }
991 log::engineWarn("A copied project had a duplicate identity; a new identity was assigned.");
992 return errors::NONE;
993 }
994
1002 {
1003 const F_err result = reserveProjectIdentity(project);
1004 if (result != errors::NONE)
1005 {
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.");
1009 return result;
1010 }
1012 log::threadProject() = project->id();
1014 return errors::NONE;
1015 }
1016
1025 {
1026 // The project's id and folder are read before taking _mutex, because the project can call back into it.
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;
1031 {
1032 std::lock_guard<std::mutex> lock(_mutex);
1033 const auto found = std::find_if(_projects.begin(), _projects.end(),
1034 [project](const auto& entry) { return entry.second.project.get() == project; });
1035 if (found == _projects.end() || !project->isOpen())
1036 return;
1038 if (found->second.restoreOrder)
1039 {
1040 const auto position = std::find_if(_openOrder.begin(), _openOrder.end(),
1041 [this, &found](ProjectManager* other)
1042 {
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;
1047 });
1048 _openOrder.insert(position, project);
1049 }
1050 else
1051 _openOrder.push_back(project);
1052 found->second.id = id;
1053 if (!id.empty())
1054 {
1055 std::lock_guard<std::mutex> logLock(_projectLogsMutex);
1056 worker = found->second.logWorker;
1057 if (!worker->queue->post([worker] { worker->opening = true; }))
1058 {
1059 throw std::runtime_error("Cannot queue project log opening: project log worker is shutting down.");
1060 }
1061 _logIds[project] = id;
1062 worker->identity = id;
1063 _projectLogRoutes[id] = worker;
1064 resolved = _logResolvedNotifier;
1065 }
1066 }
1067 if (worker)
1068 {
1069 try
1070 {
1071 _logs.openProject(id, folder, openingTag(project));
1072 }
1073 catch (...)
1074 {
1075 if (!worker->queue->post([this, worker, id, tag = openingTag(project)]
1076 {
1077 try
1078 {
1079 _logs.discardOpening(tag);
1080 }
1081 catch (const std::exception& error)
1082 {
1083 std::fprintf(stderr, "Cannot discard opening logs: %s\n", error.what());
1084 }
1085 for (const auto& entry : worker->duringOpening)
1086 {
1087 try
1088 {
1089 auto fallback = entry;
1090 if (fallback.project == tag)
1091 fallback.project = id;
1092 _logs.persistApplication(fallback);
1093 }
1094 catch (const std::exception& error)
1095 {
1096 std::fprintf(stderr, "Cannot store buffered project log: %s\n", error.what());
1097 }
1098 }
1099 worker->duringOpening.clear();
1100 worker->opening = false;
1101 }))
1102 std::fprintf(stderr, "Cannot release buffered project logs: project log worker is shutting down.\n");
1103 throw;
1104 }
1105 if (!worker->queue->post([this, worker]
1106 {
1107 for (const auto& entry : worker->duringOpening)
1108 {
1109 try
1110 {
1111 _logs.persist(entry);
1112 }
1113 catch (const std::exception& error)
1114 {
1115 std::fprintf(stderr, "Cannot store buffered project log: %s\n", error.what());
1116 }
1117 }
1118 worker->duringOpening.clear();
1119 worker->opening = false;
1120 }))
1121 std::fprintf(stderr, "Cannot release buffered project logs: project log worker is shutting down.\n");
1122 }
1123 if (resolved)
1124 resolved(openingTag(project), id);
1125 }
1126
1133 void rekey(
1135 const std::filesystem::path& path)
1136 {
1137 std::error_code error;
1138 const std::string key = projectKey(path.string(), error);
1139 if (error)
1140 {
1141 log::engineError("Cannot update renamed project path: %s", error.message().c_str());
1142 return;
1143 }
1144 {
1145 std::lock_guard<std::mutex> lock(_mutex);
1146 auto found = std::find_if(_projects.begin(), _projects.end(),
1147 [project](const auto& entry) { return entry.second.project.get() == project; });
1148 if (found == _projects.end() || found->first == key)
1149 return;
1150 const auto collision = _projects.find(key);
1151 if (collision != _projects.end())
1152 {
1153 if (collision->second.project->isOpen() || collision->second.project->isOpening())
1154 {
1155 log::engineError("Cannot register renamed project: %s is already open.", key.c_str());
1156 return;
1157 }
1158 retainRetiredLocked(std::move(collision->second));
1159 _projects.erase(collision);
1160 }
1161 auto node = _projects.extract(found);
1162 {
1163 std::lock_guard<std::mutex> logLock(_projectLogsMutex);
1164 _projectLogPaths.erase(node.key());
1165 _projectLogPaths[key] = node.mapped().logWorker;
1166 }
1167 node.key() = key;
1168 node.mapped().path = key;
1169 _projects.insert(std::move(node));
1170 }
1171 std::function<void(const std::string&, const std::string&, const std::string&)> notify;
1172 {
1173 std::lock_guard<std::mutex> lock(_mutex);
1174 notify = _renameNotifier;
1175 }
1176 if (notify)
1177 notify(project->id(), key, project->name());
1178 }
1179
1187 {
1188 F_err result = errors::NONE;
1189 const auto apply = [&](const std::string& key, const auto& value)
1190 {
1191 if (result != errors::NONE)
1192 return;
1193 F_bool exists = false;
1194 result = state.contains(key, exists);
1195 if (result == errors::NONE && !exists)
1196 result = state.set(key, value);
1197 };
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");
1202 return result;
1203 }
1204
1212 {
1213 std::string kind;
1214 const F_err result = state.get("application.info.stateKind", kind);
1215 if (result != errors::NONE || kind != "application")
1216 {
1217 log::engineError("Cannot open application state: database is not an application database.");
1218 return errors::FAILED_OPEN_STORE;
1219 }
1220 return errors::NONE;
1221 }
1222
1230 {
1231 std::string folder;
1232 bool reopen = false;
1233 bool package = false;
1234 const auto check = [&](const std::string& key, auto& value)
1235 {
1236 F_bool exists = false;
1237 const F_err result = state.contains(key, exists);
1238 return result != errors::NONE || !exists ? result : state.get(key, value);
1239 };
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.");
1247 return result;
1248 }
1249
1254 void init()
1255 {
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.");
1259 try
1260 {
1261 // Runs application-level work so it never waits on a project or on message routing.
1262 _applicationThread = _threads->spawn("application", [queue = _applicationQueue](threads::StopToken)
1263 { queue->run(); });
1264 _consoleThread = _threads->spawn("console", [queue = _consoleQueue](threads::StopToken)
1265 { queue->run(); });
1266 _logThread = _threads->spawn("application-logs", [queue = _logQueue](threads::StopToken)
1267 { queue->run(); });
1268 }
1269 catch (const std::system_error&)
1270 {
1271 _applicationQueue->shutdown();
1272 _consoleQueue->shutdown();
1274 _threads->join(_consoleThread);
1275 _active = false;
1276 throw;
1277 }
1278 catch (const std::bad_alloc&)
1279 {
1280 _applicationQueue->shutdown();
1281 _consoleQueue->shutdown();
1283 _threads->join(_consoleThread);
1284 _active = false;
1285 throw;
1286 }
1287 }
1288
1289 public:
1294
1301 void forwardLogEntry(
1302 const logs::Entry& entry,
1304 bool includeLoading);
1305
1313 const logs::Entry& entry,
1315 bool includeLoading = true)
1316 {
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");
1319 }
1320
1330 void recordCommand(
1331 const message::InData& incoming,
1333 bool received);
1334
1344 void handleReceipt(
1345 const message::InData& incoming,
1347
1355 void handleNotification(
1356 const message::InData& incoming,
1358
1372 void addNotification(
1373 ProcessKind sender,
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);
1382
1388 ConsoleEntry describeCommand(
1389 const message::InData& incoming);
1390
1397 static void sendConsoleEntry(
1398 Command operation,
1399 const ConsoleEntry& entry,
1401
1407 {
1409 _threads->join(_consoleThread);
1410 }
1411
1414 {
1415 _consoleStopping = true;
1416 _consoleQueue->shutdown();
1417 }
1418
1420 bool consoleStopped() const
1421 {
1422 return !_threads->running(_consoleThread);
1423 }
1424
1430 const logs::Entry& entry)
1431 {
1432 if (!entry.project.empty())
1433 {
1434 std::lock_guard<std::mutex> lock(_projectLogsMutex);
1435 const auto found = _projectLogRoutes.find(entry.project);
1436 if (found != _projectLogRoutes.end() && !found->second->closing)
1437 {
1438 const auto worker = found->second;
1439 if (!worker->queue->post([this, entry, worker]
1440 {
1441 if (worker->opening)
1442 worker->duringOpening.push_back(entry);
1443 else if (worker->renaming)
1444 worker->duringRename.push_back(entry);
1445 else
1446 _logs.persist(entry);
1447 }))
1448 std::fprintf(stderr, "Cannot queue project log entry: project log worker is shutting down.\n");
1449 return;
1450 }
1451 }
1452 if (!_logQueue->post([this, entry] { _logs.persistApplication(entry); }))
1453 std::fprintf(stderr, "Cannot queue log entry: application log worker is shutting down.\n");
1454 }
1455
1464 logs::Entry entry,
1466 bool includeLoading = true)
1467 {
1468 const auto prepared = _logs.prepare(std::move(entry));
1469 if (!prepared)
1470 return;
1471 if (prepared->project.empty())
1472 persistLogEntry(*prepared);
1473 if (prepared->consoleVisible && ipc && !_consoleStopping.load())
1474 queueConsoleEntry(*prepared, *ipc, includeLoading);
1475 if (!prepared->project.empty())
1476 persistLogEntry(*prepared);
1477 }
1478
1490 const char* level,
1491 F_long thread,
1492 const std::string& project,
1493 const char* text,
1495 std::uint64_t arrivedUs = 0,
1496 bool consoleVisible = true)
1497 {
1498 logs::Entry entry;
1499 entry.arrivedUs = arrivedUs;
1500 entry.process = static_cast<int>(PROCESS_KIND_ENGINE);
1501 entry.level = level;
1502 entry.thread = static_cast<std::uint32_t>(thread);
1503 entry.project = project;
1504 entry.text = text;
1505 entry.consoleVisible = consoleVisible;
1506 if (std::string(level) == "SES")
1507 entry.kind = LOG_ENTRY_KIND_SESSION;
1508 recordLogEntry(std::move(entry), ipc);
1509 }
1510
1516 explicit FrayManager(
1517 const std::string& applicationId = "Fray")
1519 _ownedThreads(std::make_unique<threads::ThreadManager>()),
1521 {
1522 init();
1523 }
1524
1531 explicit FrayManager(
1533 const std::string& applicationId = "Fray")
1535 {
1536 init();
1537 }
1538
1542 const FrayManager&) = delete;
1547 const FrayManager&) = delete;
1548
1553 {
1555 _active = false;
1556 }
1557
1564 const std::filesystem::path& directory)
1565 {
1566 std::lock_guard<std::mutex> lock(_mutex);
1567 if (_shutdownPhase != ShutdownPhase::running || _files->isOpen())
1568 {
1569 log::engineError("Cannot open application state: already open or shutting down.");
1570 return errors::FAILED_OPEN_STORE;
1571 }
1572 std::error_code directoryError;
1573 const auto resolvedDirectory = std::filesystem::canonical(directory, directoryError);
1574 if (directoryError || !std::filesystem::is_directory(resolvedDirectory, directoryError) || directoryError)
1575 {
1576 log::engineError("Cannot open application state: invalid Engine directory.");
1577 return errors::FAILED_OPEN_STORE;
1578 }
1579 _applicationDirectory = resolvedDirectory;
1580 std::filesystem::path selected;
1582 if (result != errors::NONE)
1583 return result;
1584 if (!selected.empty())
1585 return switchApplicationStateLocked(selected, false);
1586 result = _files->openDirectory(_applicationDirectory, _applicationId);
1587 if (result != errors::NONE)
1588 return result;
1589 const auto database = _files->workingDirectory() / _files->databaseFileName();
1590 std::error_code error;
1591 const bool existing = std::filesystem::exists(database, error);
1592 if (error)
1593 {
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;
1598 }
1599 auto manager = std::make_unique<state::StateManager>();
1600 result = manager->open(*_files, "Fray", _applicationId, existing);
1601 if (result == errors::NONE && existing)
1602 result = validateApplicationState(*manager);
1603 if (result == errors::NONE)
1604 result = validateApplicationPreferences(*manager);
1605 if (result == errors::NONE)
1606 result = applyApplicationDefaults(*manager);
1607 if (result != errors::NONE)
1608 {
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.");
1613 return result;
1614 }
1615 _states.emplace("Fray", std::move(manager));
1616 return errors::NONE;
1617 }
1618
1626 const std::string& defaults,
1627 std::string& css)
1628 {
1629 std::lock_guard<std::mutex> lock(_mutex);
1630 return style::loadButtonStyle(_applicationDirectory, defaults, css);
1631 }
1632
1639 const std::string& css)
1640 {
1641 std::lock_guard<std::mutex> lock(_mutex);
1643 }
1644
1645 private:
1654 const std::filesystem::path& path,
1655 bool persist)
1656 {
1658 {
1659 log::engineError("Cannot switch application state: Engine directory is unavailable or shutting down.");
1660 return errors::FAILED_OPEN_STORE;
1661 }
1662 std::error_code error;
1663 const auto status = std::filesystem::symlink_status(path, error);
1664 if (error || !std::filesystem::is_regular_file(status))
1665 {
1666 log::engineError("Cannot switch application state: file is not an existing regular file.");
1667 return errors::FAILED_OPEN_STORE;
1668 }
1669 if (_files->isOpen())
1670 {
1671 const auto current = _files->workingDirectory() / _files->databaseFileName();
1672 if (std::filesystem::equivalent(current, path, error) && !error)
1673 return persist ? state::writeApplicationLocation(_applicationDirectory, current) : errors::NONE;
1674 if (error)
1675 {
1676 log::engineError("Cannot compare application database paths: %s", error.message().c_str());
1677 return errors::FAILED_OPEN_STORE;
1678 }
1679 }
1680 auto files = std::make_unique<files::FileManager>();
1681 F_err result = files->openDatabase(path);
1682 if (result != errors::NONE)
1683 return result;
1684 auto manager = std::make_unique<state::StateManager>();
1685 result = manager->open(*files, "Fray", _applicationId, true);
1686 if (result == errors::NONE)
1687 result = validateApplicationState(*manager);
1688 if (result == errors::NONE)
1689 result = validateApplicationPreferences(*manager);
1690 if (result == errors::NONE)
1691 result = applyApplicationDefaults(*manager);
1692 if (result != errors::NONE)
1693 return result;
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)
1697 {
1698 if (entry.first == "Fray" || !entry.second->isOpen())
1699 continue;
1700 auto extra = std::make_unique<state::StateManager>();
1701 result = extra->open(*files, entry.first, _applicationId);
1702 if (result != errors::NONE)
1703 return result;
1704 states.emplace(entry.first, std::move(extra));
1705 }
1706 const auto selected = files->workingDirectory() / files->databaseFileName();
1707 if (persist)
1708 {
1710 if (result != errors::NONE)
1711 return result;
1712 }
1713 auto previousFiles = std::move(_files);
1714 auto previousStates = std::move(_states);
1715 _files = std::move(files);
1716 _states = 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;
1724 }
1725
1726 public:
1734 const std::filesystem::path& path)
1735 {
1736 if (!path.is_absolute() || path.string().find('\0') != std::string::npos)
1737 {
1738 log::engineError("Cannot switch application state: database path must be absolute.");
1739 return errors::FAILED_OPEN_STORE;
1740 }
1741 std::lock_guard<std::mutex> lock(_mutex);
1742 return switchApplicationStateLocked(path, true);
1743 }
1744
1749 std::filesystem::path applicationStatePath()
1750 {
1751 std::lock_guard<std::mutex> lock(_mutex);
1752 return _files->isOpen() ? _files->workingDirectory() / _files->databaseFileName()
1753 : std::filesystem::path();
1754 }
1755
1762 ApplicationPreferences& output)
1763 {
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())
1767 {
1768 log::engineError("Cannot read application preferences: store is not open.");
1769 return errors::FAILED_LOAD_STATE;
1770 }
1771 std::string folder;
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)
1780 return result;
1781 output.Clear();
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;
1787 }
1788
1794 {
1795 std::lock_guard<std::mutex> lock(_mutex);
1796 const auto found = _states.find("Fray");
1797 if (found == _states.end() || !found->second->isOpen())
1798 {
1799 log::engineError("Cannot reset application preferences: store is not open.");
1800 return errors::FAILED_SAVE_STATE;
1801 }
1802 auto& state = *found->second;
1803 return state.withDatabase([&](sqlite3* db)
1804 {
1805 if (sqlite3_exec(db, "BEGIN IMMEDIATE", nullptr, nullptr, nullptr) != SQLITE_OK)
1806 {
1807 log::engineError("Cannot start preferences reset: %s", sqlite3_errmsg(db));
1808 return errors::FAILED_SAVE_STATE;
1809 }
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;
1821 });
1822 }
1823
1830 const std::string& name)
1831 {
1832 std::lock_guard<std::mutex> lock(_mutex);
1833 if (_shutdownPhase != ShutdownPhase::running || !_files->isOpen())
1834 {
1835 log::engineError("Cannot open application state: files are closed or shutting down.");
1836 return errors::FAILED_OPEN_STORE;
1837 }
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>();
1842 const F_err result = manager->open(*_files, name, _applicationId);
1843 if (result != errors::NONE)
1844 return result;
1845 _states[name] = std::move(manager);
1846 return errors::NONE;
1847 }
1848
1856 const std::string& name)
1857 {
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;
1863 }
1864
1872 template<typename T>
1874 const std::string& key,
1875 const T& value)
1876 {
1877 std::lock_guard<std::mutex> lock(_mutex);
1878 const auto found = _states.find("Fray");
1879 if (found == _states.end() || !found->second->isOpen())
1880 {
1881 log::engineError("Cannot save application state: store is not open.");
1882 return errors::FAILED_SAVE_STATE;
1883 }
1884 return found->second->set(key, value);
1885 }
1886
1894 template<typename T>
1896 const std::string& key,
1897 T& value)
1898 {
1899 std::lock_guard<std::mutex> lock(_mutex);
1900 const auto found = _states.find("Fray");
1901 if (found == _states.end() || !found->second->isOpen())
1902 {
1903 log::engineError("Cannot load application state: store is not open.");
1904 return errors::FAILED_LOAD_STATE;
1905 }
1906 return found->second->get(key, value);
1907 }
1908
1914 {
1915 {
1916 std::lock_guard<std::mutex> lock(_mutex);
1918 return;
1920 {
1922 _applicationQueue->shutdown();
1923 }
1924 else
1925 {
1926 for (auto& item : _shutdownEntries)
1927 if (!_closingProjects.count(item.first))
1928 {
1929 item.second.closeAttempted = false;
1930 item.second.cancelAttempted = false;
1931 }
1932 }
1933 }
1934 cancelPrompts("Application is shutting down.", true);
1936 }
1937
1940 {
1942 }
1943
1950 {
1951 std::vector<std::string> cancellations;
1952 bool changed = false;
1953 {
1954 std::lock_guard<std::mutex> lock(_mutex);
1956 return _shutdownPhase;
1957 const bool applicationDrained = !_threads->running(_applicationThread);
1958 if (applicationDrained && !_shutdownSessionCaptured)
1960 const auto track = [&](const Entry& entry)
1961 {
1962 const bool active = entry.project->isOpen() || entry.project->isOpening() ||
1963 _closingProjects.count(entry.project.get()) || _threads->running(entry.thread) ||
1964 (entry.logWorker && _threads->running(entry.logWorker->thread));
1965 if (!active && !_shutdownEntries.count(entry.project.get()))
1966 return;
1967 auto inserted = _shutdownEntries.try_emplace(entry.project.get(), ShutdownEntry{entry});
1968 if (inserted.second)
1969 changed = true;
1970 else if (inserted.first->second.entry.path != entry.path ||
1971 inserted.first->second.entry.id != entry.id)
1972 {
1973 inserted.first->second.entry.path = entry.path;
1974 inserted.first->second.entry.id = entry.id;
1975 changed = true;
1976 }
1977 };
1978 for (const auto& entry : _projects)
1979 track(entry.second);
1980 for (const auto& entry : _retiredProjects)
1981 track(entry);
1982
1983 for (auto it = _shutdownEntries.begin(); it != _shutdownEntries.end();)
1984 {
1985 auto& tracked = it->second;
1986 const auto& entry = tracked.entry;
1987 ProjectManager* project = entry.project.get();
1988 const auto registered = _projects.find(entry.path);
1989 const bool present = registered != _projects.end() && registered->second.project == entry.project;
1990 const auto opening = _openingStatuses.find(entry.path);
1991 const auto decision = _openingDecisions.find(entry.path);
1992 const bool openingPending = opening != _openingStatuses.end() && !opening->second.result;
1993 const bool decisionPending = decision != _openingDecisions.end() && !decision->second.result;
1994 if (_closingProjects.count(project))
1995 tracked.closeAttempted = true;
1996 else if (applicationDrained && present && !openingPending && !decisionPending && project->isOpening())
1997 {
1998 if (!tracked.cancelAttempted)
1999 {
2000 tracked.cancelAttempted = true;
2001 cancellations.push_back(entry.path);
2002 }
2003 }
2004 else if (applicationDrained && present && !openingPending && !decisionPending && project->isOpen())
2005 {
2006 if (!tracked.closeAttempted)
2007 {
2008 tracked.closeAttempted = true;
2009 const F_err result = enqueueProjectTaskLocked("", true, true,
2010 [this, path = entry.path](ProjectManager& target, const std::shared_ptr<threads::TaskQueue>& queue)
2011 {
2012 CloseTaskGuard guard{*this, target, queue, true};
2013 // Closing clears the paths, so note them first.
2014 const std::string projectName = target.name();
2015 const std::string projectId = target.id();
2016 const std::string workingPath = target.fileManager().workingDirectory().string();
2017 const std::string archivePath = target.fileManager().archivePath().string();
2018 updateShutdownSessionPath(projectId, workingPath);
2019 bool packaged = false;
2020 const F_err result = target.closeNow(false, &packaged);
2021 std::function<void(const std::string&, const std::string&, F_err, bool, const std::string&)> notify;
2022 {
2023 std::lock_guard<std::mutex> notifyLock(_mutex);
2024 notify = _shutdownCloseNotifier;
2025 }
2026 // Reported before the close counts as finished, so Console delivery cannot stop first.
2027 if (notify)
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));
2033 }, project);
2034 if (result != errors::NONE)
2035 log::engineError("Cannot queue shutdown close for %s (error %lld).",
2036 entry.path.c_str(), static_cast<long long>(result));
2037 }
2038 }
2039 else if (!project->isOpen() && !project->isOpening() && !openingPending &&
2040 !decisionPending && !_closingProjects.count(project))
2041 {
2042 if (!tracked.threadsStopRequested)
2043 {
2044 project->requestStopThreads();
2045 tracked.threadsStopRequested = true;
2046 }
2047 entry.queue->shutdown();
2048 if (!_threads->running(entry.thread) && entry.logWorker && !tracked.logStopping)
2049 {
2050 std::lock_guard<std::mutex> logLock(_projectLogsMutex);
2051 entry.logWorker->closing = true;
2052 entry.logWorker->queue->shutdown();
2053 tracked.logStopping = true;
2054 }
2055 if (!_threads->running(entry.thread) &&
2056 (!entry.logWorker || !_threads->running(entry.logWorker->thread)))
2057 {
2058 it = _shutdownEntries.erase(it);
2059 changed = true;
2060 continue;
2061 }
2062 }
2063 ++it;
2064 }
2065 if (changed)
2067 if (cancellations.empty() && _shutdownEntries.empty() && applicationDrained)
2069 }
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();
2074 }
2075
2081 {
2082 std::lock_guard<std::mutex> lock(_mutex);
2083 return _shutdownPhase;
2084 }
2085
2093 {
2094 {
2095 std::lock_guard<std::mutex> lock(_mutex);
2096 if (_shutdown)
2097 return;
2098 }
2099 cancelPrompts("Application is shutting down.", true);
2100 {
2101 std::lock_guard<std::mutex> lock(_mutex);
2102 _renameNotifier = nullptr;
2103 _renameFailureNotifier = nullptr;
2104 _logResolvedNotifier = nullptr;
2105 _shutdownCloseNotifier = nullptr;
2106 _closingNotifier = nullptr;
2107 _openingNotifier = nullptr;
2108 }
2109 _applicationQueue->shutdown();
2112 {
2113 std::lock_guard<std::mutex> lock(_mutex);
2114 _shutdown = true;
2115 }
2116 if (close() != errors::NONE)
2117 log::engineError("Some project closes could not be queued during final cleanup.");
2118 std::vector<Entry> projects;
2119 {
2120 std::lock_guard<std::mutex> lock(_mutex);
2121 for (auto& entry : _projects)
2122 {
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]
2127 {
2128 if (owned->isOpening())
2129 {
2130 if (owned->cancelOpen() != errors::NONE)
2131 log::engineError("Could not cancel project opening during final cleanup.");
2132 else
2133 _logs.discardOpening(openingTag(owned.get()));
2134 queue->shutdown();
2135 return;
2136 }
2137 bool closing;
2138 {
2139 std::lock_guard<std::mutex> lock(_mutex);
2140 closing = _closingProjects.count(owned.get()) != 0;
2141 }
2142 if (closing)
2143 return;
2144 if (owned->isOpen())
2145 {
2146 const F_err result = queueProjectClose("", [](ProjectManager& target, bool& packaged)
2147 {
2148 return target.closeNow(false, &packaged);
2149 }, {}, owned.get());
2150 if (result == errors::NONE)
2151 return;
2152 log::engineError("Could not queue project close during final cleanup.");
2153 }
2154 queue->shutdown();
2155 }))
2156 {
2157 if (_threads->running(entry.second.thread))
2158 log::engineWarn("Project queue was already stopped during final cleanup.");
2159 }
2160 }
2161 projects.insert(projects.end(), _retiredProjects.begin(), _retiredProjects.end());
2162 }
2163 // Only this manager's own threads; the shared ThreadManager may hold others.
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)
2176 retire(entry);
2177 _retiredProjects.clear();
2178 {
2179 std::lock_guard<std::mutex> lock(_projectLogsMutex);
2180 _projectLogRoutes.clear();
2181 _projectLogPaths.clear();
2182 }
2183 _projects.clear();
2184 _shutdownEntries.clear();
2185 _openOrder.clear();
2186 _closingProjects.clear();
2187 _closeAllProjects.clear();
2188 {
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());
2193 _states.clear();
2194 if (_files->isOpen() && _files->close() != errors::NONE)
2195 log::engineError("Cannot close application files.");
2196 }
2197 _logQueue->shutdown();
2198 _threads->join(_logThread);
2199 }
2200
2207 const std::string& reason,
2208 bool closing = false)
2209 {
2210 std::lock_guard<std::mutex> lock(_promptMutex);
2211 if (closing)
2212 _promptClosing = true;
2213 for (auto& entry : _pendingPrompts)
2214 {
2215 if (entry.second.completed)
2216 continue;
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;
2221 }
2222 }
2223
2231 uint64_t requestId,
2232 PromptResponse& response)
2233 {
2234 std::lock_guard<std::mutex> lock(_promptMutex);
2235 const auto found = _pendingPrompts.find(requestId);
2236 if (found == _pendingPrompts.end() || !found->second.completed)
2237 return false;
2238 response = std::move(found->second.response);
2239 _pendingPrompts.erase(found);
2240 return true;
2241 }
2242
2246 const std::string& applicationId() const { return _applicationId; }
2247
2254 std::function<void()> task)
2255 {
2256 std::lock_guard<std::mutex> lock(_mutex);
2258 {
2259 log::engineError("Cannot queue application work: shutdown is in progress.");
2260 return false;
2261 }
2262 return _applicationQueue->post([this, task = std::move(task)]
2263 {
2264 struct Restore
2265 {
2266 FrayManager* previous;
2268 ~Restore() { _acceptedApplicationTask = previous; }
2269 } restore{_acceptedApplicationTask};
2271 task();
2272 });
2273 }
2274
2281 void handleApplicationMessage(
2282 const message::InData& incoming,
2284
2292 bool requestPrompt(
2294 const PromptRequest& request,
2295 uint64_t& requestId);
2296
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 = "")
2316 {
2317 reapRetired();
2318 bool down;
2319 {
2320 std::lock_guard<std::mutex> lock(_mutex);
2322 }
2323 if (down)
2324 {
2325 log::engineError("Cannot open project: FrayManager is shut down.");
2326 return errors::FAILED_OPEN_PROJECT;
2327 }
2328 if (path.empty())
2329 {
2330 log::engineError("Cannot open project: path is empty.");
2331 return errors::FAILED_OPEN_PROJECT;
2332 }
2333 std::error_code error;
2334 const std::string key = projectKey(path, error);
2335 if (error)
2336 {
2337 log::engineError("Cannot resolve project path: %s", error.message().c_str());
2338 return errors::FAILED_OPEN_PROJECT;
2339 }
2340 bool alreadyOpen = false;
2341 ProjectManager* project = nullptr;
2342 std::shared_ptr<threads::TaskQueue> queue;
2343 std::optional<bool> newProjectPackageDefault;
2344 bool posted = false;
2345 {
2346 std::lock_guard<std::mutex> lock(_mutex);
2348 {
2349 log::engineError("Cannot open project: FrayManager is shut down.");
2350 return errors::FAILED_OPEN_PROJECT;
2351 }
2352 const auto opening = _openingStatuses.find(key);
2353 if (opening != _openingStatuses.end() && !opening->second.result)
2354 alreadyOpen = true;
2355 const auto closing = _closeStatuses.find(key);
2356 if (closing != _closeStatuses.end() && closing->second.closing)
2357 alreadyOpen = true;
2358 const auto decision = _openingDecisions.find(key);
2359 if (decision != _openingDecisions.end() && !decision->second.result)
2360 alreadyOpen = true;
2361 const auto found = _projects.find(key);
2362 if (!alreadyOpen && found != _projects.end())
2363 {
2364 if (found->second.project->isOpen() || found->second.project->isOpening() ||
2365 _closingProjects.count(found->second.project.get()))
2366 alreadyOpen = true;
2367 else
2368 {
2369 forgetProject(found->second.project.get());
2370 retainRetiredLocked(std::move(found->second));
2371 _projects.erase(found);
2372 }
2373 }
2374 if (!alreadyOpen)
2375 {
2376 const bool mayCreate = mode == files::OpenMode::OpenOrCreate || mode == files::OpenMode::CreateNew ||
2378 if (mayCreate && _files->isOpen())
2379 {
2380 const auto state = _states.find("Fray");
2381 if (state == _states.end() || !state->second->isOpen())
2382 {
2383 log::engineError("Cannot create project: application state is unavailable.");
2384 return errors::FAILED_LOAD_STATE;
2385 }
2386 bool value = false;
2387 const F_err result = state->second->get("application.preferences.packageOnClose", value);
2388 if (result != errors::NONE)
2389 {
2390 log::engineError("Cannot create project: application packaging default is invalid.");
2391 return result;
2392 }
2393 newProjectPackageDefault = value;
2394 }
2395 _openingDecisions.erase(key);
2396 _closeStatuses.erase(key);
2397 Entry entry;
2398 entry.path = key;
2399 entry.restoreOrder = restoreOrder;
2400 entry.project = std::make_shared<ProjectManager>();
2401 entry.queue = std::make_shared<threads::TaskQueue>();
2402 entry.logWorker = std::make_shared<ProjectLogWorker>();
2403 project = entry.project.get();
2404 queue = entry.queue;
2405 project->setLogCloseBarrier(
2406 [worker = entry.logWorker] { return worker->closeReady.load(); });
2407 const auto tag = openingTag(project);
2408 _logs.beginOpening(tag);
2409 {
2410 std::lock_guard<std::mutex> logLock(_projectLogsMutex);
2411 entry.logWorker->identity = tag;
2412 _projectLogRoutes.emplace(tag, entry.logWorker);
2413 _projectLogPaths[key] = entry.logWorker;
2414 }
2415 {
2416 // First line under the tag, so the Console shows the session divider before any entry for this project.
2417 log::ProjectScope scope(tag);
2418 log::engineSession(std::filesystem::path(key).stem().string());
2419 }
2420 project->setCloseDispatcher([this, project](bool package)
2421 {
2422 return queueProjectClose("", [package](ProjectManager& target, bool& packaged)
2423 {
2424 return target.closeNow(package, &packaged);
2425 }, {}, project);
2426 });
2427 project->beginOpening();
2428 project->setRenameCallback([this, project](const std::filesystem::path& renamed)
2429 {
2430 rekey(project, renamed);
2431 });
2432 try
2433 {
2434 entry.logWorker->thread = _threads->spawn("project-logs:" + key,
2435 [worker = entry.logWorker](threads::StopToken) { worker->queue->run(); });
2436 entry.thread = _threads->spawn("project:" + key, [queue, project](threads::StopToken)
2437 {
2438 queue->run([project] { return project->hasThreads(); });
2439 });
2440 _projects.emplace(key, entry);
2441 _openingStatuses.insert_or_assign(key, OpeningStatus{path, std::nullopt, origin, restoreOrder.has_value()});
2442 posted = queue->post([this, owned = entry.project, queue, key, path, choice,
2443 cancelOnDatabaseConflict, mode, newProjectPackageDefault, expectedId]
2444 {
2445 ProjectManager* project = owned.get();
2446 F_err result = errors::FAILED_OPEN_PROJECT;
2447 try
2448 {
2449 {
2450 const log::ProjectScope tag(openingTag(project));
2451 result = project->open(path, _applicationId, choice, _threads, queue, mode,
2452 newProjectPackageDefault);
2453 }
2454 if (result == errors::NONE && !expectedId.empty() && project->id() != expectedId)
2455 {
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)
2459 {
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.");
2463 }
2464 result = errors::FAILED_OPEN_PROJECT;
2465 }
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)
2471 {
2472 if (project->cancelOpen() != errors::NONE)
2473 log::engineError("Could not cancel the pending database choice.");
2474 else
2475 {
2476 _logs.discardOpening(openingTag(project));
2477 queue->shutdown();
2478 }
2479 }
2480 if (result != errors::NONE && result != errors::DATABASE_CONFLICT && !project->isOpen())
2481 queue->shutdown();
2482 }
2483 catch (const std::exception& exception)
2484 {
2485 log::engineError("Could not open project: %s", exception.what());
2486 result = errors::FAILED_OPEN_PROJECT;
2487 if (!project->isOpen())
2488 {
2489 {
2490 std::lock_guard<std::recursive_mutex> lock(project->_mutex);
2491 project->abandon(true);
2492 }
2493 _logs.discardOpening(openingTag(project));
2494 queue->shutdown();
2495 }
2496 }
2497 OpeningStatus status;
2498 std::function<void(const OpeningStatus&)> notify;
2499 {
2500 std::lock_guard<std::mutex> lock(_mutex);
2501 auto& current = _openingStatuses.at(key);
2502 current.result = result;
2503 current.remainsOpen = project->isOpen();
2504 status = current;
2505 notify = _openingNotifier;
2506 }
2507 if (notify)
2508 notify(status);
2509 });
2510 if (!posted)
2511 {
2512 _openingStatuses.at(key).result = errors::FAILED_OPEN_PROJECT;
2513 _logs.discardOpening(tag);
2514 auto registered = _projects.find(key);
2515 retainRetiredLocked(std::move(registered->second));
2516 _projects.erase(registered);
2517 }
2518 }
2519 catch (const std::exception&)
2520 {
2521 const auto registered = _projects.find(key);
2522 if (registered != _projects.end() && registered->second.project == entry.project)
2523 _projects.erase(registered);
2524 _openingStatuses.erase(key);
2525 {
2526 std::lock_guard<std::mutex> logLock(_projectLogsMutex);
2527 _projectLogRoutes.erase(tag);
2528 _projectLogPaths.erase(key);
2529 }
2530 _logs.discardOpening(tag);
2531 entry.queue->shutdown();
2532 entry.logWorker->queue->shutdown();
2533 _threads->join(entry.thread);
2534 _threads->join(entry.logWorker->thread);
2535 throw;
2536 }
2537 }
2538 }
2539 if (alreadyOpen)
2540 {
2541 log::engineError("Project is already open: %s", key.c_str());
2542 return errors::PROJECT_ALREADY_OPEN;
2543 }
2544 if (!posted)
2545 {
2546 log::engineError("Cannot open project: project queue is stopped.");
2547 return errors::FAILED_OPEN_PROJECT;
2548 }
2549 return errors::NONE;
2550 }
2551
2557 std::optional<OpeningStatus> openingStatus(
2558 const std::string& path)
2559 {
2560 std::error_code error;
2561 const std::string key = projectKey(path, error);
2562 if (error)
2563 {
2564 log::engineError("Cannot resolve project path: %s", error.message().c_str());
2565 return std::nullopt;
2566 }
2567 std::lock_guard<std::mutex> lock(_mutex);
2568 const auto found = _openingStatuses.find(key);
2569 return found == _openingStatuses.end() ? std::nullopt : std::optional<OpeningStatus>(found->second);
2570 }
2571
2577 std::function<void(const OpeningStatus&)> notifier)
2578 {
2579 std::lock_guard<std::mutex> lock(_mutex);
2580 if (!_shutdown)
2581 _openingNotifier = std::move(notifier);
2582 }
2583
2589 std::vector<std::string> databaseCandidates(
2590 const std::string& name)
2591 {
2592 F_err error;
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>();
2597 }
2598
2607 const std::string& name,
2608 const DatabaseChoice& choice)
2609 {
2610 return queueOpeningDecision(name, OpeningDecision::resolve, choice);
2611 }
2612
2620 const std::string& name)
2621 {
2623 }
2624
2631 std::optional<OpeningDecisionStatus> openingDecisionStatus(
2632 const std::string& path)
2633 {
2634 std::error_code error;
2635 const std::string key = projectKey(path, error);
2636 if (error)
2637 {
2638 log::engineError("Cannot resolve project path: %s", error.message().c_str());
2639 return std::nullopt;
2640 }
2641 std::lock_guard<std::mutex> lock(_mutex);
2642 const auto found = _openingDecisions.find(key);
2643 return found == _openingDecisions.end() ? std::nullopt
2644 : std::optional<OpeningDecisionStatus>(found->second);
2645 }
2646
2656 const std::string& name)
2657 {
2658 std::lock_guard<std::mutex> lock(_mutex);
2659 F_err error;
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;
2666 }
2667
2668 private:
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)
2683 {
2684 worker->closeReady = false;
2685 bool posted;
2686 {
2687 // Finish any rename already in progress before enqueuing the log close.
2688 std::lock_guard<std::recursive_mutex> projectLock(project->_mutex);
2689 std::lock_guard<std::mutex> lock(_projectLogsMutex);
2690 worker->closing = true;
2691 auto close = [this, project, queue, worker, id, task]
2692 {
2693 bool closed = false;
2694 try
2695 {
2696 closed = _logs.closeProject(id);
2697 }
2698 catch (const std::exception& error)
2699 {
2700 std::fprintf(stderr, "Cannot close project log: %s\n", error.what());
2701 }
2702 if (!closed)
2703 {
2704 std::lock_guard<std::mutex> lock(_projectLogsMutex);
2705 worker->closing = false;
2706 }
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");
2710 };
2711 posted = worker->queue->post([worker, close = std::move(close)]
2712 {
2713 if (worker->renaming)
2714 worker->deferredClose = close;
2715 else
2716 close();
2717 });
2718 if (!posted)
2719 worker->closing = false;
2720 }
2721 if (!posted)
2722 {
2723 std::fprintf(stderr, "Cannot close project log: project log worker is stopped.\n");
2724 task(*project, queue);
2725 }
2726 }
2727
2738 const std::string& target,
2739 bool allowLatest,
2740 bool closing,
2741 std::function<void(ProjectManager&, const std::shared_ptr<threads::TaskQueue>&)> task,
2742 ProjectManager* exact = nullptr)
2743 {
2744 std::lock_guard<std::mutex> lock(_mutex);
2745 return enqueueProjectTaskLocked(target, allowLatest, closing, std::move(task), exact);
2746 }
2747
2758 const std::string& target,
2759 bool allowLatest,
2760 bool closing,
2761 std::function<void(ProjectManager&, const std::shared_ptr<threads::TaskQueue>&)> task,
2762 ProjectManager* exact)
2763 {
2765 {
2766 log::engineError("Cannot dispatch project work: shutdown is in progress.");
2767 return errors::FAILED_CLOSE_PROJECT;
2768 }
2769 _openOrder.erase(std::remove_if(_openOrder.begin(), _openOrder.end(),
2770 [](ProjectManager* project) { return !project->isOpen(); }), _openOrder.end());
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;
2775 if (exact)
2776 {
2777 for (auto& entry : _projects)
2778 if (entry.second.project.get() == exact && exact->isOpen())
2779 {
2780 project = entry.second.project;
2781 queue = entry.second.queue;
2782 logWorker = entry.second.logWorker;
2783 break;
2784 }
2785 }
2786 else if (target.empty() && allowLatest)
2787 {
2788 if (!_openOrder.empty())
2789 for (auto& entry : _projects)
2790 if (entry.second.project.get() == _openOrder.back())
2791 {
2792 project = entry.second.project;
2793 queue = entry.second.queue;
2794 logWorker = entry.second.logWorker;
2795 break;
2796 }
2797 }
2798 else if (!target.empty())
2799 {
2800 const auto found = lookup(target, lookupError);
2801 if (found != _projects.end() && found->second.project->isOpen())
2802 {
2803 project = found->second.project;
2804 queue = found->second.queue;
2805 logWorker = found->second.logWorker;
2806 }
2807 else if (lookupError == errors::NONE)
2808 lookupError = errors::PROJECT_NOT_FOUND;
2809 }
2810 if (!project || !queue)
2811 {
2812 log::engineError("Cannot dispatch project task: %s",
2813 lookupError == errors::PROJECT_AMBIGUOUS
2814 ? "multiple projects have this name; use the full path."
2815 : "no matching project is open.");
2816 return lookupError;
2817 }
2818 if (_closingProjects.count(project.get()))
2819 {
2820 log::engineError("Cannot dispatch project task: project is already closing.");
2821 return errors::FAILED_CLOSE_PROJECT;
2822 }
2823 std::string logId;
2824 if (closing)
2825 {
2826 const auto id = _logIds.find(project.get());
2827 if (!logWorker || id == _logIds.end())
2828 {
2829 log::engineError("Cannot close project: project log is not registered.");
2830 return errors::FAILED_CLOSE_PROJECT;
2831 }
2832 logId = id->second;
2833 const auto registered = std::find_if(_projects.begin(), _projects.end(),
2834 [&project](const auto& entry) { return entry.second.project == project; });
2835 if (registered == _projects.end())
2836 {
2837 log::engineError("Cannot close project: it is no longer registered.");
2838 return errors::FAILED_CLOSE_PROJECT;
2839 }
2840 _closeStatusKeys[project.get()] = registered->first;
2841 _closeStatuses.insert_or_assign(registered->first,
2842 ProjectManager::CloseStatus{true, std::nullopt});
2843 _closingProjects.insert(project.get());
2844 project->_closePending = true;
2845 {
2846 std::lock_guard<std::mutex> closeLock(project->_closeDispatchMutex);
2847 project->_closeStatus = ProjectManager::CloseStatus{true, std::nullopt};
2848 }
2849 }
2850 if (!queue->post([this, project, queue, logWorker, logId, closing, task = std::move(task)]
2851 {
2852 if (closing)
2853 queueLogClose(project, queue, logWorker, logId, task);
2854 else
2855 task(*project, queue);
2856 }))
2857 {
2858 if (closing)
2859 {
2860 _closingProjects.erase(project.get());
2861 project->_closePending = false;
2863 ProjectManager::CloseStatus{false, errors::FAILED_CLOSE_PROJECT};
2864 _closeStatusKeys.erase(project.get());
2865 std::lock_guard<std::mutex> closeLock(project->_closeDispatchMutex);
2866 project->_closeStatus = ProjectManager::CloseStatus{false, errors::FAILED_CLOSE_PROJECT};
2867 }
2868 log::engineError("Cannot dispatch project task: its queue is stopped.");
2869 return errors::FAILED_CLOSE_PROJECT;
2870 }
2871 if (closing)
2873 return errors::NONE;
2874 }
2875
2883 F_err result)
2884 {
2885 if (!_closeAllProjects.erase(project))
2886 return;
2887 if (result != errors::NONE)
2888 _closeAllFailed = true;
2889 if (_closeAllProjects.empty())
2891 false, _closeAllFailed ? errors::FAILED_CLOSE_PROJECT : errors::NONE};
2892 }
2893
2904 const std::shared_ptr<threads::TaskQueue>& queue,
2905 F_err result,
2906 bool removeOnSuccess = false)
2907 {
2908 {
2909 std::lock_guard<std::mutex> lock(_mutex);
2910 const bool changed = _closingProjects.erase(&project) != 0;
2911 project._closePending = false;
2912 const auto statusKey = _closeStatusKeys.find(&project);
2913 if (statusKey != _closeStatusKeys.end())
2914 {
2915 _closeStatuses.at(statusKey->second) = ProjectManager::CloseStatus{false, result};
2916 _closeStatusKeys.erase(statusKey);
2917 }
2918 if (result == errors::NONE)
2919 {
2921 queue->shutdown();
2922 if (removeOnSuccess)
2923 {
2924 const auto found = std::find_if(_projects.begin(), _projects.end(),
2925 [&project](const auto& entry) { return entry.second.project.get() == &project; });
2926 if (found != _projects.end())
2927 {
2928 retainRetiredLocked(std::move(found->second));
2929 _projects.erase(found);
2930 }
2931 else
2932 std::fprintf(stderr, "Cannot retire closed project: it is no longer registered.\n");
2933 }
2934 }
2935 else if (_shutdown)
2936 queue->shutdown();
2938 if (changed)
2940 {
2941 std::lock_guard<std::mutex> closeLock(project._closeDispatchMutex);
2942 project._closeStatus = ProjectManager::CloseStatus{false, result};
2943 }
2944 }
2945 }
2946
2951 {
2963 const std::shared_ptr<threads::TaskQueue>& queue;
2969 bool removeOnSuccess = false;
2970
2975 {
2976 if (active)
2977 manager.finishProjectClose(project, queue,
2978 project.isOpen() ? errors::FAILED_CLOSE_PROJECT : errors::NONE, removeOnSuccess);
2979 }
2980
2986 F_err result)
2987 {
2988 if (active)
2989 {
2990 manager.finishProjectClose(project, queue, result, removeOnSuccess);
2991 active = false;
2992 }
2993 }
2994 };
2995
3007 const std::string& target,
3008 std::function<F_err(ProjectManager&, bool&)> operation,
3009 std::function<void(const std::string&, F_err, bool)> completion,
3010 ProjectManager* exact = nullptr,
3011 bool removeOnSuccess = false)
3012 {
3013 const F_err result = enqueueProjectTask(target, true, true,
3014 [this, operation = std::move(operation), completion, removeOnSuccess](ProjectManager& project,
3015 const std::shared_ptr<threads::TaskQueue>& queue)
3016 {
3017 CloseTaskGuard guard{*this, project, queue, true, removeOnSuccess};
3018 const std::string name = project.name();
3019 bool packaged = false;
3020 const F_err result = operation(project, packaged);
3021 guard.finish(result);
3022 if (completion)
3023 completion(name, result, packaged);
3024 }, exact);
3025 if (result != errors::NONE && completion)
3026 completion(target, result, false);
3027 return result;
3028 }
3029
3035 void handleProjectMessage(
3036 const message::InData& incoming,
3038
3044 void announceActiveProject(
3046
3051 void watchProjectOpenings(
3053
3059 static void toProto(
3060 const logs::Entry& entry,
3061 LogEntry& out)
3062 {
3063 out.set_arrived_us(entry.arrivedUs);
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));
3072 out.set_operation(entry.operation);
3073 out.set_ref_uid(entry.refUid);
3074 }
3075
3081 void handleLogMessage(
3082 const message::InData& incoming,
3084
3090 void watchRenames(
3092
3093 public:
3099 F_err restoreProjects(
3101
3107 std::function<void(const ProjectClosingStatuses&)> notifier)
3108 {
3109 std::lock_guard<std::mutex> lock(_mutex);
3110 if (!_shutdown)
3111 {
3112 _closingNotifier = std::move(notifier);
3113 if (_closingNotifier)
3115 }
3116 }
3117
3121 using RenameNotifier = std::function<void(const std::string& id, const std::string& path,
3122 const std::string& name)>;
3123
3129 RenameNotifier notifier)
3130 {
3131 std::lock_guard<std::mutex> lock(_mutex);
3132 if (!_shutdown)
3133 _renameNotifier = std::move(notifier);
3134 }
3135
3141 std::function<void(const std::string&)> notifier)
3142 {
3143 std::lock_guard<std::mutex> lock(_mutex);
3144 if (!_shutdown)
3145 _renameFailureNotifier = std::move(notifier);
3146 }
3147
3153 std::function<void(const std::string& name, const std::string& id, F_err result, bool packaged,
3154 const std::string& path)> notifier)
3155 {
3156 std::lock_guard<std::mutex> lock(_mutex);
3157 if (!_shutdown)
3158 _shutdownCloseNotifier = std::move(notifier);
3159 }
3160
3166 std::function<void(const std::string& openingTag, const std::string& id)> notifier)
3167 {
3168 std::lock_guard<std::mutex> lock(_mutex);
3169 if (!_shutdown)
3170 _logResolvedNotifier = std::move(notifier);
3171 }
3172
3180 const std::string& target,
3181 bool package,
3182 std::function<void(const std::string&, F_err, bool)> completion)
3183 {
3184 queueProjectClose(target, [package](ProjectManager& project, bool& packaged)
3185 {
3186 return project.closeNow(package, &packaged);
3187 }, std::move(completion));
3188 }
3189
3197 const std::string& name)
3198 {
3199 reapRetired();
3200 std::shared_ptr<ProjectManager> project;
3201 {
3202 std::lock_guard<std::mutex> lock(_mutex);
3203 F_err error;
3204 auto found = lookup(name, error);
3205 if (found == _projects.end() && error == errors::PROJECT_NOT_FOUND)
3206 found = lookup(name, error, true);
3207 if (found == _projects.end())
3208 {
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;
3211 }
3212 project = found->second.project;
3213 if (_closingProjects.count(project.get()) || project->isOpening())
3214 {
3215 log::engineError("Cannot close project: project is already closing or opening.");
3216 return errors::FAILED_CLOSE_PROJECT;
3217 }
3218 if (!project->isOpen())
3219 {
3220 _closeStatuses.insert_or_assign(found->first,
3221 ProjectManager::CloseStatus{false, errors::NONE});
3222 forgetProject(project.get());
3223 retainRetiredLocked(std::move(found->second));
3224 _projects.erase(found);
3225 return errors::NONE;
3226 }
3227 }
3228 return queueProjectClose(name, [](ProjectManager& target, bool& packaged)
3229 {
3230 return target.closeNow(false, &packaged);
3231 }, {}, project.get(), true);
3232 }
3233
3239 std::optional<ProjectManager::CloseStatus> closeStatus(
3240 const std::string& name)
3241 {
3242 if (name.empty() || name.find('\0') != std::string::npos)
3243 {
3244 log::engineError("Cannot read project close status: invalid project name.");
3245 return std::nullopt;
3246 }
3247 std::filesystem::path input(name);
3248 std::lock_guard<std::mutex> lock(_mutex);
3249 if (input.is_absolute() || input.has_parent_path())
3250 {
3251 std::error_code error;
3252 const auto key = projectKey(name, error);
3253 if (error)
3254 {
3255 log::engineError("Cannot resolve project path: %s", error.message().c_str());
3256 return std::nullopt;
3257 }
3258 const auto found = _closeStatuses.find(key);
3259 return found == _closeStatuses.end() ? std::nullopt
3260 : std::optional<ProjectManager::CloseStatus>(found->second);
3261 }
3262 if (input.extension() == ".fry")
3263 input.replace_extension();
3264 const ProjectManager::CloseStatus* match = nullptr;
3265 for (const auto& entry : _closeStatuses)
3266 {
3267 if (std::filesystem::path(entry.first).filename() != input)
3268 continue;
3269 if (match)
3270 {
3271 log::engineError("Multiple close statuses match %s; use the full path.", name.c_str());
3272 return std::nullopt;
3273 }
3274 match = &entry.second;
3275 }
3276 return match ? std::optional<ProjectManager::CloseStatus>(*match) : std::nullopt;
3277 }
3278
3285 {
3286 reapRetired();
3287 std::lock_guard<std::mutex> lock(_mutex);
3288 if (!_closeAllStatus || !_closeAllStatus->closing)
3289 {
3290 _closeAllProjects.clear();
3291 _closeAllFailed = false;
3292 }
3293 for (const auto& entry : _projects)
3294 if (entry.second.project->isOpen() || _closingProjects.count(entry.second.project.get()))
3295 _closeAllProjects.insert(entry.second.project.get());
3296 if (_closeAllProjects.empty())
3297 {
3298 _closeAllStatus = ProjectManager::CloseStatus{false, errors::NONE};
3299 return errors::NONE;
3300 }
3301 _closeAllStatus = ProjectManager::CloseStatus{true, std::nullopt};
3302 bool rejected = false;
3303 for (const auto& entry : _projects)
3304 {
3305 auto project = entry.second.project;
3306 if (!_closeAllProjects.count(project.get()) || _closingProjects.count(project.get()))
3307 continue;
3308 const F_err queued = enqueueProjectTaskLocked("", true, true,
3309 [this](ProjectManager& target, const std::shared_ptr<threads::TaskQueue>& queue)
3310 {
3311 CloseTaskGuard guard{*this, target, queue, true};
3312 const F_err result = target.closeNow();
3313 guard.finish(result);
3314 }, project.get());
3315 if (queued != errors::NONE)
3316 {
3317 rejected = true;
3318 finishCloseAllMemberLocked(project.get(), queued);
3319 }
3320 }
3321 return rejected ? errors::FAILED_CLOSE_PROJECT : errors::NONE;
3322 }
3323
3328 std::optional<ProjectManager::CloseStatus> closeAllStatus()
3329 {
3330 std::lock_guard<std::mutex> lock(_mutex);
3331 return _closeAllStatus;
3332 }
3333 };
3334}
3335
3336#endif
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.
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).
Definition errors.hpp:13
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.
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.
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...
Definition log_store.hpp:36
std::string project
Project identifier; empty denotes the application.
Definition log_store.hpp:58
std::uint64_t operation
Command id of a command or receipt; zero for lines.
Definition log_store.hpp:68
std::string text
Log message text.
Definition log_store.hpp:62
std::uint64_t arrivedUs
Store-assigned arrival timestamp in microseconds since the Unix epoch.
Definition log_store.hpp:42
int destination
Destination process of a command or receipt; zero for lines.
Definition log_store.hpp:66
bool consoleVisible
Whether this entry may be delivered to the Console or loading window.
Definition log_store.hpp:72
std::string level
Log severity label.
Definition log_store.hpp:50
int process
Source process identifier.
Definition log_store.hpp:46
int kind
What the row records: 0 line, 1 command, 2 receipt, 3 notification, 4 session start (LogEntryKind).
Definition log_store.hpp:64
std::string refUid
For a receipt, the UID of the command it confirms; empty otherwise.
Definition log_store.hpp:70
std::string uid
Globally unique lowercase hexadecimal entry identity.
Definition log_store.hpp:38
std::uint32_t thread
Source thread identifier.
Definition log_store.hpp:54
A parsed incoming message. The payload is a view into the frame, which this keeps alive via shared ow...
Definition message.hpp:169
int32_t F_long
Signed 32-bit integer (also the base of F_err).
Definition types.hpp:32
uint32_t F_ulong
Unsigned 32-bit integer.
Definition types.hpp:34
bool F_bool
Alias for bool.
Definition types.hpp:22