Fray Engine
Loading...
Searching...
No Matches
project_manager.hpp
Go to the documentation of this file.
1#ifndef FRAY_PROJECT_MANAGER_HPP
2#define FRAY_PROJECT_MANAGER_HPP
3
4#include <algorithm>
5#include <atomic>
6#include <filesystem>
7#include <functional>
8#include <iomanip>
9#include <memory>
10#include <mutex>
11#include <optional>
12#include <random>
13#include <sstream>
14#include <stdexcept>
15#include <string>
16#include <thread>
17#include <type_traits>
18#include <unordered_map>
19#include <vector>
20
21#include "file_manager.hpp"
22#include "file_watcher.hpp"
23#include "history_manager.hpp"
24#include "state_manager.hpp"
25#include "thread_manager.hpp"
26
27namespace fray
28{
33 namespace message { struct InData; }
34
39 {
43 bool createNew = false;
47 std::string name;
48
55 const std::string& candidate) { return {false, candidate}; }
56
59 static DatabaseChoice create() { return {true, ""}; }
60 };
61
67 {
68 friend class FrayManager;
69
70 public:
73 {
74 bool closing;
75 std::optional<F_err> result;
76 };
77
80 {
82 std::optional<F_err> result;
83 };
84
90 static bool validProjectName(
91 const std::string& name)
92 {
93 return files::FileManager::safeRelative(name) && name.find('/') == std::string::npos &&
94 name != "." && name != ".." &&
95 !(name.size() >= 4 && name.compare(name.size() - 4, 4, ".fry") == 0);
96 }
97
98 private:
102 mutable std::recursive_mutex _mutex;
110 std::unordered_map<std::string, std::unique_ptr<state::StateManager>> _states;
114 std::string _applicationId;
118 std::string _projectId;
122 std::atomic<bool> _open{false};
126 std::atomic<bool> _opening{false};
128 std::atomic<bool> _closePending{false};
132 bool _closing = false;
136 bool _packageOnClose = false;
138 std::optional<bool> _newProjectPackageDefault;
142 bool _archiveComplete = false;
146 bool _pendingDatabase = false;
150 std::vector<std::string> _candidates;
151
171 std::shared_ptr<threads::TaskQueue> _queue;
175 mutable std::mutex _threadMutex;
179 std::vector<threads::ThreadManager::Id> _registered;
187 std::function<void(const std::filesystem::path&)> _onRenamed;
191 std::function<void()> _onClosing;
193 std::function<bool()> _prepareLogClose;
196 {
197 std::string name;
198 std::filesystem::path workspace;
200 std::string databaseStem;
201 };
202
203 std::function<bool(RenameRequest)> _renameDispatcher;
205 mutable std::mutex _renameStatusMutex;
207 std::optional<RenameStatus> _renameStatus;
209 std::atomic<bool> _renamePending{false};
211 std::vector<watch::Change> _renameChanges;
213 mutable std::mutex _closeDispatchMutex;
215 std::function<F_err(bool)> _closeDispatcher;
217 std::optional<CloseStatus> _closeStatus;
219 std::shared_ptr<threads::TaskQueue> _standaloneCloseQueue;
222
229 const std::filesystem::path& path)
230 {
231 sqlite3* db = nullptr;
232 const std::string file = path.string();
233 if (sqlite3_open_v2(file.c_str(), &db, SQLITE_OPEN_READONLY, nullptr) != SQLITE_OK)
234 {
235 if (db != nullptr)
236 sqlite3_close(db);
237 return false;
238 }
239 sqlite3_stmt* statement = nullptr;
240 const bool valid = sqlite3_prepare_v2(db, "SELECT key, type, value FROM fray_state_46726179 LIMIT 0",
241 -1, &statement, nullptr) == SQLITE_OK;
242 sqlite3_finalize(statement);
243 sqlite3_close(db);
244 return valid;
245 }
246
252 static std::vector<std::string> databaseFiles(
253 const std::filesystem::path& folder)
254 {
255 std::vector<std::string> stems;
256 std::error_code error;
257 std::filesystem::directory_iterator it(folder, error), end;
258 for (; !error && it != end; it.increment(error))
259 {
260 std::error_code entryError;
261 if (it->is_symlink(entryError) || !it->is_regular_file(entryError))
262 continue;
263 const auto& path = it->path();
264 if (path.extension() == ".sqlite" && !path.stem().empty())
265 stems.push_back(path.stem().string());
266 }
267 std::sort(stems.begin(), stems.end());
268 return stems;
269 }
270
277 std::string locateDatabase(
278 const std::filesystem::path& folder) const
279 {
281 const std::string current = _files.projectName();
282 if (watch::fileId(folder / (current + ".sqlite"), id) && (!_databaseId.valid() || id == _databaseId))
283 return current;
284 for (const auto& stem : databaseFiles(folder))
285 if (watch::fileId(folder / (stem + ".sqlite"), id) && id == _databaseId)
286 return stem;
287 return "";
288 }
289
296 {
297 const auto folder = _files.workingDirectory();
298 const std::string name = _files.projectName();
299 bool exists = false;
300 if (!files::FileManager::pathExists(folder / (name + ".sqlite"), exists))
301 return errors::FAILED_OPEN_PROJECT;
302 if (exists)
303 return _files.snapshotDatabase(name) ? errors::NONE : errors::FAILED_OPEN_PROJECT;
304 std::vector<std::string> likely;
305 for (const auto& stem : databaseFiles(folder))
306 if (looksLikeFrayDatabase(folder / (stem + ".sqlite")))
307 likely.push_back(stem);
308 if (likely.empty())
309 return errors::NONE;
310 if (likely.size() == 1)
311 return _files.snapshotDatabase(likely.front()) &&
312 files::FileManager::renameFolderDatabase(folder, likely.front(), name)
313 ? errors::NONE : errors::FAILED_OPEN_PROJECT;
314 _candidates = std::move(likely);
315 _pendingDatabase = true;
316 return errors::DATABASE_CONFLICT;
317 }
318
325 bool removeExtracted)
326 {
327 if (removeExtracted && _files._extracted && _files.removeWorkingDirectory() != errors::NONE)
328 log::engineError("Could not remove the extracted working folder.");
329 if (!_files.rollbackConflict())
330 log::engineError("Could not restore the unselected project after opening failed.");
331 if (_files.close() != errors::NONE)
332 log::engineError("Could not release project after opening failed.");
333 _applicationId.clear();
334 _candidates.clear();
335 _pendingDatabase = false;
336 _opening = false;
337 }
338
348 template<typename T>
351 const std::string& key,
352 const T& value)
353 {
354 F_bool exists = false;
355 const F_err result = state.contains(key, exists);
356 if (result != errors::NONE || exists)
357 return result;
358 return state.set(key, value);
359 }
360
365 static std::string newProjectId()
366 {
367 std::random_device device;
368 std::ostringstream out;
369 out << std::hex << std::setfill('0');
370 for (int part = 0; part < 4; ++part)
371 out << std::setw(8) << device();
372 return out.str();
373 }
374
381 const std::string& id)
382 {
383 std::lock_guard<std::recursive_mutex> lock(_mutex);
384 if (!_open || _states.find("Fray") == _states.end())
385 {
386 log::engineError("Cannot reassign project identity: project state is unavailable.");
387 return errors::FAILED_SAVE_STATE;
388 }
389 const F_err result = _states.at("Fray")->set("project.info.id", id);
390 if (result == errors::NONE)
391 _projectId = id;
392 return result;
393 }
394
403 {
404 F_err result = errors::NONE;
405 const auto apply = [&](const std::string& key, const auto& value)
406 {
407 if (result == errors::NONE)
408 result = setDefault(state, key, value);
409 };
410
411 /* Application Info */
412 apply("application.info.name", _applicationId);
413 apply("application.info.engineVersion.major", 0);
414 apply("application.info.engineVersion.minor", 0);
415 apply("application.info.engineVersion.bug", 0);
416 apply("application.info.uiVersion.major", 0);
417 apply("application.info.uiVersion.minor", 0);
418 apply("application.info.uiVersion.bug", 0);
419
420 /* Project Info */
421 apply("project.info.projectVersion.major", 0);
422 apply("project.info.projectVersion.minor", 0);
423 apply("project.info.projectVersion.bug", 0);
424
425 /* Project Preferences */
426 apply("project.preferences.packageOnClose", _newProjectPackageDefault.value_or(false));
427 return result;
428 }
429
436 {
437 const bool snapshot = _files._extracted;
438 auto state = std::make_unique<state::StateManager>();
439 F_err result = state->open(_files, "Fray", _applicationId);
440 if (result == errors::NONE)
441 {
442 // The file name is the source of truth for the project name.
443 F_bool exists = false;
444 std::string stored;
445 result = state->contains("project.info.name", exists);
446 if (result == errors::NONE && exists)
447 result = state->get("project.info.name", stored);
448 if (result == errors::NONE && (!exists || stored != _files.projectName()))
449 result = state->set("project.info.name", _files.projectName());
450 if (result == errors::NONE)
451 result = applyDefaults(*state);
452 // Identifies the project across renames; generated once and stored with it.
453 if (result == errors::NONE)
454 result = setDefault(*state, "project.info.id", newProjectId());
455 if (result == errors::NONE)
456 result = state->get("project.info.id", _projectId);
457 }
458 if (result != errors::NONE)
459 {
460 state.reset();
461 abandon(false);
462 return result;
463 }
464 if (!_files.commitConflict())
465 {
466 state.reset();
467 abandon(false);
468 return errors::FAILED_OPEN_PROJECT;
469 }
470 _states.emplace("Fray", std::move(state));
471 if (snapshot)
472 _files.removeArchive();
473 watch::fileId(_files.workingDirectory() / (_files.projectName() + ".sqlite"), _databaseId);
474 _open = true;
475 _opening = false;
477 return errors::NONE;
478 }
479
485 {
486 if (!_watcher.watch(_files.workingDirectory()))
487 {
488 log::engineError("Cannot watch the project folder.");
489 return;
490 }
491 _subscription = _watcher.subscribe(nullptr, [this](const watch::Change& change) { onChange(change); });
492 if (_threads == nullptr)
493 return;
494 std::weak_ptr<threads::TaskQueue> queue = _queue;
495 _watcher.setNotify([this, queue]
496 {
497 if (auto target = queue.lock())
498 target->post([this] { pump(); });
499 });
500 _watcherThread = registerThread("file-watcher", [this, queue](threads::StopToken token)
501 {
502 _watcher.run(token, [this, queue]
503 {
504 if (auto target = queue.lock())
505 target->post([this] { restoreLock(); });
506 });
507 });
508 }
509
515 {
516 if (_watcherThread != 0)
517 {
519 _watcherThread = 0;
520 }
521 _watcher.setNotify(nullptr);
522 if (_subscription != 0)
523 {
524 _watcher.unsubscribe(_subscription);
525 _subscription = 0;
526 }
527 _watcher.unwatch();
528 }
529
536 RenameRequest request)
537 {
538 if (!validProjectName(request.name))
539 {
540 log::engineError("Cannot rename project: invalid name.");
541 return errors::FAILED_RENAME_PROJECT;
542 }
543 if (_renamePending)
544 {
545 log::engineError("Cannot rename project: a rename is already in progress.");
546 return errors::FAILED_RENAME_PROJECT;
547 }
549 {
550 {
551 std::lock_guard<std::mutex> closeLock(_closeDispatchMutex);
553 {
554 log::engineError("Cannot rename project: its log worker is not ready.");
555 return errors::FAILED_RENAME_PROJECT;
556 }
557 }
558 const F_err result = applyName(request.name, request.workspace,
559 request.renameFolder, request.databaseStem);
560 std::lock_guard<std::mutex> statusLock(_renameStatusMutex);
561 _renameStatus = RenameStatus{false, result};
562 return result;
563 }
564 {
565 std::lock_guard<std::mutex> statusLock(_renameStatusMutex);
566 _renamePending = true;
567 _renameStatus = RenameStatus{true, std::nullopt};
568 }
569 if (_renameDispatcher(std::move(request)))
570 return errors::NONE;
571 finishRename(errors::FAILED_RENAME_PROJECT);
572 log::engineError("Cannot rename project: its log worker is unavailable.");
573 return errors::FAILED_RENAME_PROJECT;
574 }
575
581 F_err result)
582 {
583 std::lock_guard<std::mutex> lock(_renameStatusMutex);
584 _renameStatus = RenameStatus{false, result};
585 _renamePending = false;
586 }
587
590 {
591 std::lock_guard<std::recursive_mutex> lock(_mutex);
592 auto changes = std::move(_renameChanges);
593 _renameChanges.clear();
594 for (const auto& change : changes)
595 onChange(change);
596 }
597
605 RenameRequest request)
606 {
607 _watcher.poll();
608 _watcher.dispatch();
609 bool followsDatabase = request.renameFolder && !request.databaseStem.empty();
610 for (const auto& change : _renameChanges)
611 {
612 if (change.root && change.kind == watch::ChangeKind::Renamed &&
613 change.previousPath == request.workspace)
614 {
615 request.workspace = change.path;
616 request.databaseStem.clear();
617 if (followsDatabase)
618 {
619 request.renameFolder = false;
620 followsDatabase = false;
621 }
622 if (!request.renameFolder)
623 request.name = change.path.filename().string();
624 }
625 else if (followsDatabase && !change.root && change.kind == watch::ChangeKind::Renamed &&
626 !change.directory && change.id == _databaseId)
627 {
628 request.databaseStem = std::filesystem::path(change.relative).stem().string();
629 request.name = request.databaseStem;
630 }
631 }
632 return request;
633 }
634
641 const watch::Change& change)
642 {
643 std::lock_guard<std::recursive_mutex> lock(_mutex);
644 if (!_open || _closing)
645 return;
646 if (_renamePending)
647 {
648 if (change.root || (change.kind == watch::ChangeKind::Renamed && !change.directory &&
649 change.id == _databaseId && change.relative.find('/') == std::string::npos &&
650 std::filesystem::path(change.relative).extension() == ".sqlite"))
651 _renameChanges.push_back(change);
652 return;
653 }
654 if (_closePending)
655 return;
656 if (change.root)
657 {
658 if (change.kind == watch::ChangeKind::Removed)
659 log::engineError("The project folder was removed or moved: %s", change.previousPath.string().c_str());
660 else if (change.kind == watch::ChangeKind::Renamed &&
661 change.previousPath == _files.workingDirectory() &&
662 change.path.filename().string() != _files.projectName())
663 {
664 const std::string name = change.path.filename().string();
665 log::engineInfo("Project folder was renamed to %s.", name.c_str());
666 if (startRename({name, change.path, false, ""}) != errors::NONE)
667 log::engineError("Could not rename the project to match its folder.");
668 }
669 return;
670 }
671 if (change.kind != watch::ChangeKind::Renamed || change.directory || change.id != _databaseId ||
672 change.relative.find('/') != std::string::npos ||
673 std::filesystem::path(change.relative).extension() != ".sqlite")
674 return;
675 const std::string stem = std::filesystem::path(change.relative).stem().string();
676 watch::FileId current;
677 if (stem == _files.projectName() ||
678 !watch::fileId(_files.workingDirectory() / change.relative, current) || current != _databaseId)
679 return;
680 log::engineInfo("Project database was renamed to %s.sqlite.", stem.c_str());
681 if (startRename({stem, _files.workingDirectory(), true, stem}) != errors::NONE)
682 log::engineError("Could not rename the project to match its database.");
683 }
684
695 const std::string& newName,
696 const std::filesystem::path& workspace,
697 bool renameFolder,
698 std::string databaseStem)
699 {
700 using Files = files::FileManager;
701 const std::string oldName = _files.projectName();
702 if (!validProjectName(newName))
703 {
704 log::engineError("Cannot rename project: invalid name.");
705 return errors::FAILED_RENAME_PROJECT;
706 }
707 _files._workspace = workspace;
708 const auto parent = workspace.parent_path();
709 const auto target = parent / newName;
710 bool exists = false;
711 if (renameFolder && (!Files::pathExists(target, exists) || exists))
712 {
713 log::engineError("Cannot rename project: %s already exists.", target.string().c_str());
714 return errors::FAILED_RENAME_PROJECT;
715 }
716 if (databaseStem.empty())
717 databaseStem = locateDatabase(workspace);
718 if (databaseStem.empty())
719 {
720 log::engineError("Cannot rename project: its database file could not be found.");
721 return errors::FAILED_RENAME_PROJECT;
722 }
723 if (databaseStem != newName &&
724 (!Files::pathExists(workspace / (newName + ".sqlite"), exists) || exists))
725 {
726 log::engineError("Cannot rename project: %s.sqlite already exists.", newName.c_str());
727 return errors::FAILED_RENAME_PROJECT;
728 }
729 Files::ProjectLock newLock;
730 if (!_files.acquireRename(newName, newLock))
731 return errors::FAILED_RENAME_PROJECT;
732
733 std::vector<std::unique_lock<std::recursive_mutex>> locks;
734 std::vector<std::pair<std::string, state::StateManager*>> open;
735 for (auto& entry : _states)
736 {
737 locks.emplace_back(entry.second->mutex());
738 if (entry.second->isOpen())
739 open.emplace_back(entry.first, entry.second.get());
740 }
741 auto hold = _watcher.hold();
742 const auto reopen = [&]
743 {
744 bool ok = true;
745 for (auto& state : open)
746 if (!state.second->isOpen() && state.second->open(_files, state.first, _applicationId) != errors::NONE)
747 ok = false;
748 return ok;
749 };
750 // SQLite remembers file names (journal paths), so no connection stays open across a rename.
751 for (auto& state : open)
752 if (state.second->close() != errors::NONE)
753 {
754 reopen();
755 Files::unlockProject(newLock);
756 return errors::FAILED_RENAME_PROJECT;
757 }
758
759 const auto oldArchive = _files._archive;
760 const auto newArchive = parent / (newName + ".fry");
761 auto current = workspace;
762 bool archiveMoved = false, folderMoved = false, databaseMoved = false;
763 bool ok = true;
764 if (_files._archiveExists)
765 archiveMoved = ok = Files::renameExclusive(oldArchive, newArchive);
766 if (ok && renameFolder)
767 {
768 folderMoved = ok = Files::renameExclusive(workspace, target);
769 if (ok)
770 current = target;
771 }
772 if (ok && databaseStem != newName)
773 databaseMoved = ok = Files::renameFolderDatabase(current, databaseStem, newName);
774 if (!ok)
775 {
776 if (databaseMoved && !Files::renameFolderDatabase(current, newName, databaseStem))
777 log::engineError("Could not restore the project database name.");
778 if (folderMoved && !Files::renameExclusive(target, workspace))
779 log::engineError("Could not restore the project folder name.");
780 if (archiveMoved && !Files::renameExclusive(newArchive, oldArchive))
781 log::engineError("Could not restore the project archive name.");
782 if (databaseStem != oldName && !Files::renameFolderDatabase(workspace, databaseStem, oldName))
783 log::engineError("Could not restore the project database name.");
784 Files::unlockProject(newLock);
785 reopen();
786 return errors::FAILED_RENAME_PROJECT;
787 }
788
789 _files.commitRename(newName, current, newLock);
790 F_err result = reopen() ? errors::NONE : errors::FAILED_RENAME_PROJECT;
791 if (result == errors::NONE)
792 result = _states.at("Fray")->set("project.info.name", newName);
793 watch::fileId(current / (newName + ".sqlite"), _databaseId);
794 _watcher.watch(current);
795 log::engineInfo("Project renamed from %s to %s.", oldName.c_str(), newName.c_str());
796 if (_onRenamed)
797 _onRenamed(current);
798 return result;
799 }
800
801 public:
805 ProjectManager() = default;
810 const ProjectManager&) = delete;
815 const ProjectManager&) = delete;
816
821 {
823 _standaloneCloseQueue->shutdown();
824 if (_standaloneCloseThread.joinable())
826 if (_open && closeNow() != errors::NONE)
827 log::engineError("Project could not be closed; check its archive and working folder.");
828 else if (_pendingDatabase)
829 cancelOpen();
830 }
831
845 const std::string& path,
846 const std::string& applicationId,
849 std::shared_ptr<threads::TaskQueue> queue = nullptr,
851 std::optional<bool> newProjectPackageDefault = std::nullopt)
852 {
853 std::lock_guard<std::recursive_mutex> lock(_mutex);
854 if (_open || _files.isOpen() || _pendingDatabase)
855 {
856 log::engineError("Cannot open project: manager already has a project.");
857 return errors::FAILED_OPEN_PROJECT;
858 }
859 _opening = true;
862 _queue = std::move(queue);
863 const F_err opened = _files.open(path, choice, mode, true);
864 if (opened != errors::NONE)
865 {
866 _opening = false;
867 return opened;
868 }
871 {
872 const auto folder = _files.workingDirectory();
873 const auto named = folder / (_files.projectName() + ".sqlite");
874 bool namedExists = false;
875 if (!files::FileManager::pathExists(named, namedExists))
876 {
877 abandon(true);
878 return errors::FAILED_OPEN_PROJECT;
879 }
880 bool valid = false;
881 if (namedExists)
882 {
883 std::error_code error;
884 const auto status = std::filesystem::symlink_status(named, error);
885 valid = !error && std::filesystem::is_regular_file(status) && looksLikeFrayDatabase(named);
886 if (!valid)
887 {
888 for (const auto& stem : databaseFiles(folder))
889 {
890 if (stem != _files.projectName() && looksLikeFrayDatabase(folder / (stem + ".sqlite")))
891 {
892 log::engineError("Cannot open project: its database path is occupied.");
893 abandon(true);
894 return errors::PROJECT_DATABASE_OCCUPIED;
895 }
896 }
897 }
898 }
899 else
900 {
901 for (const auto& stem : databaseFiles(folder))
902 if (looksLikeFrayDatabase(folder / (stem + ".sqlite")))
903 {
904 valid = true;
905 break;
906 }
907 }
908 if (!valid)
909 {
910 log::engineError("Cannot open project: no valid Fray database.");
911 abandon(true);
912 return errors::INVALID_PROJECT_DATABASE;
913 }
914 }
916 {
917 const auto folder = _files.workingDirectory();
918 for (const auto& stem : databaseFiles(folder))
919 {
920 if (looksLikeFrayDatabase(folder / (stem + ".sqlite")))
921 {
922 log::engineError("Cannot create project: the folder now contains a valid Fray database.");
923 abandon(false);
924 return errors::PROJECT_FOLDER_EXISTS;
925 }
926 }
927 const auto database = folder / (_files.projectName() + ".sqlite");
928 for (const auto* suffix : {"", "-wal", "-shm", "-journal"})
929 {
930 bool exists = false;
931 if (!files::FileManager::pathExists(database.string() + suffix, exists))
932 {
933 abandon(false);
934 return errors::FAILED_OPEN_PROJECT;
935 }
936 if (exists)
937 {
938 log::engineError("Cannot create project: a database file already exists.");
939 abandon(false);
940 return errors::PROJECT_DATABASE_OCCUPIED;
941 }
942 }
943#ifdef _WIN32
944 HANDLE created = CreateFileW(database.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW,
945 FILE_ATTRIBUTE_NORMAL, nullptr);
946 if (created == INVALID_HANDLE_VALUE || !CloseHandle(created))
947#else
948 const int created = ::open(database.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600);
949 if (created < 0 || ::close(created) != 0)
950#endif
951 {
952 log::engineError("Cannot create project database without overwriting an existing file.");
953 abandon(false);
954 return errors::FAILED_OPEN_PROJECT;
955 }
956 }
957 const F_err prepared = mode == files::OpenMode::CreateInFolder ||
959 ? errors::NONE : prepareDatabase();
960 if (prepared == errors::DATABASE_CONFLICT)
961 return prepared;
962 if (prepared != errors::NONE)
963 {
964 abandon(true);
965 return prepared;
966 }
967 bool creating = mode == files::OpenMode::CreateNew || mode == files::OpenMode::CreateInFolder ||
970 {
971 bool exists = false;
973 _files.workingDirectory() / (_files.projectName() + ".sqlite"), exists))
974 {
975 abandon(true);
976 return errors::FAILED_OPEN_PROJECT;
977 }
978 creating = !exists;
979 }
980 if (creating)
981 _newProjectPackageDefault = newProjectPackageDefault;
982 return finishOpen();
983 }
984
988 std::vector<std::string> databaseCandidates() const
989 {
990 std::lock_guard<std::recursive_mutex> lock(_mutex);
991 return _candidates;
992 }
993
1000 const DatabaseChoice& choice)
1001 {
1002 std::lock_guard<std::recursive_mutex> lock(_mutex);
1003 if (!_pendingDatabase)
1004 {
1005 log::engineError("No database choice is pending.");
1006 return errors::FAILED_OPEN_PROJECT;
1007 }
1008 if (!choice.createNew)
1009 {
1010 if (std::find(_candidates.begin(), _candidates.end(), choice.name) == _candidates.end())
1011 {
1012 log::engineError("Not a database candidate: %s", choice.name.c_str());
1013 return errors::FAILED_OPEN_PROJECT;
1014 }
1015 if (!_files.snapshotDatabase(choice.name) ||
1016 !files::FileManager::renameFolderDatabase(_files.workingDirectory(), choice.name,
1017 _files.projectName()))
1018 return errors::FAILED_OPEN_PROJECT;
1019 }
1020 _pendingDatabase = false;
1021 _candidates.clear();
1022 return finishOpen();
1023 }
1024
1030 {
1031 std::lock_guard<std::recursive_mutex> lock(_mutex);
1032 if (!_pendingDatabase)
1033 {
1034 log::engineError("No database choice is pending.");
1035 return errors::FAILED_OPEN_PROJECT;
1036 }
1037 abandon(true);
1038 return errors::NONE;
1039 }
1040
1044 void beginOpening() { _opening = true; }
1048 bool isOpening() const { return _opening; }
1049
1058 const std::string& name,
1059 std::function<void(threads::StopToken)> body)
1060 {
1061 std::lock_guard<std::mutex> lock(_threadMutex);
1062 if (_threads == nullptr)
1063 return 0;
1064 const auto id = _threads->spawn(_files.projectName() + ":" + name,
1065 [project = _projectId, body = std::move(body)](threads::StopToken token)
1066 {
1067 log::threadProject() = project;
1068 body(std::move(token));
1069 });
1070 _registered.push_back(id);
1071 return id;
1072 }
1073
1081 {
1083 {
1084 std::lock_guard<std::mutex> lock(_threadMutex);
1085 threads = _threads;
1086 _registered.erase(std::remove(_registered.begin(), _registered.end(), id), _registered.end());
1087 }
1088 if (threads == nullptr)
1089 return;
1090 threads->requestStop(id);
1091 threads->join(id);
1092 }
1093
1096 {
1097 std::lock_guard<std::mutex> lock(_threadMutex);
1098 if (_threads)
1099 for (const auto id : _registered)
1100 _threads->requestStop(id);
1101 }
1102
1106 bool hasThreads() const
1107 {
1108 std::lock_guard<std::mutex> lock(_threadMutex);
1109 if (_threads == nullptr)
1110 return false;
1111 for (const auto id : _registered)
1112 if (_threads->running(id))
1113 return true;
1114 return false;
1115 }
1116
1123 std::function<void(const std::filesystem::path&)> callback)
1124 {
1125 std::lock_guard<std::recursive_mutex> lock(_mutex);
1126 _onRenamed = std::move(callback);
1127 }
1128
1135 std::function<void()> callback)
1136 {
1137 std::lock_guard<std::recursive_mutex> lock(_mutex);
1138 _onClosing = std::move(callback);
1139 }
1140
1146 std::function<F_err(bool)> dispatcher)
1147 {
1148 std::lock_guard<std::mutex> lock(_closeDispatchMutex);
1149 _closeDispatcher = std::move(dispatcher);
1150 }
1151
1157 std::function<bool()> callback)
1158 {
1159 std::lock_guard<std::recursive_mutex> lock(_mutex);
1160 _prepareLogClose = std::move(callback);
1161 }
1162
1167
1172 {
1173 std::lock_guard<std::recursive_mutex> lock(_mutex);
1174 if (_open && !_closing)
1175 _files.restoreLock();
1176 }
1177
1181 void pump()
1182 {
1183 std::lock_guard<std::recursive_mutex> lock(_mutex);
1184 if (_open && !_closing)
1185 _watcher.dispatch();
1186 }
1187
1193 {
1194 _watcher.poll();
1195 pump();
1196 return errors::NONE;
1197 }
1198
1205 const std::string& newName)
1206 {
1207 std::lock_guard<std::recursive_mutex> lock(_mutex);
1208 const log::ProjectScope tag(_projectId);
1209 if (!_open || _closing || _closePending)
1210 {
1211 log::engineError("Cannot rename project: project is closed or closing.");
1212 return errors::FAILED_RENAME_PROJECT;
1213 }
1214 if (_renamePending)
1215 {
1216 log::engineError("Cannot rename project: a rename is already in progress.");
1217 return errors::FAILED_RENAME_PROJECT;
1218 }
1219 if (newName == _files.projectName())
1220 {
1221 finishRename(errors::NONE);
1222 return errors::NONE;
1223 }
1224 return startRename({newName, _files.workingDirectory(), true, ""});
1225 }
1226
1231 std::optional<RenameStatus> renameStatus() const
1232 {
1233 std::lock_guard<std::mutex> lock(_renameStatusMutex);
1234 return _renameStatus;
1235 }
1236
1240 bool isOpen() const { return _open; }
1244 std::string name() const
1245 {
1246 std::lock_guard<std::recursive_mutex> lock(_mutex);
1247 return _files.projectName();
1248 }
1249
1252 std::string id() const
1253 {
1254 std::lock_guard<std::recursive_mutex> lock(_mutex);
1255 return _projectId;
1256 }
1257
1262 {
1266 bool redo = false;
1270 std::string domain;
1274 std::uint64_t fromRevision = 0;
1276 std::uint32_t rendererId = 0;
1277 };
1278
1281 std::optional<PendingStep> pendingStep;
1282
1286 std::string applicationId() const
1287 {
1288 std::lock_guard<std::recursive_mutex> lock(_mutex);
1289 return _applicationId;
1290 }
1291
1295
1302 const std::string& name)
1303 {
1304 std::lock_guard<std::recursive_mutex> lock(_mutex);
1305 if (!_open || _closing)
1306 {
1307 log::engineError("Cannot open state: project is closed or closing.");
1308 return errors::FAILED_OPEN_STORE;
1309 }
1310 auto found = _states.find(name);
1311 if (found != _states.end() && found->second->isOpen())
1312 return errors::NONE;
1313 auto manager = std::make_unique<state::StateManager>();
1314 const F_err result = manager->open(_files, name, _applicationId);
1315 if (result != errors::NONE)
1316 return result;
1317 _states[name] = std::move(manager);
1318 return errors::NONE;
1319 }
1320
1329 const std::string& name)
1330 {
1331 std::lock_guard<std::recursive_mutex> lock(_mutex);
1332 const auto found = _states.find(name);
1333 if (!_open || found == _states.end() || !found->second->isOpen())
1334 throw std::out_of_range("Project state manager is not open: " + name);
1335 return *found->second;
1336 }
1337
1343 {
1344 return history::HistoryManager(state("Fray"));
1345 }
1346
1354 template<typename T>
1356 const std::string& key,
1357 const T& value)
1358 {
1359 std::lock_guard<std::recursive_mutex> lock(_mutex);
1360 const log::ProjectScope tag(_projectId);
1361 if (key == "project.info.name")
1362 {
1363 // Renaming the project renames its folder and database too.
1364 if constexpr (std::is_convertible_v<const T&, std::string>)
1365 return rename(std::string(value));
1366 log::engineError("project.info.name must be a string.");
1367 return errors::FAILED_SAVE_STATE;
1368 }
1369 if (!_open || !_states.at("Fray")->isOpen())
1370 {
1371 log::engineError("Cannot save state: project is closed.");
1372 return errors::FAILED_SAVE_STATE;
1373 }
1374 return _states.at("Fray")->set(key, value);
1375 }
1376
1384 template<typename T>
1386 const std::string& key,
1387 T& value)
1388 {
1389 std::lock_guard<std::recursive_mutex> lock(_mutex);
1390 const log::ProjectScope tag(_projectId);
1391 if (!_open || !_states.at("Fray")->isOpen())
1392 {
1393 log::engineError("Cannot load state: project is closed.");
1394 return errors::FAILED_LOAD_STATE;
1395 }
1396 return _states.at("Fray")->get(key, value);
1397 }
1398
1406 const message::InData& incoming);
1407
1415 bool forcePackage = false)
1416 {
1417 std::function<F_err(bool)> dispatcher;
1418 {
1419 std::lock_guard<std::mutex> lock(_closeDispatchMutex);
1420 dispatcher = _closeDispatcher;
1421 if (!dispatcher)
1422 {
1423 if (_closeStatus && _closeStatus->closing)
1424 {
1425 log::engineError("Cannot close project: a close is already queued.");
1426 return errors::FAILED_CLOSE_PROJECT;
1427 }
1429 {
1430 auto worker = std::make_shared<threads::TaskQueue>();
1431 std::thread thread([worker] { worker->run(); });
1432 _standaloneCloseQueue = std::move(worker);
1433 _standaloneCloseThread = std::move(thread);
1434 }
1435 _closeStatus = CloseStatus{true, std::nullopt};
1436 if (!_standaloneCloseQueue->post([this, forcePackage]
1437 {
1438 F_err result = errors::FAILED_CLOSE_PROJECT;
1439 try
1440 {
1441 result = closeNow(forcePackage);
1442 }
1443 catch (const std::exception& error)
1444 {
1445 log::engineError("Cannot close project: %s", error.what());
1446 }
1447 std::lock_guard<std::mutex> lock(_closeDispatchMutex);
1448 _closeStatus = CloseStatus{false, result};
1449 }))
1450 {
1451 _closeStatus = CloseStatus{false, errors::FAILED_CLOSE_PROJECT};
1452 log::engineError("Cannot close project: the close queue is stopped.");
1453 return errors::FAILED_CLOSE_PROJECT;
1454 }
1455 return errors::NONE;
1456 }
1457 }
1458 return dispatcher(forcePackage);
1459 }
1460
1465 std::optional<CloseStatus> closeStatus() const
1466 {
1467 std::lock_guard<std::mutex> lock(_closeDispatchMutex);
1468 return _closeStatus;
1469 }
1470
1471 private:
1481 bool forcePackage = false,
1482 bool* packaged = nullptr,
1483 bool leaveWorkingFolder = false)
1484 {
1485 std::lock_guard<std::recursive_mutex> lock(_mutex);
1486 const log::ProjectScope tag(_projectId);
1487 if (!_open)
1488 {
1489 log::engineError("Cannot close project: project is not open.");
1490 return errors::FAILED_CLOSE_PROJECT;
1491 }
1492 stopWatching();
1494 return errors::FAILED_CLOSE_PROJECT;
1495 if (_onClosing)
1496 _onClosing();
1497 if (!_closing)
1498 {
1499 if (openState("Fray") != errors::NONE)
1500 return errors::FAILED_CLOSE_PROJECT;
1501 auto& state = *_states.at("Fray");
1502 F_bool exists = false;
1503 if (state.contains("project.preferences.packageOnClose", exists) != errors::NONE)
1504 return errors::FAILED_CLOSE_PROJECT;
1505 _packageOnClose = false;
1506 if (!forcePackage && !leaveWorkingFolder && exists &&
1507 state.get("project.preferences.packageOnClose", _packageOnClose) != errors::NONE)
1508 {
1509 log::engineError("Cannot close project: packageOnClose must be a boolean.");
1510 return errors::FAILED_CLOSE_PROJECT;
1511 }
1512 if (forcePackage)
1513 _packageOnClose = true;
1514 _closing = true;
1515 }
1516 else if (forcePackage)
1517 _packageOnClose = true;
1518 for (auto& entry : _states)
1519 if (entry.second->isOpen() && entry.second->close() != errors::NONE)
1520 return errors::FAILED_CLOSE_PROJECT;
1522 {
1523 if (_files.save() != errors::NONE)
1524 return errors::FAILED_SAVE_PROJECT;
1525 _archiveComplete = true;
1526 }
1527 if (_packageOnClose && _files.removeWorkingDirectory() != errors::NONE)
1528 return errors::FAILED_CLOSE_PROJECT;
1529 if (_files.close() != errors::NONE)
1530 return errors::FAILED_CLOSE_PROJECT;
1531 if (packaged)
1532 *packaged = _packageOnClose;
1533 _states.clear();
1534 _applicationId.clear();
1535 _open = false;
1536 _closing = false;
1537 _packageOnClose = false;
1538 _archiveComplete = false;
1539 return errors::NONE;
1540 }
1541 };
1542}
1543
1544#endif
F_err startRename(RenameRequest request)
Starts a rename while holding _mutex, or applies it directly for a standalone project.
void setClosingCallback(std::function< void()> callback)
Replaces the callback invoked at close start before packaging or deletion. Takes _mutex; the callback...
std::optional< PendingStep > pendingStep
Pending asynchronous history step, accessed only on the project queue.
void startWatching()
Watches the project folder and, when configured, starts a watcher thread that posts to the project qu...
history::HistoryManager history()
Returns a history manager borrowing the open Fray state store.
std::recursive_mutex _mutex
Protects project lifecycle, state map, file operations and callbacks; recursive for nested operations...
static bool validProjectName(const std::string &name)
Checks whether a project name is a safe single relative component without a .fry suffix.
watch::FileId _databaseId
File identity used to recognize the project database across renames, guarded by _mutex.
static F_err setDefault(state::StateManager &state, const std::string &key, const T &value)
Writes a default only if the state key is absent. Runs on the opening thread through the state manage...
F_err openState(const std::string &name)
Opens a named state store if not already open, under _mutex.
std::string _applicationId
Application identifier used when opening state stores, guarded by _mutex.
std::vector< watch::Change > _renameChanges
Watcher changes received while a rename is pending, guarded by _mutex.
bool _archiveComplete
Whether packaging already succeeded during a retriable close, guarded by _mutex.
std::string applicationId() const
Returns a copy of the application identifier under _mutex.
std::function< void(const std::filesystem::path &)> _onRenamed
Owned callback invoked with the new working path while _mutex is held.
std::optional< RenameStatus > _renameStatus
Latest managed or standalone rename state, guarded by _renameStatusMutex.
std::string _projectId
Persistent project identifier used for logging and identity, guarded by _mutex.
bool isOpening() const
Returns whether the atomic opening flag is set.
static std::vector< std::string > databaseFiles(const std::filesystem::path &folder)
Lists sorted stems of nonsymlink regular .sqlite files in a folder.
std::atomic< bool > _renamePending
True while a managed rename is in progress.
threads::ThreadManager::Id registerThread(const std::string &name, std::function< void(threads::StopToken)> body)
Registers and starts a project-owned thread under _threadMutex. The thread is tagged with the project...
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...
F_err applyName(const std::string &newName, const std::filesystem::path &workspace, bool renameFolder, std::string databaseStem)
Coordinates project folder, database, lock, archive and stored-name changes. Caller must hold _mutex;...
std::function< F_err(bool)> _closeDispatcher
Manager-provided dispatcher for closing an owned project.
void stopThread(threads::ThreadManager::Id id)
Removes a thread from registration, requests its stop and joins it. Releases _threadMutex before join...
bool _closing
Whether close has begun and can be retried, guarded by _mutex.
std::function< void()> _onClosing
Owned callback invoked when close starts while _mutex is held.
~ProjectManager()
Closes an open project or cancels a pending database choice, logging close failures.
void restoreLock()
Recreates a renamed or deleted project lock while open, under _mutex.
std::string id() const
Returns a copy of the persistent project ID under _mutex.
std::optional< RenameStatus > renameStatus() const
Reads the most recent rename state without waiting for its work.
files::FileManager & fileManager()
Returns a borrowed file manager reference; callers must coordinate access and lifetime.
threads::ThreadManager::Id _watcherThread
Registered watcher thread ID, or zero when none exists.
void stopWatching()
Stops and joins the watcher thread, removes its subscription and unwatches the folder....
std::unordered_map< std::string, std::unique_ptr< state::StateManager > > _states
Owns named state stores; map and lifetimes are guarded by _mutex.
watch::FileWatcher::Subscription _subscription
Watcher subscription for project changes, or zero when absent.
std::atomic< bool > _opening
Whether an opening attempt is in progress, readable without _mutex.
F_err close(bool forcePackage=false)
Requests a project close without waiting for it to finish. Keep a standalone project alive until clos...
void onChange(const watch::Change &change)
Handles project folder and database rename events on the dispatching thread. Takes _mutex and may ren...
ProjectManager(const ProjectManager &)=delete
Project managers cannot be copied.
std::function< bool(RenameRequest)> _renameDispatcher
Dispatches a managed rename to its log and project queues.
ProjectManager & operator=(const ProjectManager &)=delete
Project managers cannot be copy-assigned.
std::thread _standaloneCloseThread
Worker draining the standalone close queue.
std::optional< CloseStatus > _closeStatus
Latest close state, guarded by _closeDispatchMutex.
std::vector< threads::ThreadManager::Id > _registered
IDs registered for this project, guarded by _threadMutex.
void setRenameCallback(std::function< void(const std::filesystem::path &)> callback)
Replaces the callback invoked with the new working path after a rename. Takes _mutex; the callback ru...
bool _pendingDatabase
Whether opening awaits a database choice, guarded by _mutex.
std::mutex _renameStatusMutex
Protects the observable rename status.
files::FileManager _files
Owns project paths, lock and archive operations, normally guarded by _mutex.
ProjectMessageResult handleProjectMessage(const message::InData &incoming)
Handles a close, layout-change or history-step message on the selected project queue....
RenameRequest refreshRenameRequest(RenameRequest request)
Updates a queued rename for folder moves observed while its log was suspended. Caller holds _mutex.
F_err cancelOpen()
Abandons a pending database choice under _mutex, removing an extracted folder but leaving the archive...
F_err prepareDatabase()
Selects, snapshots or adopts a project database before opening state. Caller must hold _mutex; multip...
std::function< bool()> _prepareLogClose
Coordinates the owned log session before project files are closed or packaged.
F_err get(const std::string &key, T &value)
Reads Fray state under _mutex.
bool isOpen() const
Returns whether the atomic open flag is set.
std::optional< bool > _newProjectPackageDefault
Packaging default captured for a newly created project.
void setCloseDispatcher(std::function< F_err(bool)> dispatcher)
Installs the owner-provided asynchronous close dispatcher.
static bool looksLikeFrayDatabase(const std::filesystem::path &path)
Checks read-only for the current Fray state table and its key, type and value columns.
std::optional< CloseStatus > closeStatus() const
Reads the most recent direct or managed close state.
std::string name() const
Returns a copy of the current project name under _mutex.
std::atomic< bool > _closePending
Whether a managed close has been queued, readable without _mutex.
static std::string newProjectId()
Generates a hexadecimal project identifier from random-device values.
std::mutex _closeDispatchMutex
Protects the close dispatcher and the standalone close worker.
void pump()
Dispatches queued watcher events on the calling thread while open, under _mutex.
std::string locateDatabase(const std::filesystem::path &folder) const
Finds the database by its recorded file identity, including after a rename. Caller must hold _mutex.
void requestStopThreads()
Requests cooperative termination of registered project threads without joining them.
void abandon(bool removeExtracted)
Rolls back an unsuccessful open, releases files and clears pending state. Caller must hold _mutex; cl...
watch::FileWatcher _watcher
Owns project folder watching and dispatch.
F_err resolveDatabase(const DatabaseChoice &choice)
Resolves a pending database conflict and finishes opening under _mutex.
bool _packageOnClose
Whether the current close attempt packages the project, guarded by _mutex.
void finishRename(F_err result)
Records the result of a queued rename.
void beginOpening()
Marks the project as opening using an atomic flag.
F_err applyDefaults(state::StateManager &state)
Adds missing application and project defaults without replacing existing settings....
watch::FileWatcher & watcher()
Returns a borrowed watcher reference; its lifetime is bounded by this manager.
std::mutex _threadMutex
Protects registered-thread bookkeeping and thread-manager access in thread methods.
std::atomic< bool > _open
Whether a project is open, readable without _mutex.
state::StateManager & state(const std::string &name)
Returns a borrowed reference to an open named state store under _mutex. The reference is invalidated ...
std::shared_ptr< threads::TaskQueue > _standaloneCloseQueue
Queue used for asynchronous closes of standalone projects.
F_err refreshFiles()
Polls the watcher and dispatches changes on the calling thread.
threads::ThreadManager * _threads
Non-owning thread manager supplied at open; it must outlive registered threads.
void setLogCloseBarrier(std::function< bool()> callback)
Installs the owner-provided project-log close barrier.
std::vector< std::string > databaseCandidates() const
Returns a locked copy of database stems offered after DATABASE_CONFLICT.
bool hasThreads() const
Returns whether any registered project thread is running, under _threadMutex.
ProjectManager()=default
Constructs an initially closed project manager.
F_err set(const std::string &key, const T &value)
Writes Fray state under _mutex; project.info.name instead requests a project rename.
std::vector< std::string > _candidates
Candidate database stems for a pending choice, guarded by _mutex.
F_err reassignProjectId(const std::string &id)
Persists a replacement identity for an open copied project.
F_err rename(const std::string &newName)
Requests a project rename; managed projects complete it on their queues.
F_err finishOpen()
Opens Fray state, applies defaults, commits conflict resolution and starts watching....
void replayRenameChanges()
Replays watcher changes received while a rename was in progress.
std::shared_ptr< threads::TaskQueue > _queue
Shared project queue used to post watcher work.
F_err open(const std::string &path, const std::string &applicationId, files::ConflictChoice choice=files::ConflictChoice::Ask, threads::ThreadManager *threads=nullptr, std::shared_ptr< threads::TaskQueue > queue=nullptr, files::OpenMode mode=files::OpenMode::OpenOrCreate, std::optional< bool > newProjectPackageDefault=std::nullopt)
Opens or creates a project and its Fray state on the calling thread. Intended for the project thread;...
Owns one working directory, its database name and a nonblocking file lock. Project workspaces additio...
static bool safeRelative(const std::string &name)
Checks whether a project entry name is a safe relative path.
static bool pathExists(const std::filesystem::path &path, bool &exists)
Inspects a path without following its final symbolic link.
static bool renameFolderDatabase(const std::filesystem::path &folder, const std::string &oldName, const std::string &newName)
Renames a folder’s database and SQLite sidecars without overwriting destinations. Attempts to reverse...
Accesses project undo/redo trees stored beside state in the project database. Each domain has a head;...
Temporarily tag log lines on the calling thread, then restore its previous tag. Construct and destroy...
Owns a SQLite connection and a typed key/value state table. Database operations serialize on a recurs...
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.
Detects folder-tree changes by comparing snapshots and queues them for subscribers....
std::uint64_t Subscription
Identifier used to unregister a subscriber.
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...
F_void engineInfo(const F_char *fmt,...)
Log info for Engine.
F_void engineError(const F_char *fmt,...)
Log error for Engine.
bool fileId(const std::filesystem::path &path, FileId &id)
Reads the entry identity without following a symbolic link.
Chooses an existing candidate database or a new database when opening is ambiguous.
static DatabaseChoice use(const std::string &candidate)
Selects an existing database candidate.
std::string name
Candidate database file stem without the .sqlite extension.
static DatabaseChoice create()
Returns a choice to create a new database.
bool createNew
True to create a new database instead of adopting a candidate.
The latest queued close and its result, once finished.
Undo/redo request waiting asynchronously for renderer-supplied revisions; used only on the project qu...
std::string domain
Requested history domain, or empty to consider all domains.
std::uint64_t fromRevision
Renderer layout revision from which to step.
bool redo
True for redo; false for undo.
std::uint32_t rendererId
Renderer instance that requested the step.
Rename arguments captured before the log worker suspends its session.
The latest queued rename and its result, once finished.
Project message status and optional response frame.
A parsed incoming message. The payload is a view into the frame, which this keeps alive via shared ow...
Definition message.hpp:169
Describes a detected change to the watched root or one of its entries.
std::filesystem::path previousPath
Previous path for a rename; root removals also record the old root here.
ChangeKind kind
Kind of change detected.
bool root
Whether the change describes the watched root itself.
std::filesystem::path path
Path of the changed entry when detected, based on the watched root.
FileId id
Entry identity when available; ordinary entry removals leave it unset.
std::string relative
Entry path relative to the watched root, empty for root changes.
bool directory
Whether the changed entry is a directory.
Filesystem identity surviving renames: device and inode, or volume and file index.
bool F_bool
Alias for bool.
Definition types.hpp:22