1#ifndef FRAY_PROJECT_MANAGER_HPP
2#define FRAY_PROJECT_MANAGER_HPP
18#include <unordered_map>
55 const std::string& candidate) {
return {
false, candidate}; }
91 const std::string&
name)
95 !(
name.size() >= 4 &&
name.compare(
name.size() - 4, 4,
".fry") == 0);
110 std::unordered_map<std::string, std::unique_ptr<state::StateManager>>
_states;
171 std::shared_ptr<threads::TaskQueue>
_queue;
187 std::function<void(
const std::filesystem::path&)>
_onRenamed;
229 const std::filesystem::path& path)
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)
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);
253 const std::filesystem::path& folder)
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))
260 std::error_code entryError;
261 if (it->is_symlink(entryError) || !it->is_regular_file(entryError))
263 const auto& path = it->path();
264 if (path.extension() ==
".sqlite" && !path.stem().empty())
265 stems.push_back(path.stem().string());
267 std::sort(stems.begin(), stems.end());
278 const std::filesystem::path& folder)
const
281 const std::string current =
_files.projectName();
297 const auto folder =
_files.workingDirectory();
298 const std::string
name =
_files.projectName();
301 return errors::FAILED_OPEN_PROJECT;
303 return _files.snapshotDatabase(
name) ? errors::NONE : errors::FAILED_OPEN_PROJECT;
304 std::vector<std::string> likely;
307 likely.push_back(stem);
310 if (likely.size() == 1)
311 return _files.snapshotDatabase(likely.front()) &&
313 ? errors::NONE : errors::FAILED_OPEN_PROJECT;
316 return errors::DATABASE_CONFLICT;
325 bool removeExtracted)
327 if (removeExtracted &&
_files._extracted &&
_files.removeWorkingDirectory() != errors::NONE)
329 if (!
_files.rollbackConflict())
330 log::engineError(
"Could not restore the unselected project after opening failed.");
331 if (
_files.close() != errors::NONE)
351 const std::string& key,
355 const F_err result =
state.contains(key, exists);
356 if (result != errors::NONE || exists)
358 return state.set(key, value);
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();
381 const std::string&
id)
383 std::lock_guard<std::recursive_mutex> lock(
_mutex);
386 log::engineError(
"Cannot reassign project identity: project state is unavailable.");
387 return errors::FAILED_SAVE_STATE;
389 const F_err result =
_states.at(
"Fray")->set(
"project.info.id",
id);
390 if (result == errors::NONE)
404 F_err result = errors::NONE;
405 const auto apply = [&](
const std::string& key,
const auto& value)
407 if (result == errors::NONE)
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);
421 apply(
"project.info.projectVersion.major", 0);
422 apply(
"project.info.projectVersion.minor", 0);
423 apply(
"project.info.projectVersion.bug", 0);
437 const bool snapshot =
_files._extracted;
438 auto state = std::make_unique<state::StateManager>();
440 if (result == errors::NONE)
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)
453 if (result == errors::NONE)
455 if (result == errors::NONE)
458 if (result != errors::NONE)
464 if (!
_files.commitConflict())
468 return errors::FAILED_OPEN_PROJECT;
494 std::weak_ptr<threads::TaskQueue> queue =
_queue;
497 if (
auto target = queue.lock())
498 target->post([
this] {
pump(); });
504 if (
auto target = queue.lock())
541 return errors::FAILED_RENAME_PROJECT;
545 log::engineError(
"Cannot rename project: a rename is already in progress.");
546 return errors::FAILED_RENAME_PROJECT;
555 return errors::FAILED_RENAME_PROJECT;
573 return errors::FAILED_RENAME_PROJECT;
591 std::lock_guard<std::recursive_mutex> lock(
_mutex);
594 for (
const auto& change : changes)
613 change.previousPath == request.
workspace)
620 followsDatabase =
false;
623 request.
name = change.path.filename().string();
628 request.
databaseStem = std::filesystem::path(change.relative).stem().string();
643 std::lock_guard<std::recursive_mutex> lock(
_mutex);
650 std::filesystem::path(change.
relative).extension() ==
".sqlite"))
662 change.
path.filename().string() !=
_files.projectName())
664 const std::string
name = change.
path.filename().string();
672 change.
relative.find(
'/') != std::string::npos ||
673 std::filesystem::path(change.
relative).extension() !=
".sqlite")
675 const std::string stem = std::filesystem::path(change.
relative).stem().string();
677 if (stem ==
_files.projectName() ||
680 log::engineInfo(
"Project database was renamed to %s.sqlite.", stem.c_str());
695 const std::string& newName,
696 const std::filesystem::path& workspace,
698 std::string databaseStem)
701 const std::string oldName =
_files.projectName();
705 return errors::FAILED_RENAME_PROJECT;
707 _files._workspace = workspace;
708 const auto parent = workspace.parent_path();
709 const auto target = parent / newName;
711 if (renameFolder && (!Files::pathExists(target, exists) || exists))
713 log::engineError(
"Cannot rename project: %s already exists.", target.string().c_str());
714 return errors::FAILED_RENAME_PROJECT;
716 if (databaseStem.empty())
718 if (databaseStem.empty())
720 log::engineError(
"Cannot rename project: its database file could not be found.");
721 return errors::FAILED_RENAME_PROJECT;
723 if (databaseStem != newName &&
724 (!Files::pathExists(workspace / (newName +
".sqlite"), exists) || exists))
726 log::engineError(
"Cannot rename project: %s.sqlite already exists.", newName.c_str());
727 return errors::FAILED_RENAME_PROJECT;
729 Files::ProjectLock newLock;
730 if (!
_files.acquireRename(newName, newLock))
731 return errors::FAILED_RENAME_PROJECT;
733 std::vector<std::unique_lock<std::recursive_mutex>> locks;
734 std::vector<std::pair<std::string, state::StateManager*>>
open;
737 locks.emplace_back(entry.second->mutex());
738 if (entry.second->isOpen())
739 open.emplace_back(entry.first, entry.second.get());
742 const auto reopen = [&]
752 if (
state.second->close() != errors::NONE)
755 Files::unlockProject(newLock);
756 return errors::FAILED_RENAME_PROJECT;
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;
764 if (
_files._archiveExists)
765 archiveMoved = ok = Files::renameExclusive(oldArchive, newArchive);
766 if (ok && renameFolder)
768 folderMoved = ok = Files::renameExclusive(workspace, target);
772 if (ok && databaseStem != newName)
773 databaseMoved = ok = Files::renameFolderDatabase(current, databaseStem, newName);
776 if (databaseMoved && !Files::renameFolderDatabase(current, newName, databaseStem))
778 if (folderMoved && !Files::renameExclusive(target, workspace))
780 if (archiveMoved && !Files::renameExclusive(newArchive, oldArchive))
782 if (databaseStem != oldName && !Files::renameFolderDatabase(workspace, databaseStem, oldName))
784 Files::unlockProject(newLock);
786 return errors::FAILED_RENAME_PROJECT;
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);
795 log::engineInfo(
"Project renamed from %s to %s.", oldName.c_str(), newName.c_str());
827 log::engineError(
"Project could not be closed; check its archive and working folder.");
845 const std::string& path,
849 std::shared_ptr<threads::TaskQueue> queue =
nullptr,
851 std::optional<bool> newProjectPackageDefault = std::nullopt)
853 std::lock_guard<std::recursive_mutex> lock(
_mutex);
857 return errors::FAILED_OPEN_PROJECT;
862 _queue = std::move(queue);
863 const F_err opened =
_files.open(path, choice, mode,
true);
864 if (opened != errors::NONE)
872 const auto folder =
_files.workingDirectory();
873 const auto named = folder / (
_files.projectName() +
".sqlite");
874 bool namedExists =
false;
878 return errors::FAILED_OPEN_PROJECT;
883 std::error_code error;
884 const auto status = std::filesystem::symlink_status(named, error);
894 return errors::PROJECT_DATABASE_OCCUPIED;
912 return errors::INVALID_PROJECT_DATABASE;
917 const auto folder =
_files.workingDirectory();
922 log::engineError(
"Cannot create project: the folder now contains a valid Fray database.");
924 return errors::PROJECT_FOLDER_EXISTS;
927 const auto database = folder / (
_files.projectName() +
".sqlite");
928 for (
const auto* suffix : {
"",
"-wal",
"-shm",
"-journal"})
934 return errors::FAILED_OPEN_PROJECT;
940 return errors::PROJECT_DATABASE_OCCUPIED;
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))
948 const int created =
::open(database.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600);
949 if (created < 0 ||
::close(created) != 0)
952 log::engineError(
"Cannot create project database without overwriting an existing file.");
954 return errors::FAILED_OPEN_PROJECT;
960 if (prepared == errors::DATABASE_CONFLICT)
962 if (prepared != errors::NONE)
973 _files.workingDirectory() / (
_files.projectName() +
".sqlite"), exists))
976 return errors::FAILED_OPEN_PROJECT;
990 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1002 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1006 return errors::FAILED_OPEN_PROJECT;
1013 return errors::FAILED_OPEN_PROJECT;
1018 return errors::FAILED_OPEN_PROJECT;
1031 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1035 return errors::FAILED_OPEN_PROJECT;
1038 return errors::NONE;
1058 const std::string&
name,
1067 log::threadProject() = project;
1068 body(std::move(token));
1123 std::function<
void(
const std::filesystem::path&)> callback)
1125 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1135 std::function<
void()> callback)
1137 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1146 std::function<
F_err(
bool)> dispatcher)
1157 std::function<
bool()> callback)
1159 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1173 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1183 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1196 return errors::NONE;
1205 const std::string& newName)
1207 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1212 return errors::FAILED_RENAME_PROJECT;
1216 log::engineError(
"Cannot rename project: a rename is already in progress.");
1217 return errors::FAILED_RENAME_PROJECT;
1219 if (newName ==
_files.projectName())
1222 return errors::NONE;
1246 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1247 return _files.projectName();
1254 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1288 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1302 const std::string&
name)
1304 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1308 return errors::FAILED_OPEN_STORE;
1311 if (found !=
_states.end() && found->second->isOpen())
1312 return errors::NONE;
1313 auto manager = std::make_unique<state::StateManager>();
1315 if (result != errors::NONE)
1318 return errors::NONE;
1329 const std::string&
name)
1331 std::lock_guard<std::recursive_mutex> lock(
_mutex);
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;
1354 template<
typename T>
1356 const std::string& key,
1359 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1361 if (key ==
"project.info.name")
1364 if constexpr (std::is_convertible_v<const T&, std::string>)
1365 return rename(std::string(value));
1367 return errors::FAILED_SAVE_STATE;
1372 return errors::FAILED_SAVE_STATE;
1374 return _states.at(
"Fray")->set(key, value);
1384 template<
typename T>
1386 const std::string& key,
1389 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1394 return errors::FAILED_LOAD_STATE;
1396 return _states.at(
"Fray")->get(key, value);
1415 bool forcePackage =
false)
1417 std::function<
F_err(
bool)> dispatcher;
1426 return errors::FAILED_CLOSE_PROJECT;
1430 auto worker = std::make_shared<threads::TaskQueue>();
1431 std::thread thread([worker] { worker->run(); });
1438 F_err result = errors::FAILED_CLOSE_PROJECT;
1441 result = closeNow(forcePackage);
1443 catch (
const std::exception& error)
1453 return errors::FAILED_CLOSE_PROJECT;
1455 return errors::NONE;
1458 return dispatcher(forcePackage);
1481 bool forcePackage =
false,
1482 bool* packaged =
nullptr,
1483 bool leaveWorkingFolder =
false)
1485 std::lock_guard<std::recursive_mutex> lock(
_mutex);
1490 return errors::FAILED_CLOSE_PROJECT;
1494 return errors::FAILED_CLOSE_PROJECT;
1500 return errors::FAILED_CLOSE_PROJECT;
1503 if (
state.contains(
"project.preferences.packageOnClose", exists) != errors::NONE)
1504 return errors::FAILED_CLOSE_PROJECT;
1506 if (!forcePackage && !leaveWorkingFolder && exists &&
1509 log::engineError(
"Cannot close project: packageOnClose must be a boolean.");
1510 return errors::FAILED_CLOSE_PROJECT;
1516 else if (forcePackage)
1519 if (entry.second->isOpen() && entry.second->close() != errors::NONE)
1520 return errors::FAILED_CLOSE_PROJECT;
1523 if (
_files.save() != errors::NONE)
1524 return errors::FAILED_SAVE_PROJECT;
1528 return errors::FAILED_CLOSE_PROJECT;
1529 if (
_files.close() != errors::NONE)
1530 return errors::FAILED_CLOSE_PROJECT;
1539 return errors::NONE;
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).
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.
std::optional< F_err > result
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.
std::filesystem::path workspace
The latest queued rename and its result, once finished.
std::optional< F_err > result
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...
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.