feat(xcui): add editor layout persistence validation

This commit is contained in:
2026-04-06 16:59:15 +08:00
parent eef5de7ee9
commit 9015b461bb
17 changed files with 1849 additions and 121 deletions

View File

@@ -169,10 +169,10 @@ tests/
以下规则在当前阶段覆盖本节中所有与目录落点有关的模糊表述:
- `editor/` 当前视为 ImGui 版本冻结区;在 XCUI editor shell 成熟前,不直接在该目录中推进替换开发。
- 新的 `Editor` 层实现当前先落在 `new_editor/`,用于 editor shell、editor-only widget 与工作区壳层构建
- `tests/UI` 继续只承担 XCUI 的 `unit / integration` 验证职责,不承载正式 editor 实现
- `tests/UI` 是当前 `Editor` 基础层的唯一实验场;所有基础能力验证、交互试验、状态流检查都必须优先放在 `tests/UI/Editor/unit``tests/UI/Editor/integration`
- `new_editor/` 当前冻结为空壳目录,不承担实验场职责;在 `Editor` 基础层尚未通过测试体系收口前,禁止继续往其中添加新功能、新面板或新的验证入口
- `engine/UI` 当前继续只放 `Core / Runtime / shared` 部分,不再继续沉积 editor-only 代码。
- `new_editor/` 中的 XCUI editor shell 达到替换条件后,再计划性回收进正式 `editor/`
- `Editor` 基础层在 `tests/UI/Editor` 中稳定收口后,如确有宿主集成需要,再单独规划 `new_editor/`正式 `editor/` 的接入阶段
#### 当前过渡期目录(自 2026-04-06 起执行)
```text
@@ -185,7 +185,7 @@ new_editor/
src/
ui/
captures/
# 当前新的 Editor 层与 editor shell 先在这里构建
# 当前冻结为空壳,不作为基础层开发或实验入口
editor/
# 当前 ImGui 版本冻结,不作为本阶段 XCUI 主实现目录
@@ -1417,8 +1417,8 @@ tests/UI/Editor/
近期执行顺序调整如下:
1. 冻结当前基于 ImGui 的 `editor/` 目录,不把它作为本阶段 XCUI 替换开发的主工作区。
2. 新的 XCUI `Editor` 层先在 `new_editor/`构建
3. `tests/UI` 继续只做验证,不承载正式 editor 实现
2. 当前阶段所有 `Editor` 基础层实验、交互验证、状态流验证,一律放在 `tests/UI/Editor`完成
3. `new_editor/` 保持空壳冻结;在基础层未成熟前,不把它当作试验场,不往里面追加功能
4. 在具体 editor 面板之前,优先完成 editor shell 基础能力:
- Splitter / pane resize
- Tab strip
@@ -1438,7 +1438,8 @@ tests/UI/Editor/
- `Editor` 当前阶段只负责 editor shell、panel 生命周期、workspace 装配、menu/shortcut 这类 editor-only 上层能力。
- 凡是发现 `layout / input / style / text / render contract / shared widget` 等共享能力缺口,必须优先回补到 `Core` 或 shared UI 层。
- 禁止在 `Editor` 层硬写临时替代实现去绕过 `Core` 缺口;否则后面迁移到正式 editor 时会再次返工。
- `new_editor/` 当前只作为 `Editor` 层实现载体与试验场,不作为业务面板堆叠区
- `tests/UI/Editor` 当前 `Editor` 基础层的唯一实验与验证入口;需要人工操作检查的内容,也必须做成这里的集成测试场景
- `new_editor/` 当前保持空壳冻结,不作为试验场,不作为基础层功能承载目录,更不允许在基础层未成熟前向其中堆任何业务或验证逻辑。
- `tests/UI/Editor` 当前只验证 `Editor` 基础壳层与状态流,不提前承担具体业务面板复刻。
### 24.3 Editor基础层当前推进顺序2026-04-06

View File

@@ -14,6 +14,7 @@ set(NEW_EDITOR_RESOURCE_FILES
add_library(XCNewEditorLib STATIC
src/editor/EditorShellAsset.cpp
src/editor/UIEditorPanelRegistry.cpp
src/editor/UIEditorWorkspaceLayoutPersistence.cpp
src/editor/UIEditorWorkspaceController.cpp
src/editor/UIEditorWorkspaceModel.cpp
src/editor/UIEditorWorkspaceSession.cpp

View File

@@ -1,5 +1,6 @@
#pragma once
#include <XCNewEditor/Editor/UIEditorWorkspaceLayoutPersistence.h>
#include <XCNewEditor/Editor/UIEditorWorkspaceSession.h>
#include <cstdint>
@@ -58,6 +59,23 @@ struct UIEditorWorkspaceControllerValidationResult {
std::string_view GetUIEditorWorkspaceCommandKindName(UIEditorWorkspaceCommandKind kind);
std::string_view GetUIEditorWorkspaceCommandStatusName(UIEditorWorkspaceCommandStatus status);
enum class UIEditorWorkspaceLayoutOperationStatus : std::uint8_t {
Changed = 0,
NoOp,
Rejected
};
struct UIEditorWorkspaceLayoutOperationResult {
UIEditorWorkspaceLayoutOperationStatus status =
UIEditorWorkspaceLayoutOperationStatus::Rejected;
std::string message = {};
std::string activePanelId = {};
std::vector<std::string> visiblePanelIds = {};
};
std::string_view GetUIEditorWorkspaceLayoutOperationStatusName(
UIEditorWorkspaceLayoutOperationStatus status);
class UIEditorWorkspaceController {
public:
UIEditorWorkspaceController() = default;
@@ -79,6 +97,11 @@ public:
}
UIEditorWorkspaceControllerValidationResult ValidateState() const;
UIEditorWorkspaceLayoutSnapshot CaptureLayoutSnapshot() const;
UIEditorWorkspaceLayoutOperationResult RestoreLayoutSnapshot(
const UIEditorWorkspaceLayoutSnapshot& snapshot);
UIEditorWorkspaceLayoutOperationResult RestoreSerializedLayout(
std::string_view serializedLayout);
UIEditorWorkspaceCommandResult Dispatch(const UIEditorWorkspaceCommand& command);
private:
@@ -95,6 +118,10 @@ private:
const UIEditorWorkspaceModel& previousWorkspace,
const UIEditorWorkspaceSession& previousSession);
UIEditorWorkspaceLayoutOperationResult BuildLayoutOperationResult(
UIEditorWorkspaceLayoutOperationStatus status,
std::string message) const;
const UIEditorPanelDescriptor* FindPanelDescriptor(std::string_view panelId) const;
UIEditorPanelRegistry m_panelRegistry = {};

View File

@@ -0,0 +1,55 @@
#pragma once
#include <XCNewEditor/Editor/UIEditorWorkspaceSession.h>
#include <cstdint>
#include <string>
#include <string_view>
namespace XCEngine::NewEditor {
struct UIEditorWorkspaceLayoutSnapshot {
UIEditorWorkspaceModel workspace = {};
UIEditorWorkspaceSession session = {};
};
enum class UIEditorWorkspaceLayoutLoadCode : std::uint8_t {
None = 0,
InvalidPanelRegistry,
EmptyInput,
InvalidHeader,
UnsupportedVersion,
MissingActiveRecord,
UnexpectedEndOfInput,
InvalidNodeRecord,
InvalidSessionRecord,
InvalidWorkspace,
InvalidWorkspaceSession
};
struct UIEditorWorkspaceLayoutLoadResult {
UIEditorWorkspaceLayoutLoadCode code = UIEditorWorkspaceLayoutLoadCode::None;
std::string message = {};
UIEditorWorkspaceLayoutSnapshot snapshot = {};
[[nodiscard]] bool IsValid() const {
return code == UIEditorWorkspaceLayoutLoadCode::None;
}
};
UIEditorWorkspaceLayoutSnapshot BuildUIEditorWorkspaceLayoutSnapshot(
const UIEditorWorkspaceModel& workspace,
const UIEditorWorkspaceSession& session);
bool AreUIEditorWorkspaceLayoutSnapshotsEquivalent(
const UIEditorWorkspaceLayoutSnapshot& lhs,
const UIEditorWorkspaceLayoutSnapshot& rhs);
std::string SerializeUIEditorWorkspaceLayoutSnapshot(
const UIEditorWorkspaceLayoutSnapshot& snapshot);
UIEditorWorkspaceLayoutLoadResult DeserializeUIEditorWorkspaceLayoutSnapshot(
const UIEditorPanelRegistry& panelRegistry,
std::string_view serializedLayout);
} // namespace XCEngine::NewEditor

View File

@@ -100,6 +100,14 @@ bool ContainsUIEditorWorkspacePanel(
const UIEditorWorkspaceModel& workspace,
std::string_view panelId);
bool AreUIEditorWorkspaceNodesEquivalent(
const UIEditorWorkspaceNode& lhs,
const UIEditorWorkspaceNode& rhs);
bool AreUIEditorWorkspaceModelsEquivalent(
const UIEditorWorkspaceModel& lhs,
const UIEditorWorkspaceModel& rhs);
const UIEditorWorkspacePanelState* FindUIEditorWorkspaceActivePanel(
const UIEditorWorkspaceModel& workspace);

View File

@@ -53,6 +53,10 @@ UIEditorWorkspaceSessionValidationResult ValidateUIEditorWorkspaceSession(
const UIEditorWorkspaceModel& workspace,
const UIEditorWorkspaceSession& session);
bool AreUIEditorWorkspaceSessionsEquivalent(
const UIEditorWorkspaceSession& lhs,
const UIEditorWorkspaceSession& rhs);
std::vector<UIEditorWorkspaceVisiblePanel> CollectUIEditorWorkspaceVisiblePanels(
const UIEditorWorkspaceModel& workspace,
const UIEditorWorkspaceSession& session);

View File

@@ -6,57 +6,6 @@ namespace XCEngine::NewEditor {
namespace {
bool AreWorkspaceNodesEquivalent(
const UIEditorWorkspaceNode& lhs,
const UIEditorWorkspaceNode& rhs) {
if (lhs.kind != rhs.kind ||
lhs.nodeId != rhs.nodeId ||
lhs.splitAxis != rhs.splitAxis ||
lhs.splitRatio != rhs.splitRatio ||
lhs.selectedTabIndex != rhs.selectedTabIndex ||
lhs.panel.panelId != rhs.panel.panelId ||
lhs.panel.title != rhs.panel.title ||
lhs.panel.placeholder != rhs.panel.placeholder ||
lhs.children.size() != rhs.children.size()) {
return false;
}
for (std::size_t index = 0; index < lhs.children.size(); ++index) {
if (!AreWorkspaceNodesEquivalent(lhs.children[index], rhs.children[index])) {
return false;
}
}
return true;
}
bool AreWorkspaceModelsEquivalent(
const UIEditorWorkspaceModel& lhs,
const UIEditorWorkspaceModel& rhs) {
return lhs.activePanelId == rhs.activePanelId &&
AreWorkspaceNodesEquivalent(lhs.root, rhs.root);
}
bool AreWorkspaceSessionsEquivalent(
const UIEditorWorkspaceSession& lhs,
const UIEditorWorkspaceSession& rhs) {
if (lhs.panelStates.size() != rhs.panelStates.size()) {
return false;
}
for (std::size_t index = 0; index < lhs.panelStates.size(); ++index) {
const UIEditorPanelSessionState& lhsState = lhs.panelStates[index];
const UIEditorPanelSessionState& rhsState = rhs.panelStates[index];
if (lhsState.panelId != rhsState.panelId ||
lhsState.open != rhsState.open ||
lhsState.visible != rhsState.visible) {
return false;
}
}
return true;
}
std::vector<std::string> CollectVisiblePanelIds(
const UIEditorWorkspaceModel& workspace,
const UIEditorWorkspaceSession& session) {
@@ -106,6 +55,20 @@ std::string_view GetUIEditorWorkspaceCommandStatusName(UIEditorWorkspaceCommandS
return "Unknown";
}
std::string_view GetUIEditorWorkspaceLayoutOperationStatusName(
UIEditorWorkspaceLayoutOperationStatus status) {
switch (status) {
case UIEditorWorkspaceLayoutOperationStatus::Changed:
return "Changed";
case UIEditorWorkspaceLayoutOperationStatus::NoOp:
return "NoOp";
case UIEditorWorkspaceLayoutOperationStatus::Rejected:
return "Rejected";
}
return "Unknown";
}
UIEditorWorkspaceController::UIEditorWorkspaceController(
UIEditorPanelRegistry panelRegistry,
UIEditorWorkspaceModel workspace,
@@ -148,6 +111,10 @@ UIEditorWorkspaceControllerValidationResult UIEditorWorkspaceController::Validat
return {};
}
UIEditorWorkspaceLayoutSnapshot UIEditorWorkspaceController::CaptureLayoutSnapshot() const {
return BuildUIEditorWorkspaceLayoutSnapshot(m_workspace, m_session);
}
UIEditorWorkspaceCommandResult UIEditorWorkspaceController::BuildResult(
const UIEditorWorkspaceCommand& command,
UIEditorWorkspaceCommandStatus status,
@@ -162,6 +129,17 @@ UIEditorWorkspaceCommandResult UIEditorWorkspaceController::BuildResult(
return result;
}
UIEditorWorkspaceLayoutOperationResult UIEditorWorkspaceController::BuildLayoutOperationResult(
UIEditorWorkspaceLayoutOperationStatus status,
std::string message) const {
UIEditorWorkspaceLayoutOperationResult result = {};
result.status = status;
result.message = std::move(message);
result.activePanelId = m_workspace.activePanelId;
result.visiblePanelIds = CollectVisiblePanelIds(m_workspace, m_session);
return result;
}
UIEditorWorkspaceCommandResult UIEditorWorkspaceController::FinalizeMutation(
const UIEditorWorkspaceCommand& command,
bool changed,
@@ -197,6 +175,71 @@ const UIEditorPanelDescriptor* UIEditorWorkspaceController::FindPanelDescriptor(
return FindUIEditorPanelDescriptor(m_panelRegistry, panelId);
}
UIEditorWorkspaceLayoutOperationResult UIEditorWorkspaceController::RestoreLayoutSnapshot(
const UIEditorWorkspaceLayoutSnapshot& snapshot) {
const UIEditorPanelRegistryValidationResult registryValidation =
ValidateUIEditorPanelRegistry(m_panelRegistry);
if (!registryValidation.IsValid()) {
return BuildLayoutOperationResult(
UIEditorWorkspaceLayoutOperationStatus::Rejected,
"Panel registry invalid: " + registryValidation.message);
}
const UIEditorWorkspaceValidationResult workspaceValidation =
ValidateUIEditorWorkspace(snapshot.workspace);
if (!workspaceValidation.IsValid()) {
return BuildLayoutOperationResult(
UIEditorWorkspaceLayoutOperationStatus::Rejected,
"Layout workspace invalid: " + workspaceValidation.message);
}
const UIEditorWorkspaceSessionValidationResult sessionValidation =
ValidateUIEditorWorkspaceSession(m_panelRegistry, snapshot.workspace, snapshot.session);
if (!sessionValidation.IsValid()) {
return BuildLayoutOperationResult(
UIEditorWorkspaceLayoutOperationStatus::Rejected,
"Layout session invalid: " + sessionValidation.message);
}
if (AreUIEditorWorkspaceModelsEquivalent(m_workspace, snapshot.workspace) &&
AreUIEditorWorkspaceSessionsEquivalent(m_session, snapshot.session)) {
return BuildLayoutOperationResult(
UIEditorWorkspaceLayoutOperationStatus::NoOp,
"Current state already matches the requested layout snapshot.");
}
const UIEditorWorkspaceModel previousWorkspace = m_workspace;
const UIEditorWorkspaceSession previousSession = m_session;
m_workspace = snapshot.workspace;
m_session = snapshot.session;
const UIEditorWorkspaceControllerValidationResult validation = ValidateState();
if (!validation.IsValid()) {
m_workspace = previousWorkspace;
m_session = previousSession;
return BuildLayoutOperationResult(
UIEditorWorkspaceLayoutOperationStatus::Rejected,
"Restored layout produced invalid controller state: " + validation.message);
}
return BuildLayoutOperationResult(
UIEditorWorkspaceLayoutOperationStatus::Changed,
"Layout restored.");
}
UIEditorWorkspaceLayoutOperationResult UIEditorWorkspaceController::RestoreSerializedLayout(
std::string_view serializedLayout) {
const UIEditorWorkspaceLayoutLoadResult loadResult =
DeserializeUIEditorWorkspaceLayoutSnapshot(m_panelRegistry, serializedLayout);
if (!loadResult.IsValid()) {
return BuildLayoutOperationResult(
UIEditorWorkspaceLayoutOperationStatus::Rejected,
"Serialized layout rejected: " + loadResult.message);
}
return RestoreLayoutSnapshot(loadResult.snapshot);
}
UIEditorWorkspaceCommandResult UIEditorWorkspaceController::Dispatch(
const UIEditorWorkspaceCommand& command) {
const UIEditorWorkspaceControllerValidationResult validation = ValidateState();
@@ -326,8 +369,8 @@ UIEditorWorkspaceCommandResult UIEditorWorkspaceController::Dispatch(
previousSession);
case UIEditorWorkspaceCommandKind::ResetWorkspace:
if (AreWorkspaceModelsEquivalent(m_workspace, m_baselineWorkspace) &&
AreWorkspaceSessionsEquivalent(m_session, m_baselineSession)) {
if (AreUIEditorWorkspaceModelsEquivalent(m_workspace, m_baselineWorkspace) &&
AreUIEditorWorkspaceSessionsEquivalent(m_session, m_baselineSession)) {
return BuildResult(command, UIEditorWorkspaceCommandStatus::NoOp, "Workspace already matches the baseline state.");
}

View File

@@ -0,0 +1,497 @@
#include <XCNewEditor/Editor/UIEditorWorkspaceLayoutPersistence.h>
#include <iomanip>
#include <limits>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
namespace XCEngine::NewEditor {
namespace {
constexpr std::string_view kLayoutHeader = "XCUI_EDITOR_WORKSPACE_LAYOUT";
constexpr int kLayoutVersion = 1;
struct LayoutLine {
std::size_t number = 0u;
std::string text = {};
};
UIEditorWorkspaceLayoutLoadResult MakeLoadError(
UIEditorWorkspaceLayoutLoadCode code,
std::string message) {
UIEditorWorkspaceLayoutLoadResult result = {};
result.code = code;
result.message = std::move(message);
return result;
}
bool HasTrailingTokens(std::istringstream& stream) {
stream >> std::ws;
return !stream.eof();
}
std::string MakeLinePrefix(const LayoutLine& line) {
return "Line " + std::to_string(line.number) + ": ";
}
bool ParseBinaryFlag(
std::istringstream& stream,
const LayoutLine& line,
int& outValue,
UIEditorWorkspaceLayoutLoadResult& outError,
UIEditorWorkspaceLayoutLoadCode code,
std::string_view fieldName) {
if (!(stream >> outValue) || (outValue != 0 && outValue != 1)) {
outError = MakeLoadError(
code,
MakeLinePrefix(line) + std::string(fieldName) + " must be encoded as 0 or 1.");
return false;
}
return true;
}
bool ParseNodeLine(
const LayoutLine& line,
std::string& outTag,
std::istringstream& outStream) {
outStream = std::istringstream(line.text);
return static_cast<bool>(outStream >> outTag);
}
UIEditorWorkspaceLayoutLoadResult ParseNodeRecursive(
const std::vector<LayoutLine>& lines,
std::size_t& index,
UIEditorWorkspaceNode& outNode);
std::string SerializeAxis(UIEditorWorkspaceSplitAxis axis) {
return axis == UIEditorWorkspaceSplitAxis::Vertical ? "vertical" : "horizontal";
}
UIEditorWorkspaceLayoutLoadResult ParseAxis(
std::string_view text,
UIEditorWorkspaceSplitAxis& outAxis,
const LayoutLine& line) {
if (text == "horizontal") {
outAxis = UIEditorWorkspaceSplitAxis::Horizontal;
return {};
}
if (text == "vertical") {
outAxis = UIEditorWorkspaceSplitAxis::Vertical;
return {};
}
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidNodeRecord,
MakeLinePrefix(line) + "split axis must be \"horizontal\" or \"vertical\".");
}
void SerializeNodeRecursive(
const UIEditorWorkspaceNode& node,
std::ostringstream& stream) {
switch (node.kind) {
case UIEditorWorkspaceNodeKind::Panel:
stream << "node_panel "
<< std::quoted(node.nodeId) << ' '
<< std::quoted(node.panel.panelId) << ' '
<< std::quoted(node.panel.title) << ' '
<< (node.panel.placeholder ? 1 : 0) << '\n';
return;
case UIEditorWorkspaceNodeKind::TabStack:
stream << "node_tabstack "
<< std::quoted(node.nodeId) << ' '
<< node.selectedTabIndex << ' '
<< node.children.size() << '\n';
for (const UIEditorWorkspaceNode& child : node.children) {
SerializeNodeRecursive(child, stream);
}
return;
case UIEditorWorkspaceNodeKind::Split:
stream << "node_split "
<< std::quoted(node.nodeId) << ' '
<< std::quoted(SerializeAxis(node.splitAxis)) << ' '
<< std::setprecision(std::numeric_limits<float>::max_digits10)
<< node.splitRatio << '\n';
for (const UIEditorWorkspaceNode& child : node.children) {
SerializeNodeRecursive(child, stream);
}
return;
}
}
std::vector<LayoutLine> CollectNonEmptyLines(std::string_view serializedLayout) {
std::vector<LayoutLine> lines = {};
std::istringstream stream{ std::string(serializedLayout) };
std::string text = {};
std::size_t lineNumber = 0u;
while (std::getline(stream, text)) {
++lineNumber;
if (!text.empty() && text.back() == '\r') {
text.pop_back();
}
const std::size_t first = text.find_first_not_of(" \t");
if (first == std::string::npos) {
continue;
}
lines.push_back({ lineNumber, text });
}
return lines;
}
UIEditorWorkspaceLayoutLoadResult ParseHeader(const LayoutLine& line) {
std::istringstream stream(line.text);
std::string header = {};
int version = 0;
if (!(stream >> header >> version) || HasTrailingTokens(stream)) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidHeader,
MakeLinePrefix(line) + "invalid layout header.");
}
if (header != kLayoutHeader) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidHeader,
MakeLinePrefix(line) + "layout header magic is invalid.");
}
if (version != kLayoutVersion) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::UnsupportedVersion,
MakeLinePrefix(line) + "unsupported layout version " + std::to_string(version) + ".");
}
return {};
}
UIEditorWorkspaceLayoutLoadResult ParseActiveRecord(
const LayoutLine& line,
std::string& outActivePanelId) {
std::istringstream stream(line.text);
std::string tag = {};
if (!(stream >> tag) || tag != "active" ||
!(stream >> std::quoted(outActivePanelId)) ||
HasTrailingTokens(stream)) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::MissingActiveRecord,
MakeLinePrefix(line) + "active record must be `active \"panel-id\"`.");
}
return {};
}
UIEditorWorkspaceLayoutLoadResult ParsePanelNode(
std::istringstream& stream,
const LayoutLine& line,
UIEditorWorkspaceNode& outNode) {
std::string nodeId = {};
std::string panelId = {};
std::string title = {};
int placeholderValue = 0;
if (!(stream >> std::quoted(nodeId) >> std::quoted(panelId) >> std::quoted(title))) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidNodeRecord,
MakeLinePrefix(line) + "panel node record is malformed.");
}
UIEditorWorkspaceLayoutLoadResult boolParse = {};
if (!ParseBinaryFlag(
stream,
line,
placeholderValue,
boolParse,
UIEditorWorkspaceLayoutLoadCode::InvalidNodeRecord,
"placeholder")) {
return boolParse;
}
if (HasTrailingTokens(stream)) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidNodeRecord,
MakeLinePrefix(line) + "panel node record contains trailing tokens.");
}
outNode = BuildUIEditorWorkspacePanel(
std::move(nodeId),
std::move(panelId),
std::move(title),
placeholderValue != 0);
return {};
}
UIEditorWorkspaceLayoutLoadResult ParseTabStackNode(
const std::vector<LayoutLine>& lines,
std::size_t& index,
std::istringstream& stream,
const LayoutLine& line,
UIEditorWorkspaceNode& outNode) {
std::string nodeId = {};
std::size_t selectedTabIndex = 0u;
std::size_t childCount = 0u;
if (!(stream >> std::quoted(nodeId) >> selectedTabIndex >> childCount) ||
HasTrailingTokens(stream)) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidNodeRecord,
MakeLinePrefix(line) + "tab stack node record is malformed.");
}
outNode = {};
outNode.kind = UIEditorWorkspaceNodeKind::TabStack;
outNode.nodeId = std::move(nodeId);
outNode.selectedTabIndex = selectedTabIndex;
outNode.children.reserve(childCount);
for (std::size_t childIndex = 0; childIndex < childCount; ++childIndex) {
UIEditorWorkspaceNode child = {};
UIEditorWorkspaceLayoutLoadResult childResult = ParseNodeRecursive(lines, index, child);
if (!childResult.IsValid()) {
return childResult;
}
outNode.children.push_back(std::move(child));
}
return {};
}
UIEditorWorkspaceLayoutLoadResult ParseSplitNode(
const std::vector<LayoutLine>& lines,
std::size_t& index,
std::istringstream& stream,
const LayoutLine& line,
UIEditorWorkspaceNode& outNode) {
std::string nodeId = {};
std::string axisText = {};
float splitRatio = 0.0f;
if (!(stream >> std::quoted(nodeId) >> std::quoted(axisText) >> splitRatio) ||
HasTrailingTokens(stream)) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidNodeRecord,
MakeLinePrefix(line) + "split node record is malformed.");
}
UIEditorWorkspaceSplitAxis axis = UIEditorWorkspaceSplitAxis::Horizontal;
if (UIEditorWorkspaceLayoutLoadResult axisResult = ParseAxis(axisText, axis, line);
!axisResult.IsValid()) {
return axisResult;
}
UIEditorWorkspaceNode primary = {};
UIEditorWorkspaceNode secondary = {};
if (UIEditorWorkspaceLayoutLoadResult primaryResult = ParseNodeRecursive(lines, index, primary);
!primaryResult.IsValid()) {
return primaryResult;
}
if (UIEditorWorkspaceLayoutLoadResult secondaryResult = ParseNodeRecursive(lines, index, secondary);
!secondaryResult.IsValid()) {
return secondaryResult;
}
outNode = BuildUIEditorWorkspaceSplit(
std::move(nodeId),
axis,
splitRatio,
std::move(primary),
std::move(secondary));
return {};
}
UIEditorWorkspaceLayoutLoadResult ParseNodeRecursive(
const std::vector<LayoutLine>& lines,
std::size_t& index,
UIEditorWorkspaceNode& outNode) {
if (index >= lines.size()) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::UnexpectedEndOfInput,
"Unexpected end of input while parsing workspace nodes.");
}
const LayoutLine& line = lines[index++];
std::istringstream stream = {};
std::string tag = {};
if (!ParseNodeLine(line, tag, stream)) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidNodeRecord,
MakeLinePrefix(line) + "workspace node record is empty.");
}
if (tag == "node_panel") {
return ParsePanelNode(stream, line, outNode);
}
if (tag == "node_tabstack") {
return ParseTabStackNode(lines, index, stream, line, outNode);
}
if (tag == "node_split") {
return ParseSplitNode(lines, index, stream, line, outNode);
}
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidNodeRecord,
MakeLinePrefix(line) + "unknown workspace node tag '" + tag + "'.");
}
UIEditorWorkspaceLayoutLoadResult ParseSessionRecord(
const LayoutLine& line,
UIEditorPanelSessionState& outState) {
std::istringstream stream(line.text);
std::string tag = {};
int openValue = 0;
int visibleValue = 0;
if (!(stream >> tag) || tag != "session" ||
!(stream >> std::quoted(outState.panelId))) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidSessionRecord,
MakeLinePrefix(line) + "session record must start with `session`.");
}
UIEditorWorkspaceLayoutLoadResult boolParse = {};
if (!ParseBinaryFlag(
stream,
line,
openValue,
boolParse,
UIEditorWorkspaceLayoutLoadCode::InvalidSessionRecord,
"open")) {
return boolParse;
}
if (!ParseBinaryFlag(
stream,
line,
visibleValue,
boolParse,
UIEditorWorkspaceLayoutLoadCode::InvalidSessionRecord,
"visible")) {
return boolParse;
}
if (HasTrailingTokens(stream)) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidSessionRecord,
MakeLinePrefix(line) + "session record contains trailing tokens.");
}
outState.open = openValue != 0;
outState.visible = visibleValue != 0;
return {};
}
} // namespace
UIEditorWorkspaceLayoutSnapshot BuildUIEditorWorkspaceLayoutSnapshot(
const UIEditorWorkspaceModel& workspace,
const UIEditorWorkspaceSession& session) {
UIEditorWorkspaceLayoutSnapshot snapshot = {};
snapshot.workspace = workspace;
snapshot.session = session;
return snapshot;
}
bool AreUIEditorWorkspaceLayoutSnapshotsEquivalent(
const UIEditorWorkspaceLayoutSnapshot& lhs,
const UIEditorWorkspaceLayoutSnapshot& rhs) {
return AreUIEditorWorkspaceModelsEquivalent(lhs.workspace, rhs.workspace) &&
AreUIEditorWorkspaceSessionsEquivalent(lhs.session, rhs.session);
}
std::string SerializeUIEditorWorkspaceLayoutSnapshot(
const UIEditorWorkspaceLayoutSnapshot& snapshot) {
std::ostringstream stream = {};
stream << kLayoutHeader << ' ' << kLayoutVersion << '\n';
stream << "active " << std::quoted(snapshot.workspace.activePanelId) << '\n';
SerializeNodeRecursive(snapshot.workspace.root, stream);
for (const UIEditorPanelSessionState& state : snapshot.session.panelStates) {
stream << "session "
<< std::quoted(state.panelId) << ' '
<< (state.open ? 1 : 0) << ' '
<< (state.visible ? 1 : 0) << '\n';
}
return stream.str();
}
UIEditorWorkspaceLayoutLoadResult DeserializeUIEditorWorkspaceLayoutSnapshot(
const UIEditorPanelRegistry& panelRegistry,
std::string_view serializedLayout) {
const UIEditorPanelRegistryValidationResult registryValidation =
ValidateUIEditorPanelRegistry(panelRegistry);
if (!registryValidation.IsValid()) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidPanelRegistry,
"Panel registry invalid: " + registryValidation.message);
}
const std::vector<LayoutLine> lines = CollectNonEmptyLines(serializedLayout);
if (lines.empty()) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::EmptyInput,
"Serialized layout input is empty.");
}
if (UIEditorWorkspaceLayoutLoadResult headerResult = ParseHeader(lines.front());
!headerResult.IsValid()) {
return headerResult;
}
if (lines.size() < 2u) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::MissingActiveRecord,
"Serialized layout is missing the active panel record.");
}
UIEditorWorkspaceLayoutSnapshot snapshot = {};
if (UIEditorWorkspaceLayoutLoadResult activeResult =
ParseActiveRecord(lines[1], snapshot.workspace.activePanelId);
!activeResult.IsValid()) {
return activeResult;
}
std::size_t index = 2u;
if (UIEditorWorkspaceLayoutLoadResult rootResult =
ParseNodeRecursive(lines, index, snapshot.workspace.root);
!rootResult.IsValid()) {
return rootResult;
}
snapshot.session.panelStates.clear();
while (index < lines.size()) {
UIEditorPanelSessionState state = {};
if (UIEditorWorkspaceLayoutLoadResult stateResult =
ParseSessionRecord(lines[index], state);
!stateResult.IsValid()) {
return stateResult;
}
snapshot.session.panelStates.push_back(std::move(state));
++index;
}
if (UIEditorWorkspaceValidationResult workspaceValidation =
ValidateUIEditorWorkspace(snapshot.workspace);
!workspaceValidation.IsValid()) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidWorkspace,
workspaceValidation.message);
}
if (UIEditorWorkspaceSessionValidationResult sessionValidation =
ValidateUIEditorWorkspaceSession(panelRegistry, snapshot.workspace, snapshot.session);
!sessionValidation.IsValid()) {
return MakeLoadError(
UIEditorWorkspaceLayoutLoadCode::InvalidWorkspaceSession,
sessionValidation.message);
}
UIEditorWorkspaceLayoutLoadResult result = {};
result.snapshot = std::move(snapshot);
return result;
}
} // namespace XCEngine::NewEditor

View File

@@ -205,6 +205,37 @@ UIEditorWorkspaceValidationResult ValidateNodeRecursive(
} // namespace
bool AreUIEditorWorkspaceNodesEquivalent(
const UIEditorWorkspaceNode& lhs,
const UIEditorWorkspaceNode& rhs) {
if (lhs.kind != rhs.kind ||
lhs.nodeId != rhs.nodeId ||
lhs.splitAxis != rhs.splitAxis ||
lhs.splitRatio != rhs.splitRatio ||
lhs.selectedTabIndex != rhs.selectedTabIndex ||
lhs.panel.panelId != rhs.panel.panelId ||
lhs.panel.title != rhs.panel.title ||
lhs.panel.placeholder != rhs.panel.placeholder ||
lhs.children.size() != rhs.children.size()) {
return false;
}
for (std::size_t index = 0; index < lhs.children.size(); ++index) {
if (!AreUIEditorWorkspaceNodesEquivalent(lhs.children[index], rhs.children[index])) {
return false;
}
}
return true;
}
bool AreUIEditorWorkspaceModelsEquivalent(
const UIEditorWorkspaceModel& lhs,
const UIEditorWorkspaceModel& rhs) {
return lhs.activePanelId == rhs.activePanelId &&
AreUIEditorWorkspaceNodesEquivalent(lhs.root, rhs.root);
}
UIEditorWorkspaceModel BuildDefaultEditorShellWorkspaceModel() {
const UIEditorPanelRegistry registry = BuildDefaultEditorShellPanelRegistry();
const UIEditorPanelDescriptor& rootPanel =

View File

@@ -198,57 +198,6 @@ void NormalizeWorkspaceSession(
TryActivateUIEditorWorkspacePanel(workspace, targetActivePanelId);
}
bool AreWorkspaceNodesEquivalent(
const UIEditorWorkspaceNode& lhs,
const UIEditorWorkspaceNode& rhs) {
if (lhs.kind != rhs.kind ||
lhs.nodeId != rhs.nodeId ||
lhs.splitAxis != rhs.splitAxis ||
lhs.splitRatio != rhs.splitRatio ||
lhs.selectedTabIndex != rhs.selectedTabIndex ||
lhs.panel.panelId != rhs.panel.panelId ||
lhs.panel.title != rhs.panel.title ||
lhs.panel.placeholder != rhs.panel.placeholder ||
lhs.children.size() != rhs.children.size()) {
return false;
}
for (std::size_t index = 0; index < lhs.children.size(); ++index) {
if (!AreWorkspaceNodesEquivalent(lhs.children[index], rhs.children[index])) {
return false;
}
}
return true;
}
bool AreWorkspaceModelsEquivalent(
const UIEditorWorkspaceModel& lhs,
const UIEditorWorkspaceModel& rhs) {
return lhs.activePanelId == rhs.activePanelId &&
AreWorkspaceNodesEquivalent(lhs.root, rhs.root);
}
bool AreWorkspaceSessionsEquivalent(
const UIEditorWorkspaceSession& lhs,
const UIEditorWorkspaceSession& rhs) {
if (lhs.panelStates.size() != rhs.panelStates.size()) {
return false;
}
for (std::size_t index = 0; index < lhs.panelStates.size(); ++index) {
const UIEditorPanelSessionState& lhsState = lhs.panelStates[index];
const UIEditorPanelSessionState& rhsState = rhs.panelStates[index];
if (lhsState.panelId != rhsState.panelId ||
lhsState.open != rhsState.open ||
lhsState.visible != rhsState.visible) {
return false;
}
}
return true;
}
} // namespace
UIEditorWorkspaceSession BuildDefaultUIEditorWorkspaceSession(
@@ -348,6 +297,26 @@ UIEditorWorkspaceSessionValidationResult ValidateUIEditorWorkspaceSession(
return {};
}
bool AreUIEditorWorkspaceSessionsEquivalent(
const UIEditorWorkspaceSession& lhs,
const UIEditorWorkspaceSession& rhs) {
if (lhs.panelStates.size() != rhs.panelStates.size()) {
return false;
}
for (std::size_t index = 0; index < lhs.panelStates.size(); ++index) {
const UIEditorPanelSessionState& lhsState = lhs.panelStates[index];
const UIEditorPanelSessionState& rhsState = rhs.panelStates[index];
if (lhsState.panelId != rhsState.panelId ||
lhsState.open != rhsState.open ||
lhsState.visible != rhsState.visible) {
return false;
}
}
return true;
}
std::vector<UIEditorWorkspaceVisiblePanel> CollectUIEditorWorkspaceVisiblePanels(
const UIEditorWorkspaceModel& workspace,
const UIEditorWorkspaceSession& session) {
@@ -391,8 +360,8 @@ bool TryOpenUIEditorWorkspacePanel(
state->open = true;
state->visible = true;
NormalizeWorkspaceSession(panelRegistry, workspace, session, panelId);
return !AreWorkspaceModelsEquivalent(workspaceBefore, workspace) ||
!AreWorkspaceSessionsEquivalent(sessionBefore, session);
return !AreUIEditorWorkspaceModelsEquivalent(workspaceBefore, workspace) ||
!AreUIEditorWorkspaceSessionsEquivalent(sessionBefore, session);
}
bool TryCloseUIEditorWorkspacePanel(
@@ -412,8 +381,8 @@ bool TryCloseUIEditorWorkspacePanel(
state->open = false;
state->visible = false;
NormalizeWorkspaceSession(panelRegistry, workspace, session, {});
return !AreWorkspaceModelsEquivalent(workspaceBefore, workspace) ||
!AreWorkspaceSessionsEquivalent(sessionBefore, session);
return !AreUIEditorWorkspaceModelsEquivalent(workspaceBefore, workspace) ||
!AreUIEditorWorkspaceSessionsEquivalent(sessionBefore, session);
}
bool TryShowUIEditorWorkspacePanel(
@@ -432,8 +401,8 @@ bool TryShowUIEditorWorkspacePanel(
state->visible = true;
NormalizeWorkspaceSession(panelRegistry, workspace, session, panelId);
return !AreWorkspaceModelsEquivalent(workspaceBefore, workspace) ||
!AreWorkspaceSessionsEquivalent(sessionBefore, session);
return !AreUIEditorWorkspaceModelsEquivalent(workspaceBefore, workspace) ||
!AreUIEditorWorkspaceSessionsEquivalent(sessionBefore, session);
}
bool TryHideUIEditorWorkspacePanel(
@@ -452,8 +421,8 @@ bool TryHideUIEditorWorkspacePanel(
state->visible = false;
NormalizeWorkspaceSession(panelRegistry, workspace, session, {});
return !AreWorkspaceModelsEquivalent(workspaceBefore, workspace) ||
!AreWorkspaceSessionsEquivalent(sessionBefore, session);
return !AreUIEditorWorkspaceModelsEquivalent(workspaceBefore, workspace) ||
!AreUIEditorWorkspaceSessionsEquivalent(sessionBefore, session);
}
bool TryActivateUIEditorWorkspacePanel(
@@ -469,8 +438,8 @@ bool TryActivateUIEditorWorkspacePanel(
}
NormalizeWorkspaceSession(panelRegistry, workspace, session, panelId);
return !AreWorkspaceModelsEquivalent(workspaceBefore, workspace) ||
!AreWorkspaceSessionsEquivalent(sessionBefore, session);
return !AreUIEditorWorkspaceModelsEquivalent(workspaceBefore, workspace) ||
!AreUIEditorWorkspaceSessionsEquivalent(sessionBefore, session);
}
} // namespace XCEngine::NewEditor

View File

@@ -10,12 +10,15 @@ Current status:
splitters, tab host, panel chrome placeholders, and hot reload.
- The second scenario is `state/panel_session_flow/`, focused on editor command dispatch and panel session state only:
`command dispatch + workspace controller + open / close / show / hide / activate`.
- The third scenario is `state/layout_persistence/`, focused on editor layout save/load/reset only:
`layout snapshot + serialize / deserialize + invalid payload reject`.
Layout:
- `shared/`: editor validation scenario registry, Win32 host wrapper, shared theme
- `workspace_shell_compose/`: first manual editor shell compose scenario
- `state/panel_session_flow/`: custom host scenario for editor panel session state flow
- `state/layout_persistence/`: custom host scenario for editor layout persistence flow
Current scenario:
@@ -31,6 +34,13 @@ Additional scenario:
- Executable name: `XCUIEditorPanelSessionFlowValidation`
- Validation scope: editor command dispatch and panel session state only, no business panels
Additional scenario:
- Scenario id: `editor.state.layout_persistence`
- Build target: `editor_ui_layout_persistence_validation`
- Executable name: `XCUIEditorLayoutPersistenceValidation`
- Validation scope: layout save / load / reset / invalid payload reject only, no business panels
Run:
```bash
@@ -52,6 +62,13 @@ Panel session flow controls:
- Check `Last command` shows `Changed / NoOp / Rejected` consistently with the current state.
- Press `F12` to write screenshots into `state/panel_session_flow/captures/`.
Layout persistence controls:
- Click `Hide Active -> Save Layout -> Close Doc B -> Load Layout`.
- Check `Saved` summary captures the expected active/visible state, and `Load Layout` restores it.
- Click `Load Invalid` and confirm the result is `Rejected` while current state remains unchanged.
- Press `F12` to write screenshots into `state/layout_persistence/captures/`.
Build:
```bash

View File

@@ -1 +1,2 @@
add_subdirectory(panel_session_flow)
add_subdirectory(layout_persistence)

View File

@@ -0,0 +1,29 @@
add_executable(editor_ui_layout_persistence_validation WIN32
main.cpp
)
target_include_directories(editor_ui_layout_persistence_validation PRIVATE
${CMAKE_SOURCE_DIR}/engine/include
${CMAKE_SOURCE_DIR}/new_editor/include
)
target_compile_definitions(editor_ui_layout_persistence_validation PRIVATE
UNICODE
_UNICODE
XCENGINE_EDITOR_UI_TESTS_REPO_ROOT="${XCENGINE_EDITOR_UI_TESTS_REPO_ROOT_PATH}"
)
if(MSVC)
target_compile_options(editor_ui_layout_persistence_validation PRIVATE /utf-8 /FS)
set_property(TARGET editor_ui_layout_persistence_validation PROPERTY
MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>DLL")
endif()
target_link_libraries(editor_ui_layout_persistence_validation PRIVATE
XCNewEditorLib
XCNewEditorHost
)
set_target_properties(editor_ui_layout_persistence_validation PROPERTIES
OUTPUT_NAME "XCUIEditorLayoutPersistenceValidation"
)

View File

@@ -0,0 +1,858 @@
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <XCNewEditor/Editor/UIEditorWorkspaceController.h>
#include <XCNewEditor/Editor/UIEditorWorkspaceLayoutPersistence.h>
#include <XCNewEditor/Host/AutoScreenshot.h>
#include <XCNewEditor/Host/NativeRenderer.h>
#include <XCEngine/UI/DrawData.h>
#include <windows.h>
#include <windowsx.h>
#include <algorithm>
#include <filesystem>
#include <iomanip>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#ifndef XCENGINE_EDITOR_UI_TESTS_REPO_ROOT
#define XCENGINE_EDITOR_UI_TESTS_REPO_ROOT "."
#endif
namespace {
using XCEngine::NewEditor::BuildDefaultUIEditorWorkspaceController;
using XCEngine::NewEditor::BuildDefaultUIEditorWorkspaceSession;
using XCEngine::NewEditor::BuildUIEditorWorkspacePanel;
using XCEngine::NewEditor::BuildUIEditorWorkspaceSplit;
using XCEngine::NewEditor::BuildUIEditorWorkspaceTabStack;
using XCEngine::NewEditor::CollectUIEditorWorkspaceVisiblePanels;
using XCEngine::NewEditor::FindUIEditorPanelSessionState;
using XCEngine::NewEditor::GetUIEditorWorkspaceCommandStatusName;
using XCEngine::NewEditor::GetUIEditorWorkspaceLayoutOperationStatusName;
using XCEngine::NewEditor::SerializeUIEditorWorkspaceLayoutSnapshot;
using XCEngine::NewEditor::UIEditorPanelRegistry;
using XCEngine::NewEditor::UIEditorWorkspaceCommand;
using XCEngine::NewEditor::UIEditorWorkspaceCommandKind;
using XCEngine::NewEditor::UIEditorWorkspaceCommandResult;
using XCEngine::NewEditor::UIEditorWorkspaceCommandStatus;
using XCEngine::NewEditor::UIEditorWorkspaceController;
using XCEngine::NewEditor::UIEditorWorkspaceLayoutOperationResult;
using XCEngine::NewEditor::UIEditorWorkspaceLayoutOperationStatus;
using XCEngine::NewEditor::UIEditorWorkspaceLayoutSnapshot;
using XCEngine::NewEditor::UIEditorWorkspaceModel;
using XCEngine::NewEditor::UIEditorWorkspaceSession;
using XCEngine::NewEditor::UIEditorWorkspaceSplitAxis;
using XCEngine::UI::UIColor;
using XCEngine::UI::UIDrawData;
using XCEngine::UI::UIDrawList;
using XCEngine::UI::UIPoint;
using XCEngine::UI::UIRect;
using XCEngine::XCUI::Host::AutoScreenshotController;
using XCEngine::XCUI::Host::NativeRenderer;
constexpr const wchar_t* kWindowClassName = L"XCUIEditorLayoutPersistenceValidation";
constexpr const wchar_t* kWindowTitle = L"XCUI Editor | Layout Persistence";
constexpr UIColor kWindowBg(0.14f, 0.14f, 0.14f, 1.0f);
constexpr UIColor kCardBg(0.19f, 0.19f, 0.19f, 1.0f);
constexpr UIColor kCardBorder(0.29f, 0.29f, 0.29f, 1.0f);
constexpr UIColor kTextPrimary(0.94f, 0.94f, 0.94f, 1.0f);
constexpr UIColor kTextMuted(0.70f, 0.70f, 0.70f, 1.0f);
constexpr UIColor kAccent(0.82f, 0.82f, 0.82f, 1.0f);
constexpr UIColor kSuccess(0.43f, 0.71f, 0.47f, 1.0f);
constexpr UIColor kWarning(0.78f, 0.60f, 0.30f, 1.0f);
constexpr UIColor kDanger(0.78f, 0.34f, 0.34f, 1.0f);
constexpr UIColor kButtonEnabled(0.31f, 0.31f, 0.31f, 1.0f);
constexpr UIColor kButtonDisabled(0.24f, 0.24f, 0.24f, 1.0f);
constexpr UIColor kButtonBorder(0.42f, 0.42f, 0.42f, 1.0f);
constexpr UIColor kPanelRowBg(0.17f, 0.17f, 0.17f, 1.0f);
enum class ActionId : unsigned char {
HideActive = 0,
SaveLayout,
CloseDocB,
LoadLayout,
ActivateDetails,
LoadInvalid,
Reset
};
struct ButtonState {
ActionId action = ActionId::HideActive;
std::string label = {};
UIRect rect = {};
bool enabled = false;
};
std::filesystem::path ResolveRepoRootPath() {
std::string root = XCENGINE_EDITOR_UI_TESTS_REPO_ROOT;
if (root.size() >= 2u && root.front() == '"' && root.back() == '"') {
root = root.substr(1u, root.size() - 2u);
}
return std::filesystem::path(root).lexically_normal();
}
UIEditorPanelRegistry BuildPanelRegistry() {
UIEditorPanelRegistry registry = {};
registry.panels = {
{ "doc-a", "Document A", {}, true, true, true },
{ "doc-b", "Document B", {}, true, true, true },
{ "details", "Details", {}, true, true, true }
};
return registry;
}
UIEditorWorkspaceModel BuildWorkspace() {
UIEditorWorkspaceModel workspace = {};
workspace.root = BuildUIEditorWorkspaceSplit(
"root-split",
UIEditorWorkspaceSplitAxis::Horizontal,
0.66f,
BuildUIEditorWorkspaceTabStack(
"document-tabs",
{
BuildUIEditorWorkspacePanel("doc-a-node", "doc-a", "Document A", true),
BuildUIEditorWorkspacePanel("doc-b-node", "doc-b", "Document B", true)
},
0u),
BuildUIEditorWorkspacePanel("details-node", "details", "Details", true));
workspace.activePanelId = "doc-a";
return workspace;
}
bool ContainsPoint(const UIRect& rect, float x, float y) {
return x >= rect.x &&
x <= rect.x + rect.width &&
y >= rect.y &&
y <= rect.y + rect.height;
}
std::string JoinVisiblePanelIds(
const UIEditorWorkspaceModel& workspace,
const UIEditorWorkspaceSession& session) {
const auto panels = CollectUIEditorWorkspaceVisiblePanels(workspace, session);
if (panels.empty()) {
return "(none)";
}
std::ostringstream stream;
for (std::size_t index = 0; index < panels.size(); ++index) {
if (index > 0u) {
stream << ", ";
}
stream << panels[index].panelId;
}
return stream.str();
}
std::string DescribePanelState(
const UIEditorWorkspaceSession& session,
std::string_view panelId,
std::string_view displayName) {
const auto* state = FindUIEditorPanelSessionState(session, panelId);
if (state == nullptr) {
return std::string(displayName) + ": missing";
}
std::string visibility = {};
if (!state->open) {
visibility = "closed";
} else if (!state->visible) {
visibility = "hidden";
} else {
visibility = "visible";
}
return std::string(displayName) + ": " + visibility;
}
UIColor ResolvePanelStateColor(
const UIEditorWorkspaceSession& session,
std::string_view panelId) {
const auto* state = FindUIEditorPanelSessionState(session, panelId);
if (state == nullptr) {
return kDanger;
}
if (!state->open) {
return kDanger;
}
if (!state->visible) {
return kWarning;
}
return kSuccess;
}
void DrawCard(
UIDrawList& drawList,
const UIRect& rect,
std::string_view title,
std::string_view subtitle = {}) {
drawList.AddFilledRect(rect, kCardBg, 12.0f);
drawList.AddRectOutline(rect, kCardBorder, 1.0f, 12.0f);
drawList.AddText(UIPoint(rect.x + 18.0f, rect.y + 16.0f), std::string(title), kTextPrimary, 17.0f);
if (!subtitle.empty()) {
drawList.AddText(UIPoint(rect.x + 18.0f, rect.y + 42.0f), std::string(subtitle), kTextMuted, 12.0f);
}
}
std::string BuildSerializedPreview(std::string_view serializedLayout) {
if (serializedLayout.empty()) {
return "尚未保存布局";
}
std::istringstream stream{ std::string(serializedLayout) };
std::ostringstream preview = {};
std::string line = {};
int lineCount = 0;
while (std::getline(stream, line) && lineCount < 4) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
if (line.empty()) {
continue;
}
if (lineCount > 0) {
preview << " | ";
}
preview << line;
++lineCount;
}
return preview.str();
}
std::string ReplaceActiveRecord(
std::string serializedLayout,
std::string_view replacementPanelId) {
const std::size_t activeStart = serializedLayout.find("active ");
if (activeStart == std::string::npos) {
return {};
}
const std::size_t lineEnd = serializedLayout.find('\n', activeStart);
std::ostringstream replacement = {};
replacement << "active " << std::quoted(std::string(replacementPanelId));
serializedLayout.replace(
activeStart,
lineEnd == std::string::npos ? serializedLayout.size() - activeStart : lineEnd - activeStart,
replacement.str());
return serializedLayout;
}
UIColor ResolveCommandStatusColor(UIEditorWorkspaceCommandStatus status) {
switch (status) {
case UIEditorWorkspaceCommandStatus::Changed:
return kSuccess;
case UIEditorWorkspaceCommandStatus::NoOp:
return kWarning;
case UIEditorWorkspaceCommandStatus::Rejected:
return kDanger;
}
return kTextMuted;
}
UIColor ResolveLayoutStatusColor(UIEditorWorkspaceLayoutOperationStatus status) {
switch (status) {
case UIEditorWorkspaceLayoutOperationStatus::Changed:
return kSuccess;
case UIEditorWorkspaceLayoutOperationStatus::NoOp:
return kWarning;
case UIEditorWorkspaceLayoutOperationStatus::Rejected:
return kDanger;
}
return kTextMuted;
}
class ScenarioApp {
public:
int Run(HINSTANCE hInstance, int nCmdShow) {
if (!Initialize(hInstance, nCmdShow)) {
Shutdown();
return 1;
}
MSG message = {};
while (message.message != WM_QUIT) {
if (PeekMessageW(&message, nullptr, 0U, 0U, PM_REMOVE)) {
TranslateMessage(&message);
DispatchMessageW(&message);
continue;
}
RenderFrame();
Sleep(8);
}
Shutdown();
return static_cast<int>(message.wParam);
}
private:
static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == WM_NCCREATE) {
const auto* createStruct = reinterpret_cast<CREATESTRUCTW*>(lParam);
auto* app = reinterpret_cast<ScenarioApp*>(createStruct->lpCreateParams);
SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(app));
return TRUE;
}
auto* app = reinterpret_cast<ScenarioApp*>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
switch (message) {
case WM_SIZE:
if (app != nullptr && wParam != SIZE_MINIMIZED) {
app->OnResize(static_cast<UINT>(LOWORD(lParam)), static_cast<UINT>(HIWORD(lParam)));
}
return 0;
case WM_PAINT:
if (app != nullptr) {
PAINTSTRUCT paintStruct = {};
BeginPaint(hwnd, &paintStruct);
app->RenderFrame();
EndPaint(hwnd, &paintStruct);
return 0;
}
break;
case WM_LBUTTONUP:
if (app != nullptr) {
app->HandleClick(
static_cast<float>(GET_X_LPARAM(lParam)),
static_cast<float>(GET_Y_LPARAM(lParam)));
return 0;
}
break;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
if (app != nullptr) {
if (wParam == VK_F12) {
app->m_autoScreenshot.RequestCapture("manual_f12");
} else {
app->HandleShortcut(static_cast<UINT>(wParam));
}
return 0;
}
break;
case WM_ERASEBKGND:
return 1;
case WM_DESTROY:
if (app != nullptr) {
app->m_hwnd = nullptr;
}
PostQuitMessage(0);
return 0;
default:
break;
}
return DefWindowProcW(hwnd, message, wParam, lParam);
}
bool Initialize(HINSTANCE hInstance, int nCmdShow) {
m_hInstance = hInstance;
ResetScenario();
WNDCLASSEXW windowClass = {};
windowClass.cbSize = sizeof(windowClass);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = &ScenarioApp::WndProc;
windowClass.hInstance = hInstance;
windowClass.hCursor = LoadCursorW(nullptr, IDC_ARROW);
windowClass.lpszClassName = kWindowClassName;
m_windowClassAtom = RegisterClassExW(&windowClass);
if (m_windowClassAtom == 0) {
return false;
}
m_hwnd = CreateWindowExW(
0,
kWindowClassName,
kWindowTitle,
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
1360,
900,
nullptr,
nullptr,
hInstance,
this);
if (m_hwnd == nullptr) {
return false;
}
ShowWindow(m_hwnd, nCmdShow);
UpdateWindow(m_hwnd);
if (!m_renderer.Initialize(m_hwnd)) {
return false;
}
m_autoScreenshot.Initialize(
(ResolveRepoRootPath() / "tests/UI/Editor/integration/state/layout_persistence/captures")
.lexically_normal());
return true;
}
void Shutdown() {
m_autoScreenshot.Shutdown();
m_renderer.Shutdown();
if (m_hwnd != nullptr && IsWindow(m_hwnd)) {
DestroyWindow(m_hwnd);
}
m_hwnd = nullptr;
if (m_windowClassAtom != 0 && m_hInstance != nullptr) {
UnregisterClassW(kWindowClassName, m_hInstance);
m_windowClassAtom = 0;
}
}
void ResetScenario() {
m_controller =
BuildDefaultUIEditorWorkspaceController(BuildPanelRegistry(), BuildWorkspace());
m_savedSnapshot = {};
m_savedSerializedLayout.clear();
m_hasSavedLayout = false;
SetCustomResult(
"等待操作",
"Pending",
"先点 `1 Hide Active`,再点 `2 Save Layout`;保存后继续改状态,再用 `4 Load Layout` 检查恢复。");
}
void OnResize(UINT width, UINT height) {
if (width == 0 || height == 0) {
return;
}
m_renderer.Resize(width, height);
}
void RenderFrame() {
if (m_hwnd == nullptr) {
return;
}
RECT clientRect = {};
GetClientRect(m_hwnd, &clientRect);
const float width = static_cast<float>((std::max)(clientRect.right - clientRect.left, 1L));
const float height = static_cast<float>((std::max)(clientRect.bottom - clientRect.top, 1L));
UIDrawData drawData = {};
BuildDrawData(drawData, width, height);
const bool framePresented = m_renderer.Render(drawData);
m_autoScreenshot.CaptureIfRequested(
m_renderer,
drawData,
static_cast<unsigned int>(width),
static_cast<unsigned int>(height),
framePresented);
}
void HandleClick(float x, float y) {
for (const ButtonState& button : m_buttons) {
if (button.enabled && ContainsPoint(button.rect, x, y)) {
DispatchAction(button.action);
InvalidateRect(m_hwnd, nullptr, FALSE);
return;
}
}
}
void HandleShortcut(UINT keyCode) {
switch (keyCode) {
case '1':
DispatchAction(ActionId::HideActive);
break;
case '2':
DispatchAction(ActionId::SaveLayout);
break;
case '3':
DispatchAction(ActionId::CloseDocB);
break;
case '4':
DispatchAction(ActionId::LoadLayout);
break;
case '5':
DispatchAction(ActionId::ActivateDetails);
break;
case '6':
DispatchAction(ActionId::LoadInvalid);
break;
case 'R':
DispatchAction(ActionId::Reset);
break;
default:
return;
}
InvalidateRect(m_hwnd, nullptr, FALSE);
}
void DispatchAction(ActionId action) {
switch (action) {
case ActionId::HideActive: {
UIEditorWorkspaceCommand command = {};
command.kind = UIEditorWorkspaceCommandKind::HidePanel;
command.panelId = m_controller.GetWorkspace().activePanelId;
SetCommandResult("Hide Active", m_controller.Dispatch(command));
return;
}
case ActionId::SaveLayout:
SaveLayout();
return;
case ActionId::CloseDocB:
SetCommandResult(
"Close Doc B",
m_controller.Dispatch({ UIEditorWorkspaceCommandKind::ClosePanel, "doc-b" }));
return;
case ActionId::LoadLayout:
LoadLayout();
return;
case ActionId::ActivateDetails:
SetCommandResult(
"Activate Details",
m_controller.Dispatch({ UIEditorWorkspaceCommandKind::ActivatePanel, "details" }));
return;
case ActionId::LoadInvalid:
LoadInvalidLayout();
return;
case ActionId::Reset:
SetCommandResult(
"Reset",
m_controller.Dispatch({ UIEditorWorkspaceCommandKind::ResetWorkspace, {} }));
return;
}
}
void SaveLayout() {
const auto validation = m_controller.ValidateState();
if (!validation.IsValid()) {
SetCustomResult(
"Save Layout",
"Rejected",
"当前 controller 状态非法,不能保存布局:" + validation.message);
return;
}
const UIEditorWorkspaceLayoutSnapshot snapshot = m_controller.CaptureLayoutSnapshot();
const std::string serialized = SerializeUIEditorWorkspaceLayoutSnapshot(snapshot);
const bool changed = !m_hasSavedLayout || serialized != m_savedSerializedLayout;
m_savedSnapshot = snapshot;
m_savedSerializedLayout = serialized;
m_hasSavedLayout = true;
SetCustomResult(
"Save Layout",
changed ? "Saved" : "NoOp",
changed
? "已更新保存的布局快照。接下来继续改状态,再点 `Load Layout` 检查恢复。"
: "保存内容与当前已保存布局一致。");
}
void LoadLayout() {
if (!m_hasSavedLayout) {
SetCustomResult("Load Layout", "Rejected", "当前还没有保存过布局。");
return;
}
SetLayoutResult("Load Layout", m_controller.RestoreSerializedLayout(m_savedSerializedLayout));
}
void LoadInvalidLayout() {
const auto validation = m_controller.ValidateState();
if (!validation.IsValid()) {
SetCustomResult(
"Load Invalid",
"Rejected",
"当前 controller 状态非法,无法构造 invalid payload" + validation.message);
return;
}
const std::string source =
m_hasSavedLayout
? m_savedSerializedLayout
: SerializeUIEditorWorkspaceLayoutSnapshot(m_controller.CaptureLayoutSnapshot());
const std::string invalidSerialized = ReplaceActiveRecord(source, "missing-panel");
if (invalidSerialized.empty()) {
SetCustomResult("Load Invalid", "Rejected", "构造 invalid payload 失败。");
return;
}
SetLayoutResult("Load Invalid", m_controller.RestoreSerializedLayout(invalidSerialized));
}
void SetCommandResult(
std::string actionName,
const UIEditorWorkspaceCommandResult& result) {
m_lastActionName = std::move(actionName);
m_lastStatusLabel = std::string(GetUIEditorWorkspaceCommandStatusName(result.status));
m_lastMessage = result.message;
m_lastStatusColor = ResolveCommandStatusColor(result.status);
}
void SetLayoutResult(
std::string actionName,
const UIEditorWorkspaceLayoutOperationResult& result) {
m_lastActionName = std::move(actionName);
m_lastStatusLabel = std::string(GetUIEditorWorkspaceLayoutOperationStatusName(result.status));
m_lastMessage = result.message;
m_lastStatusColor = ResolveLayoutStatusColor(result.status);
}
void SetCustomResult(
std::string actionName,
std::string statusLabel,
std::string message) {
m_lastActionName = std::move(actionName);
m_lastStatusLabel = std::move(statusLabel);
m_lastMessage = std::move(message);
if (m_lastStatusLabel == "Rejected") {
m_lastStatusColor = kDanger;
} else if (m_lastStatusLabel == "NoOp") {
m_lastStatusColor = kWarning;
} else if (m_lastStatusLabel == "Pending") {
m_lastStatusColor = kTextMuted;
} else {
m_lastStatusColor = kSuccess;
}
}
bool IsButtonEnabled(ActionId action) const {
const UIEditorWorkspaceModel& workspace = m_controller.GetWorkspace();
const UIEditorWorkspaceSession& session = m_controller.GetSession();
switch (action) {
case ActionId::HideActive: {
if (workspace.activePanelId.empty()) {
return false;
}
const auto* state = FindUIEditorPanelSessionState(session, workspace.activePanelId);
return state != nullptr && state->open && state->visible;
}
case ActionId::SaveLayout:
return m_controller.ValidateState().IsValid();
case ActionId::CloseDocB: {
const auto* state = FindUIEditorPanelSessionState(session, "doc-b");
return state != nullptr && state->open;
}
case ActionId::LoadLayout:
return m_hasSavedLayout;
case ActionId::ActivateDetails: {
const auto* state = FindUIEditorPanelSessionState(session, "details");
return state != nullptr &&
state->open &&
state->visible &&
workspace.activePanelId != "details";
}
case ActionId::LoadInvalid:
return m_controller.ValidateState().IsValid();
case ActionId::Reset:
return true;
}
return false;
}
void DrawPanelStateRows(
UIDrawList& drawList,
float startX,
float startY,
float width,
const UIEditorWorkspaceSession& session,
std::string_view activePanelId) {
const std::vector<std::pair<std::string, std::string>> panelDefs = {
{ "doc-a", "Document A" },
{ "doc-b", "Document B" },
{ "details", "Details" }
};
float rowY = startY;
for (const auto& [panelId, label] : panelDefs) {
const UIRect rowRect(startX, rowY, width, 54.0f);
drawList.AddFilledRect(rowRect, kPanelRowBg, 8.0f);
drawList.AddRectOutline(rowRect, kCardBorder, 1.0f, 8.0f);
drawList.AddFilledRect(
UIRect(rowRect.x + 12.0f, rowRect.y + 15.0f, 10.0f, 10.0f),
ResolvePanelStateColor(session, panelId),
5.0f);
drawList.AddText(
UIPoint(rowRect.x + 32.0f, rowRect.y + 11.0f),
DescribePanelState(session, panelId, label),
kTextPrimary,
14.0f);
const bool active = activePanelId == panelId;
drawList.AddText(
UIPoint(rowRect.x + 32.0f, rowRect.y + 31.0f),
active ? "active = true" : "active = false",
active ? kAccent : kTextMuted,
12.0f);
rowY += 64.0f;
}
}
void BuildDrawData(UIDrawData& drawData, float width, float height) {
const UIEditorWorkspaceModel& workspace = m_controller.GetWorkspace();
const UIEditorWorkspaceSession& session = m_controller.GetSession();
const auto validation = m_controller.ValidateState();
UIDrawList& drawList = drawData.EmplaceDrawList("Editor Layout Persistence");
drawList.AddFilledRect(UIRect(0.0f, 0.0f, width, height), kWindowBg);
const float margin = 20.0f;
const UIRect headerRect(margin, margin, width - margin * 2.0f, 178.0f);
const UIRect actionRect(margin, headerRect.y + headerRect.height + 16.0f, 320.0f, height - 254.0f);
const UIRect stateRect(actionRect.x + actionRect.width + 16.0f, actionRect.y, width - actionRect.width - margin * 2.0f - 16.0f, height - 254.0f);
const UIRect footerRect(margin, height - 100.0f, width - margin * 2.0f, 80.0f);
DrawCard(drawList, headerRect, "测试功能Editor Layout Persistence", "只验证 Save / Load / Load Invalid / Reset 的布局恢复链路;不验证业务面板。");
drawList.AddText(UIPoint(headerRect.x + 18.0f, headerRect.y + 70.0f), "1. 点 `1 Hide Active`,把 Document A 隐藏active 应切到 doc-bvisible 应变成 `doc-b, details`。", kTextPrimary, 13.0f);
drawList.AddText(UIPoint(headerRect.x + 18.0f, headerRect.y + 92.0f), "2. 点 `2 Save Layout` 保存当前布局;右侧 Saved 摘要必须记录刚才的 active/visible。", kTextPrimary, 13.0f);
drawList.AddText(UIPoint(headerRect.x + 18.0f, headerRect.y + 114.0f), "3. 再点 `3 Close Doc B` 或 `5 Activate Details` 改状态,然后点 `4 Load Layout`;当前状态必须恢复到保存时。", kTextPrimary, 13.0f);
drawList.AddText(UIPoint(headerRect.x + 18.0f, headerRect.y + 136.0f), "4. 点 `6 Load Invalid`Result 必须是 Rejected且当前 active/visible 不得被污染。", kTextPrimary, 13.0f);
drawList.AddText(UIPoint(headerRect.x + 18.0f, headerRect.y + 158.0f), "5. `R Reset` 必须回到基线 active=doc-a按 `F12` 保存当前窗口截图。", kTextPrimary, 13.0f);
DrawCard(drawList, actionRect, "操作区", "只保留这一步需要检查的布局保存/恢复动作。");
DrawCard(drawList, stateRect, "状态摘要", "左侧看 Current右侧看 Saved重点检查 active、visible 和坏数据恢复。");
DrawCard(drawList, footerRect, "最近结果", "显示最近一次操作、状态和当前 validation。");
m_buttons.clear();
const std::vector<std::pair<ActionId, std::string>> buttonDefs = {
{ ActionId::HideActive, "1 Hide Active" },
{ ActionId::SaveLayout, "2 Save Layout" },
{ ActionId::CloseDocB, "3 Close Doc B" },
{ ActionId::LoadLayout, "4 Load Layout" },
{ ActionId::ActivateDetails, "5 Activate Details" },
{ ActionId::LoadInvalid, "6 Load Invalid" },
{ ActionId::Reset, "R Reset" }
};
float buttonY = actionRect.y + 72.0f;
for (const auto& [action, label] : buttonDefs) {
ButtonState button = {};
button.action = action;
button.label = label;
button.rect = UIRect(actionRect.x + 18.0f, buttonY, actionRect.width - 36.0f, 46.0f);
button.enabled = IsButtonEnabled(action);
m_buttons.push_back(button);
drawList.AddFilledRect(
button.rect,
button.enabled ? kButtonEnabled : kButtonDisabled,
8.0f);
drawList.AddRectOutline(button.rect, kButtonBorder, 1.0f, 8.0f);
drawList.AddText(
UIPoint(button.rect.x + 14.0f, button.rect.y + 13.0f),
button.label,
button.enabled ? kTextPrimary : kTextMuted,
13.0f);
buttonY += 58.0f;
}
const float columnGap = 20.0f;
const float contentLeft = stateRect.x + 18.0f;
const float columnWidth = (stateRect.width - 36.0f - columnGap) * 0.5f;
const float rightColumnX = contentLeft + columnWidth + columnGap;
drawList.AddText(UIPoint(contentLeft, stateRect.y + 70.0f), "Current", kAccent, 15.0f);
drawList.AddText(UIPoint(contentLeft, stateRect.y + 96.0f), "active panel", kTextMuted, 12.0f);
drawList.AddText(UIPoint(contentLeft, stateRect.y + 116.0f), workspace.activePanelId.empty() ? "(none)" : workspace.activePanelId, kTextPrimary, 14.0f);
drawList.AddText(UIPoint(contentLeft, stateRect.y + 148.0f), "visible panels", kTextMuted, 12.0f);
drawList.AddText(UIPoint(contentLeft, stateRect.y + 168.0f), JoinVisiblePanelIds(workspace, session), kTextPrimary, 14.0f);
drawList.AddText(
UIPoint(contentLeft, stateRect.y + 198.0f),
validation.IsValid() ? "validation = OK" : "validation = " + validation.message,
validation.IsValid() ? kSuccess : kDanger,
12.0f);
DrawPanelStateRows(drawList, contentLeft, stateRect.y + 236.0f, columnWidth, session, workspace.activePanelId);
drawList.AddText(UIPoint(rightColumnX, stateRect.y + 70.0f), "Saved", kAccent, 15.0f);
if (!m_hasSavedLayout) {
drawList.AddText(UIPoint(rightColumnX, stateRect.y + 104.0f), "尚未执行 Save Layout。", kTextMuted, 13.0f);
drawList.AddText(UIPoint(rightColumnX, stateRect.y + 128.0f), "先把状态改掉,再保存,这样 Load 才有恢复意义。", kTextMuted, 12.0f);
} else {
drawList.AddText(UIPoint(rightColumnX, stateRect.y + 96.0f), "active panel", kTextMuted, 12.0f);
drawList.AddText(UIPoint(rightColumnX, stateRect.y + 116.0f), m_savedSnapshot.workspace.activePanelId.empty() ? "(none)" : m_savedSnapshot.workspace.activePanelId, kTextPrimary, 14.0f);
drawList.AddText(UIPoint(rightColumnX, stateRect.y + 148.0f), "visible panels", kTextMuted, 12.0f);
drawList.AddText(
UIPoint(rightColumnX, stateRect.y + 168.0f),
JoinVisiblePanelIds(m_savedSnapshot.workspace, m_savedSnapshot.session),
kTextPrimary,
14.0f);
drawList.AddText(UIPoint(rightColumnX, stateRect.y + 198.0f), "payload preview", kTextMuted, 12.0f);
drawList.AddText(
UIPoint(rightColumnX, stateRect.y + 220.0f),
BuildSerializedPreview(m_savedSerializedLayout),
kTextPrimary,
12.0f);
}
drawList.AddText(
UIPoint(footerRect.x + 18.0f, footerRect.y + 28.0f),
"Last operation: " + m_lastActionName + " | Result: " + m_lastStatusLabel,
m_lastStatusColor,
13.0f);
drawList.AddText(UIPoint(footerRect.x + 18.0f, footerRect.y + 48.0f), m_lastMessage, kTextPrimary, 12.0f);
drawList.AddText(
UIPoint(footerRect.x + 18.0f, footerRect.y + 66.0f),
validation.IsValid() ? "Validation: OK" : "Validation: " + validation.message,
validation.IsValid() ? kSuccess : kDanger,
12.0f);
const std::string captureSummary =
m_autoScreenshot.HasPendingCapture()
? "截图排队中..."
: (m_autoScreenshot.GetLastCaptureSummary().empty()
? std::string("F12 -> tests/UI/Editor/integration/state/layout_persistence/captures/")
: m_autoScreenshot.GetLastCaptureSummary());
drawList.AddText(UIPoint(footerRect.x + 760.0f, footerRect.y + 66.0f), captureSummary, kTextMuted, 12.0f);
}
HWND m_hwnd = nullptr;
HINSTANCE m_hInstance = nullptr;
ATOM m_windowClassAtom = 0;
NativeRenderer m_renderer = {};
AutoScreenshotController m_autoScreenshot = {};
UIEditorWorkspaceController m_controller = {};
UIEditorWorkspaceLayoutSnapshot m_savedSnapshot = {};
std::string m_savedSerializedLayout = {};
bool m_hasSavedLayout = false;
std::vector<ButtonState> m_buttons = {};
std::string m_lastActionName = {};
std::string m_lastStatusLabel = {};
std::string m_lastMessage = {};
UIColor m_lastStatusColor = kTextMuted;
};
} // namespace
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR, int nCmdShow) {
ScenarioApp app;
return app.Run(hInstance, nCmdShow);
}

View File

@@ -6,6 +6,7 @@ set(EDITOR_UI_UNIT_TEST_SOURCES
test_ui_editor_collection_primitives.cpp
test_ui_editor_panel_chrome.cpp
test_ui_editor_workspace_controller.cpp
test_ui_editor_workspace_layout_persistence.cpp
test_ui_editor_workspace_model.cpp
test_ui_editor_workspace_session.cpp
)

View File

@@ -0,0 +1,185 @@
#include <gtest/gtest.h>
#include <XCNewEditor/Editor/UIEditorWorkspaceController.h>
#include <XCNewEditor/Editor/UIEditorWorkspaceLayoutPersistence.h>
#include <string>
#include <string_view>
#include <utility>
namespace {
using XCEngine::NewEditor::AreUIEditorWorkspaceLayoutSnapshotsEquivalent;
using XCEngine::NewEditor::BuildDefaultUIEditorWorkspaceController;
using XCEngine::NewEditor::BuildDefaultUIEditorWorkspaceSession;
using XCEngine::NewEditor::BuildUIEditorWorkspaceLayoutSnapshot;
using XCEngine::NewEditor::BuildUIEditorWorkspacePanel;
using XCEngine::NewEditor::BuildUIEditorWorkspaceSplit;
using XCEngine::NewEditor::BuildUIEditorWorkspaceTabStack;
using XCEngine::NewEditor::DeserializeUIEditorWorkspaceLayoutSnapshot;
using XCEngine::NewEditor::SerializeUIEditorWorkspaceLayoutSnapshot;
using XCEngine::NewEditor::TryCloseUIEditorWorkspacePanel;
using XCEngine::NewEditor::TryHideUIEditorWorkspacePanel;
using XCEngine::NewEditor::UIEditorPanelRegistry;
using XCEngine::NewEditor::UIEditorWorkspaceController;
using XCEngine::NewEditor::UIEditorWorkspaceLayoutLoadCode;
using XCEngine::NewEditor::UIEditorWorkspaceLayoutOperationStatus;
using XCEngine::NewEditor::UIEditorWorkspaceCommandKind;
using XCEngine::NewEditor::UIEditorWorkspaceCommandStatus;
using XCEngine::NewEditor::UIEditorWorkspaceModel;
using XCEngine::NewEditor::UIEditorWorkspaceSession;
using XCEngine::NewEditor::UIEditorWorkspaceSplitAxis;
UIEditorPanelRegistry BuildPanelRegistry() {
UIEditorPanelRegistry registry = {};
registry.panels = {
{ "doc-a", "Document A", {}, true, true, true },
{ "doc-b", "Document B", {}, true, true, true },
{ "details", "Details", {}, true, true, true }
};
return registry;
}
UIEditorWorkspaceModel BuildWorkspace() {
UIEditorWorkspaceModel workspace = {};
workspace.root = BuildUIEditorWorkspaceSplit(
"root-split",
UIEditorWorkspaceSplitAxis::Horizontal,
0.66f,
BuildUIEditorWorkspaceTabStack(
"document-tabs",
{
BuildUIEditorWorkspacePanel("doc-a-node", "doc-a", "Document A", true),
BuildUIEditorWorkspacePanel("doc-b-node", "doc-b", "Document B", true)
},
0u),
BuildUIEditorWorkspacePanel("details-node", "details", "Details", true));
workspace.activePanelId = "doc-a";
return workspace;
}
std::string ReplaceFirst(
std::string source,
std::string_view from,
std::string_view to) {
const std::size_t index = source.find(from);
EXPECT_NE(index, std::string::npos);
if (index == std::string::npos) {
return source;
}
source.replace(index, from.size(), to);
return source;
}
} // namespace
TEST(UIEditorWorkspaceLayoutPersistenceTest, SerializeAndDeserializeRoundTripPreservesWorkspaceAndSession) {
const UIEditorPanelRegistry registry = BuildPanelRegistry();
UIEditorWorkspaceModel workspace = BuildWorkspace();
UIEditorWorkspaceSession session =
BuildDefaultUIEditorWorkspaceSession(registry, workspace);
ASSERT_TRUE(TryHideUIEditorWorkspacePanel(registry, workspace, session, "doc-a"));
ASSERT_TRUE(TryCloseUIEditorWorkspacePanel(registry, workspace, session, "doc-b"));
const auto snapshot = BuildUIEditorWorkspaceLayoutSnapshot(workspace, session);
const std::string serialized = SerializeUIEditorWorkspaceLayoutSnapshot(snapshot);
const auto loadResult =
DeserializeUIEditorWorkspaceLayoutSnapshot(registry, serialized);
ASSERT_TRUE(loadResult.IsValid()) << loadResult.message;
EXPECT_TRUE(
AreUIEditorWorkspaceLayoutSnapshotsEquivalent(loadResult.snapshot, snapshot));
}
TEST(UIEditorWorkspaceLayoutPersistenceTest, DeserializeRejectsInvalidSelectedTabIndex) {
const UIEditorPanelRegistry registry = BuildPanelRegistry();
const UIEditorWorkspaceModel workspace = BuildWorkspace();
const UIEditorWorkspaceSession session =
BuildDefaultUIEditorWorkspaceSession(registry, workspace);
const std::string invalidSerialized = ReplaceFirst(
SerializeUIEditorWorkspaceLayoutSnapshot(
BuildUIEditorWorkspaceLayoutSnapshot(workspace, session)),
"node_tabstack \"document-tabs\" 0 2",
"node_tabstack \"document-tabs\" 5 2");
const auto loadResult =
DeserializeUIEditorWorkspaceLayoutSnapshot(registry, invalidSerialized);
EXPECT_EQ(loadResult.code, UIEditorWorkspaceLayoutLoadCode::InvalidWorkspace);
}
TEST(UIEditorWorkspaceLayoutPersistenceTest, DeserializeRejectsMissingSessionRecord) {
const UIEditorPanelRegistry registry = BuildPanelRegistry();
const UIEditorWorkspaceModel workspace = BuildWorkspace();
const UIEditorWorkspaceSession session =
BuildDefaultUIEditorWorkspaceSession(registry, workspace);
const std::string invalidSerialized = ReplaceFirst(
SerializeUIEditorWorkspaceLayoutSnapshot(
BuildUIEditorWorkspaceLayoutSnapshot(workspace, session)),
"session \"details\" 1 1\n",
"");
const auto loadResult =
DeserializeUIEditorWorkspaceLayoutSnapshot(registry, invalidSerialized);
EXPECT_EQ(loadResult.code, UIEditorWorkspaceLayoutLoadCode::InvalidWorkspaceSession);
}
TEST(UIEditorWorkspaceLayoutPersistenceTest, RestoreSerializedLayoutRestoresSavedStateAfterFurtherMutations) {
const UIEditorPanelRegistry registry = BuildPanelRegistry();
UIEditorWorkspaceController controller =
BuildDefaultUIEditorWorkspaceController(registry, BuildWorkspace());
EXPECT_EQ(
controller.Dispatch({ UIEditorWorkspaceCommandKind::HidePanel, "doc-a" }).status,
UIEditorWorkspaceCommandStatus::Changed);
const std::string savedLayout =
SerializeUIEditorWorkspaceLayoutSnapshot(controller.CaptureLayoutSnapshot());
EXPECT_EQ(
controller.Dispatch({ UIEditorWorkspaceCommandKind::ClosePanel, "doc-b" }).status,
UIEditorWorkspaceCommandStatus::Changed);
EXPECT_EQ(controller.GetWorkspace().activePanelId, "details");
const auto restoreResult = controller.RestoreSerializedLayout(savedLayout);
EXPECT_EQ(restoreResult.status, UIEditorWorkspaceLayoutOperationStatus::Changed);
EXPECT_EQ(controller.GetWorkspace().activePanelId, "doc-b");
ASSERT_EQ(restoreResult.visiblePanelIds.size(), 2u);
EXPECT_EQ(restoreResult.visiblePanelIds[0], "doc-b");
EXPECT_EQ(restoreResult.visiblePanelIds[1], "details");
}
TEST(UIEditorWorkspaceLayoutPersistenceTest, RestoreSerializedLayoutRejectsInvalidPayloadWithoutMutatingCurrentState) {
const UIEditorPanelRegistry registry = BuildPanelRegistry();
UIEditorWorkspaceController controller =
BuildDefaultUIEditorWorkspaceController(registry, BuildWorkspace());
EXPECT_EQ(
controller.Dispatch({ UIEditorWorkspaceCommandKind::ActivatePanel, "details" }).status,
UIEditorWorkspaceCommandStatus::Changed);
const auto before = controller.CaptureLayoutSnapshot();
const std::string invalidSerialized = ReplaceFirst(
SerializeUIEditorWorkspaceLayoutSnapshot(before),
"active \"details\"",
"active \"missing\"");
const auto restoreResult = controller.RestoreSerializedLayout(invalidSerialized);
EXPECT_EQ(restoreResult.status, UIEditorWorkspaceLayoutOperationStatus::Rejected);
const auto after = controller.CaptureLayoutSnapshot();
EXPECT_TRUE(AreUIEditorWorkspaceLayoutSnapshotsEquivalent(after, before));
}
TEST(UIEditorWorkspaceLayoutPersistenceTest, RestoreLayoutSnapshotReturnsNoOpWhenStateAlreadyMatchesSnapshot) {
UIEditorWorkspaceController controller =
BuildDefaultUIEditorWorkspaceController(BuildPanelRegistry(), BuildWorkspace());
const auto result = controller.RestoreLayoutSnapshot(controller.CaptureLayoutSnapshot());
EXPECT_EQ(result.status, UIEditorWorkspaceLayoutOperationStatus::NoOp);
}