Fray Engine
Loading...
Searching...
No Matches
fray_message_handler.hpp
Go to the documentation of this file.
1#ifndef FRAY_MESSAGE_HANDLER_HPP
2#define FRAY_MESSAGE_HANDLER_HPP
3
4#include "fray_manager.hpp"
5#include "ipc_manager.hpp"
7
8#include <algorithm>
9#include <chrono>
10#include <cctype>
11
12namespace fray
13{
18 const std::string& id,
19 const std::string& name,
20 bool packageOnClose,
21 const std::string& error);
22
31 FrayManager& application,
33 F_ulong renderer,
34 const std::string& error = "")
35 {
36 ApplicationPreferences preferences;
37 if (application.readApplicationPreferences(preferences) != errors::NONE)
38 preferences.set_error("Could not read application preferences. See the Engine log.");
39 else if (!error.empty())
40 preferences.set_error(error);
41 message::FrameOptions options{PROCESS_KIND_ELECTRON_RENDERER, COMMAND_APPLICATION_PREFERENCES, renderer};
42 options.payload = preferences.SerializeAsString();
43 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
44 options.messageType = MESSAGE_TYPE_APPLICATION_PREFERENCES;
45 options.flags = MESSAGE_FLAG_NO_CONSOLE;
46 ipc.sendBuilt(options);
47 }
48
58 const FrayManager::OpeningOrigin& origin,
59 const std::string& path,
60 F_err result)
61 {
62 ProjectCreateResult payload;
63 payload.set_request_id(origin.requestId);
64 payload.set_path(path);
65 if (result == errors::NONE)
66 {
67 std::filesystem::path working(path);
68 if (working.extension() == ".fry")
69 working.replace_extension();
70 payload.set_working_path(working.string());
71 payload.set_status(origin.creating ? PROJECT_CREATE_SUCCEEDED : PROJECT_OPEN_SUCCEEDED);
72 }
73 else if (result == errors::PROJECT_FOLDER_EXISTS)
74 payload.set_status(PROJECT_FOLDER_CONFLICT);
75 else if (result == errors::PROJECT_ARCHIVE_EXISTS)
76 payload.set_status(PROJECT_ARCHIVE_CONFLICT);
77 else if (result == errors::PROJECT_BOTH_EXIST || result == errors::PROJECT_CONFLICT)
78 payload.set_status(PROJECT_BOTH_CONFLICT);
79 else if (result == errors::PROJECT_ALREADY_OPEN)
80 payload.set_error("This project is already open.");
81 else if (result == errors::PROJECT_NOT_FOUND)
82 payload.set_error("The selected project no longer exists.");
83 else if (result == errors::INVALID_PROJECT_DATABASE)
84 {
85 payload.set_status(PROJECT_INVALID_DATABASE);
86 payload.set_error("The selected project has no valid Fray database.");
87 }
88 else if (result == errors::DATABASE_CONFLICT)
89 payload.set_error("The project has multiple possible databases.");
90 else if (result == errors::PROJECT_DATABASE_OCCUPIED)
91 payload.set_error("A file already occupies the project database path; it was not overwritten.");
92 else if (result == errors::INVALID_MESSAGE)
93 payload.set_error("The project path or request is invalid.");
94 else
95 payload.set_error("Could not open the project. See the Engine log for details.");
96 message::FrameOptions options{origin.sender, COMMAND_PROJECT_CREATE_RESULT, origin.senderId};
97 options.payload = payload.SerializeAsString();
98 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
99 options.messageType = MESSAGE_TYPE_PROJECT_CREATE_RESULT;
100 ipc.sendBuilt(options);
101 }
102
106 {
108 setOpeningNotifier([this, &ipc](const OpeningStatus& status)
109 {
110 if (!status.result)
111 return;
112 if (status.origin)
113 sendProjectOpenResult(ipc, *status.origin, status.path, *status.result);
114 else if (status.restoring && *status.result != errors::NONE)
115 sendProjectOpenResult(ipc, OpeningOrigin{PROCESS_KIND_ELECTRON_RENDERER, message::MAIN_WINDOW_ID, 0, false},
116 status.path, *status.result);
117 if ((*status.result == errors::NONE || status.remainsOpen) && (status.origin || status.restoring))
119 });
120 }
121
125 {
126 bool enabled = false;
127 F_err result = get("application.preferences.reopenProjectsOnLaunch", enabled);
128 if (result != errors::NONE || !enabled)
129 return result;
131 result = get("application.session.lastOpenProjects", bytes);
132 if (result == errors::STATE_NOT_FOUND)
133 return errors::NONE;
134 ProjectSession session;
135 if (result != errors::NONE || bytes.size() > 1024 * 1024 ||
136 !session.ParseFromArray(bytes.data(), static_cast<int>(bytes.size())))
137 {
138 log::engineError("Cannot restore projects: saved session is invalid.");
139 return errors::FAILED_LOAD_STATE;
140 }
141 std::unordered_set<std::string> paths;
142 std::unordered_set<std::string> ids;
143 for (const auto& project : session.projects())
144 {
145 const std::filesystem::path path(project.path());
146 if (project.id().empty() || project.id().find('\0') != std::string::npos ||
147 project.path().find('\0') != std::string::npos || !path.is_absolute() ||
148 !paths.insert(path.lexically_normal().string()).second)
149 {
150 log::engineError("Cannot restore projects: saved project identity or path is invalid.");
151 return errors::FAILED_LOAD_STATE;
152 }
153 ids.insert(project.id());
154 }
155 if ((session.projects().empty() && !session.active_id().empty()) ||
156 (!session.projects().empty() && !ids.count(session.active_id())))
157 {
158 log::engineError("Cannot restore projects: saved active project is invalid.");
159 return errors::FAILED_LOAD_STATE;
160 }
162 if (!postApplication([this, &ipc, session]
163 {
164 int activeIndex = -1;
165 for (int i = 0; i < session.projects_size(); ++i)
166 if (session.projects(i).id() == session.active_id())
167 activeIndex = i;
168 std::size_t rank = 0;
169 for (int i = 0; i < session.projects_size(); ++i)
170 {
171 const auto& project = session.projects(i);
172 const std::size_t order = i == activeIndex
173 ? static_cast<std::size_t>(session.projects_size() - 1) : rank++;
174 const F_err opened = openProject(project.path(), files::ConflictChoice::Ask, true,
175 files::OpenMode::OpenExisting, std::nullopt, order, project.id());
176 if (opened != errors::NONE)
177 sendProjectOpenResult(ipc, OpeningOrigin{PROCESS_KIND_ELECTRON_RENDERER, message::MAIN_WINDOW_ID, 0, false},
178 project.path(), opened);
179 }
180 }))
181 {
182 log::engineError("Cannot queue project restoration: application worker is stopping.");
183 return errors::FAILED_OPEN_PROJECT;
184 }
185 return errors::NONE;
186 }
187
194 const PromptRequest& request,
195 uint64_t& requestId)
196 {
197 const auto blank = [](const std::string& value)
198 {
199 return std::all_of(value.begin(), value.end(), [](unsigned char ch) { return std::isspace(ch); });
200 };
201 if (blank(request.title()) || request.buttons().empty() ||
202 std::any_of(request.buttons().begin(), request.buttons().end(),
203 [&](const PromptButton& button) { return blank(button.label()); }))
204 {
205 log::engineError("Cannot request prompt: title and labeled buttons are required.");
206 return false;
207 }
208 message::FrameOptions options{PROCESS_KIND_ELECTRON_RENDERER, COMMAND_PROMPT_REQUEST, message::MAIN_WINDOW_ID};
209 options.payload = request.SerializeAsString();
210 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
211 options.messageType = MESSAGE_TYPE_PROMPT_REQUEST;
212 ipc::Frame frame;
213 const F_err built = message::FrameBuilder{}.build(options, frame);
214 message::InData parsed;
215 if (built != errors::NONE || message::parseFrame(frame, parsed) != errors::NONE)
216 {
217 log::engineError("Cannot build prompt request.");
218 return false;
219 }
220 std::lock_guard<std::mutex> lock(_promptMutex);
221 if (_promptClosing)
222 {
223 log::engineError("Cannot request prompt: application is shutting down.");
224 return false;
225 }
226 const uint64_t id = parsed.header.message_id();
227 _pendingPrompts.emplace(id, PendingPrompt{request, {}, false});
228 if (!ipc.send(frame))
229 {
230 _pendingPrompts.erase(id);
231 return false;
232 }
233 requestId = id;
234 return true;
235 }
236
242 const message::InData& incoming,
244 {
245 const auto& prefix = incoming.prefix;
246 if (prefix.category != MESSAGE_CATEGORY_COMMAND)
247 {
248 log::engineWarn("Cannot handle application operation: expected a command.");
249 return;
250 }
251 if (prefix.operationId == COMMAND_QUIT)
252 {
253 if (prefix.destinationKind != PROCESS_KIND_ENGINE || prefix.destinationId != 0 ||
254 prefix.senderKind != PROCESS_KIND_ELECTRON_MAIN || prefix.senderId != 0 ||
255 incoming.header.payload_type() != PAYLOAD_TYPE_NONE ||
256 incoming.header.message_type() != MESSAGE_TYPE_NONE ||
257 incoming.header.has_target_project() || incoming.payloadSize() != 0)
258 {
259 log::engineError("Cannot request shutdown: invalid quit command.");
260 return;
261 }
262 log::engineInfo("Quit requested by the UI.");
264 ipc.pollShutdown();
265 return;
266 }
267 if (prefix.operationId == COMMAND_LOG_ENTRY)
268 {
269 handleLogMessage(incoming, ipc);
270 return;
271 }
272 if (prefix.operationId == COMMAND_LOADING_READY_TO_SHOW)
273 {
274 if (prefix.destinationKind != PROCESS_KIND_ENGINE || prefix.destinationId != 0 ||
275 prefix.senderKind != PROCESS_KIND_ELECTRON_RENDERER || prefix.senderId != message::LOADING_WINDOW_ID ||
276 incoming.header.payload_type() != PAYLOAD_TYPE_NONE || incoming.header.message_type() != MESSAGE_TYPE_NONE ||
277 incoming.header.has_target_project() || incoming.payloadSize() != 0)
278 {
279 log::engineError("Cannot show loading window: invalid readiness intent.");
280 return;
281 }
282 ipc.loadingReadyToShow();
283 return;
284 }
285 if (prefix.operationId == COMMAND_MAIN_FRAME_READY)
286 {
287 if (prefix.destinationKind != PROCESS_KIND_ENGINE || prefix.destinationId != 0 ||
288 prefix.senderKind != PROCESS_KIND_ELECTRON_MAIN || prefix.senderId != 0 ||
289 incoming.header.payload_type() != PAYLOAD_TYPE_NONE || incoming.header.message_type() != MESSAGE_TYPE_NONE ||
290 incoming.header.has_target_project() || incoming.payloadSize() != 0)
291 {
292 log::engineError("Cannot record main frame readiness: invalid announcement.");
293 return;
294 }
295 ipc.mainFrameIsReady();
296 return;
297 }
298 if (prefix.operationId == COMMAND_STARTUP_FAILED)
299 {
300 StartupFailure failure;
301 if (prefix.destinationKind != PROCESS_KIND_ENGINE || prefix.destinationId != 0 ||
302 prefix.senderKind != PROCESS_KIND_ELECTRON_MAIN || prefix.senderId != 0 ||
303 incoming.header.payload_type() != PAYLOAD_TYPE_PROTOBUF ||
304 incoming.header.message_type() != MESSAGE_TYPE_STARTUP_FAILURE || incoming.header.has_target_project() ||
305 !failure.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())) || failure.error().empty())
306 {
307 log::engineError("Cannot record startup failure: invalid announcement.");
308 return;
309 }
310 ipc.startupFailed(failure.error());
311 return;
312 }
313 if (prefix.operationId == COMMAND_NOTIFY)
314 {
315 handleNotification(incoming, ipc);
316 return;
317 }
318 if (prefix.operationId == COMMAND_APPLICATION_STYLE_REQUEST)
319 {
320 ApplicationStyle request;
321 if (prefix.destinationKind != PROCESS_KIND_ENGINE || prefix.destinationId != 0 ||
322 prefix.senderKind != PROCESS_KIND_ELECTRON_RENDERER || prefix.senderId != message::MAIN_WINDOW_ID ||
323 incoming.header.has_target_project() || incoming.header.payload_type() != PAYLOAD_TYPE_PROTOBUF ||
324 incoming.header.message_type() != MESSAGE_TYPE_APPLICATION_STYLE ||
325 !request.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())) ||
326 !request.error().empty() || request.css().size() > style::maximumStyleSize ||
327 request.css().find('\0') != std::string::npos)
328 {
329 log::engineError("Cannot handle application stylesheet: invalid request.");
330 return;
331 }
332 const auto renderer = prefix.senderId;
333 // Delivers an independent stylesheet result to the requesting renderer.
334 const auto deliver = [&ipc, renderer](const ApplicationStyle& style)
335 {
336 message::FrameOptions options{PROCESS_KIND_ELECTRON_RENDERER, COMMAND_APPLICATION_STYLE, renderer};
337 options.payload = style.SerializeAsString();
338 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
339 options.messageType = MESSAGE_TYPE_APPLICATION_STYLE;
340 options.flags = MESSAGE_FLAG_NO_CONSOLE;
341 ipc.sendBuilt(options);
342 };
344 if (!postApplication([this, request, deliver]
345 {
346 ApplicationStyle result;
347 result.set_save(request.save());
348 result.set_edit(request.edit());
349 std::string css = request.css();
350 const F_err status = request.save() ? saveButtonStyle(css) : loadButtonStyle(css, css);
351 if (status == errors::NONE) result.set_css(css);
352 else result.set_error(request.save() ? "Could not save button stylesheet. See the Engine log."
353 : "Could not load button stylesheet. See the Engine log.");
354 deliver(result);
355 }))
356 {
357 log::engineError("Cannot handle application stylesheet: application worker is stopping.");
358 ApplicationStyle result;
359 result.set_save(request.save());
360 result.set_edit(request.edit());
361 result.set_error("Application stylesheet is unavailable during shutdown.");
362 deliver(result);
363 }
364 return;
365 }
366 if (prefix.operationId == COMMAND_APPLICATION_PREFERENCES_REQUEST ||
367 prefix.operationId == COMMAND_APPLICATION_PREFERENCE_CHANGE)
368 {
369 const bool changing = prefix.operationId == COMMAND_APPLICATION_PREFERENCE_CHANGE;
370 ApplicationPreferenceChange change;
371 if (prefix.destinationKind != PROCESS_KIND_ENGINE || prefix.destinationId != 0 ||
372 prefix.senderKind != PROCESS_KIND_ELECTRON_RENDERER || prefix.senderId != message::MAIN_WINDOW_ID ||
373 incoming.header.has_target_project() ||
374 (changing && (incoming.header.payload_type() != PAYLOAD_TYPE_PROTOBUF ||
375 incoming.header.message_type() != MESSAGE_TYPE_APPLICATION_PREFERENCE_CHANGE ||
376 !change.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())) ||
377 change.change_case() == ApplicationPreferenceChange::CHANGE_NOT_SET)) ||
378 (!changing && (incoming.header.payload_type() != PAYLOAD_TYPE_NONE ||
379 incoming.header.message_type() != MESSAGE_TYPE_NONE || incoming.payloadSize() != 0)))
380 {
381 log::engineError("Cannot handle application preferences: invalid request.");
382 return;
383 }
384 const auto renderer = prefix.senderId;
385 if (!postApplication([this, &ipc, renderer, changing, change]
386 {
387 F_err result = errors::NONE;
388 if (changing)
389 {
390 switch (change.change_case())
391 {
392 case ApplicationPreferenceChange::kDefaultSaveLocation:
393 {
394 const auto& folder = change.default_save_location();
395 const std::filesystem::path path(folder);
396 std::error_code error;
397 if ((!folder.empty() && (!path.is_absolute() || folder.find('\0') != std::string::npos ||
398 !std::filesystem::is_directory(path, error))) || error)
399 {
400 log::engineError("Cannot set default project location: folder is unavailable.");
401 result = errors::INVALID_MESSAGE;
402 }
403 else
404 result = set("application.preferences.defaultSaveLocation", folder);
405 break;
406 }
407 case ApplicationPreferenceChange::kReopenProjectsOnLaunch:
408 result = set("application.preferences.reopenProjectsOnLaunch", change.reopen_projects_on_launch());
409 break;
410 case ApplicationPreferenceChange::kPackageOnClose:
411 result = set("application.preferences.packageOnClose", change.package_on_close());
412 break;
413 case ApplicationPreferenceChange::kDatabasePath:
414 result = switchApplicationState(change.database_path());
415 break;
416 case ApplicationPreferenceChange::kReset:
417 result = change.reset() ? resetApplicationPreferences() : errors::INVALID_MESSAGE;
418 break;
419 default:
420 result = errors::INVALID_MESSAGE;
421 break;
422 }
423 }
424 if (result != errors::NONE)
425 log::engineError("Cannot update application preferences: %s", errors::description(result));
426 sendApplicationPreferences(*this, ipc, renderer, result == errors::NONE ? "" :
427 "Could not update application preferences. See the Engine log.");
428 }))
429 {
430 log::engineError("Cannot handle application preferences: application worker is stopping.");
431 sendApplicationPreferences(*this, ipc, renderer, "Application preferences are unavailable during shutdown.");
432 }
433 return;
434 }
435 if (prefix.operationId == COMMAND_PROJECT_CLOSING_REQUEST)
436 {
437 if (prefix.destinationKind != PROCESS_KIND_ENGINE ||
438 prefix.senderKind != PROCESS_KIND_ELECTRON_RENDERER || prefix.senderId != message::MAIN_WINDOW_ID ||
439 incoming.header.payload_type() != PAYLOAD_TYPE_NONE || incoming.payloadSize() != 0)
440 {
441 log::engineError("Cannot request project closing statuses: invalid request.");
442 return;
443 }
444 setClosingNotifier([this, &ipc](const ProjectClosingStatuses& statuses)
445 {
446 if (!_consoleQueue->post([&ipc, statuses]
447 {
448 message::FrameOptions options{PROCESS_KIND_ELECTRON_RENDERER, COMMAND_PROJECT_CLOSING_STATUSES, message::MAIN_WINDOW_ID};
449 options.payload = statuses.SerializeAsString();
450 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
451 options.messageType = MESSAGE_TYPE_PROJECT_CLOSING_STATUSES;
452 options.ttlMs = 5000;
453 options.flags = message::SILENT_FLAGS; // state sync for the Console panel, not an entry of its own
454 ipc.sendBuilt(options);
455 }))
456 std::fprintf(stderr, "Cannot queue project closing statuses: Console worker is shutting down.\n");
457 });
458 return;
459 }
460 if (prefix.operationId == COMMAND_LOG_PAGE_REQUEST)
461 {
462 auto remaining = std::make_shared<std::atomic<std::size_t>>(1);
463 const auto completed = [this, incoming, &ipc, remaining]
464 {
465 if (remaining->fetch_sub(1) == 1 &&
466 !_logQueue->post([this, incoming, &ipc] { handleLogMessage(incoming, ipc); }))
467 std::fprintf(stderr, "Cannot queue log page request: application log worker is shutting down.\n");
468 };
469 {
470 std::lock_guard<std::mutex> lock(_projectLogsMutex);
471 std::unordered_set<ProjectLogWorker*> seen;
472 for (const auto& route : _projectLogRoutes)
473 {
474 if (!seen.insert(route.second.get()).second)
475 continue;
476 ++*remaining;
477 if (!route.second->queue->post(completed))
478 {
479 std::fprintf(stderr, "Cannot queue project log history barrier: worker is shutting down.\n");
480 completed();
481 }
482 }
483 }
484 completed();
485 return;
486 }
487 if (prefix.operationId == COMMAND_PROMPT_RESPONSE)
488 {
489 PromptResponse response;
490 if (prefix.destinationKind != PROCESS_KIND_ENGINE ||
491 prefix.senderKind != PROCESS_KIND_ELECTRON_RENDERER || prefix.senderId != message::MAIN_WINDOW_ID ||
492 incoming.header.payload_type() != PAYLOAD_TYPE_PROTOBUF ||
493 incoming.header.message_type() != MESSAGE_TYPE_PROMPT_RESPONSE ||
494 !response.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())))
495 {
496 log::engineError("Cannot handle prompt response: invalid sender or payload.");
497 return;
498 }
499 std::lock_guard<std::mutex> lock(_promptMutex);
500 const auto found = _pendingPrompts.find(response.request_id());
501 if (found == _pendingPrompts.end() || found->second.completed)
502 {
503 log::engineError("Cannot handle prompt response: unknown request.");
504 return;
505 }
506 const auto& request = found->second.request;
507 const bool validChoice = std::any_of(request.buttons().begin(), request.buttons().end(),
508 [&](const PromptButton& button) { return button.value() == response.value(); });
509 if (response.error().empty() &&
510 ((response.dismissed() && request.has_dismissible() && !request.dismissible()) ||
511 (!response.dismissed() && !validChoice)))
512 {
513 log::engineError("Cannot handle prompt response: invalid choice.");
514 return;
515 }
516 found->second.response = std::move(response);
517 found->second.completed = true;
518 return;
519 }
520 if (prefix.operationId == COMMAND_PROJECT_PREFERENCES_REQUEST ||
521 prefix.operationId == COMMAND_PROJECT_PREFERENCE_CHANGE)
522 {
523 const bool changing = prefix.operationId == COMMAND_PROJECT_PREFERENCE_CHANGE;
524 ProjectPreferencesRequest request;
525 ProjectPreferenceChange change;
526 const bool parsed = incoming.header.payload_type() == PAYLOAD_TYPE_PROTOBUF &&
527 (changing
528 ? incoming.header.message_type() == MESSAGE_TYPE_PROJECT_PREFERENCE_CHANGE &&
529 change.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())) &&
530 change.change_case() != ProjectPreferenceChange::CHANGE_NOT_SET
531 : incoming.header.message_type() == MESSAGE_TYPE_PROJECT_PREFERENCES_REQUEST &&
532 request.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())));
533 const std::string id = changing ? change.id() : request.id();
534 if (prefix.destinationKind != PROCESS_KIND_ENGINE || prefix.destinationId != 0 ||
535 prefix.senderKind != PROCESS_KIND_ELECTRON_RENDERER || prefix.senderId != message::MAIN_WINDOW_ID ||
536 incoming.header.has_target_project() || !parsed || id.empty() || id.find('\0') != std::string::npos)
537 {
538 log::engineError("Cannot handle project preferences: invalid request.");
539 return;
540 }
541 watchRenames(ipc);
542 F_err result = errors::PROJECT_NOT_FOUND;
543 {
544 std::lock_guard<std::mutex> lock(_mutex);
545 const auto found = std::find_if(_projects.begin(), _projects.end(),
546 [this, &id](const auto& entry) {
547 return entry.second.id == id && isActiveProjectLocked(entry.second.project.get());
548 });
549 if (found != _projects.end())
550 {
551 result = enqueueProjectTaskLocked("", false, false,
552 [this, &ipc, id, changing, change](ProjectManager& project,
553 const std::shared_ptr<threads::TaskQueue>&)
554 {
555 bool active;
556 {
557 std::lock_guard<std::mutex> lock(_mutex);
558 active = isActiveProjectLocked(&project);
559 }
560 if (!active)
561 {
562 ipc.sendBuilt(projectPreferencesFrame(id, "", false, "The active project changed."));
563 return;
564 }
565 F_err changed = errors::NONE;
566 bool renamePending = false;
567 if (changing && change.change_case() == ProjectPreferenceChange::kName)
568 {
569 renamePending = change.name() != project.name();
570 changed = project.rename(change.name());
571 }
572 else if (changing && change.change_case() == ProjectPreferenceChange::kPackageOnClose)
573 changed = project.set("project.preferences.packageOnClose", change.package_on_close());
574 if (changed != errors::NONE)
575 {
576 log::engineError("Cannot update project preferences: %s", errors::description(changed));
577 ipc.sendBuilt(projectPreferencesFrame(id, "", false,
578 "Could not update project preferences. See the Engine log."));
579 return;
580 }
581 if (renamePending)
582 return;
583 bool package = false;
584 if (project.get("project.preferences.packageOnClose", package) != errors::NONE)
585 {
586 ipc.sendBuilt(projectPreferencesFrame(id, "", false,
587 "Could not read project preferences. See the Engine log."));
588 return;
589 }
590 ipc.sendBuilt(projectPreferencesFrame(id, project.name(), package, ""));
591 }, found->second.project.get());
592 }
593 }
594 if (result != errors::NONE)
595 {
596 log::engineError("Cannot update project preferences: project is not active or unavailable.");
597 ipc.sendBuilt(projectPreferencesFrame(id, "", false, "The active project is unavailable."));
598 }
599 return;
600 }
601 if (prefix.operationId == COMMAND_CLOSE_PROJECT ||
602 (incoming.header.has_target_project() && prefix.operationId != COMMAND_CREATE_PROJECT))
603 {
604 handleProjectMessage(incoming, ipc);
605 return;
606 }
607 if (prefix.operationId == COMMAND_CREATE_PROJECT)
608 {
609 if (prefix.senderKind != PROCESS_KIND_ELECTRON_MAIN &&
610 prefix.senderKind != PROCESS_KIND_ELECTRON_RENDERER)
611 {
612 log::engineError("Cannot create project: unsupported sender.");
613 return;
614 }
615 const OpeningOrigin requestOrigin{prefix.senderKind, prefix.senderId, incoming.header.message_id(), true};
616 ProjectCreateRequest request;
617 if (prefix.destinationKind != PROCESS_KIND_ENGINE ||
618 incoming.header.payload_type() != PAYLOAD_TYPE_PROTOBUF ||
619 incoming.header.message_type() != MESSAGE_TYPE_PROJECT_CREATE_REQUEST ||
620 !request.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())) ||
621 !ProjectCreateChoice_IsValid(request.choice()))
622 {
623 log::engineError("Cannot create project: invalid request.");
624 sendProjectOpenResult(ipc, requestOrigin, "", errors::INVALID_MESSAGE);
625 return;
626 }
627 const std::string path = request.path();
628 const std::filesystem::path target(path);
629 if (path.find('\0') != std::string::npos || !target.is_absolute() ||
630 !ProjectManager::validProjectName(target.filename().string()))
631 {
632 log::engineError("Cannot create project: invalid absolute path.");
633 sendProjectOpenResult(ipc, requestOrigin, path, errors::INVALID_MESSAGE);
634 return;
635 }
636 const bool creating = request.choice() == PROJECT_CREATE_NEW || request.choice() == PROJECT_CREATE_IN_FOLDER ||
637 request.choice() == PROJECT_CREATE_IN_FOLDER_RESOLVE;
638 const auto choice = request.choice() == PROJECT_OPEN_ARCHIVE || request.choice() == PROJECT_SELECT_ARCHIVE
640 request.choice() == PROJECT_OPEN_FOLDER || request.choice() == PROJECT_SELECT_FOLDER ||
641 request.choice() == PROJECT_CREATE_IN_FOLDER_RESOLVE
644 const auto mode = request.choice() == PROJECT_CREATE_IN_FOLDER_RESOLVE ? files::OpenMode::CreateInFolderResolve :
645 request.choice() == PROJECT_CREATE_IN_FOLDER ? files::OpenMode::CreateInFolder :
646 request.choice() == PROJECT_CREATE_NEW ? files::OpenMode::CreateNew :
647 request.choice() == PROJECT_SELECT_ARCHIVE || request.choice() == PROJECT_SELECT_FOLDER
649 const OpeningOrigin origin{prefix.senderKind, prefix.senderId, incoming.header.message_id(), creating};
650 // Registered before the project opens so its opening log tag resolves on the first open too.
651 watchProjectOpenings(ipc);
652 if (!postApplication([this, &ipc, path, choice, mode, origin]
653 {
654 const F_err result = openProject(path, choice, true, mode, origin);
655 if (result != errors::NONE)
656 sendProjectOpenResult(ipc, origin, path, result);
657 }))
658 {
659 log::engineError("Cannot create project: application thread is shutting down.");
660 sendProjectOpenResult(ipc, origin, path, errors::FAILED_OPEN_PROJECT);
661 }
662 return;
663 }
664 }
665
667 inline ConsoleEntry FrayManager::describeCommand(
668 const message::InData& incoming)
669 {
670 const auto& prefix = incoming.prefix;
671 ConsoleEntry entry;
672 entry.set_uid(identity::hex(prefix.uid));
673 entry.set_timestamp_us(static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(
674 std::chrono::system_clock::now().time_since_epoch()).count()));
675 entry.set_kind(CONSOLE_ENTRY_KIND_COMMAND);
676 entry.set_sender(prefix.senderKind);
677 entry.set_destination(prefix.destinationKind);
678 if (prefix.destinationKind == PROCESS_KIND_MULTICAST)
679 *entry.mutable_recipients() = incoming.header.recipients();
680 if (incoming.header.has_target_project())
681 entry.set_project(logProjectIdentity(incoming.header.target_project()));
682 const std::string& name = Command_Name(static_cast<int>(prefix.operationId));
683 entry.set_title(name.empty() ? "COMMAND_" + std::to_string(prefix.operationId) : name);
684 entry.set_detail(std::string("From ") + message::processName(prefix.senderKind) + " to " +
685 message::processName(prefix.destinationKind) + ".");
686 entry.set_status(CONSOLE_COMMAND_STATUS_PENDING);
687 return entry;
688 }
689
692 Command operation,
693 const ConsoleEntry& entry,
695 {
696 message::FrameOptions options{PROCESS_KIND_ELECTRON_RENDERER, static_cast<F_ulong>(operation), message::MAIN_WINDOW_ID};
697 options.payload = entry.SerializeAsString();
698 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
699 options.messageType = MESSAGE_TYPE_CONSOLE_ENTRY;
700 options.ttlMs = 5000;
701 ipc.sendBuilt(options);
702 }
703
706 const message::InData& incoming,
708 bool received)
709 {
710 ConsoleEntry entry = describeCommand(incoming);
711 if (entry.uid().empty())
712 return;
713 const std::uint32_t flags = incoming.header.flags();
714 if (message::wantsLog(flags))
715 {
716 logs::Entry stored;
717 stored.uid = entry.uid();
718 stored.process = static_cast<int>(incoming.prefix.senderKind);
719 stored.level = "INF";
720 stored.project = entry.project();
721 stored.kind = LOG_ENTRY_KIND_COMMAND;
722 stored.destination = static_cast<int>(incoming.prefix.destinationKind);
723 stored.operation = incoming.prefix.operationId;
724 stored.text = "Command " + entry.title() + " from " + message::processName(incoming.prefix.senderKind) + " to " +
725 message::processName(incoming.prefix.destinationKind) + ": message_id=" +
726 std::to_string(incoming.header.message_id()) + " payload_bytes=" +
727 std::to_string(incoming.payloadSize()) + ".";
728 if (auto prepared = _logs.prepare(std::move(stored)))
729 {
730 // The entry shares its log row's arrival time, so it sorts exactly where the row was written.
731 entry.set_timestamp_us(prepared->arrivedUs);
732 persistLogEntry(*prepared);
733 }
734 }
735 if (_consoleStopping.load())
736 return;
737 if (received)
738 entry.set_status(CONSOLE_COMMAND_STATUS_RECEIVED);
739 if (!_consoleQueue->post([this, entry = std::move(entry), flags, &ipc]
740 {
741 const auto added = _consoleEntries.add(entry);
742 if (message::wantsConsole(flags))
743 sendConsoleEntry(COMMAND_CONSOLE_ADD, added, ipc);
744 }))
745 std::fprintf(stderr, "Cannot queue Console entry: Console worker is shutting down.\n");
746 }
747
750 const message::InData& incoming,
752 {
753 Notification notification;
754 if (incoming.header.payload_type() != PAYLOAD_TYPE_PROTOBUF ||
755 incoming.header.message_type() != MESSAGE_TYPE_NOTIFICATION ||
756 !notification.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())) ||
757 notification.title().empty())
758 {
759 log::engineError("Invalid notification from %s.", message::processName(incoming.prefix.senderKind));
760 return;
761 }
763 static_cast<ProcessKind>(incoming.prefix.senderKind),
764 notification.severity(),
765 notification.title(),
766 notification.description(),
767 incoming.header.has_target_project() ? logProjectIdentity(incoming.header.target_project()) : std::string(),
768 incoming.header.flags(),
769 ipc,
770 identity::hex(incoming.prefix.uid),
771 static_cast<ProcessKind>(incoming.prefix.destinationKind));
772 }
773
776 ProcessKind sender,
777 NotificationSeverity severity,
778 const std::string& title,
779 const std::string& description,
780 const std::string& project,
781 std::uint32_t flags,
783 const std::string& uid,
784 ProcessKind destination)
785 {
786 ConsoleEntry entry;
787 entry.set_uid(uid.empty() ? identity::hex(identity::generate()) : uid);
788 entry.set_timestamp_us(static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(
789 std::chrono::system_clock::now().time_since_epoch()).count()));
790 entry.set_kind(CONSOLE_ENTRY_KIND_NOTIFICATION);
791 entry.set_sender(sender);
792 entry.set_destination(destination);
793 entry.set_project(project);
794 entry.set_title(title);
795 entry.set_detail(description);
796 entry.set_severity(severity);
797 if (message::wantsLog(flags))
798 {
799 logs::Entry stored;
800 stored.uid = entry.uid();
801 stored.process = static_cast<int>(sender);
802 stored.level = severity == NOTIFICATION_SEVERITY_ERROR ? "ERR"
803 : severity == NOTIFICATION_SEVERITY_WARNING ? "WRN" : "INF";
804 stored.project = entry.project();
805 stored.kind = LOG_ENTRY_KIND_NOTIFICATION;
806 stored.operation = static_cast<std::uint64_t>(severity);
807 stored.text = title + (description.empty() ? "" : "\n" + description);
808 if (auto prepared = _logs.prepare(std::move(stored)))
809 {
810 entry.set_timestamp_us(prepared->arrivedUs);
811 persistLogEntry(*prepared);
812 }
813 }
814 if (!message::wantsConsole(flags) || _consoleStopping.load())
815 return;
816 if (!_consoleQueue->post([this, entry = std::move(entry), &ipc]
817 {
818 sendConsoleEntry(COMMAND_CONSOLE_ADD, _consoleEntries.add(entry), ipc);
819 }))
820 std::fprintf(stderr, "Cannot queue Console entry: Console worker is shutting down.\n");
821 }
822
825 const message::InData& incoming,
827 {
828 Receipt receipt;
829 if (incoming.header.payload_type() != PAYLOAD_TYPE_PROTOBUF ||
830 incoming.header.message_type() != MESSAGE_TYPE_RECEIPT ||
831 !receipt.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())) ||
832 receipt.uid().empty())
833 {
834 log::engineError("Invalid receipt from %s.", message::processName(incoming.prefix.senderKind));
835 return;
836 }
837 const std::string project = incoming.header.has_target_project()
838 ? logProjectIdentity(incoming.header.target_project()) : std::string();
839 if (message::wantsLog(receipt.flags()))
840 {
841 logs::Entry stored;
842 stored.uid = identity::hex(incoming.prefix.uid);
843 stored.process = static_cast<int>(incoming.prefix.senderKind);
844 stored.level = "INF";
845 stored.project = project;
846 stored.kind = LOG_ENTRY_KIND_RECEIPT;
847 stored.destination = static_cast<int>(receipt.destination());
848 stored.operation = receipt.operation();
849 stored.refUid = receipt.uid();
850 stored.text = std::string(message::processName(incoming.prefix.senderKind)) + " received message " +
851 receipt.uid() + ".";
852 if (auto prepared = _logs.prepare(std::move(stored)))
853 persistLogEntry(*prepared);
854 }
855 if (_consoleStopping.load())
856 return;
857 // Used only when the Engine no longer holds an entry for this UID: the receipt carries enough to show it anyway.
858 ConsoleEntry fallback;
859 fallback.set_uid(receipt.uid());
860 fallback.set_timestamp_us(static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(
861 std::chrono::system_clock::now().time_since_epoch()).count()));
862 fallback.set_kind(CONSOLE_ENTRY_KIND_COMMAND);
863 fallback.set_sender(receipt.sender());
864 fallback.set_destination(receipt.destination());
865 fallback.set_project(project);
866 const std::string& name = Command_Name(static_cast<int>(receipt.operation()));
867 fallback.set_title(name.empty() ? "COMMAND_" + std::to_string(receipt.operation()) : name);
868 fallback.set_detail(std::string("From ") + message::processName(receipt.sender()) + " to " +
869 message::processName(receipt.destination()) + ".");
870 const auto sender = incoming.prefix.senderKind;
871 const auto senderId = incoming.prefix.senderId;
872 const auto flags = receipt.flags();
873 if (!_consoleQueue->post([this, fallback = std::move(fallback), sender, senderId, flags, &ipc]
874 {
875 if (auto changed = _consoleEntries.confirm(fallback, sender, senderId))
876 if (message::wantsConsole(flags))
877 sendConsoleEntry(changed->added ? COMMAND_CONSOLE_ADD : COMMAND_CONSOLE_UPDATE, changed->entry, ipc);
878 }))
879 std::fprintf(stderr, "Cannot queue Console update: Console worker is shutting down.\n");
880 }
881
886 const logs::Entry& entry,
888 bool includeLoading)
889 {
890 LogEntry payload;
891 toProto(entry, payload);
892 message::FrameOptions options{PROCESS_KIND_ELECTRON_RENDERER, COMMAND_LOG_ENTRY, message::MAIN_WINDOW_ID};
893 if (includeLoading && ipc.loadingWindowActive())
894 {
895 options.destination = PROCESS_KIND_MULTICAST;
896 options.destinationId = 0;
897 options.recipients = {{PROCESS_KIND_ELECTRON_RENDERER, 0},
898 {PROCESS_KIND_ELECTRON_RENDERER, message::MAIN_WINDOW_ID}};
899 }
900 options.payload = payload.SerializeAsString();
901 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
902 options.messageType = MESSAGE_TYPE_LOG_ENTRY;
903 options.ttlMs = includeLoading && ipc.loadingWindowActive() ? 0 : 5000;
904 ipc.sendBuilt(options);
905 }
906
912 const message::InData& incoming,
914 {
915 const auto& prefix = incoming.prefix;
916 if (incoming.header.payload_type() != PAYLOAD_TYPE_PROTOBUF)
917 return;
918 if (prefix.operationId == COMMAND_LOG_ENTRY)
919 {
920 LogEntry entry;
921 if (prefix.senderKind == PROCESS_KIND_ENGINE ||
922 !entry.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())))
923 return;
924 logs::Entry stored;
925 stored.uid = identity::hex(prefix.uid);
926 stored.process = static_cast<int>(prefix.senderKind);
927 stored.level = entry.level();
928 stored.thread = entry.thread();
929 stored.project = entry.project();
930 stored.text = entry.text();
931 stored.consoleVisible = message::wantsConsole(incoming.header.flags());
932 const bool includeLoading = prefix.senderKind == PROCESS_KIND_ELECTRON_MAIN ||
933 (prefix.senderKind == PROCESS_KIND_ELECTRON_RENDERER && prefix.senderId == message::MAIN_WINDOW_ID);
934 recordLogEntry(std::move(stored), &ipc, includeLoading);
935 return;
936 }
937 LogPageRequest request;
938 if (prefix.senderKind != PROCESS_KIND_ELECTRON_RENDERER ||
939 !request.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())))
940 return;
941 logs::Query query;
942 query.beforeUs = request.before_us();
943 query.limit = std::min<std::uint32_t>(request.limit() ? request.limit() : 200, 1000);
944 for (const int process : request.processes())
945 query.processes.push_back(process);
946 for (const auto& level : request.levels())
947 query.levels.push_back(level);
948 query.filterProject = request.has_project();
949 query.project = request.project();
950 query.contains = request.contains();
951 query.consoleOnly = true;
952 const logs::Page page = _logs.page(query);
953 LogPage reply;
954 reply.set_request_id(request.request_id());
955 reply.set_exhausted(page.exhausted);
956 for (const auto& found : page.entries)
957 toProto(found, *reply.add_entries());
958 message::FrameOptions options{PROCESS_KIND_ELECTRON_RENDERER, COMMAND_LOG_PAGE, incoming.prefix.senderId};
959 options.payload = reply.SerializeAsString();
960 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
961 options.messageType = MESSAGE_TYPE_LOG_PAGE;
962 ipc.sendBuilt(options);
963 }
964}
965
966#endif
Owns and coordinates projects, their queues, application work, prompts, and logs. Project work runs o...
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 watchProjectOpenings(ipc::IPCManager &ipc)
Installs independent project-opening result and active-project announcements.
void handleNotification(const message::InData &incoming, ipc::IPCManager &ipc)
Handles COMMAND_NOTIFY: logs the notification and adds it to the Console as a notification entry....
std::atomic< bool > _consoleStopping
Whether new Console deliveries are disabled during final local teardown.
static void sendConsoleEntry(Command operation, const ConsoleEntry &entry, ipc::IPCManager &ipc)
Sends a Console entry to the Renderer without waiting; a dropped send is not retried.
void recordCommand(const message::InData &incoming, ipc::IPCManager &ipc, bool received)
Splits a stamped command into its disk log record and its Console entry, honoring the message's flags...
void watchRenames(ipc::IPCManager &ipc)
Installs callbacks forwarding project renames and resolved opening log tags. Callbacks capture ipc by...
void handleLogMessage(const message::InData &incoming, ipc::IPCManager &ipc)
Stores and forwards incoming log entries or sends a filtered log page.
std::string logProjectIdentity(const std::string &target)
Resolves a message's project target to its log identity without changing dispatch.
F_err switchApplicationState(const std::filesystem::path &path)
Selects and persists an existing application database without replacing active state on failure....
void addNotification(ProcessKind sender, NotificationSeverity severity, const std::string &title, const std::string &description, const std::string &project, std::uint32_t flags, ipc::IPCManager &ipc, const std::string &uid="", ProcessKind destination=PROCESS_KIND_ENGINE)
Logs a notification and adds it to the Console, as handleNotification does for received ones....
ConsoleEntry describeCommand(const message::InData &incoming)
Describes a command as a Console entry.
F_err restoreProjects(ipc::IPCManager &ipc)
Queues restoration of the saved project session when enabled.
void setOpeningNotifier(std::function< void(const OpeningStatus &)> notifier)
Installs a publisher for completed project-open states.
void requestShutdown()
Starts or retries Engine-owned shutdown without joining any worker. Previously accepted application w...
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...
logs::LogStore _logs
Store for engine and project log entries.
F_err resetApplicationPreferences()
Resets only application preference values in one database transaction.
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.
bool _promptClosing
Rejects new prompts after closing begins; guarded by _promptMutex.
std::mutex _promptMutex
Protects pending prompts and prompt shutdown state.
F_err loadButtonStyle(const std::string &defaults, std::string &css)
Loads the Engine-owned application button stylesheet.
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.
static void toProto(const logs::Entry &entry, LogEntry &out)
Copies a stored log entry into its protobuf representation.
std::shared_ptr< threads::TaskQueue > _consoleQueue
Queue of Console deliveries; it does not wait for log persistence.
bool requestPrompt(ipc::IPCManager &ipc, const PromptRequest &request, uint64_t &requestId)
Sends a renderer prompt and tracks its response under _promptMutex.
void handleReceipt(const message::InData &incoming, ipc::IPCManager &ipc)
Handles a MSG_RECEIPT: logs it under its own UID and tells the Console the original command arrived....
void handleApplicationMessage(const message::InData &incoming, ipc::IPCManager &ipc)
Routes an incoming Engine message, dispatching project work asynchronously. Called by the Engine mess...
std::unordered_map< uint64_t, PendingPrompt > _pendingPrompts
Pending prompts indexed by request message ID; guarded by _promptMutex.
void forwardLogEntry(const logs::Entry &entry, ipc::IPCManager &ipc, bool includeLoading)
Sends a prepared log line to the renderer with a limited lifetime.
F_err readApplicationPreferences(ApplicationPreferences &output)
Reads an authoritative application preferences snapshot.
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.
F_err get(const std::string &key, T &value)
Reads a value from the default application state namespace.
void announceActiveProject(ipc::IPCManager &ipc)
Announces the most recently opened eligible project and its saved layout. Selects under _mutex,...
Owns a project’s files, state stores, watcher and registered threads. Public operations synchronize t...
static bool validProjectName(const std::string &name)
Checks whether a project name is a safe single relative component without a .fry suffix.
Owns the TCP servers and the threads around them.
Builds outgoing frames sent by the Engine (sender is always the Engine). Stateless; safe to use from ...
Definition message.hpp:451
F_err build(const FrameOptions &options, std::shared_ptr< const std::vector< F_uchar > > &out) const
Builds an Engine frame from the options, stamping the protocol version, a new message id and the curr...
Definition message.hpp:460
std::vector< std::uint8_t > Binary
Byte sequence stored as a SQLite blob.
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
const F_char * description(code err)
Formats an error code as "Error <number>: <description>". Not thread-safe: the text lives in a shared...
Definition errors.hpp:96
std::string hex(const Uid &uid)
Formats a routing UID as lowercase hexadecimal.
Definition uid.hpp:38
Uid generate()
Generates a random, globally unique identifier.
Definition uid.hpp:24
std::shared_ptr< const std::vector< F_uchar > > Frame
Shared, immutable, fully built frame (prefix + header + payload); shared between threads without copy...
F_void engineInfo(const F_char *fmt,...)
Log info for Engine.
F_void engineError(const F_char *fmt,...)
Log error for Engine.
F_void engineWarn(const F_char *fmt,...)
Log warning for Engine.
const char * processName(ProcessKind kind)
Human-readable name of a process kind, also used as the header sender/destination name.
Definition message.hpp:342
bool wantsLog(std::uint32_t flags)
Tests whether a message's header flags leave it in the disk log.
Definition message.hpp:134
F_err parseFrame(std::shared_ptr< const std::vector< F_uchar > > frame, InData &out)
Parses the header of a complete frame. The payload is not read or copied.
Definition message.hpp:511
bool wantsConsole(std::uint32_t flags)
Tests whether a message's header flags leave it in the Console.
Definition message.hpp:145
constexpr std::uint32_t SILENT_FLAGS
Definition message.hpp:392
constexpr std::uint32_t MAIN_WINDOW_ID
Renderer instance ID assigned to the first application window.
Definition message.hpp:40
constexpr std::uint32_t LOADING_WINDOW_ID
Renderer instance ID assigned to the loading window.
Definition message.hpp:38
constexpr std::size_t maximumStyleSize
Maximum stylesheet size in bytes.
message::FrameOptions projectPreferencesFrame(const std::string &id, const std::string &name, bool packageOnClose, const std::string &error)
Builds a project preference snapshot or operation error.
void sendApplicationPreferences(FrayManager &application, ipc::IPCManager &ipc, F_ulong renderer, const std::string &error="")
Sends the current application preferences and an optional operation error.
void sendProjectOpenResult(ipc::IPCManager &ipc, const FrayManager::OpeningOrigin &origin, const std::string &path, F_err result)
Sends the result of a project-open or create request.
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.
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
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 page of matching log entries and its exhaustion status.
std::vector< Entry > entries
Matching entries ordered oldest first.
bool exhausted
True when no additional matching entries were found beyond this page.
Filters and cursor for a page of log entries.
Definition log_store.hpp:79
std::string project
Project identifier to match when filterProject is true; empty selects application entries.
std::uint32_t limit
Maximum results requested; page enforces a minimum of one.
Definition log_store.hpp:87
std::uint64_t beforeUs
Exclusive arrival cursor; zero selects the newest entries.
Definition log_store.hpp:83
std::vector< std::string > levels
Allowed severity labels; empty disables this filter.
Definition log_store.hpp:95
bool filterProject
Whether to filter by the exact project identifier.
Definition log_store.hpp:99
std::string contains
Literal SQLite LIKE substring filter for message text; empty disables it.
bool consoleOnly
Exclude entries intended only for the persisted log.
std::vector< int > processes
Allowed process identifiers; empty disables this filter.
Definition log_store.hpp:91
Everything FrameBuilder needs to build one outgoing Engine message.
Definition message.hpp:398
std::vector< std::pair< ProcessKind, F_ulong > > recipients
Definition message.hpp:423
A parsed incoming message. The payload is a view into the frame, which this keeps alive via shared ow...
Definition message.hpp:169
size_t payloadSize() const
Payload length in bytes (prefix.length minus headerLength).
Definition message.hpp:180
const F_uchar * payload() const
Pointer to the first payload byte inside frame (valid only while frame is held; frame must be non-nul...
Definition message.hpp:178
ProcessKind destinationKind
Definition message.hpp:57
ProcessKind senderKind
Definition message.hpp:61
identity::Uid uid
Definition message.hpp:70
uint32_t F_ulong
Unsigned 32-bit integer.
Definition types.hpp:34