diff --git a/Content/Maps/L_DemoUI.umap b/Content/Maps/L_DemoUI.umap new file mode 100644 index 0000000..89bbee3 Binary files /dev/null and b/Content/Maps/L_DemoUI.umap differ diff --git a/Content/UI/Demo/WBP_DemoHub.uasset b/Content/UI/Demo/WBP_DemoHub.uasset new file mode 100644 index 0000000..5ef81cd Binary files /dev/null and b/Content/UI/Demo/WBP_DemoHub.uasset differ diff --git a/Content/UI/Demo/WBP_DemoHubItem.uasset b/Content/UI/Demo/WBP_DemoHubItem.uasset new file mode 100644 index 0000000..9ceefa8 Binary files /dev/null and b/Content/UI/Demo/WBP_DemoHubItem.uasset differ diff --git a/Content/UI/Demo/WBP_UIDemoCached.uasset b/Content/UI/Demo/WBP_UIDemoCached.uasset new file mode 100644 index 0000000..46dbb63 Binary files /dev/null and b/Content/UI/Demo/WBP_UIDemoCached.uasset differ diff --git a/Content/UI/Demo/WBP_UIDemoFullscreen.uasset b/Content/UI/Demo/WBP_UIDemoFullscreen.uasset new file mode 100644 index 0000000..7bd3843 Binary files /dev/null and b/Content/UI/Demo/WBP_UIDemoFullscreen.uasset differ diff --git a/Content/UI/Demo/WBP_UIDemoListItem.uasset b/Content/UI/Demo/WBP_UIDemoListItem.uasset new file mode 100644 index 0000000..8b612f1 Binary files /dev/null and b/Content/UI/Demo/WBP_UIDemoListItem.uasset differ diff --git a/Content/UI/Demo/WBP_UIDemoMain.uasset b/Content/UI/Demo/WBP_UIDemoMain.uasset new file mode 100644 index 0000000..efec98d Binary files /dev/null and b/Content/UI/Demo/WBP_UIDemoMain.uasset differ diff --git a/Content/UI/Demo/WBP_UIDemoModal.uasset b/Content/UI/Demo/WBP_UIDemoModal.uasset new file mode 100644 index 0000000..8ee1ce8 Binary files /dev/null and b/Content/UI/Demo/WBP_UIDemoModal.uasset differ diff --git a/Content/UI/Demo/WBP_UIDemoMulti.uasset b/Content/UI/Demo/WBP_UIDemoMulti.uasset new file mode 100644 index 0000000..66017d0 Binary files /dev/null and b/Content/UI/Demo/WBP_UIDemoMulti.uasset differ diff --git a/Content/UI/Demo/WBP_UIDemoNormal.uasset b/Content/UI/Demo/WBP_UIDemoNormal.uasset new file mode 100644 index 0000000..4f3d59b Binary files /dev/null and b/Content/UI/Demo/WBP_UIDemoNormal.uasset differ diff --git a/Content/UI/Demo/WBP_UIDemoSystem.uasset b/Content/UI/Demo/WBP_UIDemoSystem.uasset new file mode 100644 index 0000000..62c457e Binary files /dev/null and b/Content/UI/Demo/WBP_UIDemoSystem.uasset differ diff --git a/Content/UI/Demo/WBP_UIDemoToast.uasset b/Content/UI/Demo/WBP_UIDemoToast.uasset new file mode 100644 index 0000000..b9d192b Binary files /dev/null and b/Content/UI/Demo/WBP_UIDemoToast.uasset differ diff --git a/Content/UI/Fonts/FF_DemoCJK.uasset b/Content/UI/Fonts/FF_DemoCJK.uasset new file mode 100644 index 0000000..909922d Binary files /dev/null and b/Content/UI/Fonts/FF_DemoCJK.uasset differ diff --git a/Content/UI/Fonts/F_DemoUI.uasset b/Content/UI/Fonts/F_DemoUI.uasset new file mode 100644 index 0000000..4181758 Binary files /dev/null and b/Content/UI/Fonts/F_DemoUI.uasset differ diff --git a/Content/UI/Textures/T_DemoAvatar.uasset b/Content/UI/Textures/T_DemoAvatar.uasset new file mode 100644 index 0000000..0ca3998 Binary files /dev/null and b/Content/UI/Textures/T_DemoAvatar.uasset differ diff --git a/Content/UI/Textures/T_DemoBadgeA.uasset b/Content/UI/Textures/T_DemoBadgeA.uasset new file mode 100644 index 0000000..ea77c58 Binary files /dev/null and b/Content/UI/Textures/T_DemoBadgeA.uasset differ diff --git a/Content/UI/Textures/T_DemoBadgeB.uasset b/Content/UI/Textures/T_DemoBadgeB.uasset new file mode 100644 index 0000000..f58e770 Binary files /dev/null and b/Content/UI/Textures/T_DemoBadgeB.uasset differ diff --git a/Script/lua/framework/resource/asset_catalog.lua b/Script/lua/framework/resource/asset_catalog.lua index 88a2e5e..7f34063 100644 --- a/Script/lua/framework/resource/asset_catalog.lua +++ b/Script/lua/framework/resource/asset_catalog.lua @@ -1,8 +1,42 @@ local ____exports = __module.env --- -- @noSelfInFile -____exports.ASSET_KEYS = {MINI_SETTINGS_ICON = "tex.mini_settings_icon", MINI_SETTINGS_WIDGET = "ui.mini_settings"} -____exports.BASE_ASSET_PATHS = {[____exports.ASSET_KEYS.MINI_SETTINGS_ICON] = "/Game/UI/Textures/T_MiniSettingsIcon.T_MiniSettingsIcon", [____exports.ASSET_KEYS.MINI_SETTINGS_WIDGET] = "/Game/UI/WBP_MiniSettings.WBP_MiniSettings_C"} +____exports.ASSET_KEYS = { + MINI_SETTINGS_ICON = "tex.mini_settings_icon", + MINI_SETTINGS_WIDGET = "ui.mini_settings", + DEMO_AVATAR_TEX = "tex.demo_avatar", + DEMO_BADGE_A_TEX = "tex.demo_badge_a", + DEMO_BADGE_B_TEX = "tex.demo_badge_b", + DEMO_HUB_WIDGET = "ui.demo_hub", + DEMO_HUB_ITEM_WIDGET = "ui.demo_hub_item", + UI_DEMO_MAIN_WIDGET = "ui.demo_ui_main", + UI_DEMO_LIST_ITEM_WIDGET = "ui.demo_ui_list_item", + UI_DEMO_NORMAL_WIDGET = "ui.demo_ui_normal", + UI_DEMO_FULLSCREEN_WIDGET = "ui.demo_ui_fullscreen", + UI_DEMO_MODAL_WIDGET = "ui.demo_ui_modal", + UI_DEMO_CACHED_WIDGET = "ui.demo_ui_cached", + UI_DEMO_MULTI_WIDGET = "ui.demo_ui_multi", + UI_DEMO_TOAST_WIDGET = "ui.demo_ui_toast", + UI_DEMO_SYSTEM_WIDGET = "ui.demo_ui_system" +} +____exports.BASE_ASSET_PATHS = { + [____exports.ASSET_KEYS.MINI_SETTINGS_ICON] = "/Game/UI/Textures/T_MiniSettingsIcon.T_MiniSettingsIcon", + [____exports.ASSET_KEYS.MINI_SETTINGS_WIDGET] = "/Game/UI/WBP_MiniSettings.WBP_MiniSettings_C", + [____exports.ASSET_KEYS.DEMO_AVATAR_TEX] = "/Game/UI/Textures/T_DemoAvatar.T_DemoAvatar", + [____exports.ASSET_KEYS.DEMO_BADGE_A_TEX] = "/Game/UI/Textures/T_DemoBadgeA.T_DemoBadgeA", + [____exports.ASSET_KEYS.DEMO_BADGE_B_TEX] = "/Game/UI/Textures/T_DemoBadgeB.T_DemoBadgeB", + [____exports.ASSET_KEYS.DEMO_HUB_WIDGET] = "/Game/UI/Demo/WBP_DemoHub.WBP_DemoHub_C", + [____exports.ASSET_KEYS.DEMO_HUB_ITEM_WIDGET] = "/Game/UI/Demo/WBP_DemoHubItem.WBP_DemoHubItem_C", + [____exports.ASSET_KEYS.UI_DEMO_MAIN_WIDGET] = "/Game/UI/Demo/WBP_UIDemoMain.WBP_UIDemoMain_C", + [____exports.ASSET_KEYS.UI_DEMO_LIST_ITEM_WIDGET] = "/Game/UI/Demo/WBP_UIDemoListItem.WBP_UIDemoListItem_C", + [____exports.ASSET_KEYS.UI_DEMO_NORMAL_WIDGET] = "/Game/UI/Demo/WBP_UIDemoNormal.WBP_UIDemoNormal_C", + [____exports.ASSET_KEYS.UI_DEMO_FULLSCREEN_WIDGET] = "/Game/UI/Demo/WBP_UIDemoFullscreen.WBP_UIDemoFullscreen_C", + [____exports.ASSET_KEYS.UI_DEMO_MODAL_WIDGET] = "/Game/UI/Demo/WBP_UIDemoModal.WBP_UIDemoModal_C", + [____exports.ASSET_KEYS.UI_DEMO_CACHED_WIDGET] = "/Game/UI/Demo/WBP_UIDemoCached.WBP_UIDemoCached_C", + [____exports.ASSET_KEYS.UI_DEMO_MULTI_WIDGET] = "/Game/UI/Demo/WBP_UIDemoMulti.WBP_UIDemoMulti_C", + [____exports.ASSET_KEYS.UI_DEMO_TOAST_WIDGET] = "/Game/UI/Demo/WBP_UIDemoToast.WBP_UIDemoToast_C", + [____exports.ASSET_KEYS.UI_DEMO_SYSTEM_WIDGET] = "/Game/UI/Demo/WBP_UIDemoSystem.WBP_UIDemoSystem_C" +} function ____exports.RegisterBaseAssetCatalog(subsystem) for logicalKey, softPath in pairs(____exports.BASE_ASSET_PATHS) do subsystem:RegisterBaseAssetKey(logicalKey, softPath) diff --git a/Script/lua/framework/ui/ui_delegate_bridge.lua b/Script/lua/framework/ui/ui_delegate_bridge.lua index abae0ff..001c0f7 100644 --- a/Script/lua/framework/ui/ui_delegate_bridge.lua +++ b/Script/lua/framework/ui/ui_delegate_bridge.lua @@ -21,19 +21,46 @@ end function UEButtonDelegateBackend.prototype.BindButtonClicked(self, button) return self.subsystem:BindButtonClicked(button) end +function UEButtonDelegateBackend.prototype.BindButtonHovered(self, button) + return self.subsystem:BindButtonHovered(button) +end +function UEButtonDelegateBackend.prototype.BindButtonUnhovered(self, button) + return self.subsystem:BindButtonUnhovered(button) +end +function UEButtonDelegateBackend.prototype.BindCheckBoxChanged(self, checkBox) + return self.subsystem:BindCheckBoxChanged(checkBox) +end +function UEButtonDelegateBackend.prototype.BindSliderChanged(self, slider) + return self.subsystem:BindSliderChanged(slider) +end +function UEButtonDelegateBackend.prototype.BindSpinBoxChanged(self, spinBox) + return self.subsystem:BindSpinBoxChanged(spinBox) +end +function UEButtonDelegateBackend.prototype.BindEditableTextChanged(self, textBox) + return self.subsystem:BindEditableTextChanged(textBox) +end +function UEButtonDelegateBackend.prototype.BindEditableTextCommitted(self, textBox) + return self.subsystem:BindEditableTextCommitted(textBox) +end +function UEButtonDelegateBackend.prototype.BindComboBoxSelectionChanged(self, comboBox) + return self.subsystem:BindComboBoxSelectionChanged(comboBox) +end function UEButtonDelegateBackend.prototype.UnbindButtonClicked(self, bindingId) - return self.subsystem:UnbindButtonClicked(bindingId) + return self.subsystem:UnbindWidgetEvent(bindingId) +end +function UEButtonDelegateBackend.prototype.UnbindWidgetEvent(self, bindingId) + return self.subsystem:UnbindWidgetEvent(bindingId) end function UEButtonDelegateBackend.prototype.GetActiveBindingCount(self) return self.subsystem:GetActiveBindingCount() end -local ButtonBindingHandle = __TS__DefineClass("ButtonBindingHandle", __module) -ButtonBindingHandle.name = "ButtonBindingHandle" -function ButtonBindingHandle.prototype.____constructor(self, bridge, bindingId) +local WidgetBindingHandle = __TS__DefineClass("WidgetBindingHandle", __module) +WidgetBindingHandle.name = "WidgetBindingHandle" +function WidgetBindingHandle.prototype.____constructor(self, bridge, bindingId) self.bridge = bridge self.bindingId = bindingId end -function ButtonBindingHandle.prototype.Dispose(self) +function WidgetBindingHandle.prototype.Dispose(self) if self.bridge ~= nil then local b = self.bridge self.bridge = nil @@ -56,36 +83,125 @@ function UIDelegateBridge.prototype.____constructor(self, ctx, backend) bridgeByGameInstanceKey[self.giKey] = self end end -function UIDelegateBridge.prototype.BindButtonClick(self, button, callback, owner) - local bindingId = self.backend:BindButtonClicked(button) - assert(bindingId > 0, "UIDelegateBridge.BindButtonClick: failed to bind button") +function UIDelegateBridge.prototype.RegisterBinding(self, bindingId, callback, owner) + assert(bindingId > 0, "UIDelegateBridge: failed to bind UMG widget event") self.bindings[bindingId] = {bindingId = bindingId, callback = callback, owner = owner} - local handle = __TS__New(ButtonBindingHandle, self, bindingId) + local handle = __TS__New(WidgetBindingHandle, self, bindingId) if owner ~= nil and __TS__InstanceOf(owner, ScopedObject) then owner:AddScopedObject(handle) end return handle end +function UIDelegateBridge.prototype.BindButtonClick(self, button, callback, owner) + local bindingId = self.backend:BindButtonClicked(button) + return self:RegisterBinding(bindingId, callback, owner) +end +function UIDelegateBridge.prototype.BindButtonHovered(self, button, callback, owner) + assert(self.backend.BindButtonHovered ~= nil, "UIDelegateBridge backend does not support BindButtonHovered") + local bindingId = self.backend:BindButtonHovered(button) + return self:RegisterBinding(bindingId, callback, owner) +end +function UIDelegateBridge.prototype.BindButtonUnhovered(self, button, callback, owner) + assert(self.backend.BindButtonUnhovered ~= nil, "UIDelegateBridge backend does not support BindButtonUnhovered") + local bindingId = self.backend:BindButtonUnhovered(button) + return self:RegisterBinding(bindingId, callback, owner) +end +function UIDelegateBridge.prototype.BindCheckBoxChanged(self, checkBox, callback, owner) + assert(self.backend.BindCheckBoxChanged ~= nil, "UIDelegateBridge backend does not support BindCheckBoxChanged") + local bindingId = self.backend:BindCheckBoxChanged(checkBox) + return self:RegisterBinding(bindingId, callback, owner) +end +function UIDelegateBridge.prototype.BindSliderChanged(self, slider, callback, owner) + assert(self.backend.BindSliderChanged ~= nil, "UIDelegateBridge backend does not support BindSliderChanged") + local bindingId = self.backend:BindSliderChanged(slider) + return self:RegisterBinding(bindingId, callback, owner) +end +function UIDelegateBridge.prototype.BindSpinBoxChanged(self, spinBox, callback, owner) + assert(self.backend.BindSpinBoxChanged ~= nil, "UIDelegateBridge backend does not support BindSpinBoxChanged") + local bindingId = self.backend:BindSpinBoxChanged(spinBox) + return self:RegisterBinding(bindingId, callback, owner) +end +function UIDelegateBridge.prototype.BindEditableTextChanged(self, textBox, callback, owner) + assert(self.backend.BindEditableTextChanged ~= nil, "UIDelegateBridge backend does not support BindEditableTextChanged") + local bindingId = self.backend:BindEditableTextChanged(textBox) + return self:RegisterBinding(bindingId, callback, owner) +end +function UIDelegateBridge.prototype.BindEditableTextCommitted(self, textBox, callback, owner) + assert(self.backend.BindEditableTextCommitted ~= nil, "UIDelegateBridge backend does not support BindEditableTextCommitted") + local bindingId = self.backend:BindEditableTextCommitted(textBox) + return self:RegisterBinding(bindingId, callback, owner) +end +function UIDelegateBridge.prototype.BindComboBoxSelectionChanged(self, comboBox, callback, owner) + assert(self.backend.BindComboBoxSelectionChanged ~= nil, "UIDelegateBridge backend does not support BindComboBoxSelectionChanged") + local bindingId = self.backend:BindComboBoxSelectionChanged(comboBox) + return self:RegisterBinding(bindingId, callback, owner) +end function UIDelegateBridge.prototype.UnbindById(self, bindingId) if self.bindings[bindingId] == nil then return end self.bindings[bindingId] = nil - self.backend:UnbindButtonClicked(bindingId) + if self.backend.UnbindWidgetEvent ~= nil then + self.backend:UnbindWidgetEvent(bindingId) + else + self.backend:UnbindButtonClicked(bindingId) + end end -function UIDelegateBridge.prototype.DispatchButtonClicked(self, bindingId) +function UIDelegateBridge.prototype.ResolveLiveRecord(self, bindingId) if self:IsDisposed() then - return + return nil end local rec = self.bindings[bindingId] if rec == nil then - return + return nil end if rec.owner ~= nil and rec.owner:IsDisposed() then self:UnbindById(bindingId) - return + return nil + end + return rec +end +function UIDelegateBridge.prototype.DispatchButtonClicked(self, bindingId) + local rec = self:ResolveLiveRecord(bindingId) + if rec ~= nil then + tbpcall(rec.callback) + end +end +function UIDelegateBridge.prototype.DispatchActionEvent(self, bindingId) + local rec = self:ResolveLiveRecord(bindingId) + if rec ~= nil then + tbpcall(rec.callback) + end +end +function UIDelegateBridge.prototype.DispatchBoolChanged(self, bindingId, value) + local rec = self:ResolveLiveRecord(bindingId) + if rec ~= nil then + tbpcall(rec.callback, value) + end +end +function UIDelegateBridge.prototype.DispatchFloatChanged(self, bindingId, value) + local rec = self:ResolveLiveRecord(bindingId) + if rec ~= nil then + tbpcall(rec.callback, value) + end +end +function UIDelegateBridge.prototype.DispatchTextChanged(self, bindingId, text) + local rec = self:ResolveLiveRecord(bindingId) + if rec ~= nil then + tbpcall(rec.callback, text) + end +end +function UIDelegateBridge.prototype.DispatchTextCommitted(self, bindingId, text, commitMethod) + local rec = self:ResolveLiveRecord(bindingId) + if rec ~= nil then + tbpcall(rec.callback, text, commitMethod) + end +end +function UIDelegateBridge.prototype.DispatchSelectionChanged(self, bindingId, selectedItem, selectType) + local rec = self:ResolveLiveRecord(bindingId) + if rec ~= nil then + tbpcall(rec.callback, selectedItem, selectType) end - tbpcall(rec.callback) end function UIDelegateBridge.prototype.GetActiveBindingCount(self) return self.backend:GetActiveBindingCount() @@ -110,8 +226,7 @@ function UIDelegateBridge.prototype.Dispose(self) end ScopedObject.prototype.Dispose(self) end ---- 供 C++ FLuaCallbackBridge::CallInt 回调的纯函数入口。 --- +--- -- @noSelf function ____exports.OnNativeButtonClicked(gameInstance, bindingId) local bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)] @@ -121,6 +236,54 @@ function ____exports.OnNativeButtonClicked(gameInstance, bindingId) end --- -- @noSelf +function ____exports.OnNativeActionEvent(gameInstance, bindingId) + local bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)] + if bridge ~= nil then + bridge:DispatchActionEvent(bindingId) + end +end +--- +-- @noSelf +function ____exports.OnNativeBoolChanged(gameInstance, bindingId, value) + local bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)] + if bridge ~= nil then + bridge:DispatchBoolChanged(bindingId, value) + end +end +--- +-- @noSelf +function ____exports.OnNativeFloatChanged(gameInstance, bindingId, value) + local bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)] + if bridge ~= nil then + bridge:DispatchFloatChanged(bindingId, value) + end +end +--- +-- @noSelf +function ____exports.OnNativeTextChanged(gameInstance, bindingId, text) + local bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)] + if bridge ~= nil then + bridge:DispatchTextChanged(bindingId, text) + end +end +--- +-- @noSelf +function ____exports.OnNativeTextCommitted(gameInstance, bindingId, text, commitMethod) + local bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)] + if bridge ~= nil then + bridge:DispatchTextCommitted(bindingId, text, commitMethod) + end +end +--- +-- @noSelf +function ____exports.OnNativeSelectionChanged(gameInstance, bindingId, selectedItem, selectType) + local bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)] + if bridge ~= nil then + bridge:DispatchSelectionChanged(bindingId, selectedItem, selectType) + end +end +--- +-- @noSelf function ____exports.CreateUEUIDelegateBridge(ctx) if ctx.gameInstance == nil then return nil diff --git a/Script/lua/framework/ui/ui_manager.lua b/Script/lua/framework/ui/ui_manager.lua index d965405..cd691a5 100644 --- a/Script/lua/framework/ui/ui_manager.lua +++ b/Script/lua/framework/ui/ui_manager.lua @@ -102,6 +102,7 @@ function UIManager.prototype.ShowUI(self, ctor, args, onOpened) if existing:IsLoaded() then local zOrder = self:AllocateZOrder(config) existing:ShowInternal(zOrder, args) + self:SyncFullscreenVisibility() self:SyncFocusAndInputMode() if onOpened ~= nil then tbpcall(onOpened, true, existing, nil) @@ -128,6 +129,7 @@ function UIManager.prototype.ShowUI(self, ctor, args, onOpened) self.windowStack[#self.windowStack + 1] = cached local zOrder = self:AllocateZOrder(config) cached:ReuseInternal(zOrder, args) + self:SyncFullscreenVisibility() self:SyncFocusAndInputMode() self.events.emit.OnWindowOpened(config.name, cached) if onOpened ~= nil then @@ -174,6 +176,7 @@ function UIManager.prototype.ShowUI(self, ctor, args, onOpened) win:AttachWidgetInternal(widget) local zOrder = self:AllocateZOrder(config) win:ShowInternal(zOrder, args) + self:SyncFullscreenVisibility() self:SyncFocusAndInputMode() self.events.emit.OnWindowOpened(config.name, win) if onOpened ~= nil then @@ -198,17 +201,53 @@ function UIManager.prototype.CloseSingletonUI(self, ctor) end end function UIManager.prototype.GetTopWindow(self) + local best = nil + local bestZOrder = -1 do - local i = #self.windowStack - 1 - while i >= 0 do - local win = self.windowStack[i + 1] - if not win:IsDisposed() and not win:IsClosing() then - return win + local i = 0 + while i < #self.windowStack do + do + local win = self.windowStack[i + 1] + if win:IsDisposed() or win:IsClosing() then + goto __continue46 + end + local z = win:IsLoaded() and win:GetZOrder() or UI_LAYER_ZORDER[win.config.layer] + if best == nil or z >= bestZOrder then + best = win + bestZOrder = z + end end - i = i - 1 + ::__continue46:: + i = i + 1 end end - return nil + return best +end +function UIManager.prototype.GetTopBlockingWindow(self) + local best = nil + local bestZOrder = -1 + do + local i = 0 + while i < #self.windowStack do + do + local win = self.windowStack[i + 1] + if win:IsDisposed() or win:IsClosing() or not win.config.blockWorldClick then + goto __continue51 + end + if win:IsLoaded() and not win:IsVisible() then + goto __continue51 + end + local z = win:IsLoaded() and win:GetZOrder() or UI_LAYER_ZORDER[win.config.layer] + if best == nil or z >= bestZOrder then + best = win + bestZOrder = z + end + end + ::__continue51:: + i = i + 1 + end + end + return best end function UIManager.prototype.HandleWindowCachedInternal(self, win) self:RemoveFromStackAndSingleton(win) @@ -217,11 +256,13 @@ function UIManager.prototype.HandleWindowCachedInternal(self, win) oldCached:ForceDisposeFromCacheInternal() end self.cachedByName[win.config.name] = win + self:SyncFullscreenVisibility() self:SyncFocusAndInputMode() self.events.emit.OnWindowClosed(win.config.name, win) end function UIManager.prototype.HandleWindowClosedInternal(self, win) self:RemoveFromStackAndSingleton(win) + self:SyncFullscreenVisibility() self:SyncFocusAndInputMode() self.events.emit.OnWindowClosed(win.config.name, win) end @@ -240,6 +281,35 @@ function UIManager.prototype.EvictCache(self) i = i + 1 end end + return #toEvict +end +function UIManager.prototype.CloseAllExcept(self, keepWindow, alsoEvictCache) + if alsoEvictCache == nil then + alsoEvictCache = false + end + local copy = {} + do + local i = #self.windowStack - 1 + while i >= 0 do + if self.windowStack[i + 1] ~= keepWindow then + copy[#copy + 1] = self.windowStack[i + 1] + end + i = i - 1 + end + end + do + local i = 0 + while i < #copy do + copy[i + 1]:Close() + i = i + 1 + end + end + if alsoEvictCache then + self:EvictCache() + end + self:SyncFullscreenVisibility() + self:SyncFocusAndInputMode() + return #copy end function UIManager.prototype.CloseAll(self, alsoEvictCache) if alsoEvictCache == nil then @@ -265,6 +335,41 @@ function UIManager.prototype.CloseAll(self, alsoEvictCache) end self:SyncFocusAndInputMode() end +function UIManager.prototype.GetWindowStackSnapshot(self) + local list = {} + do + local i = 0 + while i < #self.windowStack do + local w = self.windowStack[i + 1] + if not w:IsDisposed() then + list[#list + 1] = { + name = w.config.name, + layer = w.config.layer, + type = w.config.type, + zOrder = w:GetZOrder(), + visible = w:IsVisible(), + loading = w:IsLoading(), + singleton = w.config.singleton, + cacheTag = w.config.cacheTag, + blockWorldClick = w.config.blockWorldClick, + hiddenByFullscreen = w:IsHiddenByFullscreen() + } + end + i = i + 1 + end + end + return list +end +function UIManager.prototype.GetCachedWindowNames(self) + local names = {} + for name, w in pairs(self.cachedByName) do + if w ~= nil and not w:IsDisposed() then + names[#names + 1] = name + end + end + table.sort(names) + return names +end function UIManager.prototype.GetDiagnostics(self) local openWindows = 0 local loadingWindows = 0 @@ -316,9 +421,53 @@ function UIManager.prototype.RemoveFromStackAndSingleton(self, win) end end end +function UIManager.prototype.SyncFullscreenVisibility(self) + local topFullscreen = nil + local topFullscreenZ = -1 + do + local i = 0 + while i < #self.windowStack do + local win = self.windowStack[i + 1] + if not win:IsDisposed() and not win:IsClosing() and win:IsLoaded() and win.config.type == "fullscreen" then + local z = win:GetZOrder() + if topFullscreen == nil or z >= topFullscreenZ then + topFullscreen = win + topFullscreenZ = z + end + end + i = i + 1 + end + end + do + local i = 0 + while i < #self.windowStack do + do + local win = self.windowStack[i + 1] + if win:IsDisposed() or win:IsClosing() or not win:IsLoaded() then + goto __continue103 + end + local affectedLayer = win.config.layer == "background" or win.config.layer == "normal" + if not affectedLayer then + goto __continue103 + end + if topFullscreen ~= nil and win ~= topFullscreen and win:GetZOrder() < topFullscreenZ then + if win:IsVisible() then + win:SetHiddenByFullscreenInternal(true) + win:Hide() + end + elseif win:IsHiddenByFullscreen() then + win:RestoreFromFullscreenInternal() + end + end + ::__continue103:: + i = i + 1 + end + end +end function UIManager.prototype.SyncFocusAndInputMode(self) - local top = self:GetTopWindow() - local nextMode = top ~= nil and top.config.blockWorldClick and "ui" or "game" + local topBlocking = self:GetTopBlockingWindow() + local topAny = self:GetTopWindow() + local nextMode = topBlocking ~= nil and "ui" or "game" self.inputMode = nextMode local pc = self.playerCtx.playerController if pc ~= nil and UE ~= nil and UE.UKismetSystemLibrary.IsValid(pc) then @@ -326,8 +475,8 @@ function UIManager.prototype.SyncFocusAndInputMode(self) pc.bShowMouseCursor = true local ____UE_UWidgetBlueprintLibrary_SetInputMode_UIOnlyEx_1 = UE.UWidgetBlueprintLibrary.SetInputMode_UIOnlyEx local ____temp_0 - if top ~= nil then - ____temp_0 = top:GetWidget() + if topBlocking ~= nil then + ____temp_0 = topBlocking:GetWidget() else ____temp_0 = nil end @@ -337,7 +486,7 @@ function UIManager.prototype.SyncFocusAndInputMode(self) UE.UWidgetBlueprintLibrary.SetInputMode_GameOnly(pc, false) end end - self.events.emit.OnFocusRestored(top ~= nil and top.config.name or nil) + self.events.emit.OnFocusRestored(topAny ~= nil and topAny.config.name or nil) end function UIManager.prototype.Dispose(self) if self:IsDisposed() then diff --git a/Script/lua/framework/ui/ui_window.lua b/Script/lua/framework/ui/ui_window.lua index 85fb083..568ce91 100644 --- a/Script/lua/framework/ui/ui_window.lua +++ b/Script/lua/framework/ui/ui_window.lua @@ -20,7 +20,9 @@ function UIWindow.prototype.____constructor(self, ...) self.isVisible = false self.isClosing = false self.isCached = false - self.buttonBindings = {} + self.hiddenByFullscreen = false + self.currentZOrder = 0 + self.widgetBindings = {} end function UIWindow.prototype.InitContextInternal(self, ctx, uiManager, config, widgetAdapter) self.ctx = ctx @@ -31,6 +33,9 @@ end function UIWindow.prototype.GetWidget(self) return self.widget end +function UIWindow.prototype.GetZOrder(self) + return self.currentZOrder +end function UIWindow.prototype.IsLoading(self) return self.isLoading end @@ -46,6 +51,12 @@ end function UIWindow.prototype.IsCached(self) return self.isCached end +function UIWindow.prototype.IsHiddenByFullscreen(self) + return self.hiddenByFullscreen +end +function UIWindow.prototype.SetHiddenByFullscreenInternal(self, hidden) + self.hiddenByFullscreen = hidden +end function UIWindow.prototype.SetLoadingStateInternal(self, loading, handle) self.isLoading = loading self.classLoadHandle = handle @@ -69,30 +80,99 @@ function UIWindow.prototype.RequireWidget(self, widgetName) ) return child end -function UIWindow.prototype.BindButtonClick(self, button, callback) +function UIWindow.prototype.TrackWidgetBinding(self, handle) + if handle ~= nil then + self.widgetBindings[#self.widgetBindings + 1] = handle + end + return handle +end +function UIWindow.prototype.GetDelegateBridge(self) local bridge = self.ctx:GetService("uiDelegateBridge") if bridge == nil then logger:Warn("UIDelegateBridge not registered on context", {window = self.config.name}) return nil end - local handle = bridge:BindButtonClick(button, callback, self) - self.buttonBindings[#self.buttonBindings + 1] = handle - return handle + return bridge end -function UIWindow.prototype.UnbindAllButtons(self) +function UIWindow.prototype.BindButtonClick(self, button, callback) + local bridge = self:GetDelegateBridge() + if bridge == nil then + return nil + end + return self:TrackWidgetBinding(bridge:BindButtonClick(button, callback, self)) +end +function UIWindow.prototype.BindButtonHovered(self, button, callback) + local bridge = self:GetDelegateBridge() + if bridge == nil then + return nil + end + return self:TrackWidgetBinding(bridge:BindButtonHovered(button, callback, self)) +end +function UIWindow.prototype.BindButtonUnhovered(self, button, callback) + local bridge = self:GetDelegateBridge() + if bridge == nil then + return nil + end + return self:TrackWidgetBinding(bridge:BindButtonUnhovered(button, callback, self)) +end +function UIWindow.prototype.BindCheckBoxChanged(self, checkBox, callback) + local bridge = self:GetDelegateBridge() + if bridge == nil then + return nil + end + return self:TrackWidgetBinding(bridge:BindCheckBoxChanged(checkBox, callback, self)) +end +function UIWindow.prototype.BindSliderChanged(self, slider, callback) + local bridge = self:GetDelegateBridge() + if bridge == nil then + return nil + end + return self:TrackWidgetBinding(bridge:BindSliderChanged(slider, callback, self)) +end +function UIWindow.prototype.BindSpinBoxChanged(self, spinBox, callback) + local bridge = self:GetDelegateBridge() + if bridge == nil then + return nil + end + return self:TrackWidgetBinding(bridge:BindSpinBoxChanged(spinBox, callback, self)) +end +function UIWindow.prototype.BindEditableTextChanged(self, textBox, callback) + local bridge = self:GetDelegateBridge() + if bridge == nil then + return nil + end + return self:TrackWidgetBinding(bridge:BindEditableTextChanged(textBox, callback, self)) +end +function UIWindow.prototype.BindEditableTextCommitted(self, textBox, callback) + local bridge = self:GetDelegateBridge() + if bridge == nil then + return nil + end + return self:TrackWidgetBinding(bridge:BindEditableTextCommitted(textBox, callback, self)) +end +function UIWindow.prototype.BindComboBoxChanged(self, comboBox, callback) + local bridge = self:GetDelegateBridge() + if bridge == nil then + return nil + end + return self:TrackWidgetBinding(bridge:BindComboBoxSelectionChanged(comboBox, callback, self)) +end +function UIWindow.prototype.UnbindAllWidgetEvents(self) do local i = 0 - while i < #self.buttonBindings do - self.buttonBindings[i + 1]:Dispose() + while i < #self.widgetBindings do + self.widgetBindings[i + 1]:Dispose() i = i + 1 end end - self.buttonBindings = {} + self.widgetBindings = {} end function UIWindow.prototype.ShowInternal(self, zOrder, args) if self:IsDisposed() or self.isClosing then return end + self.currentZOrder = zOrder + self.hiddenByFullscreen = false tbpcall(function() self:OnPreShow(args) end) @@ -111,6 +191,7 @@ function UIWindow.prototype.ReuseInternal(self, zOrder, args) end self.isCached = false self.isClosing = false + self.hiddenByFullscreen = false self:EnableAllEventListeners() self:OnBindWidgets() tbpcall(function() @@ -118,6 +199,22 @@ function UIWindow.prototype.ReuseInternal(self, zOrder, args) end) self:ShowInternal(zOrder, args) end +function UIWindow.prototype.RestoreFromFullscreenInternal(self) + if self:IsDisposed() or self.isClosing or self.isCached or not self.isLoaded then + return + end + self.hiddenByFullscreen = false + if self.isVisible then + return + end + if self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) then + self.widgetAdapter:SetVisible(self.widget, true) + end + self.isVisible = true + tbpcall(function() + self:OnShow() + end) +end function UIWindow.prototype.Hide(self) if not self.isVisible then return @@ -143,9 +240,10 @@ function UIWindow.prototype.Close(self, onClosed) local canCache = self.config.cacheTag == "cache" and self.isLoaded and self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) and not self.ctx:IsShuttingDown() if canCache then self.isVisible = false + self.hiddenByFullscreen = false self.isCached = true self.isClosing = false - self:UnbindAllButtons() + self:UnbindAllWidgetEvents() self:DisableAllEventListeners() self.widgetAdapter:RemoveFromParent(self.widget) tbpcall(function() @@ -163,7 +261,8 @@ function UIWindow.prototype.Close(self, onClosed) end) end self.isVisible = false - self:UnbindAllButtons() + self.hiddenByFullscreen = false + self:UnbindAllWidgetEvents() if self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) then self.widgetAdapter:RemoveFromParent(self.widget) end @@ -176,7 +275,8 @@ function UIWindow.prototype.Close(self, onClosed) end function UIWindow.prototype.ForceDisposeFromCacheInternal(self) self.isCached = false - self:UnbindAllButtons() + self.hiddenByFullscreen = false + self:UnbindAllWidgetEvents() if self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) then self.widgetAdapter:RemoveFromParent(self.widget) end diff --git a/Script/lua/game/bootstrap_player.lua b/Script/lua/game/bootstrap_player.lua index 1f38e0b..85cd00c 100644 --- a/Script/lua/game/bootstrap_player.lua +++ b/Script/lua/game/bootstrap_player.lua @@ -1,9 +1,9 @@ local ____exports = __module.env local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module) local GetGameInstanceContext = M__framework_context_game_context.GetGameInstanceContext -local M__game_startup = __MODULE__.Import("game.startup", __module) -local OpenMiniSettings = M__game_startup.OpenMiniSettings ---- PIE / 启动地图玩家入口:绑定 LocalPlayer(0) 的 PlayerController 并打开首期最小设置窗口。 +local M__game_demo_demo_router = __MODULE__.Import("game.demo.demo_router", __module) +local RouteCurrentLevel = M__game_demo_demo_router.RouteCurrentLevel +--- PIE / 启动地图玩家入口:绑定 LocalPlayer(0) 的 PlayerController 并按当前关卡路由对应 Demo 场景。 function ____exports.OnBeginPlay(pc) local world = pc:GetWorld() local gi = UE.UGameplayStatics.GetGameInstance(pc) @@ -18,7 +18,7 @@ function ____exports.OnBeginPlay(pc) ctx:OnWorldCleanup(world) end ctx:GetOrCreateLocalPlayer(0, pc) - OpenMiniSettings(ctx) + RouteCurrentLevel(ctx, pc) end function ____exports.OnEndPlay(pc, _endPlayReason) local gi = UE.UGameplayStatics.GetGameInstance(pc) @@ -36,5 +36,5 @@ function ____exports.OnEndPlay(pc, _endPlayReason) end function __module.UpdateImports() GetGameInstanceContext = M__framework_context_game_context.GetGameInstanceContext - OpenMiniSettings = M__game_startup.OpenMiniSettings + RouteCurrentLevel = M__game_demo_demo_router.RouteCurrentLevel end diff --git a/Script/lua/game/demo/demo_hub_window.lua b/Script/lua/game/demo/demo_hub_window.lua new file mode 100644 index 0000000..c490ac0 --- /dev/null +++ b/Script/lua/game/demo/demo_hub_window.lua @@ -0,0 +1,179 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__framework_resource_asset_catalog = __MODULE__.Import("framework.resource.asset_catalog", __module) +local ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS +local M__framework_ui_ui_config = __MODULE__.Import("framework.ui.ui_config", __module) +local RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig +local M__framework_ui_ui_window = __MODULE__.Import("framework.ui.ui_window", __module) +local UIWindow = M__framework_ui_ui_window.UIWindow +local M__game_startup = __MODULE__.Import("game.startup", __module) +local OpenMiniSettings = M__game_startup.OpenMiniSettings +local M__game_demo_demo_registry = __MODULE__.Import("game.demo.demo_registry", __module) +local GetDemoScenes = M__game_demo_demo_registry.GetDemoScenes +local logger = Logger("DemoHubWindow") +____exports.DemoHubWindow = __TS__DefineClass("DemoHubWindow", __module) +local DemoHubWindow = ____exports.DemoHubWindow +DemoHubWindow.name = "DemoHubWindow" +__TS__ClassExtends(DemoHubWindow, UIWindow) +function DemoHubWindow.prototype.____constructor(self, ...) + UIWindow.prototype.____constructor(self, ...) + self.itemWidgets = {} + self.itemEnterButtons = {} +end +function DemoHubWindow.prototype.OnBindWidgets(self) + self.txtRuntimeInfo = self:RequireWidget("TxtRuntimeInfo") + self.scrollDemoList = self:RequireWidget("ScrollDemoList") + self.btnOpenMiniSettings = self:RequireWidget("BtnOpenMiniSettings") + self:BindButtonClick( + self.btnOpenMiniSettings, + function() + OpenMiniSettings(self.ctx) + end + ) +end +function DemoHubWindow.prototype.OnPreShow(self, args) + local openArgs = args + local ____temp_0 + if openArgs ~= nil then + ____temp_0 = openArgs.onSelectDemo + else + ____temp_0 = nil + end + self.onSelectDemo = ____temp_0 + self:RefreshRuntimeInfo() + self:PopulateDemoCards() +end +function DemoHubWindow.prototype.OnClose(self) + self:ClearDemoCards() +end +function DemoHubWindow.prototype.RefreshRuntimeInfo(self) + local resSvc = self.ctx:GetService("resource") + local modeText = resSvc ~= nil and resSvc:IsPackagedMode() and "Packaged" or "PIE / Editor" + local info = string.format( + "Lua 运行时:%s | Context #%d | 资源模式:%s | 已注册 Demo:%d 个", + _VERSION, + self.ctx.contextId, + modeText, + #GetDemoScenes() + ) + if self.txtRuntimeInfo ~= nil and self.txtRuntimeInfo.SetText ~= nil then + self.txtRuntimeInfo:SetText(info) + end +end +function DemoHubWindow.prototype.ClearDemoCards(self) + if self.itemScope ~= nil then + self.itemScope:Dispose() + self.itemScope = nil + end + if self.scrollDemoList ~= nil and self.scrollDemoList.ClearChildren ~= nil then + self.scrollDemoList:ClearChildren() + end + self.itemWidgets = {} + self.itemEnterButtons = {} +end +function DemoHubWindow.prototype.PopulateDemoCards(self) + self:ClearDemoCards() + local resSvc = self.ctx:GetService("resource") + if resSvc == nil or self.scrollDemoList == nil then + return + end + local scope = __TS__New(ScopedObject) + self.itemScope = scope + self:AddScopedObject(scope) + resSvc:LoadClassAsync( + ASSET_KEYS.DEMO_HUB_ITEM_WIDGET, + scope, + function(ok, itemClass, _lease, err) + if not ok or itemClass == nil or self:IsDisposed() or scope:IsDisposed() then + logger:Error("Failed to load WBP_DemoHubItem", {err = err}) + return + end + self:BuildDemoCardWidgets(itemClass, scope) + end + ) +end +function DemoHubWindow.prototype.BuildDemoCardWidgets(self, itemClass, scope) + if self.scrollDemoList == nil then + return + end + local worldContext = self.ctx:GetWorldContext().world or self.ctx.gameInstance + if worldContext == nil then + return + end + local lp0 = self.ctx:GetOrCreateLocalPlayer(0) + local bridge = self.ctx:GetService("uiDelegateBridge") + local scenes = GetDemoScenes() + do + local i = 0 + while i < #scenes do + do + local demo = scenes[i + 1] + local card = UE.UWidgetBlueprintLibrary.Create(worldContext, itemClass, lp0.playerController) + if card == nil then + goto __continue19 + end + local txtTitle = UE.ULuaUIEventSubsystem.FindChildWidgetByName(card, "TxtDemoTitle") + local txtDesc = UE.ULuaUIEventSubsystem.FindChildWidgetByName(card, "TxtDemoDesc") + local txtMeta = UE.ULuaUIEventSubsystem.FindChildWidgetByName(card, "TxtDemoMeta") + local btnEnter = UE.ULuaUIEventSubsystem.FindChildWidgetByName(card, "BtnEnterDemo") + local txtEnterLabel = UE.ULuaUIEventSubsystem.FindChildWidgetByName(card, "TxtEnterLabel") + if txtTitle ~= nil then + txtTitle:SetText(demo.title) + end + if txtDesc ~= nil then + txtDesc:SetText(demo.description) + end + if txtMeta ~= nil then + txtMeta:SetText(string.format("%s | 关卡:%s", demo.tags, demo.mapAssetPath)) + end + if txtEnterLabel ~= nil then + txtEnterLabel:SetText(demo.enabled and "进入场景" or "敬请期待") + end + if btnEnter ~= nil then + btnEnter:SetIsEnabled(demo.enabled) + self.itemEnterButtons[demo.id] = btnEnter + if demo.enabled and bridge ~= nil then + local handle = bridge:BindButtonClick( + btnEnter, + function() + if self.onSelectDemo ~= nil then + self.onSelectDemo(demo) + end + end, + scope + ) + scope:AddScopedObject(handle) + end + end + self.scrollDemoList:AddChild(card) + self.itemWidgets[#self.itemWidgets + 1] = card + end + ::__continue19:: + i = i + 1 + end + end +end +RegisterUIConfig(____exports.DemoHubWindow, { + name = "DemoHubWindow", + assetKey = ASSET_KEYS.DEMO_HUB_WIDGET, + singleton = true, + layer = "normal", + type = "normal", + cacheTag = "no_cache", + blockWorldClick = true +}) +function __module.UpdateImports() + Logger = M__share_base_logger.Logger + ScopedObject = M__share_base_scoped_object.ScopedObject + ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS + RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig + UIWindow = M__framework_ui_ui_window.UIWindow + OpenMiniSettings = M__game_startup.OpenMiniSettings + GetDemoScenes = M__game_demo_demo_registry.GetDemoScenes +end diff --git a/Script/lua/game/demo/demo_registry.lua b/Script/lua/game/demo/demo_registry.lua new file mode 100644 index 0000000..bb7b5b4 --- /dev/null +++ b/Script/lua/game/demo/demo_registry.lua @@ -0,0 +1,59 @@ +local ____exports = __module.env +____exports.BOOTSTRAP_MAP_NAME = "L_Bootstrap" +____exports.BOOTSTRAP_MAP_PATH = "/Game/Maps/L_Bootstrap" +____exports.UI_DEMO_MAP_NAME = "L_DemoUI" +____exports.UI_DEMO_MAP_PATH = "/Game/Maps/L_DemoUI" +____exports.DEMO_SCENES = {{ + id = "ui_demo", + title = "UI 主界面与窗口实验室(UI Demo)", + description = "完整演示游戏主界面布局、常用 UMG 控件(按钮/复选框/滑条/进度条/微调器/输入框/下拉框/动态列表/异步贴图)及 7 类窗口策略(普通/全屏互斥/模态/缓存复用/多实例/飘字/系统顶层)。", + mapName = ____exports.UI_DEMO_MAP_NAME, + mapAssetPath = ____exports.UI_DEMO_MAP_PATH, + tags = "UMG · 多层窗口栈 · 委托自动解绑 · 中文字体", + enabled = true +}, { + id = "coming_resource_demo", + title = "资源热更与异步加载演示(预留槽位)", + description = "后续将在此扩展 PatchManifest 覆盖、并发合并加载与 GC 引用计数可视化演示。", + mapName = "L_DemoResource", + mapAssetPath = "/Game/Maps/L_DemoResource", + tags = "规划中 · ResourceService", + enabled = false +}, { + id = "coming_gameplay_demo", + title = "3D 角色控制与输入演示(预留槽位)", + description = "后续将在此扩展 EnhancedInput、角色移动、射线检测与 HUD 非阻塞交互演示。", + mapName = "L_DemoGameplay", + mapAssetPath = "/Game/Maps/L_DemoGameplay", + tags = "规划中 · Gameplay / HUD", + enabled = false +}} +function ____exports.GetDemoScenes() + return ____exports.DEMO_SCENES +end +function ____exports.FindDemoSceneById(id) + do + local i = 0 + while i < #____exports.DEMO_SCENES do + if ____exports.DEMO_SCENES[i + 1].id == id then + return ____exports.DEMO_SCENES[i + 1] + end + i = i + 1 + end + end + return nil +end +function ____exports.FindDemoSceneByMapName(mapName) + do + local i = 0 + while i < #____exports.DEMO_SCENES do + if ____exports.DEMO_SCENES[i + 1].mapName == mapName then + return ____exports.DEMO_SCENES[i + 1] + end + i = i + 1 + end + end + return nil +end +function __module.UpdateImports() +end diff --git a/Script/lua/game/demo/demo_router.lua b/Script/lua/game/demo/demo_router.lua new file mode 100644 index 0000000..c9b2214 --- /dev/null +++ b/Script/lua/game/demo/demo_router.lua @@ -0,0 +1,94 @@ +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local M__game_startup = __MODULE__.Import("game.startup", __module) +local GetPrimaryUIManager = M__game_startup.GetPrimaryUIManager +local M__game_demo_demo_hub_window = __MODULE__.Import("game.demo.demo_hub_window", __module) +local DemoHubWindow = M__game_demo_demo_hub_window.DemoHubWindow +local M__game_demo_demo_registry = __MODULE__.Import("game.demo.demo_registry", __module) +local BOOTSTRAP_MAP_NAME = M__game_demo_demo_registry.BOOTSTRAP_MAP_NAME +local BOOTSTRAP_MAP_PATH = M__game_demo_demo_registry.BOOTSTRAP_MAP_PATH +local FindDemoSceneById = M__game_demo_demo_registry.FindDemoSceneById +local UI_DEMO_MAP_NAME = M__game_demo_demo_registry.UI_DEMO_MAP_NAME +local M__game_demo_ui_demo_ui_demo_main_window = __MODULE__.Import("game.demo.ui_demo.ui_demo_main_window", __module) +local UIDemoMainWindow = M__game_demo_ui_demo_ui_demo_main_window.UIDemoMainWindow +local logger +function ____exports.SwitchToDemoById(ctx, demoId) + local demo = FindDemoSceneById(demoId) + if demo == nil or not demo.enabled then + logger:Warn("Demo scene unavailable or disabled", {demoId = demoId}) + return false + end + local worldContext = ctx:GetWorldContext().world or ctx:GetOrCreateLocalPlayer(0).playerController + if worldContext == nil then + logger:Error("Cannot OpenLevel: no valid WorldContext", {demoId = demoId}) + return false + end + logger:Info("Switching to demo level", {demoId = demo.id, map = demo.mapAssetPath}) + UE.UGameplayStatics.OpenLevel(worldContext, demo.mapAssetPath, true, "") + return true +end +function ____exports.ReturnToBootstrap(ctx) + local worldContext = ctx:GetWorldContext().world or ctx:GetOrCreateLocalPlayer(0).playerController + if worldContext == nil then + logger:Error("Cannot return to Bootstrap: no valid WorldContext") + return false + end + logger:Info("Returning to Bootstrap Hub", {map = BOOTSTRAP_MAP_PATH}) + UE.UGameplayStatics.OpenLevel(worldContext, BOOTSTRAP_MAP_PATH, true, "") + return true +end +logger = Logger("DemoRouter") +function ____exports.OpenDemoHub(ctx, onOpened) + local uiMgr = GetPrimaryUIManager(ctx) + if uiMgr == nil then + return nil + end + return uiMgr:ShowUI( + DemoHubWindow, + {onSelectDemo = function(demo) + ____exports.SwitchToDemoById(ctx, demo.id) + end}, + onOpened + ) +end +function ____exports.OpenUIDemoMain(ctx, onOpened) + local uiMgr = GetPrimaryUIManager(ctx) + if uiMgr == nil then + return nil + end + return uiMgr:ShowUI( + UIDemoMainWindow, + {onReturnToHub = function() + ____exports.ReturnToBootstrap(ctx) + end}, + onOpened + ) +end +--- 按当前 UE 关卡名称自动挂载对应的 Demo 场景入口: +-- - L_Bootstrap -> DemoHubWindow(场景切换大厅) +-- - L_DemoUI -> UIDemoMainWindow(UI 组件与窗口实验室主界面) +-- - 其他未知关卡 -> 默认兜底打开 DemoHubWindow +function ____exports.RouteCurrentLevel(ctx, pc) + local levelName = UE.UGameplayStatics.GetCurrentLevelName(pc, true) + logger:Info("Routing player entry for level", {levelName = levelName}) + if levelName == UI_DEMO_MAP_NAME then + ____exports.OpenUIDemoMain(ctx) + return + end + if levelName == BOOTSTRAP_MAP_NAME then + ____exports.OpenDemoHub(ctx) + return + end + ____exports.OpenDemoHub(ctx) +end +function __module.UpdateImports() + Logger = M__share_base_logger.Logger + GetPrimaryUIManager = M__game_startup.GetPrimaryUIManager + DemoHubWindow = M__game_demo_demo_hub_window.DemoHubWindow + BOOTSTRAP_MAP_NAME = M__game_demo_demo_registry.BOOTSTRAP_MAP_NAME + BOOTSTRAP_MAP_PATH = M__game_demo_demo_registry.BOOTSTRAP_MAP_PATH + FindDemoSceneById = M__game_demo_demo_registry.FindDemoSceneById + UI_DEMO_MAP_NAME = M__game_demo_demo_registry.UI_DEMO_MAP_NAME + UIDemoMainWindow = M__game_demo_ui_demo_ui_demo_main_window.UIDemoMainWindow +end diff --git a/Script/lua/game/demo/ui_demo/ui_demo_main_window.lua b/Script/lua/game/demo/ui_demo/ui_demo_main_window.lua new file mode 100644 index 0000000..54e7040 --- /dev/null +++ b/Script/lua/game/demo/ui_demo/ui_demo_main_window.lua @@ -0,0 +1,993 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__framework_resource_asset_catalog = __MODULE__.Import("framework.resource.asset_catalog", __module) +local ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS +local M__framework_ui_ui_config = __MODULE__.Import("framework.ui.ui_config", __module) +local RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig +local M__framework_ui_ui_window = __MODULE__.Import("framework.ui.ui_window", __module) +local UIWindow = M__framework_ui_ui_window.UIWindow +local M__game_startup = __MODULE__.Import("game.startup", __module) +local OpenMiniSettings = M__game_startup.OpenMiniSettings +local M__game_demo_ui_demo_ui_demo_windows = __MODULE__.Import("game.demo.ui_demo.ui_demo_windows", __module) +local UIDemoCachedWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoCachedWindow +local UIDemoFullscreenWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoFullscreenWindow +local UIDemoModalWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoModalWindow +local UIDemoMultiWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoMultiWindow +local UIDemoNormalWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoNormalWindow +local UIDemoSystemWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoSystemWindow +local UIDemoToastWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoToastWindow +local logger = Logger("UIDemoMainWindow") +local THEME_PRESETS = {{label = "深海蓝(普通)", r = 0.149, g = 0.431, b = 0.855}, {label = "翡翠绿(稀有)", r = 0.133, g = 0.588, b = 0.388}, {label = "琥珀金(传说)", r = 0.761, g = 0.49, b = 0.11}, {label = "星云紫(史诗)", r = 0.478, g = 0.294, b = 0.784}} +local TEXT_COLORS = {{name = "纯白", r = 0.941, g = 0.961, b = 0.988}, {name = "天青", r = 0.451, g = 0.788, b = 0.98}, {name = "金黄", r = 0.98, g = 0.812, b = 0.31}, {name = "珊瑚红", r = 0.98, g = 0.51, b = 0.51}} +local TEXT_SIZES = {14, 18, 22} +local PREVIEW_TEXTURES = {{label = "冒险者头像", key = ASSET_KEYS.DEMO_AVATAR_TEX}, {label = "翡翠菱形徽章", key = ASSET_KEYS.DEMO_BADGE_A_TEX}, {label = "绯红星纹徽章", key = ASSET_KEYS.DEMO_BADGE_B_TEX}, {label = "经典设置图标", key = ASSET_KEYS.MINI_SETTINGS_ICON}} +local TINT_COLORS = {{name = "原色", r = 1, g = 1, b = 1}, {name = "青蓝着色", r = 0.55, g = 0.9, b = 1}, {name = "金黄着色", r = 1, g = 0.85, b = 0.45}, {name = "玫红着色", r = 1, g = 0.55, b = 0.7}} +local function MakeLinearColor(self, r, g, b, a) + if a == nil then + a = 1 + end + local c = UE.FLinearColor() + c.R = r + c.G = g + c.B = b + c.A = a + return c +end +local function MakeSlateColor(self, r, g, b, a) + if a == nil then + a = 1 + end + local sc = UE.FSlateColor() + sc.SpecifiedColor = MakeLinearColor( + nil, + r, + g, + b, + a + ) + sc.ColorUseRule = UE.ESlateColorStylingMode.UseColor_Specified + return sc +end +____exports.UIDemoMainWindow = __TS__DefineClass("UIDemoMainWindow", __module) +local UIDemoMainWindow = ____exports.UIDemoMainWindow +UIDemoMainWindow.name = "UIDemoMainWindow" +__TS__ClassExtends(UIDemoMainWindow, UIWindow) +function UIDemoMainWindow.prototype.____constructor(self, ...) + UIWindow.prototype.____constructor(self, ...) + self.activeTabIndex = 0 + self.actionClickCount = 0 + self.actionHovered = false + self.targetEnabled = true + self.targetClickCount = 0 + self.checkboxChecked = false + self.sliderValue = 0.5 + self.spinValue = 100 + self.currentNickname = "冒险者_01" + self.draftNickname = "" + self.selectedTheme = "深海蓝(普通)" + self.dynamicItemCount = 0 + self.multiSeq = 0 + self.toastSeq = 0 + self.textColorIndex = 0 + self.textSizeIndex = 0 + self.previewTexIndex = 0 + self.previewTintIndex = 0 + self.previewVisIndex = 0 + self.nextListItemId = 0 + self.dynamicItems = {} + self.logLines = {} +end +function UIDemoMainWindow.prototype.OnBindWidgets(self) + self.imgPlayerAvatar = self:RequireWidget("ImgPlayerAvatar") + self.txtPlayerName = self:RequireWidget("TxtPlayerName") + self.barPlayerExp = self:RequireWidget("BarPlayerExp") + self.txtHudStats = self:RequireWidget("TxtHudStats") + self.btnTopSettings = self:RequireWidget("BtnTopSettings") + self.btnBackToHub = self:RequireWidget("BtnBackToHub") + self:BindButtonClick( + self.btnTopSettings, + function() + self:AppendLog("[TopBar] 打开 MiniSettingsWindow") + OpenMiniSettings(self.ctx) + end + ) + self:BindButtonClick( + self.btnBackToHub, + function() + self:AppendLog("[TopBar] 返回 Bootstrap 场景大厅") + if self.onReturnToHub ~= nil then + self.onReturnToHub() + end + end + ) + self.btnWinNormal = self:RequireWidget("BtnWinNormal") + self.btnWinFullscreen = self:RequireWidget("BtnWinFullscreen") + self.btnWinModal = self:RequireWidget("BtnWinModal") + self.btnWinCached = self:RequireWidget("BtnWinCached") + self.btnWinMulti = self:RequireWidget("BtnWinMulti") + self.btnWinToast = self:RequireWidget("BtnWinToast") + self.btnWinSystem = self:RequireWidget("BtnWinSystem") + self.btnEvictCache = self:RequireWidget("BtnEvictCache") + self.btnCloseOthers = self:RequireWidget("BtnCloseOthers") + self:BindButtonClick( + self.btnWinNormal, + function() + self:OpenNormalDemoWindow() + end + ) + self:BindButtonClick( + self.btnWinFullscreen, + function() + self:OpenFullscreenDemoWindow() + end + ) + self:BindButtonClick( + self.btnWinModal, + function() + self:OpenModalDemoWindow("确认操作", "这是一条带半透明遮罩的模态弹窗,点击「确认」或「取消」将在右侧日志记录结果。") + end + ) + self:BindButtonClick( + self.btnWinCached, + function() + self:OpenCachedDemoWindow() + end + ) + self:BindButtonClick( + self.btnWinMulti, + function() + self:OpenMultiDemoWindow() + end + ) + self:BindButtonClick( + self.btnWinToast, + function() + self:ShowToast(string.format("飘字通知 #%d(Tips 层,不抢占 UI 焦点)", self.toastSeq + 1)) + end + ) + self:BindButtonClick( + self.btnWinSystem, + function() + self:OpenSystemDemoWindow() + end + ) + self:BindButtonClick( + self.btnEvictCache, + function() + local evicted = self.uiManager:EvictCache() + self:AppendLog(string.format("[Cache] 已主动清空缓存池,释放 %d 个缓存窗口", evicted)) + self:RefreshHudAndDiagnostics() + end + ) + self:BindButtonClick( + self.btnCloseOthers, + function() + local closed = self.uiManager:CloseAllExcept(self, false) + self:AppendLog(string.format("[UIManager] 已关闭除主界面外的 %d 个窗口", closed)) + self:RefreshHudAndDiagnostics() + end + ) + self.btnTabBasic = self:RequireWidget("BtnTabBasic") + self.btnTabInput = self:RequireWidget("BtnTabInput") + self.btnTabMedia = self:RequireWidget("BtnTabMedia") + self.btnTabDiag = self:RequireWidget("BtnTabDiag") + self.tabSwitcher = self:RequireWidget("TabSwitcher") + self:BindButtonClick( + self.btnTabBasic, + function() return self:SelectTab(0, "基础交互") end + ) + self:BindButtonClick( + self.btnTabInput, + function() return self:SelectTab(1, "输入与选择") end + ) + self:BindButtonClick( + self.btnTabMedia, + function() return self:SelectTab(2, "图片与列表") end + ) + self:BindButtonClick( + self.btnTabDiag, + function() + self:SelectTab(3, "框架诊断") + self:RefreshHudAndDiagnostics() + end + ) + self.txtBasicBtnStatus = self:RequireWidget("TxtBasicBtnStatus") + self.btnDemoAction = self:RequireWidget("BtnDemoAction") + self.btnToggleDisable = self:RequireWidget("BtnToggleDisable") + self.btnDemoTarget = self:RequireWidget("BtnDemoTarget") + self.txtDemoTarget = self:RequireWidget("TxtDemoTarget") + self.chkFeature = self:RequireWidget("ChkFeature") + self.txtCheckStatus = self:RequireWidget("TxtCheckStatus") + self.txtSliderStatus = self:RequireWidget("TxtSliderStatus") + self.sliderDemo = self:RequireWidget("SliderDemo") + self.progressDemo = self:RequireWidget("ProgressDemo") + self.btnProgressPlay = self:RequireWidget("BtnProgressPlay") + self.txtProgressPlay = self:RequireWidget("TxtProgressPlay") + self.btnProgressReset = self:RequireWidget("BtnProgressReset") + self.spinDemo = self:RequireWidget("SpinDemo") + self.txtSpinStatus = self:RequireWidget("TxtSpinStatus") + self:BindButtonClick( + self.btnDemoAction, + function() + self.actionClickCount = self.actionClickCount + 1 + self:RefreshBasicButtonStatus() + self:AppendLog(string.format("[Button] 测试按钮被点击(第 %d 次)", self.actionClickCount)) + end + ) + self:BindButtonHovered( + self.btnDemoAction, + function() + self.actionHovered = true + self:RefreshBasicButtonStatus() + self:AppendLog("[Button] 鼠标悬停进入测试按钮") + end + ) + self:BindButtonUnhovered( + self.btnDemoAction, + function() + self.actionHovered = false + self:RefreshBasicButtonStatus() + end + ) + self:BindButtonClick( + self.btnToggleDisable, + function() + self.targetEnabled = not self.targetEnabled + if self.btnDemoTarget ~= nil then + self.btnDemoTarget:SetIsEnabled(self.targetEnabled) + end + if self.txtDemoTarget ~= nil then + self.txtDemoTarget:SetText(self.targetEnabled and "目标受控按钮(已启用)" or "目标受控按钮(已禁用)") + end + self:RefreshBasicButtonStatus() + self:AppendLog(self.targetEnabled and "[Button] 目标按钮已启用" or "[Button] 目标按钮已禁用") + end + ) + self:BindButtonClick( + self.btnDemoTarget, + function() + self.targetClickCount = self.targetClickCount + 1 + self:AppendLog(string.format("[Button] 受控按钮触发点击 #%d", self.targetClickCount)) + end + ) + self:BindCheckBoxChanged( + self.chkFeature, + function(checked) + self.checkboxChecked = checked + if self.txtCheckStatus ~= nil then + self.txtCheckStatus:SetText(checked and "复选框状态:已勾选(开启特性)" or "复选框状态:未勾选(关闭特性)") + end + self:AppendLog(checked and "[CheckBox] 已勾选" or "[CheckBox] 已取消勾选") + end + ) + self:BindSliderChanged( + self.sliderDemo, + function(val) + self:ApplySliderProgress(val, false) + end + ) + self:BindButtonClick( + self.btnProgressPlay, + function() + self:ToggleProgressAnimation() + end + ) + self:BindButtonClick( + self.btnProgressReset, + function() + self:StopProgressAnimation() + self:ApplySliderProgress(0, true) + self:AppendLog("[ProgressBar] 进度已重置为 0%") + end + ) + self:BindSpinBoxChanged( + self.spinDemo, + function(val) + self.spinValue = val + if self.txtSpinStatus ~= nil then + self.txtSpinStatus:SetText(string.format("当前数值:%.1f(范围 0 ~ 999)", val)) + end + self:AppendLog(string.format("[SpinBox] 数值变更 -> %.1f", val)) + end + ) + self.inputNickname = self:RequireWidget("InputNickname") + self.txtInputStatus = self:RequireWidget("TxtInputStatus") + self.btnApplyNickname = self:RequireWidget("BtnApplyNickname") + self.comboTheme = self:RequireWidget("ComboTheme") + self.borderThemePreview = self:RequireWidget("BorderThemePreview") + self.txtComboStatus = self:RequireWidget("TxtComboStatus") + self.txtRichSample = self:RequireWidget("TxtRichSample") + self.btnCycleTextColor = self:RequireWidget("BtnCycleTextColor") + self.btnCycleTextSize = self:RequireWidget("BtnCycleTextSize") + self:BindEditableTextChanged( + self.inputNickname, + function(text) + self.draftNickname = text + local charCount = utf8.len(text) or string.len(text) + if self.txtInputStatus ~= nil then + self.txtInputStatus:SetText(charCount > 0 and string.format("实时内容:%s(%d 字符)", text, charCount) or "实时内容:空(0 字符)") + end + end + ) + self:BindEditableTextCommitted( + self.inputNickname, + function(text, commitMethod) + self.draftNickname = text + self:AppendLog(string.format("[EditableTextBox] 提交文本:%s(Method=%d)", text, commitMethod)) + if text ~= "" then + self:ApplyNickname(text) + end + end + ) + self:BindButtonClick( + self.btnApplyNickname, + function() + local nextName = self.draftNickname ~= "" and self.draftNickname or "天命旅人_88" + self:ApplyNickname(nextName) + end + ) + self:BindComboBoxChanged( + self.comboTheme, + function(option) + self:ApplyThemePreset(option) + end + ) + self:BindButtonClick( + self.btnCycleTextColor, + function() + self.textColorIndex = (self.textColorIndex + 1) % #TEXT_COLORS + local c = TEXT_COLORS[self.textColorIndex + 1] + if self.txtRichSample ~= nil then + self.txtRichSample:SetColorAndOpacity(MakeSlateColor( + nil, + c.r, + c.g, + c.b, + 1 + )) + end + self:AppendLog(string.format("[TextBlock] 切换文本颜色 -> %s", c.name)) + end + ) + self:BindButtonClick( + self.btnCycleTextSize, + function() + self.textSizeIndex = (self.textSizeIndex + 1) % #TEXT_SIZES + local size = TEXT_SIZES[self.textSizeIndex + 1] + if self.txtRichSample ~= nil then + self.txtRichSample:SetFontSize(size) + end + self:AppendLog(string.format("[TextBlock] 切换字号 -> %dpt", size)) + end + ) + self.imgPreview = self:RequireWidget("ImgPreview") + self.txtImageStatus = self:RequireWidget("TxtImageStatus") + self.btnSwitchTex = self:RequireWidget("BtnSwitchTex") + self.btnTintTex = self:RequireWidget("BtnTintTex") + self.btnCycleVis = self:RequireWidget("BtnCycleVis") + self.txtListSummary = self:RequireWidget("TxtListSummary") + self.btnListAddOne = self:RequireWidget("BtnListAddOne") + self.btnListAddTen = self:RequireWidget("BtnListAddTen") + self.btnListClear = self:RequireWidget("BtnListClear") + self.scrollDynamicList = self:RequireWidget("ScrollDynamicList") + self:BindButtonClick( + self.btnSwitchTex, + function() + self.previewTexIndex = (self.previewTexIndex + 1) % #PREVIEW_TEXTURES + self:LoadPreviewTexture() + end + ) + self:BindButtonClick( + self.btnTintTex, + function() + self.previewTintIndex = (self.previewTintIndex + 1) % #TINT_COLORS + local tint = TINT_COLORS[self.previewTintIndex + 1] + if self.imgPreview ~= nil then + self.imgPreview:SetColorAndOpacity(MakeLinearColor( + nil, + tint.r, + tint.g, + tint.b, + 1 + )) + end + self:AppendLog(string.format("[Image] 切换着色 -> %s", tint.name)) + self:RefreshImageStatus() + end + ) + self:BindButtonClick( + self.btnCycleVis, + function() + self.previewVisIndex = (self.previewVisIndex + 1) % 3 + local visModes = {UE.ESlateVisibility.Visible, UE.ESlateVisibility.Hidden, UE.ESlateVisibility.Collapsed} + if self.imgPreview ~= nil then + self.imgPreview:SetVisibility(visModes[self.previewVisIndex + 1]) + end + self:RefreshImageStatus() + self:AppendLog(string.format( + "[Image] 切换可见性 -> %s", + self:GetVisibilityLabel() + )) + end + ) + self:BindButtonClick( + self.btnListAddOne, + function() return self:AddDynamicListItems(1) end + ) + self:BindButtonClick( + self.btnListAddTen, + function() return self:AddDynamicListItems(10) end + ) + self:BindButtonClick( + self.btnListClear, + function() return self:ClearDynamicListItems() end + ) + self.txtDiagDetail = self:RequireWidget("TxtDiagDetail") + self.btnDiagRefresh = self:RequireWidget("BtnDiagRefresh") + self.btnDiagConcurrent = self:RequireWidget("BtnDiagConcurrent") + self.btnDiagCancelLoad = self:RequireWidget("BtnDiagCancelLoad") + self:BindButtonClick( + self.btnDiagRefresh, + function() + self:RefreshHudAndDiagnostics() + self:AppendLog("[Diag] 已手动刷新诊断快照") + end + ) + self:BindButtonClick( + self.btnDiagConcurrent, + function() + local w1 = self:OpenNormalDemoWindow() + local w2 = self:OpenNormalDemoWindow() + local same = w1 == w2 + self:AppendLog(string.format( + "[Diag] 并发双开单例测试:同一控制器=%s", + tostring(same) + )) + self:ShowToast(same and "并发双开测试通过:返回同一单例" or "并发双开测试异常") + end + ) + self:BindButtonClick( + self.btnDiagCancelLoad, + function() + local w = self.uiManager:ShowUI( + UIDemoSystemWindow, + {onLog = function(____, m) return self:AppendLog(m) end} + ) + if w ~= nil then + w:Close() + end + self:AppendLog("[Diag] 已执行「打开后立即关闭」取消加载验证") + self:RefreshHudAndDiagnostics() + end + ) + self.btnClearLog = self:RequireWidget("BtnClearLog") + self.scrollEventLog = self:RequireWidget("ScrollEventLog") + self.txtEventLog = self:RequireWidget("TxtEventLog") + self:BindButtonClick( + self.btnClearLog, + function() + self.logLines = {} + self:RenderLogText() + end + ) +end +function UIDemoMainWindow.prototype.OnPreShow(self, args) + local a = args + local ____temp_0 + if a ~= nil then + ____temp_0 = a.onReturnToHub + else + ____temp_0 = nil + end + self.onReturnToHub = ____temp_0 + self.uiManager.events.on.OnWindowOpened( + function(winName) + self:AppendLog(string.format("[UIManager] 窗口打开:%s", winName)) + self:RefreshHudAndDiagnostics() + end, + self + ) + self.uiManager.events.on.OnWindowClosed( + function(winName) + self:AppendLog(string.format("[UIManager] 窗口关闭:%s", winName)) + self:RefreshHudAndDiagnostics() + end, + self + ) + self.uiManager.events.on.OnFocusRestored( + function() + self:RefreshHudAndDiagnostics() + end, + self + ) + self:LoadAvatarAndPreview() + self:PreloadDynamicListItemClass() + self:SelectTab(0, "基础交互") + self:RefreshBasicButtonStatus() + self:ApplySliderProgress(self.sliderValue, true) + self:RefreshListSummary() + self:AppendLog("[UIDemoMain] 主界面已就绪,可测试全部 UI 控件与 7 类窗口") +end +function UIDemoMainWindow.prototype.OnShow(self) + self:RefreshHudAndDiagnostics() +end +function UIDemoMainWindow.prototype.OnHide(self) + self:AppendLog("[UIDemoMain] OnHide(已被全屏窗口遮盖隐藏)") +end +function UIDemoMainWindow.prototype.OnClose(self) + self:StopProgressAnimation() + self:ClearDynamicListItems() +end +function UIDemoMainWindow.prototype.SelectTab(self, index, label) + self.activeTabIndex = index + if self.tabSwitcher ~= nil then + self.tabSwitcher:SetActiveWidgetIndex(index) + end + self:AppendLog(string.format("[Tab] 切换至:%s", label)) +end +function UIDemoMainWindow.prototype.OpenNormalDemoWindow(self) + return self.uiManager:ShowUI( + UIDemoNormalWindow, + {onLog = function(____, m) return self:AppendLog(m) end} + ) +end +function UIDemoMainWindow.prototype.OpenFullscreenDemoWindow(self) + return self.uiManager:ShowUI( + UIDemoFullscreenWindow, + { + onLog = function(____, m) return self:AppendLog(m) end, + onOpenModal = function() + self:OpenModalDemoWindow("全屏页上的模态弹窗", "验证 popup 层正确叠加在 fullscreen 全屏页面之上。") + end + } + ) +end +function UIDemoMainWindow.prototype.OpenModalDemoWindow(self, title, message) + return self.uiManager:ShowUI( + UIDemoModalWindow, + { + title = title, + message = message, + onConfirm = function() + self:AppendLog("[Modal] 用户点击了「确认」") + self:ShowToast("模态弹窗:已确认") + end, + onCancel = function() + self:AppendLog("[Modal] 用户点击了「取消」") + end + } + ) +end +function UIDemoMainWindow.prototype.OpenCachedDemoWindow(self) + return self.uiManager:ShowUI( + UIDemoCachedWindow, + {onLog = function(____, m) return self:AppendLog(m) end} + ) +end +function UIDemoMainWindow.prototype.OpenMultiDemoWindow(self) + self.multiSeq = self.multiSeq + 1 + return self.uiManager:ShowUI( + UIDemoMultiWindow, + { + instanceSeq = self.multiSeq, + onLog = function(____, m) return self:AppendLog(m) end + } + ) +end +function UIDemoMainWindow.prototype.ShowToast(self, message, durationSec) + if durationSec == nil then + durationSec = 2.2 + end + self.toastSeq = self.toastSeq + 1 + return self.uiManager:ShowUI( + UIDemoToastWindow, + { + message = message, + durationSec = durationSec, + offsetIndex = self.toastSeq - 1, + onLog = function(____, m) return self:AppendLog(m) end + } + ) +end +function UIDemoMainWindow.prototype.OpenSystemDemoWindow(self) + return self.uiManager:ShowUI( + UIDemoSystemWindow, + {onLog = function(____, m) return self:AppendLog(m) end} + ) +end +function UIDemoMainWindow.prototype.AddDynamicListItems(self, count) + if self.scrollDynamicList == nil then + return + end + if self.listItemClass == nil then + self:PreloadDynamicListItemClass(function() + self:AddDynamicListItems(count) + end) + return + end + local worldContext = self.ctx:GetWorldContext().world or self.ctx.gameInstance + if worldContext == nil then + return + end + local lp0 = self.ctx:GetOrCreateLocalPlayer(0) + local bridge = self.ctx:GetService("uiDelegateBridge") + do + local i = 0 + while i < count do + do + self.nextListItemId = self.nextListItemId + 1 + local itemId = self.nextListItemId + local itemWidget = UE.UWidgetBlueprintLibrary.Create(worldContext, self.listItemClass, lp0.playerController) + if itemWidget == nil then + goto __continue90 + end + local itemScope = __TS__New(ScopedObject) + local txtTitle = UE.ULuaUIEventSubsystem.FindChildWidgetByName(itemWidget, "TxtItemTitle") + local btnAct = UE.ULuaUIEventSubsystem.FindChildWidgetByName(itemWidget, "BtnItemAction") + local btnDel = UE.ULuaUIEventSubsystem.FindChildWidgetByName(itemWidget, "BtnItemDelete") + if txtTitle ~= nil then + txtTitle:SetText(string.format("动态条目 #%d — 测试委托自动回收", itemId)) + end + local entry = {id = itemId, widget = itemWidget, scope = itemScope} + if bridge ~= nil then + if btnAct ~= nil then + local hAct = bridge:BindButtonClick( + btnAct, + function() + self:AppendLog(string.format("[ListItem #%d] 点击了「触发」", itemId)) + self:ShowToast( + string.format("触发了列表项 #%d", itemId), + 1.5 + ) + end, + itemScope + ) + itemScope:AddScopedObject(hAct) + end + if btnDel ~= nil then + local hDel = bridge:BindButtonClick( + btnDel, + function() + self:RemoveDynamicListItem(itemId) + end, + itemScope + ) + itemScope:AddScopedObject(hDel) + end + end + self.scrollDynamicList:AddChild(itemWidget) + self.dynamicItems[#self.dynamicItems + 1] = entry + end + ::__continue90:: + i = i + 1 + end + end + self.dynamicItemCount = #self.dynamicItems + self:RefreshListSummary() + self:RefreshHudAndDiagnostics() + self:AppendLog(string.format("[ScrollBox] 新增 %d 个动态列表项(当前共 %d 项)", count, self.dynamicItemCount)) +end +function UIDemoMainWindow.prototype.RemoveDynamicListItem(self, itemId) + do + local i = #self.dynamicItems - 1 + while i >= 0 do + local entry = self.dynamicItems[i + 1] + if entry.id == itemId then + entry.scope:Dispose() + if entry.widget.RemoveFromParent ~= nil then + entry.widget:RemoveFromParent() + end + table.remove(self.dynamicItems, i + 1) + break + end + i = i - 1 + end + end + self.dynamicItemCount = #self.dynamicItems + self:RefreshListSummary() + self:RefreshHudAndDiagnostics() + self:AppendLog(string.format("[ScrollBox] 删除列表项 #%d(委托已自动解绑,剩余 %d 项)", itemId, self.dynamicItemCount)) +end +function UIDemoMainWindow.prototype.ClearDynamicListItems(self) + local prev = #self.dynamicItems + do + local i = 0 + while i < #self.dynamicItems do + self.dynamicItems[i + 1].scope:Dispose() + i = i + 1 + end + end + self.dynamicItems = {} + self.dynamicItemCount = 0 + if self.scrollDynamicList ~= nil and self.scrollDynamicList.ClearChildren ~= nil then + self.scrollDynamicList:ClearChildren() + end + self:RefreshListSummary() + if prev > 0 then + self:AppendLog(string.format("[ScrollBox] 已清空 %d 个动态列表项并释放全部子委托", prev)) + self:RefreshHudAndDiagnostics() + end +end +function UIDemoMainWindow.prototype.PreloadDynamicListItemClass(self, onReady) + local resSvc = self.ctx:GetService("resource") + if resSvc == nil then + return + end + resSvc:LoadClassAsync( + ASSET_KEYS.UI_DEMO_LIST_ITEM_WIDGET, + self, + function(ok, cls, _lease, err) + if not ok or cls == nil then + logger:Warn("Failed to load WBP_UIDemoListItem", {err = err}) + return + end + self.listItemClass = cls + if onReady ~= nil and not self:IsDisposed() then + onReady() + end + end + ) +end +function UIDemoMainWindow.prototype.LoadAvatarAndPreview(self) + local resSvc = self.ctx:GetService("resource") + if resSvc == nil then + return + end + resSvc:LoadTextureAsync( + ASSET_KEYS.DEMO_AVATAR_TEX, + self, + function(ok, tex) + if ok and tex ~= nil and self.imgPlayerAvatar ~= nil and not self:IsDisposed() then + self.imgPlayerAvatar:SetBrushFromTexture(tex, false) + end + end + ) + self:LoadPreviewTexture() +end +function UIDemoMainWindow.prototype.LoadPreviewTexture(self) + local resSvc = self.ctx:GetService("resource") + if resSvc == nil then + return + end + local spec = PREVIEW_TEXTURES[self.previewTexIndex + 1] + resSvc:LoadTextureAsync( + spec.key, + self, + function(ok, tex) + if ok and tex ~= nil and self.imgPreview ~= nil and not self:IsDisposed() then + self.imgPreview:SetBrushFromTexture(tex, false) + self:RefreshImageStatus() + self:AppendLog(string.format("[Image] 异步贴图加载完成 -> %s", spec.label)) + end + end + ) +end +function UIDemoMainWindow.prototype.GetVisibilityLabel(self) + if self.previewVisIndex == 0 then + return "Visible(可见)" + end + if self.previewVisIndex == 1 then + return "Hidden(隐身占位)" + end + return "Collapsed(折叠不占位)" +end +function UIDemoMainWindow.prototype.RefreshImageStatus(self) + local spec = PREVIEW_TEXTURES[self.previewTexIndex + 1] + local tint = TINT_COLORS[self.previewTintIndex + 1] + if self.txtImageStatus ~= nil then + self.txtImageStatus:SetText(string.format( + "贴图:%s | 着色:%s | 可见性:%s", + spec.label, + tint.name, + self:GetVisibilityLabel() + )) + end +end +function UIDemoMainWindow.prototype.RefreshBasicButtonStatus(self) + if self.txtBasicBtnStatus ~= nil then + self.txtBasicBtnStatus:SetText(string.format("按钮状态:点击 %d 次 | 悬停:%s | 受控按钮:%s", self.actionClickCount, self.actionHovered and "是" or "否", self.targetEnabled and "已启用" or "已禁用")) + end +end +function UIDemoMainWindow.prototype.ApplySliderProgress(self, val, syncSliderWidget) + local clamped = math.max( + 0, + math.min(1, val) + ) + self.sliderValue = clamped + if syncSliderWidget and self.sliderDemo ~= nil then + self.sliderDemo:SetValue(clamped) + end + if self.progressDemo ~= nil then + self.progressDemo:SetPercent(clamped) + end + if self.barPlayerExp ~= nil then + self.barPlayerExp:SetPercent(clamped) + end + if self.txtSliderStatus ~= nil then + self.txtSliderStatus:SetText(string.format( + "当前进度:%d%%(同时驱动主界面顶部经验条)", + math.floor(clamped * 100 + 0.5) + )) + end +end +function UIDemoMainWindow.prototype.ToggleProgressAnimation(self) + if self.progressTimer ~= nil and self.progressTimer:IsActive() then + self:StopProgressAnimation() + self:AppendLog("[ProgressBar] 暂停进度动画") + return + end + if self.txtProgressPlay ~= nil then + self.txtProgressPlay:SetText("暂停自动进度动画") + end + self:AppendLog("[ProgressBar] 启动 WorldTimer 自动进度动画") + self.progressTimer = self.ctx.scheduler:AddWorldRepeatTimer( + 0.05, + function() + local nextVal = self.sliderValue + 0.025 + if nextVal > 1 then + nextVal = 0 + end + self:ApplySliderProgress(nextVal, true) + end, + self + ) +end +function UIDemoMainWindow.prototype.StopProgressAnimation(self) + if self.progressTimer ~= nil then + self.progressTimer:Cancel() + self.progressTimer = nil + end + if self.txtProgressPlay ~= nil then + self.txtProgressPlay:SetText("开始自动进度动画") + end +end +function UIDemoMainWindow.prototype.ApplyNickname(self, name) + self.currentNickname = name + if self.txtPlayerName ~= nil then + self.txtPlayerName:SetText(string.format("%s Lv.12", name)) + end + self:AppendLog(string.format("[Player] 昵称已更新为:%s", name)) + self:ShowToast( + string.format("昵称已更新:%s", name), + 1.8 + ) +end +function UIDemoMainWindow.prototype.ApplyThemePreset(self, option) + self.selectedTheme = option + local matched = THEME_PRESETS[1] + do + local i = 0 + while i < #THEME_PRESETS do + if THEME_PRESETS[i + 1].label == option then + matched = THEME_PRESETS[i + 1] + break + end + i = i + 1 + end + end + if self.borderThemePreview ~= nil then + self.borderThemePreview:SetBrushColor(MakeLinearColor( + nil, + matched.r, + matched.g, + matched.b, + 1 + )) + end + if self.txtComboStatus ~= nil then + self.txtComboStatus:SetText(string.format("当前选中:%s", option)) + end + self:AppendLog(string.format("[ComboBox] 切换主题 -> %s", option)) +end +function UIDemoMainWindow.prototype.RefreshListSummary(self) + if self.txtListSummary ~= nil then + self.txtListSummary:SetText(string.format("动态列表项:%d 条(新增/删除时观察顶部活跃绑定数变化)", self.dynamicItemCount)) + end +end +function UIDemoMainWindow.prototype.RefreshHudAndDiagnostics(self) + if self:IsDisposed() then + return + end + local uiDiag = self.uiManager:GetDiagnostics() + local bridge = self.ctx:GetService("uiDelegateBridge") + local resSvc = self.ctx:GetService("resource") + local activeBindings = bridge ~= nil and bridge:GetActiveBindingCount() or 0 + if self.txtHudStats ~= nil then + self.txtHudStats:SetText(string.format( + "窗口:%d | 缓存:%d | 绑定:%d | 模式:%s | 顶层:%s", + uiDiag.openWindows, + uiDiag.cachedWindows, + activeBindings, + uiDiag.inputMode == "ui" and "UI" or "Game", + uiDiag.topWindowName or "无" + )) + end + if self.txtDiagDetail ~= nil then + local stack = self.uiManager:GetWindowStackSnapshot() + local cachedNames = self.uiManager:GetCachedWindowNames() + local schedStats = self.ctx.scheduler:GetStats() + local resDiag = resSvc ~= nil and resSvc:GetDiagnostics() or nil + local lines = {} + lines[#lines + 1] = string.format( + "【UIManager】打开: %d | 加载中: %d | 缓存: %d | 输入模式: %s | 顶层: %s", + uiDiag.openWindows, + uiDiag.loadingWindows, + uiDiag.cachedWindows, + uiDiag.inputMode, + uiDiag.topWindowName or "无" + ) + lines[#lines + 1] = string.format("【UIDelegateBridge】活跃 UMG 控件委托数:%d", activeBindings) + if resDiag ~= nil then + lines[#lines + 1] = string.format("【ResourceService】在途加载: %d | 驻留资产: %d | 总引用计数: %d", resDiag.nativeInFlight, resDiag.nativeRetainedAssets, resDiag.nativeTotalRefCount) + end + lines[#lines + 1] = string.format("【FrameScheduler】Frame: %d | World: %d | Monotonic: %d", schedStats.frameTasks, schedStats.worldTasks, schedStats.monotonicTasks) + lines[#lines + 1] = "--- 活动窗口栈 ---" + do + local i = 0 + while i < #stack do + local s = stack[i + 1] + lines[#lines + 1] = string.format( + " %d. %s [layer=%s, type=%s, z=%d, vis=%s, block=%s%s]", + i + 1, + s.name, + s.layer, + s.type, + s.zOrder, + s.visible and "Y" or "N", + s.blockWorldClick and "Y" or "N", + s.hiddenByFullscreen and ", hiddenByFull" or "" + ) + i = i + 1 + end + end + lines[#lines + 1] = #cachedNames > 0 and "--- 缓存池:" .. table.concat(cachedNames, ", ") or "--- 缓存池:空" + self.txtDiagDetail:SetText(table.concat(lines, "\n")) + end +end +function UIDemoMainWindow.prototype.AppendLog(self, entry) + local now = self.ctx.scheduler:NowSeconds() + local line = string.format("[%.1fs] %s", now, entry) + self.logLines[#self.logLines + 1] = line + if #self.logLines > 40 then + table.remove(self.logLines, 1) + end + self:RenderLogText() +end +function UIDemoMainWindow.prototype.RenderLogText(self) + if self.txtEventLog ~= nil then + self.txtEventLog:SetText(#self.logLines > 0 and table.concat(self.logLines, "\n") or "[日志已清空]") + end + if self.scrollEventLog ~= nil and self.scrollEventLog.ScrollToEnd ~= nil then + self.scrollEventLog:ScrollToEnd() + end +end +RegisterUIConfig(____exports.UIDemoMainWindow, { + name = "UIDemoMainWindow", + assetKey = ASSET_KEYS.UI_DEMO_MAIN_WIDGET, + singleton = true, + layer = "normal", + type = "normal", + cacheTag = "no_cache", + blockWorldClick = true +}) +function __module.UpdateImports() + Logger = M__share_base_logger.Logger + ScopedObject = M__share_base_scoped_object.ScopedObject + ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS + RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig + UIWindow = M__framework_ui_ui_window.UIWindow + OpenMiniSettings = M__game_startup.OpenMiniSettings + UIDemoCachedWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoCachedWindow + UIDemoFullscreenWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoFullscreenWindow + UIDemoModalWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoModalWindow + UIDemoMultiWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoMultiWindow + UIDemoNormalWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoNormalWindow + UIDemoSystemWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoSystemWindow + UIDemoToastWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoToastWindow +end diff --git a/Script/lua/game/demo/ui_demo/ui_demo_windows.lua b/Script/lua/game/demo/ui_demo/ui_demo_windows.lua new file mode 100644 index 0000000..908a43e --- /dev/null +++ b/Script/lua/game/demo/ui_demo/ui_demo_windows.lua @@ -0,0 +1,471 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local ____exports = __module.env +local M__framework_resource_asset_catalog = __MODULE__.Import("framework.resource.asset_catalog", __module) +local ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS +local M__framework_ui_ui_config = __MODULE__.Import("framework.ui.ui_config", __module) +local RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig +local M__framework_ui_ui_window = __MODULE__.Import("framework.ui.ui_window", __module) +local UIWindow = M__framework_ui_ui_window.UIWindow +____exports.UIDemoNormalWindow = __TS__DefineClass("UIDemoNormalWindow", __module) +local UIDemoNormalWindow = ____exports.UIDemoNormalWindow +UIDemoNormalWindow.name = "UIDemoNormalWindow" +__TS__ClassExtends(UIDemoNormalWindow, UIWindow) +function UIDemoNormalWindow.prototype.____constructor(self, ...) + UIWindow.prototype.____constructor(self, ...) + self.openOrRefreshCount = 0 + self.pingCount = 0 +end +function UIDemoNormalWindow.prototype.OnBindWidgets(self) + self.txtNormalTitle = self:RequireWidget("TxtNormalTitle") + self.txtNormalBody = self:RequireWidget("TxtNormalBody") + self.btnNormalPing = self:RequireWidget("BtnNormalPing") + self.btnNormalClose = self:RequireWidget("BtnNormalClose") + self:BindButtonClick( + self.btnNormalPing, + function() + self.pingCount = self.pingCount + 1 + self:RefreshBody() + self:EmitLog(string.format("[Normal] 触发交互 #%d", self.pingCount)) + end + ) + self:BindButtonClick( + self.btnNormalClose, + function() + self:Close() + end + ) +end +function UIDemoNormalWindow.prototype.OnPreShow(self, args) + local a = args + if a ~= nil and a.onLog ~= nil then + self.onLog = a.onLog + end + self.openOrRefreshCount = self.openOrRefreshCount + 1 + self:RefreshBody() + self:EmitLog(string.format( + "[Normal] OnPreShow(第 %d 次打开/刷新,ZOrder=%d)", + self.openOrRefreshCount, + self:GetZOrder() + )) +end +function UIDemoNormalWindow.prototype.OnClose(self) + self:EmitLog("[Normal] OnClose 窗口已销毁") +end +function UIDemoNormalWindow.prototype.RefreshBody(self) + if self.txtNormalBody ~= nil then + self.txtNormalBody:SetText(string.format( + "Layer: normal | Type: normal | Singleton: true\n当前 ZOrder:%d | 打开/复用刷新次数:%d | 按钮交互:%d 次\n重复点击左侧「普通窗口」不会创建第二个实例,而是直接刷新本窗。", + self:GetZOrder(), + self.openOrRefreshCount, + self.pingCount + )) + end +end +function UIDemoNormalWindow.prototype.EmitLog(self, msg) + if self.onLog ~= nil then + self.onLog(msg) + end +end +RegisterUIConfig(____exports.UIDemoNormalWindow, { + name = "UIDemoNormalWindow", + assetKey = ASSET_KEYS.UI_DEMO_NORMAL_WIDGET, + singleton = true, + layer = "normal", + type = "normal", + cacheTag = "no_cache", + blockWorldClick = true +}) +____exports.UIDemoFullscreenWindow = __TS__DefineClass("UIDemoFullscreenWindow", __module) +local UIDemoFullscreenWindow = ____exports.UIDemoFullscreenWindow +UIDemoFullscreenWindow.name = "UIDemoFullscreenWindow" +__TS__ClassExtends(UIDemoFullscreenWindow, UIWindow) +function UIDemoFullscreenWindow.prototype.OnBindWidgets(self) + self.txtFullDesc = self:RequireWidget("TxtFullDesc") + self.imgFullPreview = self:RequireWidget("ImgFullPreview") + self.btnFullOpenModal = self:RequireWidget("BtnFullOpenModal") + self.btnFullClose = self:RequireWidget("BtnFullClose") + self:BindButtonClick( + self.btnFullOpenModal, + function() + if self.onOpenModal ~= nil then + self.onOpenModal() + end + end + ) + self:BindButtonClick( + self.btnFullClose, + function() + self:Close() + end + ) +end +function UIDemoFullscreenWindow.prototype.OnPreShow(self, args) + local a = args + local ____temp_0 + if a ~= nil then + ____temp_0 = a.onLog + else + ____temp_0 = nil + end + self.onLog = ____temp_0 + local ____temp_1 + if a ~= nil then + ____temp_1 = a.onOpenModal + else + ____temp_1 = nil + end + self.onOpenModal = ____temp_1 + local resSvc = self.ctx:GetService("resource") + if resSvc ~= nil then + resSvc:LoadTextureAsync( + ASSET_KEYS.DEMO_BADGE_B_TEX, + self, + function(ok, tex) + if ok and tex ~= nil and self.imgFullPreview ~= nil and not self:IsDisposed() then + self.imgFullPreview:SetBrushFromTexture(tex, false) + end + end + ) + end + if self.onLog ~= nil then + self.onLog(string.format( + "[Fullscreen] 打开全屏窗口(ZOrder=%d),已自动隐藏下层 Normal 窗口", + self:GetZOrder() + )) + end +end +function UIDemoFullscreenWindow.prototype.OnClose(self) + if self.onLog ~= nil then + self.onLog("[Fullscreen] 关闭全屏窗口,自动恢复下层主界面显示") + end +end +RegisterUIConfig(____exports.UIDemoFullscreenWindow, { + name = "UIDemoFullscreenWindow", + assetKey = ASSET_KEYS.UI_DEMO_FULLSCREEN_WIDGET, + singleton = true, + layer = "normal", + type = "fullscreen", + cacheTag = "no_cache", + blockWorldClick = true +}) +____exports.UIDemoModalWindow = __TS__DefineClass("UIDemoModalWindow", __module) +local UIDemoModalWindow = ____exports.UIDemoModalWindow +UIDemoModalWindow.name = "UIDemoModalWindow" +__TS__ClassExtends(UIDemoModalWindow, UIWindow) +function UIDemoModalWindow.prototype.OnBindWidgets(self) + self.txtModalTitle = self:RequireWidget("TxtModalTitle") + self.txtModalMessage = self:RequireWidget("TxtModalMessage") + self.btnModalConfirm = self:RequireWidget("BtnModalConfirm") + self.btnModalCancel = self:RequireWidget("BtnModalCancel") + self:BindButtonClick( + self.btnModalConfirm, + function() + local cb = self.onConfirm + self:Close() + if cb ~= nil then + cb() + end + end + ) + self:BindButtonClick( + self.btnModalCancel, + function() + local cb = self.onCancel + self:Close() + if cb ~= nil then + cb() + end + end + ) +end +function UIDemoModalWindow.prototype.OnPreShow(self, args) + local a = args + local ____temp_2 + if a ~= nil then + ____temp_2 = a.onConfirm + else + ____temp_2 = nil + end + self.onConfirm = ____temp_2 + local ____temp_3 + if a ~= nil then + ____temp_3 = a.onCancel + else + ____temp_3 = nil + end + self.onCancel = ____temp_3 + if self.txtModalTitle ~= nil then + self.txtModalTitle:SetText(a ~= nil and a.title ~= nil and a.title or "二次确认模态弹窗") + end + if self.txtModalMessage ~= nil then + self.txtModalMessage:SetText(a ~= nil and a.message ~= nil and a.message or "半透明遮罩已拦截底层点击。请选择确认或取消以测试回调透传。") + end +end +RegisterUIConfig(____exports.UIDemoModalWindow, { + name = "UIDemoModalWindow", + assetKey = ASSET_KEYS.UI_DEMO_MODAL_WIDGET, + singleton = true, + layer = "popup", + type = "popup", + cacheTag = "no_cache", + blockWorldClick = true +}) +____exports.UIDemoCachedWindow = __TS__DefineClass("UIDemoCachedWindow", __module) +local UIDemoCachedWindow = ____exports.UIDemoCachedWindow +UIDemoCachedWindow.name = "UIDemoCachedWindow" +__TS__ClassExtends(UIDemoCachedWindow, UIWindow) +function UIDemoCachedWindow.prototype.____constructor(self, ...) + UIWindow.prototype.____constructor(self, ...) + self.reuseCount = 0 + self.clickCount = 0 +end +function UIDemoCachedWindow.prototype.OnBindWidgets(self) + self.txtCachedStats = self:RequireWidget("TxtCachedStats") + self.btnCachedAction = self:RequireWidget("BtnCachedAction") + self.btnCachedClose = self:RequireWidget("BtnCachedClose") + self:BindButtonClick( + self.btnCachedAction, + function() + self.clickCount = self.clickCount + 1 + self:RefreshStats() + self:EmitLog(string.format("[Cached] 点击按钮(累计 %d 次,严格 +1 无重复绑定)", self.clickCount)) + end + ) + self:BindButtonClick( + self.btnCachedClose, + function() + self:Close() + end + ) +end +function UIDemoCachedWindow.prototype.OnReuseUI(self) + self.reuseCount = self.reuseCount + 1 + self:EmitLog(string.format("[Cached] OnReuseUI 命中缓存秒开(第 %d 次复用)", self.reuseCount)) +end +function UIDemoCachedWindow.prototype.OnPreShow(self, args) + local a = args + if a ~= nil and a.onLog ~= nil then + self.onLog = a.onLog + end + self:RefreshStats() + if self.reuseCount == 0 then + self:EmitLog("[Cached] 首次实例化创建成功") + end +end +function UIDemoCachedWindow.prototype.OnClose(self) + self:EmitLog("[Cached] 关闭并归还缓存池(委托已自动解绑)") +end +function UIDemoCachedWindow.prototype.RefreshStats(self) + if self.txtCachedStats ~= nil then + self.txtCachedStats:SetText(string.format( + "缓存复用次数 (OnReuseUI):%d 次\n按钮累计点击:%d 次 | 当前 ZOrder:%d\n关闭后窗口实例进入缓存池,再次打开不重新创建 Widget,且按钮点击不会重复触发。", + self.reuseCount, + self.clickCount, + self:GetZOrder() + )) + end +end +function UIDemoCachedWindow.prototype.EmitLog(self, msg) + if self.onLog ~= nil then + self.onLog(msg) + end +end +RegisterUIConfig(____exports.UIDemoCachedWindow, { + name = "UIDemoCachedWindow", + assetKey = ASSET_KEYS.UI_DEMO_CACHED_WIDGET, + singleton = true, + layer = "popup", + type = "normal", + cacheTag = "cache", + blockWorldClick = true +}) +____exports.UIDemoMultiWindow = __TS__DefineClass("UIDemoMultiWindow", __module) +local UIDemoMultiWindow = ____exports.UIDemoMultiWindow +UIDemoMultiWindow.name = "UIDemoMultiWindow" +__TS__ClassExtends(UIDemoMultiWindow, UIWindow) +function UIDemoMultiWindow.prototype.____constructor(self, ...) + UIWindow.prototype.____constructor(self, ...) + self.instanceSeq = 1 + self.localCount = 0 +end +function UIDemoMultiWindow.prototype.OnBindWidgets(self) + self.multiCard = self:RequireWidget("MultiCard") + self.txtMultiTitle = self:RequireWidget("TxtMultiTitle") + self.txtMultiBody = self:RequireWidget("TxtMultiBody") + self.btnMultiCount = self:RequireWidget("BtnMultiCount") + self.btnMultiClose = self:RequireWidget("BtnMultiClose") + self:BindButtonClick( + self.btnMultiCount, + function() + self.localCount = self.localCount + 1 + self:RefreshDisplay() + self:EmitLog(string.format("[Multi #%d] 独立计数 -> %d", self.instanceSeq, self.localCount)) + end + ) + self:BindButtonClick( + self.btnMultiClose, + function() + self:Close() + end + ) +end +function UIDemoMultiWindow.prototype.OnPreShow(self, args) + local a = args + self.instanceSeq = a ~= nil and a.instanceSeq or 1 + local ____temp_4 + if a ~= nil then + ____temp_4 = a.onLog + else + ____temp_4 = nil + end + self.onLog = ____temp_4 + local slotIndex = (self.instanceSeq - 1) % 6 + local offsetX = -150 + slotIndex * 60 + local offsetY = -90 + slotIndex * 38 + if self.multiCard ~= nil and UE ~= nil and UE.ULuaUIEventSubsystem ~= nil then + local pos = UE.FVector2D() + pos.X = offsetX + pos.Y = offsetY + UE.ULuaUIEventSubsystem.SetCanvasPosition(self.multiCard, pos) + end + self:RefreshDisplay() + self:EmitLog(string.format( + "[Multi #%d] 多实例打开(ZOrder=%d)", + self.instanceSeq, + self:GetZOrder() + )) +end +function UIDemoMultiWindow.prototype.OnClose(self) + self:EmitLog(string.format("[Multi #%d] 已独立关闭", self.instanceSeq)) +end +function UIDemoMultiWindow.prototype.RefreshDisplay(self) + if self.txtMultiTitle ~= nil then + self.txtMultiTitle:SetText(string.format("多实例便签窗 #%d", self.instanceSeq)) + end + if self.txtMultiBody ~= nil then + self.txtMultiBody:SetText(string.format( + "singleton = false | ZOrder = %d\n本实例独立计数:%d\n可连续点击「多实例窗」同时存在多个窗口。", + self:GetZOrder(), + self.localCount + )) + end +end +function UIDemoMultiWindow.prototype.EmitLog(self, msg) + if self.onLog ~= nil then + self.onLog(msg) + end +end +RegisterUIConfig(____exports.UIDemoMultiWindow, { + name = "UIDemoMultiWindow", + assetKey = ASSET_KEYS.UI_DEMO_MULTI_WIDGET, + singleton = false, + layer = "popup", + type = "normal", + cacheTag = "no_cache", + blockWorldClick = true +}) +____exports.UIDemoToastWindow = __TS__DefineClass("UIDemoToastWindow", __module) +local UIDemoToastWindow = ____exports.UIDemoToastWindow +UIDemoToastWindow.name = "UIDemoToastWindow" +__TS__ClassExtends(UIDemoToastWindow, UIWindow) +function UIDemoToastWindow.prototype.OnBindWidgets(self) + self.toastPill = self:RequireWidget("ToastPill") + self.txtToastMessage = self:RequireWidget("TxtToastMessage") +end +function UIDemoToastWindow.prototype.OnPreShow(self, args) + local a = args + local msg = a ~= nil and a.message or "飘字通知" + local duration = a ~= nil and a.durationSec ~= nil and a.durationSec or 2.2 + local offsetIdx = a ~= nil and a.offsetIndex ~= nil and a.offsetIndex or 0 + local ____temp_5 + if a ~= nil then + ____temp_5 = a.onLog + else + ____temp_5 = nil + end + self.onLog = ____temp_5 + if self.txtToastMessage ~= nil then + self.txtToastMessage:SetText(msg) + end + if self.toastPill ~= nil and UE ~= nil and UE.ULuaUIEventSubsystem ~= nil then + local pos = UE.FVector2D() + pos.X = 0 + pos.Y = 92 + offsetIdx % 4 * 48 + UE.ULuaUIEventSubsystem.SetCanvasPosition(self.toastPill, pos) + end + self.ctx.scheduler:AddWorldTimer( + duration, + function() + self:Close() + end, + self + ) + if self.onLog ~= nil then + self.onLog(string.format("[Toast] 弹出提示:%s(%.1fs 后自动关闭,不抢焦点)", msg, duration)) + end +end +RegisterUIConfig(____exports.UIDemoToastWindow, { + name = "UIDemoToastWindow", + assetKey = ASSET_KEYS.UI_DEMO_TOAST_WIDGET, + singleton = false, + layer = "tips", + type = "popup", + cacheTag = "no_cache", + blockWorldClick = false +}) +____exports.UIDemoSystemWindow = __TS__DefineClass("UIDemoSystemWindow", __module) +local UIDemoSystemWindow = ____exports.UIDemoSystemWindow +UIDemoSystemWindow.name = "UIDemoSystemWindow" +__TS__ClassExtends(UIDemoSystemWindow, UIWindow) +function UIDemoSystemWindow.prototype.OnBindWidgets(self) + self.txtSystemBody = self:RequireWidget("TxtSystemBody") + self.btnSystemAck = self:RequireWidget("BtnSystemAck") + self:BindButtonClick( + self.btnSystemAck, + function() + self:Close() + end + ) +end +function UIDemoSystemWindow.prototype.OnPreShow(self, args) + local a = args + local ____temp_6 + if a ~= nil then + ____temp_6 = a.onLog + else + ____temp_6 = nil + end + self.onLog = ____temp_6 + if self.txtSystemBody ~= nil then + self.txtSystemBody:SetText(string.format( + "Layer: system | ZOrder: %d\n优先级始终高于 normal / popup / tips 全部层级,常用于断线重连或强制系统公告。", + self:GetZOrder() + )) + end + if self.onLog ~= nil then + self.onLog(string.format( + "[System] 打开系统级顶层弹窗(ZOrder=%d)", + self:GetZOrder() + )) + end +end +function UIDemoSystemWindow.prototype.OnClose(self) + if self.onLog ~= nil then + self.onLog("[System] 已确认关闭系统弹窗") + end +end +RegisterUIConfig(____exports.UIDemoSystemWindow, { + name = "UIDemoSystemWindow", + assetKey = ASSET_KEYS.UI_DEMO_SYSTEM_WIDGET, + singleton = true, + layer = "system", + type = "popup", + cacheTag = "no_cache", + blockWorldClick = true +}) +function __module.UpdateImports() + ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS + RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig + UIWindow = M__framework_ui_ui_window.UIWindow +end diff --git a/Script/lua/tests/ue/run_ue_tests.lua b/Script/lua/tests/ue/run_ue_tests.lua index 2957ed1..9536890 100644 --- a/Script/lua/tests/ue/run_ue_tests.lua +++ b/Script/lua/tests/ue/run_ue_tests.lua @@ -15,6 +15,19 @@ local M__game_setting_mini_settings_window = __MODULE__.Import("game.setting.min local MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow local M__game_setting_setting_service = __MODULE__.Import("game.setting.setting_service", __module) local SettingService = M__game_setting_setting_service.SettingService +local M__game_demo_demo_hub_window = __MODULE__.Import("game.demo.demo_hub_window", __module) +local DemoHubWindow = M__game_demo_demo_hub_window.DemoHubWindow +local M__game_demo_demo_router = __MODULE__.Import("game.demo.demo_router", __module) +local OpenDemoHub = M__game_demo_demo_router.OpenDemoHub +local OpenUIDemoMain = M__game_demo_demo_router.OpenUIDemoMain +local M__game_demo_ui_demo_ui_demo_windows = __MODULE__.Import("game.demo.ui_demo.ui_demo_windows", __module) +local UIDemoCachedWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoCachedWindow +local UIDemoFullscreenWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoFullscreenWindow +local UIDemoModalWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoModalWindow +local UIDemoMultiWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoMultiWindow +local UIDemoNormalWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoNormalWindow +local UIDemoSystemWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoSystemWindow +local UIDemoToastWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoToastWindow local M__game_startup = __MODULE__.Import("game.startup", __module) local GetPrimaryUIManager = M__game_startup.GetPrimaryUIManager local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) @@ -387,6 +400,232 @@ function ____exports.RunAllUETests(gameInstance, world) UE.ULuaStorageLibrary.DeleteSlot("sdata", 0, true) end }} + }, + { + name = "UE.DemoHubAndUIDemo", + cases = { + { + name = "Bootstrap DemoHubWindow loads Chinese UMG cards and cleans up with zero leaks", + fn = function() + Assert(gameInstance ~= nil and world ~= nil, "GI & World required") + local ctx = GetGameInstanceContext(gameInstance) + local uiMgr = GetPrimaryUIManager(ctx) + local resSvc = ctx:GetService("resource") + local uiBridge = ctx:GetService("uiDelegateBridge") + ctx:OnWorldCleanup(world) + local hubOpened = false + local hub = OpenDemoHub( + ctx, + function(ok) + hubOpened = ok + end + ) + Assert(hub ~= nil, "DemoHubWindow controller created") + PumpUEFrames(25, 0.02) + Assert( + hubOpened and hub:IsLoaded(), + "DemoHubWindow loaded" + ) + Assert(#hub.itemWidgets >= 1, "DemoHub dynamically populated demo cards") + Assert(hub.itemEnterButtons.ui_demo ~= nil, "UI Demo entry button created") + hub:Close() + Assert( + hub:IsDisposed(), + "DemoHubWindow disposed cleanly" + ) + AssertEqual( + uiMgr:GetDiagnostics().openWindows, + 0, + "openWindows back to 0" + ) + AssertEqual( + uiBridge:GetActiveBindingCount(), + 0, + "delegate bindings back to 0" + ) + AssertEqual( + resSvc:GetDiagnostics().nativeTotalRefCount, + 0, + "resource refs back to 0" + ) + end + }, + { + name = "UIDemoMainWindow exercises all UMG widgets and all 7 window types with zero leaks", + fn = function() + Assert(gameInstance ~= nil and world ~= nil, "GI & World required") + local ctx = GetGameInstanceContext(gameInstance) + local uiMgr = GetPrimaryUIManager(ctx) + local resSvc = ctx:GetService("resource") + local uiBridge = ctx:GetService("uiDelegateBridge") + ctx:OnWorldCleanup(world) + local mainOpened = false + local mainWin = OpenUIDemoMain( + ctx, + function(ok) + mainOpened = ok + end + ) + Assert(mainWin ~= nil, "UIDemoMainWindow created") + PumpUEFrames(30, 0.02) + Assert( + mainOpened and mainWin:IsLoaded(), + "UIDemoMainWindow loaded" + ) + Assert( + UE.ULuaUIEventSubsystem.SimulateButtonClick(mainWin.btnDemoAction), + "Button click" + ) + Assert( + UE.ULuaUIEventSubsystem.SimulateButtonHover(mainWin.btnDemoAction, true), + "Button hover" + ) + AssertEqual(mainWin.actionClickCount, 1) + AssertEqual(mainWin.actionHovered, true) + Assert( + UE.ULuaUIEventSubsystem.SimulateCheckBoxToggle(mainWin.chkFeature, true), + "CheckBox toggle" + ) + AssertEqual(mainWin.checkboxChecked, true) + Assert( + UE.ULuaUIEventSubsystem.SimulateSliderValue(mainWin.sliderDemo, 0.75), + "Slider value" + ) + Assert( + math.abs(mainWin.sliderValue - 0.75) < 0.001, + "sliderValue updated" + ) + Assert( + UE.ULuaUIEventSubsystem.SimulateSpinBoxValue(mainWin.spinDemo, 250), + "SpinBox value" + ) + AssertEqual(mainWin.spinValue, 250) + Assert( + UE.ULuaUIEventSubsystem.SimulateEditableTextChange(mainWin.inputNickname, "星河骑士"), + "EditableText change" + ) + AssertEqual(mainWin.draftNickname, "星河骑士") + Assert( + UE.ULuaUIEventSubsystem.SimulateEditableTextCommit(mainWin.inputNickname, "星河骑士", 1), + "EditableText commit" + ) + AssertEqual(mainWin.currentNickname, "星河骑士") + Assert( + UE.ULuaUIEventSubsystem.SimulateComboBoxSelect(mainWin.comboTheme, "翡翠绿(稀有)"), + "ComboBox select" + ) + AssertEqual(mainWin.selectedTheme, "翡翠绿(稀有)") + local bindingsBeforeList = uiBridge:GetActiveBindingCount() + mainWin:AddDynamicListItems(3) + AssertEqual(mainWin.dynamicItemCount, 3, "3 dynamic items added") + Assert( + uiBridge:GetActiveBindingCount() > bindingsBeforeList, + "list item button delegates bound" + ) + mainWin:ClearDynamicListItems() + AssertEqual(mainWin.dynamicItemCount, 0, "dynamic items cleared") + AssertEqual( + uiBridge:GetActiveBindingCount(), + bindingsBeforeList, + "list item delegates fully unbound" + ) + local norm1 = mainWin:OpenNormalDemoWindow() + local norm2 = mainWin:OpenNormalDemoWindow() + AssertEqual(norm1, norm2, "Normal window is singleton") + local fullWin = mainWin:OpenFullscreenDemoWindow() + local modalConfirmed = false + local modalWin = uiMgr:ShowUI( + UIDemoModalWindow, + { + title = "测试弹窗", + message = "测试模态确认", + onConfirm = function() + modalConfirmed = true + end + } + ) + local cachedWin = mainWin:OpenCachedDemoWindow() + local multi1 = mainWin:OpenMultiDemoWindow() + local multi2 = mainWin:OpenMultiDemoWindow() + Assert(multi1 ~= multi2, "Multi-instance creates distinct windows") + local sysWin = mainWin:OpenSystemDemoWindow() + local toastWin = mainWin:ShowToast("自动测试飘字", 0.1) + PumpUEFrames(30, 0.02) + Assert( + toastWin:IsDisposed(), + "Toast auto-closed via WorldTimer" + ) + Assert( + not mainWin:IsVisible(), + "MainWindow hidden while Fullscreen is open" + ) + AssertEqual( + uiMgr:GetDiagnostics().topWindowName, + "UIDemoSystemWindow", + "System window on top" + ) + AssertEqual( + uiMgr:GetDiagnostics().inputMode, + "ui", + "Input mode stays UI" + ) + Assert( + UE.ULuaUIEventSubsystem.SimulateButtonClick(modalWin.btnModalConfirm), + "Click Modal Confirm" + ) + Assert(modalConfirmed, "Modal confirm callback fired") + Assert( + modalWin:IsDisposed(), + "Modal disposed after confirm" + ) + Assert( + UE.ULuaUIEventSubsystem.SimulateButtonClick(cachedWin.btnCachedAction), + "Cached click #1" + ) + AssertEqual(cachedWin.clickCount, 1) + cachedWin:Close() + Assert( + cachedWin:IsCached(), + "Cached window moved to cache" + ) + local cachedReused = mainWin:OpenCachedDemoWindow() + AssertEqual(cachedReused, cachedWin, "Cached window reused") + AssertEqual(cachedReused.reuseCount, 1, "OnReuseUI invoked once") + Assert( + UE.ULuaUIEventSubsystem.SimulateButtonClick(cachedReused.btnCachedAction), + "Cached click #2" + ) + AssertEqual(cachedReused.clickCount, 2, "Cached click after reuse increments by exactly 1") + fullWin:Close() + Assert( + mainWin:IsVisible(), + "MainWindow automatically restored after Fullscreen closed" + ) + uiMgr:CloseAll(true) + AssertEqual( + uiMgr:GetDiagnostics().openWindows, + 0, + "openWindows back to 0" + ) + AssertEqual( + uiMgr:GetDiagnostics().cachedWindows, + 0, + "cachedWindows back to 0" + ) + AssertEqual( + uiBridge:GetActiveBindingCount(), + 0, + "delegate bindings back to 0" + ) + AssertEqual( + resSvc:GetDiagnostics().nativeTotalRefCount, + 0, + "resource refcount back to 0" + ) + Assert(DemoHubWindow ~= nil and UIDemoNormalWindow ~= nil and UIDemoFullscreenWindow ~= nil and UIDemoCachedWindow ~= nil and UIDemoMultiWindow ~= nil and UIDemoToastWindow ~= nil and UIDemoSystemWindow ~= nil, "all demo window classes registered") + end + } + } } } local summary = RunSuites(suites) @@ -401,6 +640,16 @@ function __module.UpdateImports() UEStorageBackend = M__framework_storage_storage_backend.UEStorageBackend MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow SettingService = M__game_setting_setting_service.SettingService + DemoHubWindow = M__game_demo_demo_hub_window.DemoHubWindow + OpenDemoHub = M__game_demo_demo_router.OpenDemoHub + OpenUIDemoMain = M__game_demo_demo_router.OpenUIDemoMain + UIDemoCachedWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoCachedWindow + UIDemoFullscreenWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoFullscreenWindow + UIDemoModalWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoModalWindow + UIDemoMultiWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoMultiWindow + UIDemoNormalWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoNormalWindow + UIDemoSystemWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoSystemWindow + UIDemoToastWindow = M__game_demo_ui_demo_ui_demo_windows.UIDemoToastWindow GetPrimaryUIManager = M__game_startup.GetPrimaryUIManager ScopedObject = M__share_base_scoped_object.ScopedObject Assert = M__tests_harness_test_runner.Assert diff --git a/Script/lua/tests/unit/ui_and_resource_test.lua b/Script/lua/tests/unit/ui_and_resource_test.lua index 98949d5..84ab8e3 100644 --- a/Script/lua/tests/unit/ui_and_resource_test.lua +++ b/Script/lua/tests/unit/ui_and_resource_test.lua @@ -302,6 +302,51 @@ RegisterUIConfig(CachedTestWindow, { layer = "normal", cacheTag = "cache" }) +local FullscreenTestWindow = __TS__DefineClass("FullscreenTestWindow", __module) +FullscreenTestWindow.name = "FullscreenTestWindow" +__TS__ClassExtends(FullscreenTestWindow, UIWindow) +function FullscreenTestWindow.prototype.OnBindWidgets(self) + self:RequireWidget("BtnClose") +end +RegisterUIConfig(FullscreenTestWindow, { + name = "FullscreenTestWindow", + assetKey = ASSET_KEYS.MINI_SETTINGS_WIDGET, + singleton = true, + layer = "normal", + type = "fullscreen", + cacheTag = "no_cache", + blockWorldClick = true +}) +local ToastTestWindow = __TS__DefineClass("ToastTestWindow", __module) +ToastTestWindow.name = "ToastTestWindow" +__TS__ClassExtends(ToastTestWindow, UIWindow) +function ToastTestWindow.prototype.OnBindWidgets(self) + self:RequireWidget("TxtStatus") +end +RegisterUIConfig(ToastTestWindow, { + name = "ToastTestWindow", + assetKey = ASSET_KEYS.MINI_SETTINGS_WIDGET, + singleton = false, + layer = "tips", + type = "popup", + cacheTag = "no_cache", + blockWorldClick = false +}) +local SystemTestWindow = __TS__DefineClass("SystemTestWindow", __module) +SystemTestWindow.name = "SystemTestWindow" +__TS__ClassExtends(SystemTestWindow, UIWindow) +function SystemTestWindow.prototype.OnBindWidgets(self) + self:RequireWidget("BtnClose") +end +RegisterUIConfig(SystemTestWindow, { + name = "SystemTestWindow", + assetKey = ASSET_KEYS.MINI_SETTINGS_WIDGET, + singleton = true, + layer = "system", + type = "popup", + cacheTag = "no_cache", + blockWorldClick = true +}) function ____exports.CreateUIAndResourceSuite() return { name = "Step2B_3.UIAndResource", @@ -467,6 +512,96 @@ function ____exports.CreateUIAndResourceSuite() ) ctx:Dispose() end + }, + { + name = "UIManager fullscreen auto-hide/restore, non-blocking tips focus preservation, and layer ZOrder priority", + fn = function() + local ctx = __TS__New(GameInstanceContext) + local resBackend = __TS__New(MockResourceBackend) + local resSvc = __TS__New(ResourceService, ctx, resBackend) + resBackend.service = resSvc + local btnBackend = __TS__New(MockButtonBackend) + local btnBridge = __TS__New(UIDelegateBridge, ctx, btnBackend) + btnBackend.bridge = btnBridge + ctx:RegisterService("resource", resSvc) + ctx:RegisterService("uiDelegateBridge", btnBridge) + local widgetFactory = __TS__New(MockWidgetFactory) + local lp = ctx:GetOrCreateLocalPlayer(0) + local uiMgr = lp:RegisterService( + "uiManager", + __TS__New( + UIManager, + ctx, + lp, + resSvc, + widgetFactory, + __TS__New(MockWidgetAdapter) + ) + ) + local baseWin = uiMgr:ShowUI(CachedTestWindow) + resBackend:FlushAll() + Assert( + baseWin:IsVisible(), + "base window visible" + ) + AssertEqual( + uiMgr:GetDiagnostics().inputMode, + "ui" + ) + local toast1 = uiMgr:ShowUI(ToastTestWindow) + resBackend:FlushAll() + AssertEqual( + uiMgr:GetDiagnostics().inputMode, + "ui", + "non-blocking tips preserves underlying UI input mode" + ) + AssertEqual( + uiMgr:GetDiagnostics().topWindowName, + "ToastTestWindow", + "tips has higher ZOrder than normal" + ) + toast1:Close() + local fullWin = uiMgr:ShowUI(FullscreenTestWindow) + resBackend:FlushAll() + Assert( + not baseWin:IsVisible(), + "base window hidden while fullscreen is active" + ) + Assert( + baseWin:IsHiddenByFullscreen(), + "base window marked hiddenByFullscreen" + ) + local sysWin = uiMgr:ShowUI(SystemTestWindow) + resBackend:FlushAll() + AssertEqual( + uiMgr:GetDiagnostics().topWindowName, + "SystemTestWindow" + ) + local closedCount = uiMgr:CloseAllExcept(baseWin, false) + AssertEqual(closedCount, 2, "closed fullscreen and system windows") + Assert( + baseWin:IsVisible(), + "base window restored after fullscreen closed" + ) + Assert( + not baseWin:IsHiddenByFullscreen(), + "hiddenByFullscreen cleared" + ) + uiMgr:CloseAll(true) + AssertEqual( + uiMgr:GetDiagnostics().openWindows, + 0 + ) + AssertEqual( + btnBackend:GetActiveBindingCount(), + 0 + ) + AssertEqual( + resSvc:GetDiagnostics().nativeTotalRefCount, + 0 + ) + ctx:Dispose() + end } } } diff --git a/Script/ts/src/framework/resource/asset_catalog.ts b/Script/ts/src/framework/resource/asset_catalog.ts index 76d95bc..fd01ed8 100644 --- a/Script/ts/src/framework/resource/asset_catalog.ts +++ b/Script/ts/src/framework/resource/asset_catalog.ts @@ -3,11 +3,48 @@ export const ASSET_KEYS = { MINI_SETTINGS_ICON: "tex.mini_settings_icon", MINI_SETTINGS_WIDGET: "ui.mini_settings", + + // Demo textures + DEMO_AVATAR_TEX: "tex.demo_avatar", + DEMO_BADGE_A_TEX: "tex.demo_badge_a", + DEMO_BADGE_B_TEX: "tex.demo_badge_b", + + // Bootstrap Demo Hub widgets + DEMO_HUB_WIDGET: "ui.demo_hub", + DEMO_HUB_ITEM_WIDGET: "ui.demo_hub_item", + + // UI Demo widgets + UI_DEMO_MAIN_WIDGET: "ui.demo_ui_main", + UI_DEMO_LIST_ITEM_WIDGET: "ui.demo_ui_list_item", + UI_DEMO_NORMAL_WIDGET: "ui.demo_ui_normal", + UI_DEMO_FULLSCREEN_WIDGET: "ui.demo_ui_fullscreen", + UI_DEMO_MODAL_WIDGET: "ui.demo_ui_modal", + UI_DEMO_CACHED_WIDGET: "ui.demo_ui_cached", + UI_DEMO_MULTI_WIDGET: "ui.demo_ui_multi", + UI_DEMO_TOAST_WIDGET: "ui.demo_ui_toast", + UI_DEMO_SYSTEM_WIDGET: "ui.demo_ui_system", } as const; export const BASE_ASSET_PATHS: Record = { [ASSET_KEYS.MINI_SETTINGS_ICON]: "/Game/UI/Textures/T_MiniSettingsIcon.T_MiniSettingsIcon", [ASSET_KEYS.MINI_SETTINGS_WIDGET]: "/Game/UI/WBP_MiniSettings.WBP_MiniSettings_C", + + [ASSET_KEYS.DEMO_AVATAR_TEX]: "/Game/UI/Textures/T_DemoAvatar.T_DemoAvatar", + [ASSET_KEYS.DEMO_BADGE_A_TEX]: "/Game/UI/Textures/T_DemoBadgeA.T_DemoBadgeA", + [ASSET_KEYS.DEMO_BADGE_B_TEX]: "/Game/UI/Textures/T_DemoBadgeB.T_DemoBadgeB", + + [ASSET_KEYS.DEMO_HUB_WIDGET]: "/Game/UI/Demo/WBP_DemoHub.WBP_DemoHub_C", + [ASSET_KEYS.DEMO_HUB_ITEM_WIDGET]: "/Game/UI/Demo/WBP_DemoHubItem.WBP_DemoHubItem_C", + + [ASSET_KEYS.UI_DEMO_MAIN_WIDGET]: "/Game/UI/Demo/WBP_UIDemoMain.WBP_UIDemoMain_C", + [ASSET_KEYS.UI_DEMO_LIST_ITEM_WIDGET]: "/Game/UI/Demo/WBP_UIDemoListItem.WBP_UIDemoListItem_C", + [ASSET_KEYS.UI_DEMO_NORMAL_WIDGET]: "/Game/UI/Demo/WBP_UIDemoNormal.WBP_UIDemoNormal_C", + [ASSET_KEYS.UI_DEMO_FULLSCREEN_WIDGET]: "/Game/UI/Demo/WBP_UIDemoFullscreen.WBP_UIDemoFullscreen_C", + [ASSET_KEYS.UI_DEMO_MODAL_WIDGET]: "/Game/UI/Demo/WBP_UIDemoModal.WBP_UIDemoModal_C", + [ASSET_KEYS.UI_DEMO_CACHED_WIDGET]: "/Game/UI/Demo/WBP_UIDemoCached.WBP_UIDemoCached_C", + [ASSET_KEYS.UI_DEMO_MULTI_WIDGET]: "/Game/UI/Demo/WBP_UIDemoMulti.WBP_UIDemoMulti_C", + [ASSET_KEYS.UI_DEMO_TOAST_WIDGET]: "/Game/UI/Demo/WBP_UIDemoToast.WBP_UIDemoToast_C", + [ASSET_KEYS.UI_DEMO_SYSTEM_WIDGET]: "/Game/UI/Demo/WBP_UIDemoSystem.WBP_UIDemoSystem_C", }; export function RegisterBaseAssetCatalog(subsystem: UE.ULuaResourceSubsystem): void { diff --git a/Script/ts/src/framework/ui/ui_delegate_bridge.ts b/Script/ts/src/framework/ui/ui_delegate_bridge.ts index 55d2cfc..29ba98c 100644 --- a/Script/ts/src/framework/ui/ui_delegate_bridge.ts +++ b/Script/ts/src/framework/ui/ui_delegate_bridge.ts @@ -10,6 +10,16 @@ export interface IButtonDelegateBackend { BindButtonClicked(button: any): number; UnbindButtonClicked(bindingId: number): boolean; GetActiveBindingCount(): number; + + BindButtonHovered?(button: any): number; + BindButtonUnhovered?(button: any): number; + BindCheckBoxChanged?(checkBox: any): number; + BindSliderChanged?(slider: any): number; + BindSpinBoxChanged?(spinBox: any): number; + BindEditableTextChanged?(textBox: any): number; + BindEditableTextCommitted?(textBox: any): number; + BindComboBoxSelectionChanged?(comboBox: any): number; + UnbindWidgetEvent?(bindingId: number): boolean; } export class UEButtonDelegateBackend implements IButtonDelegateBackend { @@ -23,8 +33,44 @@ export class UEButtonDelegateBackend implements IButtonDelegateBackend { return this.subsystem.BindButtonClicked(button); } + BindButtonHovered(button: UE.UButton): number { + return this.subsystem.BindButtonHovered(button); + } + + BindButtonUnhovered(button: UE.UButton): number { + return this.subsystem.BindButtonUnhovered(button); + } + + BindCheckBoxChanged(checkBox: UE.UCheckBox): number { + return this.subsystem.BindCheckBoxChanged(checkBox); + } + + BindSliderChanged(slider: UE.USlider): number { + return this.subsystem.BindSliderChanged(slider); + } + + BindSpinBoxChanged(spinBox: UE.USpinBox): number { + return this.subsystem.BindSpinBoxChanged(spinBox); + } + + BindEditableTextChanged(textBox: UE.UEditableTextBox): number { + return this.subsystem.BindEditableTextChanged(textBox); + } + + BindEditableTextCommitted(textBox: UE.UEditableTextBox): number { + return this.subsystem.BindEditableTextCommitted(textBox); + } + + BindComboBoxSelectionChanged(comboBox: UE.UComboBoxString): number { + return this.subsystem.BindComboBoxSelectionChanged(comboBox); + } + UnbindButtonClicked(bindingId: number): boolean { - return this.subsystem.UnbindButtonClicked(bindingId); + return this.subsystem.UnbindWidgetEvent(bindingId); + } + + UnbindWidgetEvent(bindingId: number): boolean { + return this.subsystem.UnbindWidgetEvent(bindingId); } GetActiveBindingCount(): number { @@ -32,13 +78,20 @@ export class UEButtonDelegateBackend implements IButtonDelegateBackend { } } -interface ButtonBindingRecord { +type WidgetCallback = + | ((this: void) => void) + | ((this: void, value: boolean) => void) + | ((this: void, value: number) => void) + | ((this: void, text: string) => void) + | ((this: void, text: string, extra: number) => void); + +interface WidgetBindingRecord { bindingId: number; - callback: (this: void) => void; + callback: WidgetCallback; owner?: IsDisposedChecker; } -class ButtonBindingHandle implements IDisposable { +class WidgetBindingHandle implements IDisposable { private bridge: UIDelegateBridge | undefined; private readonly bindingId: number; @@ -61,13 +114,14 @@ const bridgeByGameInstanceKey: Record = {} /** * 纯 TS 侧 UMG 委托桥接器(按 GameInstance 隔离): - * 配合 C++ ULuaUIEventSubsystem 实现纯 TS 控制器绑定 UButton.OnClicked, + * 配合 C++ ULuaUIEventSubsystem 实现纯 TS 控制器绑定常见 UMG 控件委托 + * (Button / CheckBox / Slider / SpinBox / EditableTextBox / ComboBoxString), * 无需 @unlua 继承 UUserWidget,100% 纳入单文件热更与 ScopedObject 自动解绑。 */ export class UIDelegateBridge extends ScopedObject { private readonly backend: IButtonDelegateBackend; private readonly giKey?: string; - private bindings: Record = {}; + private bindings: Record = {}; constructor(ctx: GameInstanceContext, backend: IButtonDelegateBackend) { super(); @@ -78,44 +132,180 @@ export class UIDelegateBridge extends ScopedObject { } } - BindButtonClick(button: any, callback: (this: void) => void, owner?: IsDisposedChecker): IDisposable { - const bindingId = this.backend.BindButtonClicked(button); - assert(bindingId > 0, "UIDelegateBridge.BindButtonClick: failed to bind button"); - + private RegisterBinding(bindingId: number, callback: WidgetCallback, owner?: IsDisposedChecker): IDisposable { + assert(bindingId > 0, "UIDelegateBridge: failed to bind UMG widget event"); this.bindings[bindingId] = { bindingId, callback, owner, }; - - const handle = new ButtonBindingHandle(this, bindingId); + const handle = new WidgetBindingHandle(this, bindingId); if (owner !== undefined && owner instanceof ScopedObject) { owner.AddScopedObject(handle); } return handle; } + BindButtonClick(button: any, callback: (this: void) => void, owner?: IsDisposedChecker): IDisposable { + const bindingId = this.backend.BindButtonClicked(button); + return this.RegisterBinding(bindingId, callback, owner); + } + + BindButtonHovered(button: any, callback: (this: void) => void, owner?: IsDisposedChecker): IDisposable { + assert(this.backend.BindButtonHovered !== undefined, "UIDelegateBridge backend does not support BindButtonHovered"); + const bindingId = this.backend.BindButtonHovered!(button); + return this.RegisterBinding(bindingId, callback, owner); + } + + BindButtonUnhovered(button: any, callback: (this: void) => void, owner?: IsDisposedChecker): IDisposable { + assert(this.backend.BindButtonUnhovered !== undefined, "UIDelegateBridge backend does not support BindButtonUnhovered"); + const bindingId = this.backend.BindButtonUnhovered!(button); + return this.RegisterBinding(bindingId, callback, owner); + } + + BindCheckBoxChanged( + checkBox: any, + callback: (this: void, isChecked: boolean) => void, + owner?: IsDisposedChecker + ): IDisposable { + assert(this.backend.BindCheckBoxChanged !== undefined, "UIDelegateBridge backend does not support BindCheckBoxChanged"); + const bindingId = this.backend.BindCheckBoxChanged!(checkBox); + return this.RegisterBinding(bindingId, callback, owner); + } + + BindSliderChanged( + slider: any, + callback: (this: void, value: number) => void, + owner?: IsDisposedChecker + ): IDisposable { + assert(this.backend.BindSliderChanged !== undefined, "UIDelegateBridge backend does not support BindSliderChanged"); + const bindingId = this.backend.BindSliderChanged!(slider); + return this.RegisterBinding(bindingId, callback, owner); + } + + BindSpinBoxChanged( + spinBox: any, + callback: (this: void, value: number) => void, + owner?: IsDisposedChecker + ): IDisposable { + assert(this.backend.BindSpinBoxChanged !== undefined, "UIDelegateBridge backend does not support BindSpinBoxChanged"); + const bindingId = this.backend.BindSpinBoxChanged!(spinBox); + return this.RegisterBinding(bindingId, callback, owner); + } + + BindEditableTextChanged( + textBox: any, + callback: (this: void, text: string) => void, + owner?: IsDisposedChecker + ): IDisposable { + assert( + this.backend.BindEditableTextChanged !== undefined, + "UIDelegateBridge backend does not support BindEditableTextChanged" + ); + const bindingId = this.backend.BindEditableTextChanged!(textBox); + return this.RegisterBinding(bindingId, callback, owner); + } + + BindEditableTextCommitted( + textBox: any, + callback: (this: void, text: string, commitMethod: number) => void, + owner?: IsDisposedChecker + ): IDisposable { + assert( + this.backend.BindEditableTextCommitted !== undefined, + "UIDelegateBridge backend does not support BindEditableTextCommitted" + ); + const bindingId = this.backend.BindEditableTextCommitted!(textBox); + return this.RegisterBinding(bindingId, callback, owner); + } + + BindComboBoxSelectionChanged( + comboBox: any, + callback: (this: void, selectedItem: string, selectType: number) => void, + owner?: IsDisposedChecker + ): IDisposable { + assert( + this.backend.BindComboBoxSelectionChanged !== undefined, + "UIDelegateBridge backend does not support BindComboBoxSelectionChanged" + ); + const bindingId = this.backend.BindComboBoxSelectionChanged!(comboBox); + return this.RegisterBinding(bindingId, callback, owner); + } + UnbindById(bindingId: number): void { if (this.bindings[bindingId] === undefined) { return; } this.bindings[bindingId] = undefined; - this.backend.UnbindButtonClicked(bindingId); + if (this.backend.UnbindWidgetEvent !== undefined) { + this.backend.UnbindWidgetEvent(bindingId); + } else { + this.backend.UnbindButtonClicked(bindingId); + } } - DispatchButtonClicked(bindingId: number): void { + private ResolveLiveRecord(bindingId: number): WidgetBindingRecord | undefined { if (this.IsDisposed()) { - return; + return undefined; } const rec = this.bindings[bindingId]; if (rec === undefined) { - return; + return undefined; } if (rec.owner !== undefined && rec.owner.IsDisposed()) { this.UnbindById(bindingId); - return; + return undefined; + } + return rec; + } + + DispatchButtonClicked(bindingId: number): void { + const rec = this.ResolveLiveRecord(bindingId); + if (rec !== undefined) { + tbpcall(rec.callback as (this: void) => void); + } + } + + DispatchActionEvent(bindingId: number): void { + const rec = this.ResolveLiveRecord(bindingId); + if (rec !== undefined) { + tbpcall(rec.callback as (this: void) => void); + } + } + + DispatchBoolChanged(bindingId: number, value: boolean): void { + const rec = this.ResolveLiveRecord(bindingId); + if (rec !== undefined) { + tbpcall(rec.callback as (this: void, v: boolean) => void, value); + } + } + + DispatchFloatChanged(bindingId: number, value: number): void { + const rec = this.ResolveLiveRecord(bindingId); + if (rec !== undefined) { + tbpcall(rec.callback as (this: void, v: number) => void, value); + } + } + + DispatchTextChanged(bindingId: number, text: string): void { + const rec = this.ResolveLiveRecord(bindingId); + if (rec !== undefined) { + tbpcall(rec.callback as (this: void, t: string) => void, text); + } + } + + DispatchTextCommitted(bindingId: number, text: string, commitMethod: number): void { + const rec = this.ResolveLiveRecord(bindingId); + if (rec !== undefined) { + tbpcall(rec.callback as (this: void, t: string, m: number) => void, text, commitMethod); + } + } + + DispatchSelectionChanged(bindingId: number, selectedItem: string, selectType: number): void { + const rec = this.ResolveLiveRecord(bindingId); + if (rec !== undefined) { + tbpcall(rec.callback as (this: void, s: string, t: number) => void, selectedItem, selectType); } - tbpcall(rec.callback); } GetActiveBindingCount(): number { @@ -140,10 +330,7 @@ export class UIDelegateBridge extends ScopedObject { } } -/** - * 供 C++ FLuaCallbackBridge::CallInt 回调的纯函数入口。 - * @noSelf - */ +/** @noSelf */ export function OnNativeButtonClicked(gameInstance: UE.ULuaGameInstance, bindingId: number): void { const bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)]; if (bridge !== undefined) { @@ -151,6 +338,64 @@ export function OnNativeButtonClicked(gameInstance: UE.ULuaGameInstance, binding } } +/** @noSelf */ +export function OnNativeActionEvent(gameInstance: UE.ULuaGameInstance, bindingId: number): void { + const bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)]; + if (bridge !== undefined) { + bridge.DispatchActionEvent(bindingId); + } +} + +/** @noSelf */ +export function OnNativeBoolChanged(gameInstance: UE.ULuaGameInstance, bindingId: number, value: boolean): void { + const bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)]; + if (bridge !== undefined) { + bridge.DispatchBoolChanged(bindingId, value); + } +} + +/** @noSelf */ +export function OnNativeFloatChanged(gameInstance: UE.ULuaGameInstance, bindingId: number, value: number): void { + const bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)]; + if (bridge !== undefined) { + bridge.DispatchFloatChanged(bindingId, value); + } +} + +/** @noSelf */ +export function OnNativeTextChanged(gameInstance: UE.ULuaGameInstance, bindingId: number, text: string): void { + const bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)]; + if (bridge !== undefined) { + bridge.DispatchTextChanged(bindingId, text); + } +} + +/** @noSelf */ +export function OnNativeTextCommitted( + gameInstance: UE.ULuaGameInstance, + bindingId: number, + text: string, + commitMethod: number +): void { + const bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)]; + if (bridge !== undefined) { + bridge.DispatchTextCommitted(bindingId, text, commitMethod); + } +} + +/** @noSelf */ +export function OnNativeSelectionChanged( + gameInstance: UE.ULuaGameInstance, + bindingId: number, + selectedItem: string, + selectType: number +): void { + const bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)]; + if (bridge !== undefined) { + bridge.DispatchSelectionChanged(bindingId, selectedItem, selectType); + } +} + /** @noSelf */ export function CreateUEUIDelegateBridge(ctx: GameInstanceContext): UIDelegateBridge | undefined { if (ctx.gameInstance === undefined) { diff --git a/Script/ts/src/framework/ui/ui_manager.ts b/Script/ts/src/framework/ui/ui_manager.ts index b71d2df..3733e4e 100644 --- a/Script/ts/src/framework/ui/ui_manager.ts +++ b/Script/ts/src/framework/ui/ui_manager.ts @@ -5,7 +5,7 @@ import { EventHub } from "../../share/event/event_hub"; import { tbpcall } from "../../share/base/traceback"; import type { GameInstanceContext, LocalPlayerContext } from "../context/game_context"; import type { ResourceService } from "../resource/resource_service"; -import { GetUIConfig, UI_LAYER_ZORDER, type UIConfigItem } from "./ui_config"; +import { GetUIConfig, UI_LAYER_ZORDER, type UICacheTag, type UIConfigItem, type UILayer, type UIType } from "./ui_config"; import type { IWidgetAdapter, UIWindow } from "./ui_window"; const logger = Logger("UIManager"); @@ -28,6 +28,19 @@ export interface UIDiagnostics { inputMode: "game" | "ui"; } +export interface WindowStackEntry { + name: string; + layer: UILayer; + type: UIType; + zOrder: number; + visible: boolean; + loading: boolean; + singleton: boolean; + cacheTag: UICacheTag; + blockWorldClick: boolean; + hiddenByFullscreen: boolean; +} + export class UEWidgetAdapter implements IWidgetAdapter { FindChild(widget: UE.UUserWidget, name: string): UE.UWidget | undefined { return UE.ULuaUIEventSubsystem.FindChildWidgetByName(widget, name); @@ -78,7 +91,7 @@ export class UEWidgetFactory implements IWidgetFactory { /** * 玩家级窗口管理器(归属 LocalPlayerContext,支持多 PIE 实例隔离): * - 单例去重与并发打开防重复创建; - * - 窗口栈 ZOrder 层级管理、缓存复用与焦点/输入模式恢复; + * - 窗口栈 ZOrder 层级管理、全屏互斥隐藏/恢复、缓存复用与焦点/输入模式恢复; * - 切图/退出时安全取消在途加载并释放所有窗口与缓存。 */ export class UIManager extends ScopedObject { @@ -143,6 +156,7 @@ export class UIManager extends ScopedObject { if (existing.IsLoaded()) { const zOrder = this.AllocateZOrder(config); existing.ShowInternal(zOrder, args); + this.SyncFullscreenVisibility(); this.SyncFocusAndInputMode(); if (onOpened !== undefined) { tbpcall(onOpened, true, existing as T, undefined); @@ -169,6 +183,7 @@ export class UIManager extends ScopedObject { this.windowStack[this.windowStack.length] = cached; const zOrder = this.AllocateZOrder(config); cached.ReuseInternal(zOrder, args); + this.SyncFullscreenVisibility(); this.SyncFocusAndInputMode(); this.events.emit.OnWindowOpened(config.name, cached); if (onOpened !== undefined) { @@ -228,6 +243,7 @@ export class UIManager extends ScopedObject { win.AttachWidgetInternal(widget); const zOrder = this.AllocateZOrder(config); win.ShowInternal(zOrder, args); + this.SyncFullscreenVisibility(); this.SyncFocusAndInputMode(); this.events.emit.OnWindowOpened(config.name, win); if (onOpened !== undefined) { @@ -255,14 +271,48 @@ export class UIManager extends ScopedObject { } } + /** + * 按实际 ZOrder 优先返回当前顶层活动窗口(而非纯打开顺序), + * 确保高 Layer(如 system / popup)始终正确识别为顶层窗口。 + */ GetTopWindow(): UIWindow | undefined { - for (let i = this.windowStack.length - 1; i >= 0; i--) { + let best: UIWindow | undefined = undefined; + let bestZOrder = -1; + for (let i = 0; i < this.windowStack.length; i++) { const win = this.windowStack[i]; - if (!win.IsDisposed() && !win.IsClosing()) { - return win; + if (win.IsDisposed() || win.IsClosing()) { + continue; + } + const z = win.IsLoaded() ? win.GetZOrder() : UI_LAYER_ZORDER[win.config.layer]; + if (best === undefined || z >= bestZOrder) { + best = win; + bestZOrder = z; } } - return undefined; + return best; + } + + /** + * 返回当前最高 ZOrder 的可见且需要 UI 输入焦点的窗口(跳过 tips 等非阻塞窗口)。 + */ + GetTopBlockingWindow(): UIWindow | undefined { + let best: UIWindow | undefined = undefined; + let bestZOrder = -1; + for (let i = 0; i < this.windowStack.length; i++) { + const win = this.windowStack[i]; + if (win.IsDisposed() || win.IsClosing() || !win.config.blockWorldClick) { + continue; + } + if (win.IsLoaded() && !win.IsVisible()) { + continue; + } + const z = win.IsLoaded() ? win.GetZOrder() : UI_LAYER_ZORDER[win.config.layer]; + if (best === undefined || z >= bestZOrder) { + best = win; + bestZOrder = z; + } + } + return best; } HandleWindowCachedInternal(win: UIWindow): void { @@ -272,17 +322,19 @@ export class UIManager extends ScopedObject { oldCached.ForceDisposeFromCacheInternal(); } this.cachedByName[win.config.name] = win; + this.SyncFullscreenVisibility(); this.SyncFocusAndInputMode(); this.events.emit.OnWindowClosed(win.config.name, win); } HandleWindowClosedInternal(win: UIWindow): void { this.RemoveFromStackAndSingleton(win); + this.SyncFullscreenVisibility(); this.SyncFocusAndInputMode(); this.events.emit.OnWindowClosed(win.config.name, win); } - EvictCache(): void { + EvictCache(): number { const toEvict: UIWindow[] = []; for (const [name, win] of pairs(this.cachedByName)) { if (win !== undefined) { @@ -293,6 +345,25 @@ export class UIManager extends ScopedObject { for (let i = 0; i < toEvict.length; i++) { toEvict[i].ForceDisposeFromCacheInternal(); } + return toEvict.length; + } + + CloseAllExcept(keepWindow: UIWindow, alsoEvictCache = false): number { + const copy: UIWindow[] = []; + for (let i = this.windowStack.length - 1; i >= 0; i--) { + if (this.windowStack[i] !== keepWindow) { + copy[copy.length] = this.windowStack[i]; + } + } + for (let i = 0; i < copy.length; i++) { + copy[i].Close(); + } + if (alsoEvictCache) { + this.EvictCache(); + } + this.SyncFullscreenVisibility(); + this.SyncFocusAndInputMode(); + return copy.length; } CloseAll(alsoEvictCache = true): void { @@ -309,6 +380,39 @@ export class UIManager extends ScopedObject { this.SyncFocusAndInputMode(); } + GetWindowStackSnapshot(): WindowStackEntry[] { + const list: WindowStackEntry[] = []; + for (let i = 0; i < this.windowStack.length; i++) { + const w = this.windowStack[i]; + if (!w.IsDisposed()) { + list[list.length] = { + name: w.config.name, + layer: w.config.layer, + type: w.config.type, + zOrder: w.GetZOrder(), + visible: w.IsVisible(), + loading: w.IsLoading(), + singleton: w.config.singleton, + cacheTag: w.config.cacheTag, + blockWorldClick: w.config.blockWorldClick, + hiddenByFullscreen: w.IsHiddenByFullscreen(), + }; + } + } + return list; + } + + GetCachedWindowNames(): string[] { + const names: string[] = []; + for (const [name, w] of pairs(this.cachedByName)) { + if (w !== undefined && !w.IsDisposed()) { + names[names.length] = name; + } + } + table.sort(names); + return names; + } + GetDiagnostics(): UIDiagnostics { let openWindows = 0; let loadingWindows = 0; @@ -355,9 +459,56 @@ export class UIManager extends ScopedObject { } } + /** + * 全屏窗口互斥管理: + * 打开 type="fullscreen" 窗口时,自动隐藏其下方的 background/normal 窗口; + * 全屏窗口关闭后,自动恢复原先被隐藏的下层窗口显示。 + */ + private SyncFullscreenVisibility(): void { + let topFullscreen: UIWindow | undefined = undefined; + let topFullscreenZ = -1; + + for (let i = 0; i < this.windowStack.length; i++) { + const win = this.windowStack[i]; + if ( + !win.IsDisposed() && + !win.IsClosing() && + win.IsLoaded() && + win.config.type === "fullscreen" + ) { + const z = win.GetZOrder(); + if (topFullscreen === undefined || z >= topFullscreenZ) { + topFullscreen = win; + topFullscreenZ = z; + } + } + } + + for (let i = 0; i < this.windowStack.length; i++) { + const win = this.windowStack[i]; + if (win.IsDisposed() || win.IsClosing() || !win.IsLoaded()) { + continue; + } + const affectedLayer = win.config.layer === "background" || win.config.layer === "normal"; + if (!affectedLayer) { + continue; + } + + if (topFullscreen !== undefined && win !== topFullscreen && win.GetZOrder() < topFullscreenZ) { + if (win.IsVisible()) { + win.SetHiddenByFullscreenInternal(true); + win.Hide(); + } + } else if (win.IsHiddenByFullscreen()) { + win.RestoreFromFullscreenInternal(); + } + } + } + private SyncFocusAndInputMode(): void { - const top = this.GetTopWindow(); - const nextMode: "game" | "ui" = top !== undefined && top.config.blockWorldClick ? "ui" : "game"; + const topBlocking = this.GetTopBlockingWindow(); + const topAny = this.GetTopWindow(); + const nextMode: "game" | "ui" = topBlocking !== undefined ? "ui" : "game"; this.inputMode = nextMode; const pc = this.playerCtx.playerController; @@ -366,7 +517,7 @@ export class UIManager extends ScopedObject { pc.bShowMouseCursor = true; UE.UWidgetBlueprintLibrary.SetInputMode_UIOnlyEx( pc, - top !== undefined ? (top.GetWidget() as UE.UWidget | undefined) : undefined, + topBlocking !== undefined ? (topBlocking.GetWidget() as UE.UWidget | undefined) : undefined, UE.EMouseLockMode.DoNotLock, false ); @@ -376,7 +527,7 @@ export class UIManager extends ScopedObject { } } - this.events.emit.OnFocusRestored(top !== undefined ? top.config.name : undefined); + this.events.emit.OnFocusRestored(topAny !== undefined ? topAny.config.name : undefined); } override Dispose(): void { diff --git a/Script/ts/src/framework/ui/ui_window.ts b/Script/ts/src/framework/ui/ui_window.ts index b42e246..b2d5ec9 100644 --- a/Script/ts/src/framework/ui/ui_window.ts +++ b/Script/ts/src/framework/ui/ui_window.ts @@ -19,9 +19,9 @@ export interface IWidgetAdapter { } /** - * 纯 TS UMG 窗口控制器基类(拆分原 GameObjectWrapper 继承 -> 组合持有 UUserWidget 视图): - * - 100% 纳入 ts2lua-unreal v0.3.0 单文件热更闭环; - * - 统一托管资源加载句柄、按钮委托绑定、事件监听与防重入关闭状态机。 + * 纯 TS UMG 窗口控制器基类(组合持有 UUserWidget 视图): + * - 100% 纳入 ts2lua-unreal 单文件热更闭环; + * - 统一托管资源加载句柄、全部 UMG 控件委托绑定、事件监听与防重入关闭状态机。 */ export abstract class UIWindow extends ScopedObject { public config!: UIConfigItem; @@ -35,8 +35,10 @@ export abstract class UIWindow extends ScopedObject { private isVisible = false; private isClosing = false; private isCached = false; + private hiddenByFullscreen = false; + private currentZOrder = 0; private classLoadHandle?: ResourceLoadHandle; - private buttonBindings: IDisposable[] = []; + private widgetBindings: IDisposable[] = []; InitContextInternal( ctx: GameInstanceContext, @@ -54,6 +56,10 @@ export abstract class UIWindow extends ScopedObject { return this.widget; } + GetZOrder(): number { + return this.currentZOrder; + } + IsLoading(): boolean { return this.isLoading; } @@ -74,6 +80,14 @@ export abstract class UIWindow extends ScopedObject { return this.isCached; } + IsHiddenByFullscreen(): boolean { + return this.hiddenByFullscreen; + } + + SetHiddenByFullscreenInternal(hidden: boolean): void { + this.hiddenByFullscreen = hidden; + } + SetLoadingStateInternal(loading: boolean, handle?: ResourceLoadHandle): void { this.isLoading = loading; this.classLoadHandle = handle; @@ -100,31 +114,104 @@ export abstract class UIWindow extends ScopedObject { return child as T; } - /** - * 绑定 UButton 点击事件,缓存/关闭/销毁时统一成对解绑,防止复用重复上报。 - */ - protected BindButtonClick(button: any, callback: (this: void) => void): IDisposable | undefined { + private TrackWidgetBinding(handle: IDisposable | undefined): IDisposable | undefined { + if (handle !== undefined) { + this.widgetBindings[this.widgetBindings.length] = handle; + } + return handle; + } + + private GetDelegateBridge(): UIDelegateBridge | undefined { const bridge = this.ctx.GetService("uiDelegateBridge"); if (bridge === undefined) { logger.Warn("UIDelegateBridge not registered on context", { window: this.config.name }); return undefined; } - const handle = bridge.BindButtonClick(button, callback, this); - this.buttonBindings[this.buttonBindings.length] = handle; - return handle; + return bridge; } - private UnbindAllButtons(): void { - for (let i = 0; i < this.buttonBindings.length; i++) { - this.buttonBindings[i].Dispose(); + /** + * 绑定 UButton 点击事件,缓存/关闭/销毁时统一成对解绑,防止复用重复上报。 + */ + protected BindButtonClick(button: any, callback: (this: void) => void): IDisposable | undefined { + const bridge = this.GetDelegateBridge(); + if (bridge === undefined) return undefined; + return this.TrackWidgetBinding(bridge.BindButtonClick(button, callback, this)); + } + + protected BindButtonHovered(button: any, callback: (this: void) => void): IDisposable | undefined { + const bridge = this.GetDelegateBridge(); + if (bridge === undefined) return undefined; + return this.TrackWidgetBinding(bridge.BindButtonHovered(button, callback, this)); + } + + protected BindButtonUnhovered(button: any, callback: (this: void) => void): IDisposable | undefined { + const bridge = this.GetDelegateBridge(); + if (bridge === undefined) return undefined; + return this.TrackWidgetBinding(bridge.BindButtonUnhovered(button, callback, this)); + } + + protected BindCheckBoxChanged( + checkBox: any, + callback: (this: void, isChecked: boolean) => void + ): IDisposable | undefined { + const bridge = this.GetDelegateBridge(); + if (bridge === undefined) return undefined; + return this.TrackWidgetBinding(bridge.BindCheckBoxChanged(checkBox, callback, this)); + } + + protected BindSliderChanged(slider: any, callback: (this: void, value: number) => void): IDisposable | undefined { + const bridge = this.GetDelegateBridge(); + if (bridge === undefined) return undefined; + return this.TrackWidgetBinding(bridge.BindSliderChanged(slider, callback, this)); + } + + protected BindSpinBoxChanged(spinBox: any, callback: (this: void, value: number) => void): IDisposable | undefined { + const bridge = this.GetDelegateBridge(); + if (bridge === undefined) return undefined; + return this.TrackWidgetBinding(bridge.BindSpinBoxChanged(spinBox, callback, this)); + } + + protected BindEditableTextChanged( + textBox: any, + callback: (this: void, text: string) => void + ): IDisposable | undefined { + const bridge = this.GetDelegateBridge(); + if (bridge === undefined) return undefined; + return this.TrackWidgetBinding(bridge.BindEditableTextChanged(textBox, callback, this)); + } + + protected BindEditableTextCommitted( + textBox: any, + callback: (this: void, text: string, commitMethod: number) => void + ): IDisposable | undefined { + const bridge = this.GetDelegateBridge(); + if (bridge === undefined) return undefined; + return this.TrackWidgetBinding(bridge.BindEditableTextCommitted(textBox, callback, this)); + } + + protected BindComboBoxChanged( + comboBox: any, + callback: (this: void, selectedItem: string, selectType: number) => void + ): IDisposable | undefined { + const bridge = this.GetDelegateBridge(); + if (bridge === undefined) return undefined; + return this.TrackWidgetBinding(bridge.BindComboBoxSelectionChanged(comboBox, callback, this)); + } + + private UnbindAllWidgetEvents(): void { + for (let i = 0; i < this.widgetBindings.length; i++) { + this.widgetBindings[i].Dispose(); } - this.buttonBindings = []; + this.widgetBindings = []; } ShowInternal(zOrder: number, args?: unknown): void { if (this.IsDisposed() || this.isClosing) { return; } + this.currentZOrder = zOrder; + this.hiddenByFullscreen = false; tbpcall(() => { this.OnPreShow(args); }); @@ -144,6 +231,7 @@ export abstract class UIWindow extends ScopedObject { } this.isCached = false; this.isClosing = false; + this.hiddenByFullscreen = false; this.EnableAllEventListeners(); this.OnBindWidgets(); tbpcall(() => { @@ -152,6 +240,23 @@ export abstract class UIWindow extends ScopedObject { this.ShowInternal(zOrder, args); } + RestoreFromFullscreenInternal(): void { + if (this.IsDisposed() || this.isClosing || this.isCached || !this.isLoaded) { + return; + } + this.hiddenByFullscreen = false; + if (this.isVisible) { + return; + } + if (this.widget !== undefined && this.widgetAdapter.IsWidgetValid(this.widget)) { + this.widgetAdapter.SetVisible(this.widget, true); + } + this.isVisible = true; + tbpcall(() => { + this.OnShow(); + }); + } + Hide(): void { if (!this.isVisible) { return; @@ -169,7 +274,7 @@ export abstract class UIWindow extends ScopedObject { * 幂等且防重入的窗口关闭入口: * - 加载中关闭:取消在途类加载句柄,直接收尾; * - 关闭中重复 Close:直接忽略; - * - 缓存策略窗口:解绑按钮委托、暂停事件监听、从视口摘除并交还缓存池; + * - 缓存策略窗口:解绑控件委托、暂停事件监听、从视口摘除并交还缓存池; * - 非缓存窗口:执行 OnClose、解绑并 Dispose 全部托管资源。 */ Close(onClosed?: (this: void) => void): void { @@ -193,9 +298,10 @@ export abstract class UIWindow extends ScopedObject { if (canCache) { this.isVisible = false; + this.hiddenByFullscreen = false; this.isCached = true; this.isClosing = false; - this.UnbindAllButtons(); + this.UnbindAllWidgetEvents(); this.DisableAllEventListeners(); this.widgetAdapter.RemoveFromParent(this.widget); tbpcall(() => { @@ -215,7 +321,8 @@ export abstract class UIWindow extends ScopedObject { } this.isVisible = false; - this.UnbindAllButtons(); + this.hiddenByFullscreen = false; + this.UnbindAllWidgetEvents(); if (this.widget !== undefined && this.widgetAdapter.IsWidgetValid(this.widget)) { this.widgetAdapter.RemoveFromParent(this.widget); } @@ -231,7 +338,8 @@ export abstract class UIWindow extends ScopedObject { ForceDisposeFromCacheInternal(): void { this.isCached = false; - this.UnbindAllButtons(); + this.hiddenByFullscreen = false; + this.UnbindAllWidgetEvents(); if (this.widget !== undefined && this.widgetAdapter.IsWidgetValid(this.widget)) { this.widgetAdapter.RemoveFromParent(this.widget); } diff --git a/Script/ts/src/game/bootstrap_player.ts b/Script/ts/src/game/bootstrap_player.ts index ddaade9..ecdeade 100644 --- a/Script/ts/src/game/bootstrap_player.ts +++ b/Script/ts/src/game/bootstrap_player.ts @@ -1,10 +1,10 @@ /** @noSelfInFile */ import { GetGameInstanceContext } from "../framework/context/game_context"; -import { OpenMiniSettings } from "./startup"; +import { RouteCurrentLevel } from "./demo/demo_router"; /** - * PIE / 启动地图玩家入口:绑定 LocalPlayer(0) 的 PlayerController 并打开首期最小设置窗口。 + * PIE / 启动地图玩家入口:绑定 LocalPlayer(0) 的 PlayerController 并按当前关卡路由对应 Demo 场景。 */ export function OnBeginPlay(pc: UE.ALuaPlayerController): void { const world = pc.GetWorld(); @@ -20,7 +20,7 @@ export function OnBeginPlay(pc: UE.ALuaPlayerController): void { ctx.OnWorldCleanup(world); } ctx.GetOrCreateLocalPlayer(0, pc); - OpenMiniSettings(ctx); + RouteCurrentLevel(ctx, pc); } export function OnEndPlay(pc: UE.ALuaPlayerController, _endPlayReason: number): void { diff --git a/Script/ts/src/game/demo/demo_hub_window.ts b/Script/ts/src/game/demo/demo_hub_window.ts new file mode 100644 index 0000000..a8b86fc --- /dev/null +++ b/Script/ts/src/game/demo/demo_hub_window.ts @@ -0,0 +1,183 @@ +import type { IDisposable } from "../../share/base/interface"; +import { Logger } from "../../share/base/logger"; +import { ScopedObject } from "../../share/base/scoped_object"; +import { ASSET_KEYS } from "../../framework/resource/asset_catalog"; +import type { ResourceService } from "../../framework/resource/resource_service"; +import { RegisterUIConfig } from "../../framework/ui/ui_config"; +import type { UIDelegateBridge } from "../../framework/ui/ui_delegate_bridge"; +import { UIWindow } from "../../framework/ui/ui_window"; +import { OpenMiniSettings } from "../startup"; +import { GetDemoScenes, type DemoSceneDescriptor } from "./demo_registry"; + +const logger = Logger("DemoHubWindow"); + +export interface DemoHubOpenArgs { + onSelectDemo?: (this: void, demo: DemoSceneDescriptor) => void; +} + +/** + * Bootstrap 关卡的 Demo 场景切换面板(绑定 /Game/UI/Demo/WBP_DemoHub): + * - 动态读取 DemoRegistry 渲染场景入口卡片; + * - 支持一键切换至各个 Demo 关卡,并保留已有 MiniSettings 快捷验证入口。 + */ +export class DemoHubWindow extends UIWindow { + public txtRuntimeInfo?: UE.UTextBlock; + public scrollDemoList?: UE.UScrollBox; + public btnOpenMiniSettings?: UE.UButton; + + public itemWidgets: UE.UUserWidget[] = []; + public itemEnterButtons: Record = {}; + + private itemScope?: ScopedObject; + private onSelectDemo?: (this: void, demo: DemoSceneDescriptor) => void; + + protected override OnBindWidgets(): void { + this.txtRuntimeInfo = this.RequireWidget("TxtRuntimeInfo"); + this.scrollDemoList = this.RequireWidget("ScrollDemoList"); + this.btnOpenMiniSettings = this.RequireWidget("BtnOpenMiniSettings"); + + this.BindButtonClick(this.btnOpenMiniSettings, () => { + OpenMiniSettings(this.ctx); + }); + } + + protected override OnPreShow(args?: unknown): void { + const openArgs = args as DemoHubOpenArgs | undefined; + this.onSelectDemo = openArgs !== undefined ? openArgs.onSelectDemo : undefined; + + this.RefreshRuntimeInfo(); + this.PopulateDemoCards(); + } + + protected override OnClose(): void { + this.ClearDemoCards(); + } + + private RefreshRuntimeInfo(): void { + const resSvc = this.ctx.GetService("resource"); + const modeText = resSvc !== undefined && resSvc.IsPackagedMode() ? "Packaged" : "PIE / Editor"; + const info = string.format( + "Lua 运行时:%s | Context #%d | 资源模式:%s | 已注册 Demo:%d 个", + _VERSION, + this.ctx.contextId, + modeText, + GetDemoScenes().length + ); + if (this.txtRuntimeInfo !== undefined && this.txtRuntimeInfo.SetText !== undefined) { + this.txtRuntimeInfo.SetText(info); + } + } + + private ClearDemoCards(): void { + if (this.itemScope !== undefined) { + this.itemScope.Dispose(); + this.itemScope = undefined; + } + if (this.scrollDemoList !== undefined && this.scrollDemoList.ClearChildren !== undefined) { + this.scrollDemoList.ClearChildren(); + } + this.itemWidgets = []; + this.itemEnterButtons = {}; + } + + private PopulateDemoCards(): void { + this.ClearDemoCards(); + const resSvc = this.ctx.GetService("resource"); + if (resSvc === undefined || this.scrollDemoList === undefined) { + return; + } + + const scope = new ScopedObject(); + this.itemScope = scope; + this.AddScopedObject(scope); + + resSvc.LoadClassAsync(ASSET_KEYS.DEMO_HUB_ITEM_WIDGET, scope, (ok, itemClass, _lease, err) => { + if (!ok || itemClass === undefined || this.IsDisposed() || scope.IsDisposed()) { + logger.Error("Failed to load WBP_DemoHubItem", { err }); + return; + } + this.BuildDemoCardWidgets(itemClass, scope); + }); + } + + private BuildDemoCardWidgets(itemClass: UE.UClass, scope: ScopedObject): void { + if (this.scrollDemoList === undefined) { + return; + } + const worldContext = + (this.ctx.GetWorldContext().world as UE.UObject | undefined) ?? + (this.ctx.gameInstance as UE.UObject | undefined); + if (worldContext === undefined) { + return; + } + const lp0 = this.ctx.GetOrCreateLocalPlayer(0); + const bridge = this.ctx.GetService("uiDelegateBridge"); + const scenes = GetDemoScenes(); + + for (let i = 0; i < scenes.length; i++) { + const demo = scenes[i]; + const card = UE.UWidgetBlueprintLibrary.Create(worldContext, itemClass, lp0.playerController); + if (card === undefined) { + continue; + } + + const txtTitle = UE.ULuaUIEventSubsystem.FindChildWidgetByName(card, "TxtDemoTitle") as + | UE.UTextBlock + | undefined; + const txtDesc = UE.ULuaUIEventSubsystem.FindChildWidgetByName(card, "TxtDemoDesc") as + | UE.UTextBlock + | undefined; + const txtMeta = UE.ULuaUIEventSubsystem.FindChildWidgetByName(card, "TxtDemoMeta") as + | UE.UTextBlock + | undefined; + const btnEnter = UE.ULuaUIEventSubsystem.FindChildWidgetByName(card, "BtnEnterDemo") as + | UE.UButton + | undefined; + const txtEnterLabel = UE.ULuaUIEventSubsystem.FindChildWidgetByName(card, "TxtEnterLabel") as + | UE.UTextBlock + | undefined; + + if (txtTitle !== undefined) { + txtTitle.SetText(demo.title); + } + if (txtDesc !== undefined) { + txtDesc.SetText(demo.description); + } + if (txtMeta !== undefined) { + txtMeta.SetText(string.format("%s | 关卡:%s", demo.tags, demo.mapAssetPath)); + } + if (txtEnterLabel !== undefined) { + txtEnterLabel.SetText(demo.enabled ? "进入场景" : "敬请期待"); + } + if (btnEnter !== undefined) { + btnEnter.SetIsEnabled(demo.enabled); + this.itemEnterButtons[demo.id] = btnEnter; + if (demo.enabled && bridge !== undefined) { + const handle: IDisposable = bridge.BindButtonClick( + btnEnter, + () => { + if (this.onSelectDemo !== undefined) { + this.onSelectDemo(demo); + } + }, + scope + ); + scope.AddScopedObject(handle); + } + } + + this.scrollDemoList.AddChild(card); + this.itemWidgets[this.itemWidgets.length] = card; + } + } +} + +RegisterUIConfig(DemoHubWindow, { + name: "DemoHubWindow", + assetKey: ASSET_KEYS.DEMO_HUB_WIDGET, + singleton: true, + layer: "normal", + type: "normal", + cacheTag: "no_cache", + blockWorldClick: true, +}); diff --git a/Script/ts/src/game/demo/demo_registry.ts b/Script/ts/src/game/demo/demo_registry.ts new file mode 100644 index 0000000..9e42246 --- /dev/null +++ b/Script/ts/src/game/demo/demo_registry.ts @@ -0,0 +1,74 @@ +/** @noSelfInFile */ + +import type { GameInstanceContext } from "../../framework/context/game_context"; + +export interface DemoSceneDescriptor { + id: string; + title: string; + description: string; + mapName: string; + mapAssetPath: string; + tags: string; + enabled: boolean; +} + +export const BOOTSTRAP_MAP_NAME = "L_Bootstrap"; +export const BOOTSTRAP_MAP_PATH = "/Game/Maps/L_Bootstrap"; + +export const UI_DEMO_MAP_NAME = "L_DemoUI"; +export const UI_DEMO_MAP_PATH = "/Game/Maps/L_DemoUI"; + +export const DEMO_SCENES: DemoSceneDescriptor[] = [ + { + id: "ui_demo", + title: "UI 主界面与窗口实验室(UI Demo)", + description: + "完整演示游戏主界面布局、常用 UMG 控件(按钮/复选框/滑条/进度条/微调器/输入框/下拉框/动态列表/异步贴图)及 7 类窗口策略(普通/全屏互斥/模态/缓存复用/多实例/飘字/系统顶层)。", + mapName: UI_DEMO_MAP_NAME, + mapAssetPath: UI_DEMO_MAP_PATH, + tags: "UMG · 多层窗口栈 · 委托自动解绑 · 中文字体", + enabled: true, + }, + { + id: "coming_resource_demo", + title: "资源热更与异步加载演示(预留槽位)", + description: "后续将在此扩展 PatchManifest 覆盖、并发合并加载与 GC 引用计数可视化演示。", + mapName: "L_DemoResource", + mapAssetPath: "/Game/Maps/L_DemoResource", + tags: "规划中 · ResourceService", + enabled: false, + }, + { + id: "coming_gameplay_demo", + title: "3D 角色控制与输入演示(预留槽位)", + description: "后续将在此扩展 EnhancedInput、角色移动、射线检测与 HUD 非阻塞交互演示。", + mapName: "L_DemoGameplay", + mapAssetPath: "/Game/Maps/L_DemoGameplay", + tags: "规划中 · Gameplay / HUD", + enabled: false, + }, +]; + +export function GetDemoScenes(): DemoSceneDescriptor[] { + return DEMO_SCENES; +} + +export function FindDemoSceneById(id: string): DemoSceneDescriptor | undefined { + for (let i = 0; i < DEMO_SCENES.length; i++) { + if (DEMO_SCENES[i].id === id) { + return DEMO_SCENES[i]; + } + } + return undefined; +} + +export function FindDemoSceneByMapName(mapName: string): DemoSceneDescriptor | undefined { + for (let i = 0; i < DEMO_SCENES.length; i++) { + if (DEMO_SCENES[i].mapName === mapName) { + return DEMO_SCENES[i]; + } + } + return undefined; +} + +export type DemoSceneEntryFn = (this: void, ctx: GameInstanceContext) => void; diff --git a/Script/ts/src/game/demo/demo_router.ts b/Script/ts/src/game/demo/demo_router.ts new file mode 100644 index 0000000..b8a19a3 --- /dev/null +++ b/Script/ts/src/game/demo/demo_router.ts @@ -0,0 +1,110 @@ +/** @noSelfInFile */ + +import { Logger } from "../../share/base/logger"; +import type { GameInstanceContext } from "../../framework/context/game_context"; +import { GetPrimaryUIManager } from "../startup"; +import { DemoHubWindow } from "./demo_hub_window"; +import { + BOOTSTRAP_MAP_NAME, + BOOTSTRAP_MAP_PATH, + FindDemoSceneById, + UI_DEMO_MAP_NAME, + type DemoSceneDescriptor, +} from "./demo_registry"; +import { UIDemoMainWindow } from "./ui_demo/ui_demo_main_window"; + +const logger = Logger("DemoRouter"); + +export function OpenDemoHub( + ctx: GameInstanceContext, + onOpened?: (this: void, ok: boolean, win?: DemoHubWindow, err?: string) => void +): DemoHubWindow | undefined { + const uiMgr = GetPrimaryUIManager(ctx); + if (uiMgr === undefined) { + return undefined; + } + return uiMgr.ShowUI( + DemoHubWindow, + { + onSelectDemo: (demo: DemoSceneDescriptor) => { + SwitchToDemoById(ctx, demo.id); + }, + }, + onOpened + ); +} + +export function OpenUIDemoMain( + ctx: GameInstanceContext, + onOpened?: (this: void, ok: boolean, win?: UIDemoMainWindow, err?: string) => void +): UIDemoMainWindow | undefined { + const uiMgr = GetPrimaryUIManager(ctx); + if (uiMgr === undefined) { + return undefined; + } + return uiMgr.ShowUI( + UIDemoMainWindow, + { + onReturnToHub: () => { + ReturnToBootstrap(ctx); + }, + }, + onOpened + ); +} + +export function SwitchToDemoById(ctx: GameInstanceContext, demoId: string): boolean { + const demo = FindDemoSceneById(demoId); + if (demo === undefined || !demo.enabled) { + logger.Warn("Demo scene unavailable or disabled", { demoId }); + return false; + } + + const worldContext = + (ctx.GetWorldContext().world as UE.UObject | undefined) ?? + (ctx.GetOrCreateLocalPlayer(0).playerController as UE.UObject | undefined); + if (worldContext === undefined) { + logger.Error("Cannot OpenLevel: no valid WorldContext", { demoId }); + return false; + } + + logger.Info("Switching to demo level", { demoId: demo.id, map: demo.mapAssetPath }); + UE.UGameplayStatics.OpenLevel(worldContext, demo.mapAssetPath, true, ""); + return true; +} + +export function ReturnToBootstrap(ctx: GameInstanceContext): boolean { + const worldContext = + (ctx.GetWorldContext().world as UE.UObject | undefined) ?? + (ctx.GetOrCreateLocalPlayer(0).playerController as UE.UObject | undefined); + if (worldContext === undefined) { + logger.Error("Cannot return to Bootstrap: no valid WorldContext"); + return false; + } + + logger.Info("Returning to Bootstrap Hub", { map: BOOTSTRAP_MAP_PATH }); + UE.UGameplayStatics.OpenLevel(worldContext, BOOTSTRAP_MAP_PATH, true, ""); + return true; +} + +/** + * 按当前 UE 关卡名称自动挂载对应的 Demo 场景入口: + * - L_Bootstrap -> DemoHubWindow(场景切换大厅) + * - L_DemoUI -> UIDemoMainWindow(UI 组件与窗口实验室主界面) + * - 其他未知关卡 -> 默认兜底打开 DemoHubWindow + */ +export function RouteCurrentLevel(ctx: GameInstanceContext, pc: UE.APlayerController): void { + const levelName = UE.UGameplayStatics.GetCurrentLevelName(pc, true); + logger.Info("Routing player entry for level", { levelName }); + + if (levelName === UI_DEMO_MAP_NAME) { + OpenUIDemoMain(ctx); + return; + } + if (levelName === BOOTSTRAP_MAP_NAME) { + OpenDemoHub(ctx); + return; + } + + OpenDemoHub(ctx); +} diff --git a/Script/ts/src/game/demo/ui_demo/ui_demo_main_window.ts b/Script/ts/src/game/demo/ui_demo/ui_demo_main_window.ts new file mode 100644 index 0000000..bded103 --- /dev/null +++ b/Script/ts/src/game/demo/ui_demo/ui_demo_main_window.ts @@ -0,0 +1,976 @@ +import type { IDisposable } from "../../../share/base/interface"; +import { Logger } from "../../../share/base/logger"; +import { ScopedObject } from "../../../share/base/scoped_object"; +import type { TimerHandle } from "../../../framework/core/scheduler"; +import { ASSET_KEYS } from "../../../framework/resource/asset_catalog"; +import type { ResourceService } from "../../../framework/resource/resource_service"; +import { RegisterUIConfig } from "../../../framework/ui/ui_config"; +import type { UIDelegateBridge } from "../../../framework/ui/ui_delegate_bridge"; +import { UIWindow } from "../../../framework/ui/ui_window"; +import { OpenMiniSettings } from "../../startup"; +import { + UIDemoCachedWindow, + UIDemoFullscreenWindow, + UIDemoModalWindow, + UIDemoMultiWindow, + UIDemoNormalWindow, + UIDemoSystemWindow, + UIDemoToastWindow, +} from "./ui_demo_windows"; + +const logger = Logger("UIDemoMainWindow"); + +export interface UIDemoMainArgs { + onReturnToHub?: (this: void) => void; +} + +interface DynamicListEntry { + id: number; + widget: UE.UUserWidget; + scope: ScopedObject; +} + +interface ThemePreset { + label: string; + r: number; + g: number; + b: number; +} + +const THEME_PRESETS: ThemePreset[] = [ + { label: "深海蓝(普通)", r: 0.149, g: 0.431, b: 0.855 }, + { label: "翡翠绿(稀有)", r: 0.133, g: 0.588, b: 0.388 }, + { label: "琥珀金(传说)", r: 0.761, g: 0.490, b: 0.110 }, + { label: "星云紫(史诗)", r: 0.478, g: 0.294, b: 0.784 }, +]; + +const TEXT_COLORS: Array<{ name: string; r: number; g: number; b: number }> = [ + { name: "纯白", r: 0.941, g: 0.961, b: 0.988 }, + { name: "天青", r: 0.451, g: 0.788, b: 0.980 }, + { name: "金黄", r: 0.980, g: 0.812, b: 0.310 }, + { name: "珊瑚红", r: 0.980, g: 0.510, b: 0.510 }, +]; + +const TEXT_SIZES: number[] = [14, 18, 22]; + +const PREVIEW_TEXTURES: Array<{ label: string; key: string }> = [ + { label: "冒险者头像", key: ASSET_KEYS.DEMO_AVATAR_TEX }, + { label: "翡翠菱形徽章", key: ASSET_KEYS.DEMO_BADGE_A_TEX }, + { label: "绯红星纹徽章", key: ASSET_KEYS.DEMO_BADGE_B_TEX }, + { label: "经典设置图标", key: ASSET_KEYS.MINI_SETTINGS_ICON }, +]; + +const TINT_COLORS: Array<{ name: string; r: number; g: number; b: number }> = [ + { name: "原色", r: 1.0, g: 1.0, b: 1.0 }, + { name: "青蓝着色", r: 0.55, g: 0.90, b: 1.0 }, + { name: "金黄着色", r: 1.0, g: 0.85, b: 0.45 }, + { name: "玫红着色", r: 1.0, g: 0.55, b: 0.70 }, +]; + +function MakeLinearColor(r: number, g: number, b: number, a = 1.0): UE.FLinearColor { + const c = UE.FLinearColor(); + c.R = r; + c.G = g; + c.B = b; + c.A = a; + return c; +} + +function MakeSlateColor(r: number, g: number, b: number, a = 1.0): UE.FSlateColor { + const sc = UE.FSlateColor(); + sc.SpecifiedColor = MakeLinearColor(r, g, b, a); + sc.ColorUseRule = UE.ESlateColorStylingMode.UseColor_Specified; + return sc; +} + +/** + * UI Demo 主界面窗口(绑定 /Game/UI/Demo/WBP_UIDemoMain): + * 集成了游戏主界面顶部栏、左侧 7 类窗口测试入口、中央 4 Tab UMG 组件实验室与右侧实时交互日志。 + */ +export class UIDemoMainWindow extends UIWindow { + // TopBar + public imgPlayerAvatar?: UE.UImage; + public txtPlayerName?: UE.UTextBlock; + public barPlayerExp?: UE.UProgressBar; + public txtHudStats?: UE.UTextBlock; + public btnTopSettings?: UE.UButton; + public btnBackToHub?: UE.UButton; + + // LeftNav + public btnWinNormal?: UE.UButton; + public btnWinFullscreen?: UE.UButton; + public btnWinModal?: UE.UButton; + public btnWinCached?: UE.UButton; + public btnWinMulti?: UE.UButton; + public btnWinToast?: UE.UButton; + public btnWinSystem?: UE.UButton; + public btnEvictCache?: UE.UButton; + public btnCloseOthers?: UE.UButton; + + // Tabs + public btnTabBasic?: UE.UButton; + public btnTabInput?: UE.UButton; + public btnTabMedia?: UE.UButton; + public btnTabDiag?: UE.UButton; + public tabSwitcher?: UE.UWidgetSwitcher; + + // Page 0: Basic + public txtBasicBtnStatus?: UE.UTextBlock; + public btnDemoAction?: UE.UButton; + public btnToggleDisable?: UE.UButton; + public btnDemoTarget?: UE.UButton; + public txtDemoTarget?: UE.UTextBlock; + public chkFeature?: UE.UCheckBox; + public txtCheckStatus?: UE.UTextBlock; + public txtSliderStatus?: UE.UTextBlock; + public sliderDemo?: UE.USlider; + public progressDemo?: UE.UProgressBar; + public btnProgressPlay?: UE.UButton; + public txtProgressPlay?: UE.UTextBlock; + public btnProgressReset?: UE.UButton; + public spinDemo?: UE.USpinBox; + public txtSpinStatus?: UE.UTextBlock; + + // Page 1: Input & Selection + public inputNickname?: UE.UEditableTextBox; + public txtInputStatus?: UE.UTextBlock; + public btnApplyNickname?: UE.UButton; + public comboTheme?: UE.UComboBoxString; + public borderThemePreview?: UE.UBorder; + public txtComboStatus?: UE.UTextBlock; + public txtRichSample?: UE.UTextBlock; + public btnCycleTextColor?: UE.UButton; + public btnCycleTextSize?: UE.UButton; + + // Page 2: Media & Containers + public imgPreview?: UE.UImage; + public txtImageStatus?: UE.UTextBlock; + public btnSwitchTex?: UE.UButton; + public btnTintTex?: UE.UButton; + public btnCycleVis?: UE.UButton; + public txtListSummary?: UE.UTextBlock; + public btnListAddOne?: UE.UButton; + public btnListAddTen?: UE.UButton; + public btnListClear?: UE.UButton; + public scrollDynamicList?: UE.UScrollBox; + + // Page 3: Diagnostics + public txtDiagDetail?: UE.UTextBlock; + public btnDiagRefresh?: UE.UButton; + public btnDiagConcurrent?: UE.UButton; + public btnDiagCancelLoad?: UE.UButton; + + // RightLog + public btnClearLog?: UE.UButton; + public scrollEventLog?: UE.UScrollBox; + public txtEventLog?: UE.UTextBlock; + + // Observable state for automated UE tests & diagnostics + public activeTabIndex = 0; + public actionClickCount = 0; + public actionHovered = false; + public targetEnabled = true; + public targetClickCount = 0; + public checkboxChecked = false; + public sliderValue = 0.5; + public spinValue = 100; + public currentNickname = "冒险者_01"; + public draftNickname = ""; + public selectedTheme = "深海蓝(普通)"; + public dynamicItemCount = 0; + + private onReturnToHub?: (this: void) => void; + private multiSeq = 0; + private toastSeq = 0; + private progressTimer?: TimerHandle; + private textColorIndex = 0; + private textSizeIndex = 0; + private previewTexIndex = 0; + private previewTintIndex = 0; + private previewVisIndex = 0; + private nextListItemId = 0; + private listItemClass?: UE.UClass; + private dynamicItems: DynamicListEntry[] = []; + private logLines: string[] = []; + + protected override OnBindWidgets(): void { + // TopBar + this.imgPlayerAvatar = this.RequireWidget("ImgPlayerAvatar"); + this.txtPlayerName = this.RequireWidget("TxtPlayerName"); + this.barPlayerExp = this.RequireWidget("BarPlayerExp"); + this.txtHudStats = this.RequireWidget("TxtHudStats"); + this.btnTopSettings = this.RequireWidget("BtnTopSettings"); + this.btnBackToHub = this.RequireWidget("BtnBackToHub"); + + this.BindButtonClick(this.btnTopSettings, () => { + this.AppendLog("[TopBar] 打开 MiniSettingsWindow"); + OpenMiniSettings(this.ctx); + }); + this.BindButtonClick(this.btnBackToHub, () => { + this.AppendLog("[TopBar] 返回 Bootstrap 场景大厅"); + if (this.onReturnToHub !== undefined) { + this.onReturnToHub(); + } + }); + + // LeftNav (Window types) + this.btnWinNormal = this.RequireWidget("BtnWinNormal"); + this.btnWinFullscreen = this.RequireWidget("BtnWinFullscreen"); + this.btnWinModal = this.RequireWidget("BtnWinModal"); + this.btnWinCached = this.RequireWidget("BtnWinCached"); + this.btnWinMulti = this.RequireWidget("BtnWinMulti"); + this.btnWinToast = this.RequireWidget("BtnWinToast"); + this.btnWinSystem = this.RequireWidget("BtnWinSystem"); + this.btnEvictCache = this.RequireWidget("BtnEvictCache"); + this.btnCloseOthers = this.RequireWidget("BtnCloseOthers"); + + this.BindButtonClick(this.btnWinNormal, () => { + this.OpenNormalDemoWindow(); + }); + this.BindButtonClick(this.btnWinFullscreen, () => { + this.OpenFullscreenDemoWindow(); + }); + this.BindButtonClick(this.btnWinModal, () => { + this.OpenModalDemoWindow("确认操作", "这是一条带半透明遮罩的模态弹窗,点击「确认」或「取消」将在右侧日志记录结果。"); + }); + this.BindButtonClick(this.btnWinCached, () => { + this.OpenCachedDemoWindow(); + }); + this.BindButtonClick(this.btnWinMulti, () => { + this.OpenMultiDemoWindow(); + }); + this.BindButtonClick(this.btnWinToast, () => { + this.ShowToast(string.format("飘字通知 #%d(Tips 层,不抢占 UI 焦点)", this.toastSeq + 1)); + }); + this.BindButtonClick(this.btnWinSystem, () => { + this.OpenSystemDemoWindow(); + }); + this.BindButtonClick(this.btnEvictCache, () => { + const evicted = this.uiManager.EvictCache(); + this.AppendLog(string.format("[Cache] 已主动清空缓存池,释放 %d 个缓存窗口", evicted)); + this.RefreshHudAndDiagnostics(); + }); + this.BindButtonClick(this.btnCloseOthers, () => { + const closed = this.uiManager.CloseAllExcept(this, false); + this.AppendLog(string.format("[UIManager] 已关闭除主界面外的 %d 个窗口", closed)); + this.RefreshHudAndDiagnostics(); + }); + + // Tabs + this.btnTabBasic = this.RequireWidget("BtnTabBasic"); + this.btnTabInput = this.RequireWidget("BtnTabInput"); + this.btnTabMedia = this.RequireWidget("BtnTabMedia"); + this.btnTabDiag = this.RequireWidget("BtnTabDiag"); + this.tabSwitcher = this.RequireWidget("TabSwitcher"); + + this.BindButtonClick(this.btnTabBasic, () => this.SelectTab(0, "基础交互")); + this.BindButtonClick(this.btnTabInput, () => this.SelectTab(1, "输入与选择")); + this.BindButtonClick(this.btnTabMedia, () => this.SelectTab(2, "图片与列表")); + this.BindButtonClick(this.btnTabDiag, () => { + this.SelectTab(3, "框架诊断"); + this.RefreshHudAndDiagnostics(); + }); + + // Page 0: Basic + this.txtBasicBtnStatus = this.RequireWidget("TxtBasicBtnStatus"); + this.btnDemoAction = this.RequireWidget("BtnDemoAction"); + this.btnToggleDisable = this.RequireWidget("BtnToggleDisable"); + this.btnDemoTarget = this.RequireWidget("BtnDemoTarget"); + this.txtDemoTarget = this.RequireWidget("TxtDemoTarget"); + this.chkFeature = this.RequireWidget("ChkFeature"); + this.txtCheckStatus = this.RequireWidget("TxtCheckStatus"); + this.txtSliderStatus = this.RequireWidget("TxtSliderStatus"); + this.sliderDemo = this.RequireWidget("SliderDemo"); + this.progressDemo = this.RequireWidget("ProgressDemo"); + this.btnProgressPlay = this.RequireWidget("BtnProgressPlay"); + this.txtProgressPlay = this.RequireWidget("TxtProgressPlay"); + this.btnProgressReset = this.RequireWidget("BtnProgressReset"); + this.spinDemo = this.RequireWidget("SpinDemo"); + this.txtSpinStatus = this.RequireWidget("TxtSpinStatus"); + + this.BindButtonClick(this.btnDemoAction, () => { + this.actionClickCount = this.actionClickCount + 1; + this.RefreshBasicButtonStatus(); + this.AppendLog(string.format("[Button] 测试按钮被点击(第 %d 次)", this.actionClickCount)); + }); + this.BindButtonHovered(this.btnDemoAction, () => { + this.actionHovered = true; + this.RefreshBasicButtonStatus(); + this.AppendLog("[Button] 鼠标悬停进入测试按钮"); + }); + this.BindButtonUnhovered(this.btnDemoAction, () => { + this.actionHovered = false; + this.RefreshBasicButtonStatus(); + }); + this.BindButtonClick(this.btnToggleDisable, () => { + this.targetEnabled = !this.targetEnabled; + if (this.btnDemoTarget !== undefined) { + this.btnDemoTarget.SetIsEnabled(this.targetEnabled); + } + if (this.txtDemoTarget !== undefined) { + this.txtDemoTarget.SetText(this.targetEnabled ? "目标受控按钮(已启用)" : "目标受控按钮(已禁用)"); + } + this.RefreshBasicButtonStatus(); + this.AppendLog(this.targetEnabled ? "[Button] 目标按钮已启用" : "[Button] 目标按钮已禁用"); + }); + this.BindButtonClick(this.btnDemoTarget, () => { + this.targetClickCount = this.targetClickCount + 1; + this.AppendLog(string.format("[Button] 受控按钮触发点击 #%d", this.targetClickCount)); + }); + + this.BindCheckBoxChanged(this.chkFeature, (checked: boolean) => { + this.checkboxChecked = checked; + if (this.txtCheckStatus !== undefined) { + this.txtCheckStatus.SetText(checked ? "复选框状态:已勾选(开启特性)" : "复选框状态:未勾选(关闭特性)"); + } + this.AppendLog(checked ? "[CheckBox] 已勾选" : "[CheckBox] 已取消勾选"); + }); + + this.BindSliderChanged(this.sliderDemo, (val: number) => { + this.ApplySliderProgress(val, false); + }); + this.BindButtonClick(this.btnProgressPlay, () => { + this.ToggleProgressAnimation(); + }); + this.BindButtonClick(this.btnProgressReset, () => { + this.StopProgressAnimation(); + this.ApplySliderProgress(0, true); + this.AppendLog("[ProgressBar] 进度已重置为 0%"); + }); + + this.BindSpinBoxChanged(this.spinDemo, (val: number) => { + this.spinValue = val; + if (this.txtSpinStatus !== undefined) { + this.txtSpinStatus.SetText(string.format("当前数值:%.1f(范围 0 ~ 999)", val)); + } + this.AppendLog(string.format("[SpinBox] 数值变更 -> %.1f", val)); + }); + + // Page 1: Input & Selection + this.inputNickname = this.RequireWidget("InputNickname"); + this.txtInputStatus = this.RequireWidget("TxtInputStatus"); + this.btnApplyNickname = this.RequireWidget("BtnApplyNickname"); + this.comboTheme = this.RequireWidget("ComboTheme"); + this.borderThemePreview = this.RequireWidget("BorderThemePreview"); + this.txtComboStatus = this.RequireWidget("TxtComboStatus"); + this.txtRichSample = this.RequireWidget("TxtRichSample"); + this.btnCycleTextColor = this.RequireWidget("BtnCycleTextColor"); + this.btnCycleTextSize = this.RequireWidget("BtnCycleTextSize"); + + this.BindEditableTextChanged(this.inputNickname, (text: string) => { + this.draftNickname = text; + const charCount = utf8.len(text) ?? string.len(text); + if (this.txtInputStatus !== undefined) { + this.txtInputStatus.SetText( + charCount > 0 + ? string.format("实时内容:%s(%d 字符)", text, charCount) + : "实时内容:空(0 字符)" + ); + } + }); + this.BindEditableTextCommitted(this.inputNickname, (text: string, commitMethod: number) => { + this.draftNickname = text; + this.AppendLog(string.format("[EditableTextBox] 提交文本:%s(Method=%d)", text, commitMethod)); + if (text !== "") { + this.ApplyNickname(text); + } + }); + this.BindButtonClick(this.btnApplyNickname, () => { + const nextName = this.draftNickname !== "" ? this.draftNickname : "天命旅人_88"; + this.ApplyNickname(nextName); + }); + + this.BindComboBoxChanged(this.comboTheme, (option: string) => { + this.ApplyThemePreset(option); + }); + this.BindButtonClick(this.btnCycleTextColor, () => { + this.textColorIndex = (this.textColorIndex + 1) % TEXT_COLORS.length; + const c = TEXT_COLORS[this.textColorIndex]; + if (this.txtRichSample !== undefined) { + this.txtRichSample.SetColorAndOpacity(MakeSlateColor(c.r, c.g, c.b, 1.0)); + } + this.AppendLog(string.format("[TextBlock] 切换文本颜色 -> %s", c.name)); + }); + this.BindButtonClick(this.btnCycleTextSize, () => { + this.textSizeIndex = (this.textSizeIndex + 1) % TEXT_SIZES.length; + const size = TEXT_SIZES[this.textSizeIndex]; + if (this.txtRichSample !== undefined) { + this.txtRichSample.SetFontSize(size); + } + this.AppendLog(string.format("[TextBlock] 切换字号 -> %dpt", size)); + }); + + // Page 2: Media & Containers + this.imgPreview = this.RequireWidget("ImgPreview"); + this.txtImageStatus = this.RequireWidget("TxtImageStatus"); + this.btnSwitchTex = this.RequireWidget("BtnSwitchTex"); + this.btnTintTex = this.RequireWidget("BtnTintTex"); + this.btnCycleVis = this.RequireWidget("BtnCycleVis"); + this.txtListSummary = this.RequireWidget("TxtListSummary"); + this.btnListAddOne = this.RequireWidget("BtnListAddOne"); + this.btnListAddTen = this.RequireWidget("BtnListAddTen"); + this.btnListClear = this.RequireWidget("BtnListClear"); + this.scrollDynamicList = this.RequireWidget("ScrollDynamicList"); + + this.BindButtonClick(this.btnSwitchTex, () => { + this.previewTexIndex = (this.previewTexIndex + 1) % PREVIEW_TEXTURES.length; + this.LoadPreviewTexture(); + }); + this.BindButtonClick(this.btnTintTex, () => { + this.previewTintIndex = (this.previewTintIndex + 1) % TINT_COLORS.length; + const tint = TINT_COLORS[this.previewTintIndex]; + if (this.imgPreview !== undefined) { + this.imgPreview.SetColorAndOpacity(MakeLinearColor(tint.r, tint.g, tint.b, 1.0)); + } + this.AppendLog(string.format("[Image] 切换着色 -> %s", tint.name)); + this.RefreshImageStatus(); + }); + this.BindButtonClick(this.btnCycleVis, () => { + this.previewVisIndex = (this.previewVisIndex + 1) % 3; + const visModes = [ + UE.ESlateVisibility.Visible, + UE.ESlateVisibility.Hidden, + UE.ESlateVisibility.Collapsed, + ]; + if (this.imgPreview !== undefined) { + this.imgPreview.SetVisibility(visModes[this.previewVisIndex]); + } + this.RefreshImageStatus(); + this.AppendLog(string.format("[Image] 切换可见性 -> %s", this.GetVisibilityLabel())); + }); + + this.BindButtonClick(this.btnListAddOne, () => this.AddDynamicListItems(1)); + this.BindButtonClick(this.btnListAddTen, () => this.AddDynamicListItems(10)); + this.BindButtonClick(this.btnListClear, () => this.ClearDynamicListItems()); + + // Page 3: Diagnostics + this.txtDiagDetail = this.RequireWidget("TxtDiagDetail"); + this.btnDiagRefresh = this.RequireWidget("BtnDiagRefresh"); + this.btnDiagConcurrent = this.RequireWidget("BtnDiagConcurrent"); + this.btnDiagCancelLoad = this.RequireWidget("BtnDiagCancelLoad"); + + this.BindButtonClick(this.btnDiagRefresh, () => { + this.RefreshHudAndDiagnostics(); + this.AppendLog("[Diag] 已手动刷新诊断快照"); + }); + this.BindButtonClick(this.btnDiagConcurrent, () => { + const w1 = this.OpenNormalDemoWindow(); + const w2 = this.OpenNormalDemoWindow(); + const same = w1 === w2; + this.AppendLog(string.format("[Diag] 并发双开单例测试:同一控制器=%s", tostring(same))); + this.ShowToast(same ? "并发双开测试通过:返回同一单例" : "并发双开测试异常"); + }); + this.BindButtonClick(this.btnDiagCancelLoad, () => { + const w = this.uiManager.ShowUI(UIDemoSystemWindow, { onLog: (m: string) => this.AppendLog(m) }); + if (w !== undefined) { + w.Close(); + } + this.AppendLog("[Diag] 已执行「打开后立即关闭」取消加载验证"); + this.RefreshHudAndDiagnostics(); + }); + + // RightLog + this.btnClearLog = this.RequireWidget("BtnClearLog"); + this.scrollEventLog = this.RequireWidget("ScrollEventLog"); + this.txtEventLog = this.RequireWidget("TxtEventLog"); + this.BindButtonClick(this.btnClearLog, () => { + this.logLines = []; + this.RenderLogText(); + }); + } + + protected override OnPreShow(args?: unknown): void { + const a = args as UIDemoMainArgs | undefined; + this.onReturnToHub = a !== undefined ? a.onReturnToHub : undefined; + + // Subscribe to UIManager lifecycle events so TopBar & Diagnostics stay live + this.uiManager.events.on.OnWindowOpened((winName: string) => { + this.AppendLog(string.format("[UIManager] 窗口打开:%s", winName)); + this.RefreshHudAndDiagnostics(); + }, this); + this.uiManager.events.on.OnWindowClosed((winName: string) => { + this.AppendLog(string.format("[UIManager] 窗口关闭:%s", winName)); + this.RefreshHudAndDiagnostics(); + }, this); + this.uiManager.events.on.OnFocusRestored(() => { + this.RefreshHudAndDiagnostics(); + }, this); + + this.LoadAvatarAndPreview(); + this.PreloadDynamicListItemClass(); + this.SelectTab(0, "基础交互"); + this.RefreshBasicButtonStatus(); + this.ApplySliderProgress(this.sliderValue, true); + this.RefreshListSummary(); + this.AppendLog("[UIDemoMain] 主界面已就绪,可测试全部 UI 控件与 7 类窗口"); + } + + protected override OnShow(): void { + this.RefreshHudAndDiagnostics(); + } + + protected override OnHide(): void { + this.AppendLog("[UIDemoMain] OnHide(已被全屏窗口遮盖隐藏)"); + } + + protected override OnClose(): void { + this.StopProgressAnimation(); + this.ClearDynamicListItems(); + } + + public SelectTab(index: number, label: string): void { + this.activeTabIndex = index; + if (this.tabSwitcher !== undefined) { + this.tabSwitcher.SetActiveWidgetIndex(index); + } + this.AppendLog(string.format("[Tab] 切换至:%s", label)); + } + + public OpenNormalDemoWindow(): UIDemoNormalWindow | undefined { + return this.uiManager.ShowUI(UIDemoNormalWindow, { + onLog: (m: string) => this.AppendLog(m), + }); + } + + public OpenFullscreenDemoWindow(): UIDemoFullscreenWindow | undefined { + return this.uiManager.ShowUI(UIDemoFullscreenWindow, { + onLog: (m: string) => this.AppendLog(m), + onOpenModal: () => { + this.OpenModalDemoWindow("全屏页上的模态弹窗", "验证 popup 层正确叠加在 fullscreen 全屏页面之上。"); + }, + }); + } + + public OpenModalDemoWindow(title: string, message: string): UIDemoModalWindow | undefined { + return this.uiManager.ShowUI(UIDemoModalWindow, { + title, + message, + onConfirm: () => { + this.AppendLog("[Modal] 用户点击了「确认」"); + this.ShowToast("模态弹窗:已确认"); + }, + onCancel: () => { + this.AppendLog("[Modal] 用户点击了「取消」"); + }, + }); + } + + public OpenCachedDemoWindow(): UIDemoCachedWindow | undefined { + return this.uiManager.ShowUI(UIDemoCachedWindow, { + onLog: (m: string) => this.AppendLog(m), + }); + } + + public OpenMultiDemoWindow(): UIDemoMultiWindow | undefined { + this.multiSeq = this.multiSeq + 1; + return this.uiManager.ShowUI(UIDemoMultiWindow, { + instanceSeq: this.multiSeq, + onLog: (m: string) => this.AppendLog(m), + }); + } + + public ShowToast(message: string, durationSec = 2.2): UIDemoToastWindow | undefined { + this.toastSeq = this.toastSeq + 1; + return this.uiManager.ShowUI(UIDemoToastWindow, { + message, + durationSec, + offsetIndex: this.toastSeq - 1, + onLog: (m: string) => this.AppendLog(m), + }); + } + + public OpenSystemDemoWindow(): UIDemoSystemWindow | undefined { + return this.uiManager.ShowUI(UIDemoSystemWindow, { + onLog: (m: string) => this.AppendLog(m), + }); + } + + public AddDynamicListItems(count: number): void { + if (this.scrollDynamicList === undefined) { + return; + } + if (this.listItemClass === undefined) { + this.PreloadDynamicListItemClass(() => { + this.AddDynamicListItems(count); + }); + return; + } + + const worldContext = + (this.ctx.GetWorldContext().world as UE.UObject | undefined) ?? + (this.ctx.gameInstance as UE.UObject | undefined); + if (worldContext === undefined) { + return; + } + const lp0 = this.ctx.GetOrCreateLocalPlayer(0); + const bridge = this.ctx.GetService("uiDelegateBridge"); + + for (let i = 0; i < count; i++) { + this.nextListItemId = this.nextListItemId + 1; + const itemId = this.nextListItemId; + const itemWidget = UE.UWidgetBlueprintLibrary.Create(worldContext, this.listItemClass, lp0.playerController); + if (itemWidget === undefined) { + continue; + } + + const itemScope = new ScopedObject(); + const txtTitle = UE.ULuaUIEventSubsystem.FindChildWidgetByName(itemWidget, "TxtItemTitle") as + | UE.UTextBlock + | undefined; + const btnAct = UE.ULuaUIEventSubsystem.FindChildWidgetByName(itemWidget, "BtnItemAction") as + | UE.UButton + | undefined; + const btnDel = UE.ULuaUIEventSubsystem.FindChildWidgetByName(itemWidget, "BtnItemDelete") as + | UE.UButton + | undefined; + + if (txtTitle !== undefined) { + txtTitle.SetText(string.format("动态条目 #%d — 测试委托自动回收", itemId)); + } + + const entry: DynamicListEntry = { + id: itemId, + widget: itemWidget, + scope: itemScope, + }; + + if (bridge !== undefined) { + if (btnAct !== undefined) { + const hAct: IDisposable = bridge.BindButtonClick( + btnAct, + () => { + this.AppendLog(string.format("[ListItem #%d] 点击了「触发」", itemId)); + this.ShowToast(string.format("触发了列表项 #%d", itemId), 1.5); + }, + itemScope + ); + itemScope.AddScopedObject(hAct); + } + if (btnDel !== undefined) { + const hDel: IDisposable = bridge.BindButtonClick( + btnDel, + () => { + this.RemoveDynamicListItem(itemId); + }, + itemScope + ); + itemScope.AddScopedObject(hDel); + } + } + + this.scrollDynamicList.AddChild(itemWidget); + this.dynamicItems[this.dynamicItems.length] = entry; + } + + this.dynamicItemCount = this.dynamicItems.length; + this.RefreshListSummary(); + this.RefreshHudAndDiagnostics(); + this.AppendLog(string.format("[ScrollBox] 新增 %d 个动态列表项(当前共 %d 项)", count, this.dynamicItemCount)); + } + + public RemoveDynamicListItem(itemId: number): void { + for (let i = this.dynamicItems.length - 1; i >= 0; i--) { + const entry = this.dynamicItems[i]; + if (entry.id === itemId) { + entry.scope.Dispose(); + if (entry.widget.RemoveFromParent !== undefined) { + entry.widget.RemoveFromParent(); + } + table.remove(this.dynamicItems, i + 1); + break; + } + } + this.dynamicItemCount = this.dynamicItems.length; + this.RefreshListSummary(); + this.RefreshHudAndDiagnostics(); + this.AppendLog(string.format("[ScrollBox] 删除列表项 #%d(委托已自动解绑,剩余 %d 项)", itemId, this.dynamicItemCount)); + } + + public ClearDynamicListItems(): void { + const prev = this.dynamicItems.length; + for (let i = 0; i < this.dynamicItems.length; i++) { + this.dynamicItems[i].scope.Dispose(); + } + this.dynamicItems = []; + this.dynamicItemCount = 0; + if (this.scrollDynamicList !== undefined && this.scrollDynamicList.ClearChildren !== undefined) { + this.scrollDynamicList.ClearChildren(); + } + this.RefreshListSummary(); + if (prev > 0) { + this.AppendLog(string.format("[ScrollBox] 已清空 %d 个动态列表项并释放全部子委托", prev)); + this.RefreshHudAndDiagnostics(); + } + } + + private PreloadDynamicListItemClass(onReady?: (this: void) => void): void { + const resSvc = this.ctx.GetService("resource"); + if (resSvc === undefined) { + return; + } + resSvc.LoadClassAsync(ASSET_KEYS.UI_DEMO_LIST_ITEM_WIDGET, this, (ok, cls, _lease, err) => { + if (!ok || cls === undefined) { + logger.Warn("Failed to load WBP_UIDemoListItem", { err }); + return; + } + this.listItemClass = cls; + if (onReady !== undefined && !this.IsDisposed()) { + onReady(); + } + }); + } + + private LoadAvatarAndPreview(): void { + const resSvc = this.ctx.GetService("resource"); + if (resSvc === undefined) { + return; + } + resSvc.LoadTextureAsync(ASSET_KEYS.DEMO_AVATAR_TEX, this, (ok, tex) => { + if (ok && tex !== undefined && this.imgPlayerAvatar !== undefined && !this.IsDisposed()) { + this.imgPlayerAvatar.SetBrushFromTexture(tex, false); + } + }); + this.LoadPreviewTexture(); + } + + private LoadPreviewTexture(): void { + const resSvc = this.ctx.GetService("resource"); + if (resSvc === undefined) { + return; + } + const spec = PREVIEW_TEXTURES[this.previewTexIndex]; + resSvc.LoadTextureAsync(spec.key, this, (ok, tex) => { + if (ok && tex !== undefined && this.imgPreview !== undefined && !this.IsDisposed()) { + this.imgPreview.SetBrushFromTexture(tex, false); + this.RefreshImageStatus(); + this.AppendLog(string.format("[Image] 异步贴图加载完成 -> %s", spec.label)); + } + }); + } + + private GetVisibilityLabel(): string { + if (this.previewVisIndex === 0) return "Visible(可见)"; + if (this.previewVisIndex === 1) return "Hidden(隐身占位)"; + return "Collapsed(折叠不占位)"; + } + + private RefreshImageStatus(): void { + const spec = PREVIEW_TEXTURES[this.previewTexIndex]; + const tint = TINT_COLORS[this.previewTintIndex]; + if (this.txtImageStatus !== undefined) { + this.txtImageStatus.SetText( + string.format("贴图:%s | 着色:%s | 可见性:%s", spec.label, tint.name, this.GetVisibilityLabel()) + ); + } + } + + private RefreshBasicButtonStatus(): void { + if (this.txtBasicBtnStatus !== undefined) { + this.txtBasicBtnStatus.SetText( + string.format( + "按钮状态:点击 %d 次 | 悬停:%s | 受控按钮:%s", + this.actionClickCount, + this.actionHovered ? "是" : "否", + this.targetEnabled ? "已启用" : "已禁用" + ) + ); + } + } + + private ApplySliderProgress(val: number, syncSliderWidget: boolean): void { + const clamped = math.max(0, math.min(1, val)); + this.sliderValue = clamped; + if (syncSliderWidget && this.sliderDemo !== undefined) { + this.sliderDemo.SetValue(clamped); + } + if (this.progressDemo !== undefined) { + this.progressDemo.SetPercent(clamped); + } + if (this.barPlayerExp !== undefined) { + this.barPlayerExp.SetPercent(clamped); + } + if (this.txtSliderStatus !== undefined) { + this.txtSliderStatus.SetText( + string.format("当前进度:%d%%(同时驱动主界面顶部经验条)", math.floor(clamped * 100 + 0.5)) + ); + } + } + + private ToggleProgressAnimation(): void { + if (this.progressTimer !== undefined && this.progressTimer.IsActive()) { + this.StopProgressAnimation(); + this.AppendLog("[ProgressBar] 暂停进度动画"); + return; + } + if (this.txtProgressPlay !== undefined) { + this.txtProgressPlay.SetText("暂停自动进度动画"); + } + this.AppendLog("[ProgressBar] 启动 WorldTimer 自动进度动画"); + this.progressTimer = this.ctx.scheduler.AddWorldRepeatTimer( + 0.05, + () => { + let nextVal = this.sliderValue + 0.025; + if (nextVal > 1.0) { + nextVal = 0.0; + } + this.ApplySliderProgress(nextVal, true); + }, + this + ); + } + + private StopProgressAnimation(): void { + if (this.progressTimer !== undefined) { + this.progressTimer.Cancel(); + this.progressTimer = undefined; + } + if (this.txtProgressPlay !== undefined) { + this.txtProgressPlay.SetText("开始自动进度动画"); + } + } + + private ApplyNickname(name: string): void { + this.currentNickname = name; + if (this.txtPlayerName !== undefined) { + this.txtPlayerName.SetText(string.format("%s Lv.12", name)); + } + this.AppendLog(string.format("[Player] 昵称已更新为:%s", name)); + this.ShowToast(string.format("昵称已更新:%s", name), 1.8); + } + + private ApplyThemePreset(option: string): void { + this.selectedTheme = option; + let matched = THEME_PRESETS[0]; + for (let i = 0; i < THEME_PRESETS.length; i++) { + if (THEME_PRESETS[i].label === option) { + matched = THEME_PRESETS[i]; + break; + } + } + if (this.borderThemePreview !== undefined) { + this.borderThemePreview.SetBrushColor(MakeLinearColor(matched.r, matched.g, matched.b, 1.0)); + } + if (this.txtComboStatus !== undefined) { + this.txtComboStatus.SetText(string.format("当前选中:%s", option)); + } + this.AppendLog(string.format("[ComboBox] 切换主题 -> %s", option)); + } + + private RefreshListSummary(): void { + if (this.txtListSummary !== undefined) { + this.txtListSummary.SetText( + string.format("动态列表项:%d 条(新增/删除时观察顶部活跃绑定数变化)", this.dynamicItemCount) + ); + } + } + + public RefreshHudAndDiagnostics(): void { + if (this.IsDisposed()) { + return; + } + const uiDiag = this.uiManager.GetDiagnostics(); + const bridge = this.ctx.GetService("uiDelegateBridge"); + const resSvc = this.ctx.GetService("resource"); + const activeBindings = bridge !== undefined ? bridge.GetActiveBindingCount() : 0; + + if (this.txtHudStats !== undefined) { + this.txtHudStats.SetText( + string.format( + "窗口:%d | 缓存:%d | 绑定:%d | 模式:%s | 顶层:%s", + uiDiag.openWindows, + uiDiag.cachedWindows, + activeBindings, + uiDiag.inputMode === "ui" ? "UI" : "Game", + uiDiag.topWindowName ?? "无" + ) + ); + } + + if (this.txtDiagDetail !== undefined) { + const stack = this.uiManager.GetWindowStackSnapshot(); + const cachedNames = this.uiManager.GetCachedWindowNames(); + const schedStats = this.ctx.scheduler.GetStats(); + const resDiag = resSvc !== undefined ? resSvc.GetDiagnostics() : undefined; + + const lines: string[] = []; + lines[lines.length] = string.format( + "【UIManager】打开: %d | 加载中: %d | 缓存: %d | 输入模式: %s | 顶层: %s", + uiDiag.openWindows, + uiDiag.loadingWindows, + uiDiag.cachedWindows, + uiDiag.inputMode, + uiDiag.topWindowName ?? "无" + ); + lines[lines.length] = string.format( + "【UIDelegateBridge】活跃 UMG 控件委托数:%d", + activeBindings + ); + if (resDiag !== undefined) { + lines[lines.length] = string.format( + "【ResourceService】在途加载: %d | 驻留资产: %d | 总引用计数: %d", + resDiag.nativeInFlight, + resDiag.nativeRetainedAssets, + resDiag.nativeTotalRefCount + ); + } + lines[lines.length] = string.format( + "【FrameScheduler】Frame: %d | World: %d | Monotonic: %d", + schedStats.frameTasks, + schedStats.worldTasks, + schedStats.monotonicTasks + ); + lines[lines.length] = "--- 活动窗口栈 ---"; + for (let i = 0; i < stack.length; i++) { + const s = stack[i]; + lines[lines.length] = string.format( + " %d. %s [layer=%s, type=%s, z=%d, vis=%s, block=%s%s]", + i + 1, + s.name, + s.layer, + s.type, + s.zOrder, + s.visible ? "Y" : "N", + s.blockWorldClick ? "Y" : "N", + s.hiddenByFullscreen ? ", hiddenByFull" : "" + ); + } + lines[lines.length] = + cachedNames.length > 0 + ? "--- 缓存池:" + table.concat(cachedNames, ", ") + : "--- 缓存池:空"; + + this.txtDiagDetail.SetText(table.concat(lines, "\n")); + } + } + + public AppendLog(entry: string): void { + const now = this.ctx.scheduler.NowSeconds(); + const line = string.format("[%.1fs] %s", now, entry); + this.logLines[this.logLines.length] = line; + if (this.logLines.length > 40) { + table.remove(this.logLines, 1); + } + this.RenderLogText(); + } + + private RenderLogText(): void { + if (this.txtEventLog !== undefined) { + this.txtEventLog.SetText( + this.logLines.length > 0 ? table.concat(this.logLines, "\n") : "[日志已清空]" + ); + } + if (this.scrollEventLog !== undefined && this.scrollEventLog.ScrollToEnd !== undefined) { + this.scrollEventLog.ScrollToEnd(); + } + } +} + +RegisterUIConfig(UIDemoMainWindow, { + name: "UIDemoMainWindow", + assetKey: ASSET_KEYS.UI_DEMO_MAIN_WIDGET, + singleton: true, + layer: "normal", + type: "normal", + cacheTag: "no_cache", + blockWorldClick: true, +}); diff --git a/Script/ts/src/game/demo/ui_demo/ui_demo_windows.ts b/Script/ts/src/game/demo/ui_demo/ui_demo_windows.ts new file mode 100644 index 0000000..59d913f --- /dev/null +++ b/Script/ts/src/game/demo/ui_demo/ui_demo_windows.ts @@ -0,0 +1,504 @@ +import { ASSET_KEYS } from "../../../framework/resource/asset_catalog"; +import type { ResourceService } from "../../../framework/resource/resource_service"; +import { RegisterUIConfig } from "../../../framework/ui/ui_config"; +import { UIWindow } from "../../../framework/ui/ui_window"; + +export type DemoLogFn = (this: void, message: string) => void; + +// ===== 1. 普通信息窗口 (Normal / Singleton) ===== + +export interface NormalWindowArgs { + onLog?: DemoLogFn; +} + +export class UIDemoNormalWindow extends UIWindow { + public txtNormalTitle?: UE.UTextBlock; + public txtNormalBody?: UE.UTextBlock; + public btnNormalPing?: UE.UButton; + public btnNormalClose?: UE.UButton; + + public openOrRefreshCount = 0; + public pingCount = 0; + private onLog?: DemoLogFn; + + protected override OnBindWidgets(): void { + this.txtNormalTitle = this.RequireWidget("TxtNormalTitle"); + this.txtNormalBody = this.RequireWidget("TxtNormalBody"); + this.btnNormalPing = this.RequireWidget("BtnNormalPing"); + this.btnNormalClose = this.RequireWidget("BtnNormalClose"); + + this.BindButtonClick(this.btnNormalPing, () => { + this.pingCount = this.pingCount + 1; + this.RefreshBody(); + this.EmitLog(string.format("[Normal] 触发交互 #%d", this.pingCount)); + }); + this.BindButtonClick(this.btnNormalClose, () => { + this.Close(); + }); + } + + protected override OnPreShow(args?: unknown): void { + const a = args as NormalWindowArgs | undefined; + if (a !== undefined && a.onLog !== undefined) { + this.onLog = a.onLog; + } + this.openOrRefreshCount = this.openOrRefreshCount + 1; + this.RefreshBody(); + this.EmitLog(string.format("[Normal] OnPreShow(第 %d 次打开/刷新,ZOrder=%d)", this.openOrRefreshCount, this.GetZOrder())); + } + + protected override OnClose(): void { + this.EmitLog("[Normal] OnClose 窗口已销毁"); + } + + private RefreshBody(): void { + if (this.txtNormalBody !== undefined) { + this.txtNormalBody.SetText( + string.format( + "Layer: normal | Type: normal | Singleton: true\n当前 ZOrder:%d | 打开/复用刷新次数:%d | 按钮交互:%d 次\n重复点击左侧「普通窗口」不会创建第二个实例,而是直接刷新本窗。", + this.GetZOrder(), + this.openOrRefreshCount, + this.pingCount + ) + ); + } + } + + private EmitLog(msg: string): void { + if (this.onLog !== undefined) { + this.onLog(msg); + } + } +} + +RegisterUIConfig(UIDemoNormalWindow, { + name: "UIDemoNormalWindow", + assetKey: ASSET_KEYS.UI_DEMO_NORMAL_WIDGET, + singleton: true, + layer: "normal", + type: "normal", + cacheTag: "no_cache", + blockWorldClick: true, +}); + +// ===== 2. 全屏窗口 (Fullscreen,自动隐藏并恢复下层 Normal 窗口) ===== + +export interface FullscreenWindowArgs { + onLog?: DemoLogFn; + onOpenModal?: (this: void) => void; +} + +export class UIDemoFullscreenWindow extends UIWindow { + public txtFullDesc?: UE.UTextBlock; + public imgFullPreview?: UE.UImage; + public btnFullOpenModal?: UE.UButton; + public btnFullClose?: UE.UButton; + + private onLog?: DemoLogFn; + private onOpenModal?: (this: void) => void; + + protected override OnBindWidgets(): void { + this.txtFullDesc = this.RequireWidget("TxtFullDesc"); + this.imgFullPreview = this.RequireWidget("ImgFullPreview"); + this.btnFullOpenModal = this.RequireWidget("BtnFullOpenModal"); + this.btnFullClose = this.RequireWidget("BtnFullClose"); + + this.BindButtonClick(this.btnFullOpenModal, () => { + if (this.onOpenModal !== undefined) { + this.onOpenModal(); + } + }); + this.BindButtonClick(this.btnFullClose, () => { + this.Close(); + }); + } + + protected override OnPreShow(args?: unknown): void { + const a = args as FullscreenWindowArgs | undefined; + this.onLog = a !== undefined ? a.onLog : undefined; + this.onOpenModal = a !== undefined ? a.onOpenModal : undefined; + + const resSvc = this.ctx.GetService("resource"); + if (resSvc !== undefined) { + resSvc.LoadTextureAsync(ASSET_KEYS.DEMO_BADGE_B_TEX, this, (ok, tex) => { + if (ok && tex !== undefined && this.imgFullPreview !== undefined && !this.IsDisposed()) { + this.imgFullPreview.SetBrushFromTexture(tex, false); + } + }); + } + + if (this.onLog !== undefined) { + this.onLog(string.format("[Fullscreen] 打开全屏窗口(ZOrder=%d),已自动隐藏下层 Normal 窗口", this.GetZOrder())); + } + } + + protected override OnClose(): void { + if (this.onLog !== undefined) { + this.onLog("[Fullscreen] 关闭全屏窗口,自动恢复下层主界面显示"); + } + } +} + +RegisterUIConfig(UIDemoFullscreenWindow, { + name: "UIDemoFullscreenWindow", + assetKey: ASSET_KEYS.UI_DEMO_FULLSCREEN_WIDGET, + singleton: true, + layer: "normal", + type: "fullscreen", + cacheTag: "no_cache", + blockWorldClick: true, +}); + +// ===== 3. 模态弹窗 (Popup / Modal,遮罩拦截 + 确认/取消回调) ===== + +export interface ModalWindowArgs { + title?: string; + message?: string; + onConfirm?: (this: void) => void; + onCancel?: (this: void) => void; +} + +export class UIDemoModalWindow extends UIWindow { + public txtModalTitle?: UE.UTextBlock; + public txtModalMessage?: UE.UTextBlock; + public btnModalConfirm?: UE.UButton; + public btnModalCancel?: UE.UButton; + + private onConfirm?: (this: void) => void; + private onCancel?: (this: void) => void; + + protected override OnBindWidgets(): void { + this.txtModalTitle = this.RequireWidget("TxtModalTitle"); + this.txtModalMessage = this.RequireWidget("TxtModalMessage"); + this.btnModalConfirm = this.RequireWidget("BtnModalConfirm"); + this.btnModalCancel = this.RequireWidget("BtnModalCancel"); + + this.BindButtonClick(this.btnModalConfirm, () => { + const cb = this.onConfirm; + this.Close(); + if (cb !== undefined) { + cb(); + } + }); + this.BindButtonClick(this.btnModalCancel, () => { + const cb = this.onCancel; + this.Close(); + if (cb !== undefined) { + cb(); + } + }); + } + + protected override OnPreShow(args?: unknown): void { + const a = args as ModalWindowArgs | undefined; + this.onConfirm = a !== undefined ? a.onConfirm : undefined; + this.onCancel = a !== undefined ? a.onCancel : undefined; + + if (this.txtModalTitle !== undefined) { + this.txtModalTitle.SetText(a !== undefined && a.title !== undefined ? a.title : "二次确认模态弹窗"); + } + if (this.txtModalMessage !== undefined) { + this.txtModalMessage.SetText( + a !== undefined && a.message !== undefined + ? a.message + : "半透明遮罩已拦截底层点击。请选择确认或取消以测试回调透传。" + ); + } + } +} + +RegisterUIConfig(UIDemoModalWindow, { + name: "UIDemoModalWindow", + assetKey: ASSET_KEYS.UI_DEMO_MODAL_WIDGET, + singleton: true, + layer: "popup", + type: "popup", + cacheTag: "no_cache", + blockWorldClick: true, +}); + +// ===== 4. 缓存复用窗口 (cacheTag = "cache") ===== + +export interface CachedWindowArgs { + onLog?: DemoLogFn; +} + +export class UIDemoCachedWindow extends UIWindow { + public txtCachedStats?: UE.UTextBlock; + public btnCachedAction?: UE.UButton; + public btnCachedClose?: UE.UButton; + + public reuseCount = 0; + public clickCount = 0; + private onLog?: DemoLogFn; + + protected override OnBindWidgets(): void { + this.txtCachedStats = this.RequireWidget("TxtCachedStats"); + this.btnCachedAction = this.RequireWidget("BtnCachedAction"); + this.btnCachedClose = this.RequireWidget("BtnCachedClose"); + + this.BindButtonClick(this.btnCachedAction, () => { + this.clickCount = this.clickCount + 1; + this.RefreshStats(); + this.EmitLog(string.format("[Cached] 点击按钮(累计 %d 次,严格 +1 无重复绑定)", this.clickCount)); + }); + this.BindButtonClick(this.btnCachedClose, () => { + this.Close(); + }); + } + + protected override OnReuseUI(): void { + this.reuseCount = this.reuseCount + 1; + this.EmitLog(string.format("[Cached] OnReuseUI 命中缓存秒开(第 %d 次复用)", this.reuseCount)); + } + + protected override OnPreShow(args?: unknown): void { + const a = args as CachedWindowArgs | undefined; + if (a !== undefined && a.onLog !== undefined) { + this.onLog = a.onLog; + } + this.RefreshStats(); + if (this.reuseCount === 0) { + this.EmitLog("[Cached] 首次实例化创建成功"); + } + } + + protected override OnClose(): void { + this.EmitLog("[Cached] 关闭并归还缓存池(委托已自动解绑)"); + } + + private RefreshStats(): void { + if (this.txtCachedStats !== undefined) { + this.txtCachedStats.SetText( + string.format( + "缓存复用次数 (OnReuseUI):%d 次\n按钮累计点击:%d 次 | 当前 ZOrder:%d\n关闭后窗口实例进入缓存池,再次打开不重新创建 Widget,且按钮点击不会重复触发。", + this.reuseCount, + this.clickCount, + this.GetZOrder() + ) + ); + } + } + + private EmitLog(msg: string): void { + if (this.onLog !== undefined) { + this.onLog(msg); + } + } +} + +RegisterUIConfig(UIDemoCachedWindow, { + name: "UIDemoCachedWindow", + assetKey: ASSET_KEYS.UI_DEMO_CACHED_WIDGET, + singleton: true, + layer: "popup", + type: "normal", + cacheTag: "cache", + blockWorldClick: true, +}); + +// ===== 5. 多实例浮窗 (singleton = false) ===== + +export interface MultiWindowArgs { + instanceSeq: number; + onLog?: DemoLogFn; +} + +export class UIDemoMultiWindow extends UIWindow { + public multiCard?: UE.UBorder; + public txtMultiTitle?: UE.UTextBlock; + public txtMultiBody?: UE.UTextBlock; + public btnMultiCount?: UE.UButton; + public btnMultiClose?: UE.UButton; + + public instanceSeq = 1; + public localCount = 0; + private onLog?: DemoLogFn; + + protected override OnBindWidgets(): void { + this.multiCard = this.RequireWidget("MultiCard"); + this.txtMultiTitle = this.RequireWidget("TxtMultiTitle"); + this.txtMultiBody = this.RequireWidget("TxtMultiBody"); + this.btnMultiCount = this.RequireWidget("BtnMultiCount"); + this.btnMultiClose = this.RequireWidget("BtnMultiClose"); + + this.BindButtonClick(this.btnMultiCount, () => { + this.localCount = this.localCount + 1; + this.RefreshDisplay(); + this.EmitLog(string.format("[Multi #%d] 独立计数 -> %d", this.instanceSeq, this.localCount)); + }); + this.BindButtonClick(this.btnMultiClose, () => { + this.Close(); + }); + } + + protected override OnPreShow(args?: unknown): void { + const a = args as MultiWindowArgs | undefined; + this.instanceSeq = a !== undefined ? a.instanceSeq : 1; + this.onLog = a !== undefined ? a.onLog : undefined; + + // 按实例序号错位排布,便于视觉区分多个并发实例 + const slotIndex = (this.instanceSeq - 1) % 6; + const offsetX = -150 + slotIndex * 60; + const offsetY = -90 + slotIndex * 38; + if (this.multiCard !== undefined && UE !== undefined && UE.ULuaUIEventSubsystem !== undefined) { + const pos = UE.FVector2D(); + pos.X = offsetX; + pos.Y = offsetY; + UE.ULuaUIEventSubsystem.SetCanvasPosition(this.multiCard, pos); + } + + this.RefreshDisplay(); + this.EmitLog(string.format("[Multi #%d] 多实例打开(ZOrder=%d)", this.instanceSeq, this.GetZOrder())); + } + + protected override OnClose(): void { + this.EmitLog(string.format("[Multi #%d] 已独立关闭", this.instanceSeq)); + } + + private RefreshDisplay(): void { + if (this.txtMultiTitle !== undefined) { + this.txtMultiTitle.SetText(string.format("多实例便签窗 #%d", this.instanceSeq)); + } + if (this.txtMultiBody !== undefined) { + this.txtMultiBody.SetText( + string.format( + "singleton = false | ZOrder = %d\n本实例独立计数:%d\n可连续点击「多实例窗」同时存在多个窗口。", + this.GetZOrder(), + this.localCount + ) + ); + } + } + + private EmitLog(msg: string): void { + if (this.onLog !== undefined) { + this.onLog(msg); + } + } +} + +RegisterUIConfig(UIDemoMultiWindow, { + name: "UIDemoMultiWindow", + assetKey: ASSET_KEYS.UI_DEMO_MULTI_WIDGET, + singleton: false, + layer: "popup", + type: "normal", + cacheTag: "no_cache", + blockWorldClick: true, +}); + +// ===== 6. 飘字提示 Toast (layer = "tips", blockWorldClick = false, 自动消失) ===== + +export interface ToastWindowArgs { + message: string; + durationSec?: number; + offsetIndex?: number; + onLog?: DemoLogFn; +} + +export class UIDemoToastWindow extends UIWindow { + public toastPill?: UE.UBorder; + public txtToastMessage?: UE.UTextBlock; + + private onLog?: DemoLogFn; + + protected override OnBindWidgets(): void { + this.toastPill = this.RequireWidget("ToastPill"); + this.txtToastMessage = this.RequireWidget("TxtToastMessage"); + } + + protected override OnPreShow(args?: unknown): void { + const a = args as ToastWindowArgs | undefined; + const msg = a !== undefined ? a.message : "飘字通知"; + const duration = a !== undefined && a.durationSec !== undefined ? a.durationSec : 2.2; + const offsetIdx = a !== undefined && a.offsetIndex !== undefined ? a.offsetIndex : 0; + this.onLog = a !== undefined ? a.onLog : undefined; + + if (this.txtToastMessage !== undefined) { + this.txtToastMessage.SetText(msg); + } + if (this.toastPill !== undefined && UE !== undefined && UE.ULuaUIEventSubsystem !== undefined) { + const pos = UE.FVector2D(); + pos.X = 0; + pos.Y = 92 + (offsetIdx % 4) * 48; + UE.ULuaUIEventSubsystem.SetCanvasPosition(this.toastPill, pos); + } + + // 使用 WorldTimer 定时自动关闭,切图或手动关闭时通过 owner=this 自动取消 + this.ctx.scheduler.AddWorldTimer( + duration, + () => { + this.Close(); + }, + this + ); + + if (this.onLog !== undefined) { + this.onLog(string.format("[Toast] 弹出提示:%s(%.1fs 后自动关闭,不抢焦点)", msg, duration)); + } + } +} + +RegisterUIConfig(UIDemoToastWindow, { + name: "UIDemoToastWindow", + assetKey: ASSET_KEYS.UI_DEMO_TOAST_WIDGET, + singleton: false, + layer: "tips", + type: "popup", + cacheTag: "no_cache", + blockWorldClick: false, +}); + +// ===== 7. 系统顶层弹窗 (layer = "system", ZOrder 400+) ===== + +export interface SystemWindowArgs { + onLog?: DemoLogFn; +} + +export class UIDemoSystemWindow extends UIWindow { + public txtSystemBody?: UE.UTextBlock; + public btnSystemAck?: UE.UButton; + private onLog?: DemoLogFn; + + protected override OnBindWidgets(): void { + this.txtSystemBody = this.RequireWidget("TxtSystemBody"); + this.btnSystemAck = this.RequireWidget("BtnSystemAck"); + + this.BindButtonClick(this.btnSystemAck, () => { + this.Close(); + }); + } + + protected override OnPreShow(args?: unknown): void { + const a = args as SystemWindowArgs | undefined; + this.onLog = a !== undefined ? a.onLog : undefined; + if (this.txtSystemBody !== undefined) { + this.txtSystemBody.SetText( + string.format( + "Layer: system | ZOrder: %d\n优先级始终高于 normal / popup / tips 全部层级,常用于断线重连或强制系统公告。", + this.GetZOrder() + ) + ); + } + if (this.onLog !== undefined) { + this.onLog(string.format("[System] 打开系统级顶层弹窗(ZOrder=%d)", this.GetZOrder())); + } + } + + protected override OnClose(): void { + if (this.onLog !== undefined) { + this.onLog("[System] 已确认关闭系统弹窗"); + } + } +} + +RegisterUIConfig(UIDemoSystemWindow, { + name: "UIDemoSystemWindow", + assetKey: ASSET_KEYS.UI_DEMO_SYSTEM_WIDGET, + singleton: true, + layer: "system", + type: "popup", + cacheTag: "no_cache", + blockWorldClick: true, +}); diff --git a/Script/ts/src/tests/ue/run_ue_tests.ts b/Script/ts/src/tests/ue/run_ue_tests.ts index ffe9b32..40e30ea 100644 --- a/Script/ts/src/tests/ue/run_ue_tests.ts +++ b/Script/ts/src/tests/ue/run_ue_tests.ts @@ -9,6 +9,17 @@ import { UEStorageBackend } from "../../framework/storage/storage_backend"; import type { UIDelegateBridge } from "../../framework/ui/ui_delegate_bridge"; import { MiniSettingsWindow } from "../../game/setting/mini_settings_window"; import { SettingService } from "../../game/setting/setting_service"; +import { DemoHubWindow } from "../../game/demo/demo_hub_window"; +import { OpenDemoHub, OpenUIDemoMain } from "../../game/demo/demo_router"; +import { + UIDemoCachedWindow, + UIDemoFullscreenWindow, + UIDemoModalWindow, + UIDemoMultiWindow, + UIDemoNormalWindow, + UIDemoSystemWindow, + UIDemoToastWindow, +} from "../../game/demo/ui_demo/ui_demo_windows"; import { GetPrimaryUIManager } from "../../game/startup"; import { ScopedObject } from "../../share/base/scoped_object"; import { Assert, AssertEqual, FormatReport, RunSuites, type TestSuite, type TestSummary } from "../harness/test_runner"; @@ -290,6 +301,184 @@ export function RunAllUETests( }, ], }, + { + name: "UE.DemoHubAndUIDemo", + cases: [ + { + name: "Bootstrap DemoHubWindow loads Chinese UMG cards and cleans up with zero leaks", + fn: () => { + Assert(gameInstance !== undefined && world !== undefined, "GI & World required"); + const ctx = GetGameInstanceContext(gameInstance!)!; + const uiMgr = GetPrimaryUIManager(ctx)!; + const resSvc = ctx.GetService("resource")!; + const uiBridge = ctx.GetService("uiDelegateBridge")!; + + ctx.OnWorldCleanup(world); + + let hubOpened = false; + const hub = OpenDemoHub(ctx, (ok) => { + hubOpened = ok; + }); + Assert(hub !== undefined, "DemoHubWindow controller created"); + + PumpUEFrames(25, 0.02); + + Assert(hubOpened && hub!.IsLoaded(), "DemoHubWindow loaded"); + Assert(hub!.itemWidgets.length >= 1, "DemoHub dynamically populated demo cards"); + Assert(hub!.itemEnterButtons["ui_demo"] !== undefined, "UI Demo entry button created"); + + hub!.Close(); + Assert(hub!.IsDisposed(), "DemoHubWindow disposed cleanly"); + AssertEqual(uiMgr.GetDiagnostics().openWindows, 0, "openWindows back to 0"); + AssertEqual(uiBridge.GetActiveBindingCount(), 0, "delegate bindings back to 0"); + AssertEqual(resSvc.GetDiagnostics().nativeTotalRefCount, 0, "resource refs back to 0"); + }, + }, + { + name: "UIDemoMainWindow exercises all UMG widgets and all 7 window types with zero leaks", + fn: () => { + Assert(gameInstance !== undefined && world !== undefined, "GI & World required"); + const ctx = GetGameInstanceContext(gameInstance!)!; + const uiMgr = GetPrimaryUIManager(ctx)!; + const resSvc = ctx.GetService("resource")!; + const uiBridge = ctx.GetService("uiDelegateBridge")!; + + ctx.OnWorldCleanup(world); + + let mainOpened = false; + const mainWin = OpenUIDemoMain(ctx, (ok) => { + mainOpened = ok; + })!; + Assert(mainWin !== undefined, "UIDemoMainWindow created"); + + PumpUEFrames(30, 0.02); + Assert(mainOpened && mainWin.IsLoaded(), "UIDemoMainWindow loaded"); + + // 1. Test UMG widget delegates via real UE C++ Simulate* helpers + Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(mainWin.btnDemoAction), "Button click"); + Assert(UE.ULuaUIEventSubsystem.SimulateButtonHover(mainWin.btnDemoAction, true), "Button hover"); + AssertEqual(mainWin.actionClickCount, 1); + AssertEqual(mainWin.actionHovered, true); + + Assert(UE.ULuaUIEventSubsystem.SimulateCheckBoxToggle(mainWin.chkFeature, true), "CheckBox toggle"); + AssertEqual(mainWin.checkboxChecked, true); + + Assert(UE.ULuaUIEventSubsystem.SimulateSliderValue(mainWin.sliderDemo, 0.75), "Slider value"); + Assert(math.abs(mainWin.sliderValue - 0.75) < 0.001, "sliderValue updated"); + + Assert(UE.ULuaUIEventSubsystem.SimulateSpinBoxValue(mainWin.spinDemo, 250), "SpinBox value"); + AssertEqual(mainWin.spinValue, 250); + + Assert( + UE.ULuaUIEventSubsystem.SimulateEditableTextChange(mainWin.inputNickname, "星河骑士"), + "EditableText change" + ); + AssertEqual(mainWin.draftNickname, "星河骑士"); + + Assert( + UE.ULuaUIEventSubsystem.SimulateEditableTextCommit(mainWin.inputNickname, "星河骑士", 1), + "EditableText commit" + ); + AssertEqual(mainWin.currentNickname, "星河骑士"); + + Assert( + UE.ULuaUIEventSubsystem.SimulateComboBoxSelect(mainWin.comboTheme, "翡翠绿(稀有)"), + "ComboBox select" + ); + AssertEqual(mainWin.selectedTheme, "翡翠绿(稀有)"); + + // 2. Test dynamic ScrollBox list items & delegate cleanup + const bindingsBeforeList = uiBridge.GetActiveBindingCount(); + mainWin.AddDynamicListItems(3); + AssertEqual(mainWin.dynamicItemCount, 3, "3 dynamic items added"); + Assert(uiBridge.GetActiveBindingCount() > bindingsBeforeList, "list item button delegates bound"); + mainWin.ClearDynamicListItems(); + AssertEqual(mainWin.dynamicItemCount, 0, "dynamic items cleared"); + AssertEqual(uiBridge.GetActiveBindingCount(), bindingsBeforeList, "list item delegates fully unbound"); + + // 3. Test all 7 window types + // 3a. Normal singleton + const norm1 = mainWin.OpenNormalDemoWindow()!; + const norm2 = mainWin.OpenNormalDemoWindow()!; + AssertEqual(norm1, norm2, "Normal window is singleton"); + + // 3b. Fullscreen hides MainWindow and restores it upon close + const fullWin = mainWin.OpenFullscreenDemoWindow()!; + + // 3c. Modal popup with confirm callback + let modalConfirmed = false; + const modalWin = uiMgr.ShowUI(UIDemoModalWindow, { + title: "测试弹窗", + message: "测试模态确认", + onConfirm: () => { + modalConfirmed = true; + }, + })!; + + // 3d. Cached window + const cachedWin = mainWin.OpenCachedDemoWindow()!; + + // 3e. Multi-instance (2 distinct controllers) + const multi1 = mainWin.OpenMultiDemoWindow()!; + const multi2 = mainWin.OpenMultiDemoWindow()!; + Assert(multi1 !== multi2, "Multi-instance creates distinct windows"); + + // 3f. System top layer + const sysWin = mainWin.OpenSystemDemoWindow()!; + + // 3g. Toast (tips layer, non-blocking, short duration) + const toastWin = mainWin.ShowToast("自动测试飘字", 0.1)!; + + PumpUEFrames(30, 0.02); + + // After 0.6s of pumped frames, toast (0.1s) should have auto-closed! + Assert(toastWin.IsDisposed(), "Toast auto-closed via WorldTimer"); + Assert(!mainWin.IsVisible(), "MainWindow hidden while Fullscreen is open"); + AssertEqual(uiMgr.GetDiagnostics().topWindowName, "UIDemoSystemWindow", "System window on top"); + AssertEqual(uiMgr.GetDiagnostics().inputMode, "ui", "Input mode stays UI"); + + // Confirm modal + Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(modalWin.btnModalConfirm), "Click Modal Confirm"); + Assert(modalConfirmed, "Modal confirm callback fired"); + Assert(modalWin.IsDisposed(), "Modal disposed after confirm"); + + // Cached window: click -> close to cache -> reopen -> click strictly once + Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(cachedWin.btnCachedAction), "Cached click #1"); + AssertEqual(cachedWin.clickCount, 1); + cachedWin.Close(); + Assert(cachedWin.IsCached(), "Cached window moved to cache"); + const cachedReused = mainWin.OpenCachedDemoWindow()!; + AssertEqual(cachedReused, cachedWin, "Cached window reused"); + AssertEqual(cachedReused.reuseCount, 1, "OnReuseUI invoked once"); + Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(cachedReused.btnCachedAction), "Cached click #2"); + AssertEqual(cachedReused.clickCount, 2, "Cached click after reuse increments by exactly 1"); + + // Close fullscreen -> MainWindow automatically restored! + fullWin.Close(); + Assert(mainWin.IsVisible(), "MainWindow automatically restored after Fullscreen closed"); + + // Clean teardown everything -> 0 leaks across UI, Delegates, Resources + uiMgr.CloseAll(true); + AssertEqual(uiMgr.GetDiagnostics().openWindows, 0, "openWindows back to 0"); + AssertEqual(uiMgr.GetDiagnostics().cachedWindows, 0, "cachedWindows back to 0"); + AssertEqual(uiBridge.GetActiveBindingCount(), 0, "delegate bindings back to 0"); + AssertEqual(resSvc.GetDiagnostics().nativeTotalRefCount, 0, "resource refcount back to 0"); + + // Verify unused symbol check stays clean + Assert( + DemoHubWindow !== undefined && + UIDemoNormalWindow !== undefined && + UIDemoFullscreenWindow !== undefined && + UIDemoCachedWindow !== undefined && + UIDemoMultiWindow !== undefined && + UIDemoToastWindow !== undefined && + UIDemoSystemWindow !== undefined, + "all demo window classes registered" + ); + }, + }, + ], + }, ]; const summary = RunSuites(suites); diff --git a/Script/ts/src/tests/unit/ui_and_resource_test.ts b/Script/ts/src/tests/unit/ui_and_resource_test.ts index 29638c9..0622a9f 100644 --- a/Script/ts/src/tests/unit/ui_and_resource_test.ts +++ b/Script/ts/src/tests/unit/ui_and_resource_test.ts @@ -257,6 +257,54 @@ RegisterUIConfig(CachedTestWindow, { cacheTag: "cache", }); +class FullscreenTestWindow extends UIWindow { + protected override OnBindWidgets(): void { + this.RequireWidget("BtnClose"); + } +} + +RegisterUIConfig(FullscreenTestWindow, { + name: "FullscreenTestWindow", + assetKey: ASSET_KEYS.MINI_SETTINGS_WIDGET, + singleton: true, + layer: "normal", + type: "fullscreen", + cacheTag: "no_cache", + blockWorldClick: true, +}); + +class ToastTestWindow extends UIWindow { + protected override OnBindWidgets(): void { + this.RequireWidget("TxtStatus"); + } +} + +RegisterUIConfig(ToastTestWindow, { + name: "ToastTestWindow", + assetKey: ASSET_KEYS.MINI_SETTINGS_WIDGET, + singleton: false, + layer: "tips", + type: "popup", + cacheTag: "no_cache", + blockWorldClick: false, +}); + +class SystemTestWindow extends UIWindow { + protected override OnBindWidgets(): void { + this.RequireWidget("BtnClose"); + } +} + +RegisterUIConfig(SystemTestWindow, { + name: "SystemTestWindow", + assetKey: ASSET_KEYS.MINI_SETTINGS_WIDGET, + singleton: true, + layer: "system", + type: "popup", + cacheTag: "no_cache", + blockWorldClick: true, +}); + export function CreateUIAndResourceSuite(): TestSuite { return { name: "Step2B_3.UIAndResource", @@ -385,6 +433,63 @@ export function CreateUIAndResourceSuite(): TestSuite { ctx.Dispose(); }, }, + { + name: "UIManager fullscreen auto-hide/restore, non-blocking tips focus preservation, and layer ZOrder priority", + fn: () => { + const ctx = new GameInstanceContext(); + const resBackend = new MockResourceBackend(); + const resSvc = new ResourceService(ctx, resBackend); + resBackend.service = resSvc; + const btnBackend = new MockButtonBackend(); + const btnBridge = new UIDelegateBridge(ctx, btnBackend); + btnBackend.bridge = btnBridge; + ctx.RegisterService("resource", resSvc); + ctx.RegisterService("uiDelegateBridge", btnBridge); + + const widgetFactory = new MockWidgetFactory(); + const lp = ctx.GetOrCreateLocalPlayer(0); + const uiMgr = lp.RegisterService( + "uiManager", + new UIManager(ctx, lp, resSvc, widgetFactory, new MockWidgetAdapter()) + ); + + // 1. Open base normal window (blocking) + const baseWin = uiMgr.ShowUI(CachedTestWindow)!; + resBackend.FlushAll(); + Assert(baseWin.IsVisible(), "base window visible"); + AssertEqual(uiMgr.GetDiagnostics().inputMode, "ui"); + + // 2. Open non-blocking tips toast -> must NOT drop inputMode back to game + const toast1 = uiMgr.ShowUI(ToastTestWindow)!; + resBackend.FlushAll(); + AssertEqual(uiMgr.GetDiagnostics().inputMode, "ui", "non-blocking tips preserves underlying UI input mode"); + AssertEqual(uiMgr.GetDiagnostics().topWindowName, "ToastTestWindow", "tips has higher ZOrder than normal"); + toast1.Close(); + + // 3. Open fullscreen window -> hides underlying normal window, restores on close + const fullWin = uiMgr.ShowUI(FullscreenTestWindow)!; + resBackend.FlushAll(); + Assert(!baseWin.IsVisible(), "base window hidden while fullscreen is active"); + Assert(baseWin.IsHiddenByFullscreen(), "base window marked hiddenByFullscreen"); + + // 4. Open system window on top -> highest layer ZOrder wins GetTopWindow + const sysWin = uiMgr.ShowUI(SystemTestWindow)!; + resBackend.FlushAll(); + AssertEqual(uiMgr.GetDiagnostics().topWindowName, "SystemTestWindow"); + + // CloseAllExcept(baseWin) closes fullscreen + system and restores baseWin + const closedCount = uiMgr.CloseAllExcept(baseWin, false); + AssertEqual(closedCount, 2, "closed fullscreen and system windows"); + Assert(baseWin.IsVisible(), "base window restored after fullscreen closed"); + Assert(!baseWin.IsHiddenByFullscreen(), "hiddenByFullscreen cleared"); + + uiMgr.CloseAll(true); + AssertEqual(uiMgr.GetDiagnostics().openWindows, 0); + AssertEqual(btnBackend.GetActiveBindingCount(), 0); + AssertEqual(resSvc.GetDiagnostics().nativeTotalRefCount, 0); + ctx.Dispose(); + }, + }, ], }; } diff --git a/Script/ts/types/ue/Game/UI/Demo.d.ts b/Script/ts/types/ue/Game/UI/Demo.d.ts new file mode 100644 index 0000000..a4e394b --- /dev/null +++ b/Script/ts/types/ue/Game/UI/Demo.d.ts @@ -0,0 +1,152 @@ +// Auto-generated by UnLua TypeScript Generator (Generate IntelliSense & TS). +// Do not edit manually. Excludes runtime types owned by unlua.d.ts. + +declare namespace UE { + class WBP_DemoHub_C extends UUserWidget { + TxtRuntimeInfo: UTextBlock; + TxtHubTitle: UTextBlock; + TxtHubSubtitle: UTextBlock; + ScrollDemoList: UScrollBox; + BtnOpenMiniSettings: UButton; + static StaticClass(this: void): UClass; + } + + class WBP_DemoHubItem_C extends UUserWidget { + TxtEnterLabel: UTextBlock; + TxtDemoTitle: UTextBlock; + TxtDemoMeta: UTextBlock; + TxtDemoDesc: UTextBlock; + CardBorder: UBorder; + BtnEnterDemo: UButton; + static StaticClass(this: void): UClass; + } + + class WBP_UIDemoCached_C extends UUserWidget { + TxtCachedTitle: UTextBlock; + TxtCachedStats: UTextBlock; + BtnCachedClose: UButton; + BtnCachedAction: UButton; + static StaticClass(this: void): UClass; + } + + class WBP_UIDemoFullscreen_C extends UUserWidget { + TxtFullTitle: UTextBlock; + TxtFullDesc: UTextBlock; + ImgFullPreview: UImage; + BtnFullOpenModal: UButton; + BtnFullClose: UButton; + static StaticClass(this: void): UClass; + } + + class WBP_UIDemoListItem_C extends UUserWidget { + TxtItemTitle: UTextBlock; + BtnItemDelete: UButton; + BtnItemAction: UButton; + static StaticClass(this: void): UClass; + } + + class WBP_UIDemoMain_C extends UUserWidget { + TxtSpinStatus: UTextBlock; + TxtSliderStatus: UTextBlock; + TxtRichSample: UTextBlock; + TxtProgressPlay: UTextBlock; + TxtPlayerName: UTextBlock; + TxtListSummary: UTextBlock; + TxtInputStatus: UTextBlock; + TxtImageStatus: UTextBlock; + TxtHudStats: UTextBlock; + TxtEventLog: UTextBlock; + TxtDiagDetail: UTextBlock; + TxtDemoTarget: UTextBlock; + TxtComboStatus: UTextBlock; + TxtCheckStatus: UTextBlock; + TxtBasicBtnStatus: UTextBlock; + TabSwitcher: UWidgetSwitcher; + SpinDemo: USpinBox; + SliderDemo: USlider; + ScrollEventLog: UScrollBox; + ScrollDynamicList: UScrollBox; + ProgressDemo: UProgressBar; + InputNickname: UEditableTextBox; + ImgPreview: UImage; + ImgPlayerAvatar: UImage; + GridBadges: UUniformGridPanel; + ComboTheme: UComboBoxString; + ChkFeature: UCheckBox; + BtnWinToast: UButton; + BtnWinSystem: UButton; + BtnWinNormal: UButton; + BtnWinMulti: UButton; + BtnWinModal: UButton; + BtnWinFullscreen: UButton; + BtnWinCached: UButton; + BtnTopSettings: UButton; + BtnToggleDisable: UButton; + BtnTintTex: UButton; + BtnTabMedia: UButton; + BtnTabInput: UButton; + BtnTabDiag: UButton; + BtnTabBasic: UButton; + BtnSwitchTex: UButton; + BtnProgressReset: UButton; + BtnProgressPlay: UButton; + BtnListClear: UButton; + BtnListAddTen: UButton; + BtnListAddOne: UButton; + BtnEvictCache: UButton; + BtnDiagRefresh: UButton; + BtnDiagConcurrent: UButton; + BtnDiagCancelLoad: UButton; + BtnDemoTarget: UButton; + BtnDemoAction: UButton; + BtnCycleVis: UButton; + BtnCycleTextSize: UButton; + BtnCycleTextColor: UButton; + BtnCloseOthers: UButton; + BtnClearLog: UButton; + BtnBackToHub: UButton; + BtnApplyNickname: UButton; + BorderThemePreview: UBorder; + BarPlayerExp: UProgressBar; + static StaticClass(this: void): UClass; + } + + class WBP_UIDemoModal_C extends UUserWidget { + TxtModalTitle: UTextBlock; + TxtModalMessage: UTextBlock; + BtnModalConfirm: UButton; + BtnModalCancel: UButton; + static StaticClass(this: void): UClass; + } + + class WBP_UIDemoMulti_C extends UUserWidget { + TxtMultiTitle: UTextBlock; + TxtMultiBody: UTextBlock; + MultiCard: UBorder; + BtnMultiCount: UButton; + BtnMultiClose: UButton; + static StaticClass(this: void): UClass; + } + + class WBP_UIDemoNormal_C extends UUserWidget { + TxtNormalTitle: UTextBlock; + TxtNormalBody: UTextBlock; + BtnNormalPing: UButton; + BtnNormalClose: UButton; + static StaticClass(this: void): UClass; + } + + class WBP_UIDemoSystem_C extends UUserWidget { + TxtSystemTitle: UTextBlock; + TxtSystemBody: UTextBlock; + BtnSystemAck: UButton; + static StaticClass(this: void): UClass; + } + + class WBP_UIDemoToast_C extends UUserWidget { + TxtToastMessage: UTextBlock; + ToastPill: UBorder; + static StaticClass(this: void): UClass; + } + +} diff --git a/Script/ts/types/ue/Script/UnrealLuaDemo.d.ts b/Script/ts/types/ue/Script/UnrealLuaDemo.d.ts index ce364ea..e55a616 100644 --- a/Script/ts/types/ue/Script/UnrealLuaDemo.d.ts +++ b/Script/ts/types/ue/Script/UnrealLuaDemo.d.ts @@ -64,8 +64,24 @@ declare namespace UE { static StaticClass(this: void): UClass; } - class ULuaButtonClickProxy extends UObject { - HandleClicked(): void; + class ULuaButtonClickProxy extends ULuaWidgetEventProxyBase { + HandleEvent(): void; + static StaticClass(this: void): UClass; + } + + class ULuaCheckBoxProxy extends ULuaWidgetEventProxyBase { + HandleCheckStateChanged(bIsChecked: boolean): void; + static StaticClass(this: void): UClass; + } + + class ULuaComboBoxProxy extends ULuaWidgetEventProxyBase { + HandleSelectionChanged(SelectedItem: string, SelectionType: ESelectInfo): void; + static StaticClass(this: void): UClass; + } + + class ULuaEditableTextProxy extends ULuaWidgetEventProxyBase { + HandleTextCommitted(Text: string, CommitMethod: ETextCommit): void; + HandleTextChanged(Text: string): void; static StaticClass(this: void): UClass; } @@ -128,6 +144,16 @@ declare namespace UE { static StaticClass(this: void): UClass; } + class ULuaSliderProxy extends ULuaWidgetEventProxyBase { + HandleValueChanged(Value: number): void; + static StaticClass(this: void): UClass; + } + + class ULuaSpinBoxProxy extends ULuaWidgetEventProxyBase { + HandleValueChanged(Value: number): void; + static StaticClass(this: void): UClass; + } + class ULuaStorageLibrary extends UBlueprintFunctionLibrary { static WriteCorruptRawSlotForTest(this: void, SlotName: string, RawGarbage: string, UserIndex?: number): boolean; static SaveSlotUtf8(this: void, SlotName: string, PayloadUtf8: string, UserIndex?: number): ELuaStorageStatus; @@ -140,14 +166,35 @@ declare namespace UE { } class ULuaUIEventSubsystem extends UGameInstanceSubsystem { - ActiveButtonProxies: TMap; + ActiveProxies: TMap; + UnbindWidgetEvent(BindingId: number): boolean; UnbindButtonClicked(BindingId: number): boolean; + static SimulateSpinBoxValue(this: void, SpinBox: USpinBox | undefined, Value: number): boolean; + static SimulateSliderValue(this: void, Slider: USlider | undefined, Value: number): boolean; + static SimulateEditableTextCommit(this: void, TextBox: UEditableTextBox | undefined, NewText: string, CommitMethod: number): boolean; + static SimulateEditableTextChange(this: void, TextBox: UEditableTextBox | undefined, NewText: string): boolean; + static SimulateComboBoxSelect(this: void, ComboBox: UComboBoxString | undefined, Option: string): boolean; + static SimulateCheckBoxToggle(this: void, CheckBox: UCheckBox | undefined, bIsChecked: boolean): boolean; + static SimulateButtonHover(this: void, Button: UButton | undefined, bHovered: boolean): boolean; static SimulateButtonClick(this: void, Button: UButton | undefined): boolean; + static SetCanvasPosition(this: void, Widget: UWidget | undefined, Position: FVector2D): boolean; static GetFromGameInstance(this: void, GameInstance: UGameInstance | undefined): ULuaUIEventSubsystem; GetActiveBindingCount(): number; static FindChildWidgetByName(this: void, RootWidget: UUserWidget | undefined, WidgetName: string): UWidget; + BindSpinBoxChanged(SpinBox: USpinBox | undefined): number; + BindSliderChanged(Slider: USlider | undefined): number; + BindEditableTextCommitted(TextBox: UEditableTextBox | undefined): number; + BindEditableTextChanged(TextBox: UEditableTextBox | undefined): number; + BindComboBoxSelectionChanged(ComboBox: UComboBoxString | undefined): number; + BindCheckBoxChanged(CheckBox: UCheckBox | undefined): number; + BindButtonUnhovered(Button: UButton | undefined): number; + BindButtonHovered(Button: UButton | undefined): number; BindButtonClicked(Button: UButton | undefined): number; static StaticClass(this: void): UClass; } + class ULuaWidgetEventProxyBase extends UObject { + static StaticClass(this: void): UClass; + } + } diff --git a/Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp index 8a94253..4f694bf 100644 --- a/Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp +++ b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp @@ -200,6 +200,149 @@ bool FLuaCallbackBridge::CallInt(UObject* Target, const FString& ModuleName, con return bOk; } +bool FLuaCallbackBridge::CallIntBool(UObject* Target, const FString& ModuleName, const char* FuncName, int32 IntValue, bool bBoolValue) +{ + if (ModuleName.IsEmpty()) + { + return false; + } + + UnLua::FLuaEnv* Env = ResolveLuaEnv(Target); + if (!Env) + { + return false; + } + + lua_State* L = Env->GetMainState(); + if (!L) + { + return false; + } + + const int32 Top = lua_gettop(L); + int32 ErrHandlerIdx = 0; + if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx)) + { + lua_settop(L, Top); + return false; + } + + UnLua::PushUObject(L, Target); + lua_pushinteger(L, static_cast(IntValue)); + lua_pushboolean(L, bBoolValue ? 1 : 0); + const bool bOk = (lua_pcall(L, 3, 0, ErrHandlerIdx) == LUA_OK); + lua_settop(L, Top); + return bOk; +} + +bool FLuaCallbackBridge::CallIntFloat(UObject* Target, const FString& ModuleName, const char* FuncName, int32 IntValue, float FloatValue) +{ + if (ModuleName.IsEmpty()) + { + return false; + } + + UnLua::FLuaEnv* Env = ResolveLuaEnv(Target); + if (!Env) + { + return false; + } + + lua_State* L = Env->GetMainState(); + if (!L) + { + return false; + } + + const int32 Top = lua_gettop(L); + int32 ErrHandlerIdx = 0; + if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx)) + { + lua_settop(L, Top); + return false; + } + + UnLua::PushUObject(L, Target); + lua_pushinteger(L, static_cast(IntValue)); + lua_pushnumber(L, static_cast(FloatValue)); + const bool bOk = (lua_pcall(L, 3, 0, ErrHandlerIdx) == LUA_OK); + lua_settop(L, Top); + return bOk; +} + +bool FLuaCallbackBridge::CallIntString(UObject* Target, const FString& ModuleName, const char* FuncName, int32 IntValue, const FString& StrValue) +{ + if (ModuleName.IsEmpty()) + { + return false; + } + + UnLua::FLuaEnv* Env = ResolveLuaEnv(Target); + if (!Env) + { + return false; + } + + lua_State* L = Env->GetMainState(); + if (!L) + { + return false; + } + + const int32 Top = lua_gettop(L); + int32 ErrHandlerIdx = 0; + if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx)) + { + lua_settop(L, Top); + return false; + } + + UnLua::PushUObject(L, Target); + lua_pushinteger(L, static_cast(IntValue)); + const FTCHARToUTF8 StrUtf8(*StrValue); + lua_pushlstring(L, StrUtf8.Get(), StrUtf8.Length()); + const bool bOk = (lua_pcall(L, 3, 0, ErrHandlerIdx) == LUA_OK); + lua_settop(L, Top); + return bOk; +} + +bool FLuaCallbackBridge::CallIntStringInt(UObject* Target, const FString& ModuleName, const char* FuncName, int32 IntValue, const FString& StrValue, int32 ExtraInt) +{ + if (ModuleName.IsEmpty()) + { + return false; + } + + UnLua::FLuaEnv* Env = ResolveLuaEnv(Target); + if (!Env) + { + return false; + } + + lua_State* L = Env->GetMainState(); + if (!L) + { + return false; + } + + const int32 Top = lua_gettop(L); + int32 ErrHandlerIdx = 0; + if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx)) + { + lua_settop(L, Top); + return false; + } + + UnLua::PushUObject(L, Target); + lua_pushinteger(L, static_cast(IntValue)); + const FTCHARToUTF8 StrUtf8(*StrValue); + lua_pushlstring(L, StrUtf8.Get(), StrUtf8.Length()); + lua_pushinteger(L, static_cast(ExtraInt)); + const bool bOk = (lua_pcall(L, 4, 0, ErrHandlerIdx) == LUA_OK); + lua_settop(L, Top); + return bOk; +} + bool FLuaCallbackBridge::CallResourceLoadCallback( UObject* GameInstanceTarget, const FString& ModuleName, diff --git a/Source/UnrealLuaDemo/Core/LuaCallbackBridge.h b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.h index 76cae6b..aba28da 100644 --- a/Source/UnrealLuaDemo/Core/LuaCallbackBridge.h +++ b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.h @@ -18,6 +18,10 @@ public: static bool Call(UObject* Target, const FString& ModuleName, const char* FuncName); static bool CallFloat(UObject* Target, const FString& ModuleName, const char* FuncName, float Value); static bool CallInt(UObject* Target, const FString& ModuleName, const char* FuncName, int32 Value); + static bool CallIntBool(UObject* Target, const FString& ModuleName, const char* FuncName, int32 IntValue, bool bBoolValue); + static bool CallIntFloat(UObject* Target, const FString& ModuleName, const char* FuncName, int32 IntValue, float FloatValue); + static bool CallIntString(UObject* Target, const FString& ModuleName, const char* FuncName, int32 IntValue, const FString& StrValue); + static bool CallIntStringInt(UObject* Target, const FString& ModuleName, const char* FuncName, int32 IntValue, const FString& StrValue, int32 ExtraInt); static bool CallResourceLoadCallback( UObject* GameInstanceTarget, const FString& ModuleName, diff --git a/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.cpp b/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.cpp index fe3db82..58ae651 100644 --- a/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.cpp +++ b/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.cpp @@ -5,17 +5,37 @@ #include "Blueprint/UserWidget.h" #include "Blueprint/WidgetTree.h" #include "Components/Button.h" +#include "Components/CanvasPanelSlot.h" +#include "Components/CheckBox.h" +#include "Components/ComboBoxString.h" +#include "Components/EditableTextBox.h" +#include "Components/Slider.h" +#include "Components/SpinBox.h" #include "Engine/GameInstance.h" -void ULuaButtonClickProxy::Init(ULuaUIEventSubsystem* InOwner, UButton* InButton, int32 InBindingId) +void ULuaButtonClickProxy::Init(ULuaUIEventSubsystem* InOwner, UButton* InButton, int32 InBindingId, EButtonEventKind InKind) { OwnerSubsystem = InOwner; BoundButton = InButton; BindingId = InBindingId; + EventKind = InKind; - if (InButton) + if (!InButton) { - InButton->OnClicked.AddDynamic(this, &ULuaButtonClickProxy::HandleClicked); + return; + } + + if (EventKind == EButtonEventKind::Clicked) + { + InButton->OnClicked.AddDynamic(this, &ULuaButtonClickProxy::HandleEvent); + } + else if (EventKind == EButtonEventKind::Hovered) + { + InButton->OnHovered.AddDynamic(this, &ULuaButtonClickProxy::HandleEvent); + } + else + { + InButton->OnUnhovered.AddDynamic(this, &ULuaButtonClickProxy::HandleEvent); } } @@ -23,17 +43,210 @@ void ULuaButtonClickProxy::Unbind() { if (UButton* Button = BoundButton.Get()) { - Button->OnClicked.RemoveDynamic(this, &ULuaButtonClickProxy::HandleClicked); + if (EventKind == EButtonEventKind::Clicked) + { + Button->OnClicked.RemoveDynamic(this, &ULuaButtonClickProxy::HandleEvent); + } + else if (EventKind == EButtonEventKind::Hovered) + { + Button->OnHovered.RemoveDynamic(this, &ULuaButtonClickProxy::HandleEvent); + } + else + { + Button->OnUnhovered.RemoveDynamic(this, &ULuaButtonClickProxy::HandleEvent); + } } BoundButton.Reset(); OwnerSubsystem.Reset(); } -void ULuaButtonClickProxy::HandleClicked() +void ULuaButtonClickProxy::HandleEvent() { if (ULuaUIEventSubsystem* Owner = OwnerSubsystem.Get()) { - Owner->DispatchButtonClicked(BindingId); + if (EventKind == EButtonEventKind::Clicked) + { + Owner->DispatchButtonClicked(BindingId); + } + else + { + Owner->DispatchActionEvent(BindingId); + } + } +} + +void ULuaCheckBoxProxy::Init(ULuaUIEventSubsystem* InOwner, UCheckBox* InCheckBox, int32 InBindingId) +{ + OwnerSubsystem = InOwner; + BoundCheckBox = InCheckBox; + BindingId = InBindingId; + + if (InCheckBox) + { + InCheckBox->OnCheckStateChanged.AddDynamic(this, &ULuaCheckBoxProxy::HandleCheckStateChanged); + } +} + +void ULuaCheckBoxProxy::Unbind() +{ + if (UCheckBox* CheckBox = BoundCheckBox.Get()) + { + CheckBox->OnCheckStateChanged.RemoveDynamic(this, &ULuaCheckBoxProxy::HandleCheckStateChanged); + } + BoundCheckBox.Reset(); + OwnerSubsystem.Reset(); +} + +void ULuaCheckBoxProxy::HandleCheckStateChanged(bool bIsChecked) +{ + if (ULuaUIEventSubsystem* Owner = OwnerSubsystem.Get()) + { + Owner->DispatchBoolChanged(BindingId, bIsChecked); + } +} + +void ULuaSliderProxy::Init(ULuaUIEventSubsystem* InOwner, USlider* InSlider, int32 InBindingId) +{ + OwnerSubsystem = InOwner; + BoundSlider = InSlider; + BindingId = InBindingId; + + if (InSlider) + { + InSlider->OnValueChanged.AddDynamic(this, &ULuaSliderProxy::HandleValueChanged); + } +} + +void ULuaSliderProxy::Unbind() +{ + if (USlider* Slider = BoundSlider.Get()) + { + Slider->OnValueChanged.RemoveDynamic(this, &ULuaSliderProxy::HandleValueChanged); + } + BoundSlider.Reset(); + OwnerSubsystem.Reset(); +} + +void ULuaSliderProxy::HandleValueChanged(float Value) +{ + if (ULuaUIEventSubsystem* Owner = OwnerSubsystem.Get()) + { + Owner->DispatchFloatChanged(BindingId, Value); + } +} + +void ULuaSpinBoxProxy::Init(ULuaUIEventSubsystem* InOwner, USpinBox* InSpinBox, int32 InBindingId) +{ + OwnerSubsystem = InOwner; + BoundSpinBox = InSpinBox; + BindingId = InBindingId; + + if (InSpinBox) + { + InSpinBox->OnValueChanged.AddDynamic(this, &ULuaSpinBoxProxy::HandleValueChanged); + } +} + +void ULuaSpinBoxProxy::Unbind() +{ + if (USpinBox* SpinBox = BoundSpinBox.Get()) + { + SpinBox->OnValueChanged.RemoveDynamic(this, &ULuaSpinBoxProxy::HandleValueChanged); + } + BoundSpinBox.Reset(); + OwnerSubsystem.Reset(); +} + +void ULuaSpinBoxProxy::HandleValueChanged(float Value) +{ + if (ULuaUIEventSubsystem* Owner = OwnerSubsystem.Get()) + { + Owner->DispatchFloatChanged(BindingId, Value); + } +} + +void ULuaEditableTextProxy::Init(ULuaUIEventSubsystem* InOwner, UEditableTextBox* InTextBox, int32 InBindingId, ETextEventKind InKind) +{ + OwnerSubsystem = InOwner; + BoundTextBox = InTextBox; + BindingId = InBindingId; + EventKind = InKind; + + if (!InTextBox) + { + return; + } + + if (EventKind == ETextEventKind::Changed) + { + InTextBox->OnTextChanged.AddDynamic(this, &ULuaEditableTextProxy::HandleTextChanged); + } + else + { + InTextBox->OnTextCommitted.AddDynamic(this, &ULuaEditableTextProxy::HandleTextCommitted); + } +} + +void ULuaEditableTextProxy::Unbind() +{ + if (UEditableTextBox* TextBox = BoundTextBox.Get()) + { + if (EventKind == ETextEventKind::Changed) + { + TextBox->OnTextChanged.RemoveDynamic(this, &ULuaEditableTextProxy::HandleTextChanged); + } + else + { + TextBox->OnTextCommitted.RemoveDynamic(this, &ULuaEditableTextProxy::HandleTextCommitted); + } + } + BoundTextBox.Reset(); + OwnerSubsystem.Reset(); +} + +void ULuaEditableTextProxy::HandleTextChanged(const FText& Text) +{ + if (ULuaUIEventSubsystem* Owner = OwnerSubsystem.Get()) + { + Owner->DispatchTextChanged(BindingId, Text.ToString()); + } +} + +void ULuaEditableTextProxy::HandleTextCommitted(const FText& Text, ETextCommit::Type CommitMethod) +{ + if (ULuaUIEventSubsystem* Owner = OwnerSubsystem.Get()) + { + Owner->DispatchTextCommitted(BindingId, Text.ToString(), static_cast(CommitMethod)); + } +} + +void ULuaComboBoxProxy::Init(ULuaUIEventSubsystem* InOwner, UComboBoxString* InComboBox, int32 InBindingId) +{ + OwnerSubsystem = InOwner; + BoundComboBox = InComboBox; + BindingId = InBindingId; + + if (InComboBox) + { + InComboBox->OnSelectionChanged.AddDynamic(this, &ULuaComboBoxProxy::HandleSelectionChanged); + } +} + +void ULuaComboBoxProxy::Unbind() +{ + if (UComboBoxString* ComboBox = BoundComboBox.Get()) + { + ComboBox->OnSelectionChanged.RemoveDynamic(this, &ULuaComboBoxProxy::HandleSelectionChanged); + } + BoundComboBox.Reset(); + OwnerSubsystem.Reset(); +} + +void ULuaComboBoxProxy::HandleSelectionChanged(FString SelectedItem, ESelectInfo::Type SelectionType) +{ + if (ULuaUIEventSubsystem* Owner = OwnerSubsystem.Get()) + { + Owner->DispatchSelectionChanged(BindingId, SelectedItem, static_cast(SelectionType)); } } @@ -44,14 +257,14 @@ ULuaUIEventSubsystem* ULuaUIEventSubsystem::GetFromGameInstance(UGameInstance* G void ULuaUIEventSubsystem::Deinitialize() { - for (TPair>& Pair : ActiveButtonProxies) + for (TPair>& Pair : ActiveProxies) { if (Pair.Value) { Pair.Value->Unbind(); } } - ActiveButtonProxies.Reset(); + ActiveProxies.Reset(); Super::Deinitialize(); } @@ -64,15 +277,132 @@ int32 ULuaUIEventSubsystem::BindButtonClicked(UButton* Button) const int32 BindingId = ++NextBindingId; ULuaButtonClickProxy* Proxy = NewObject(this); - Proxy->Init(this, Button, BindingId); - ActiveButtonProxies.Add(BindingId, Proxy); + Proxy->Init(this, Button, BindingId, ULuaButtonClickProxy::EButtonEventKind::Clicked); + ActiveProxies.Add(BindingId, Proxy); + return BindingId; +} + +int32 ULuaUIEventSubsystem::BindButtonHovered(UButton* Button) +{ + if (!IsValid(Button)) + { + return 0; + } + + const int32 BindingId = ++NextBindingId; + ULuaButtonClickProxy* Proxy = NewObject(this); + Proxy->Init(this, Button, BindingId, ULuaButtonClickProxy::EButtonEventKind::Hovered); + ActiveProxies.Add(BindingId, Proxy); + return BindingId; +} + +int32 ULuaUIEventSubsystem::BindButtonUnhovered(UButton* Button) +{ + if (!IsValid(Button)) + { + return 0; + } + + const int32 BindingId = ++NextBindingId; + ULuaButtonClickProxy* Proxy = NewObject(this); + Proxy->Init(this, Button, BindingId, ULuaButtonClickProxy::EButtonEventKind::Unhovered); + ActiveProxies.Add(BindingId, Proxy); + return BindingId; +} + +int32 ULuaUIEventSubsystem::BindCheckBoxChanged(UCheckBox* CheckBox) +{ + if (!IsValid(CheckBox)) + { + return 0; + } + + const int32 BindingId = ++NextBindingId; + ULuaCheckBoxProxy* Proxy = NewObject(this); + Proxy->Init(this, CheckBox, BindingId); + ActiveProxies.Add(BindingId, Proxy); + return BindingId; +} + +int32 ULuaUIEventSubsystem::BindSliderChanged(USlider* Slider) +{ + if (!IsValid(Slider)) + { + return 0; + } + + const int32 BindingId = ++NextBindingId; + ULuaSliderProxy* Proxy = NewObject(this); + Proxy->Init(this, Slider, BindingId); + ActiveProxies.Add(BindingId, Proxy); + return BindingId; +} + +int32 ULuaUIEventSubsystem::BindSpinBoxChanged(USpinBox* SpinBox) +{ + if (!IsValid(SpinBox)) + { + return 0; + } + + const int32 BindingId = ++NextBindingId; + ULuaSpinBoxProxy* Proxy = NewObject(this); + Proxy->Init(this, SpinBox, BindingId); + ActiveProxies.Add(BindingId, Proxy); + return BindingId; +} + +int32 ULuaUIEventSubsystem::BindEditableTextChanged(UEditableTextBox* TextBox) +{ + if (!IsValid(TextBox)) + { + return 0; + } + + const int32 BindingId = ++NextBindingId; + ULuaEditableTextProxy* Proxy = NewObject(this); + Proxy->Init(this, TextBox, BindingId, ULuaEditableTextProxy::ETextEventKind::Changed); + ActiveProxies.Add(BindingId, Proxy); + return BindingId; +} + +int32 ULuaUIEventSubsystem::BindEditableTextCommitted(UEditableTextBox* TextBox) +{ + if (!IsValid(TextBox)) + { + return 0; + } + + const int32 BindingId = ++NextBindingId; + ULuaEditableTextProxy* Proxy = NewObject(this); + Proxy->Init(this, TextBox, BindingId, ULuaEditableTextProxy::ETextEventKind::Committed); + ActiveProxies.Add(BindingId, Proxy); + return BindingId; +} + +int32 ULuaUIEventSubsystem::BindComboBoxSelectionChanged(UComboBoxString* ComboBox) +{ + if (!IsValid(ComboBox)) + { + return 0; + } + + const int32 BindingId = ++NextBindingId; + ULuaComboBoxProxy* Proxy = NewObject(this); + Proxy->Init(this, ComboBox, BindingId); + ActiveProxies.Add(BindingId, Proxy); return BindingId; } bool ULuaUIEventSubsystem::UnbindButtonClicked(int32 BindingId) { - TObjectPtr Proxy; - if (!ActiveButtonProxies.RemoveAndCopyValue(BindingId, Proxy)) + return UnbindWidgetEvent(BindingId); +} + +bool ULuaUIEventSubsystem::UnbindWidgetEvent(int32 BindingId) +{ + TObjectPtr Proxy; + if (!ActiveProxies.RemoveAndCopyValue(BindingId, Proxy)) { return false; } @@ -93,6 +423,20 @@ UWidget* ULuaUIEventSubsystem::FindChildWidgetByName(UUserWidget* RootWidget, co return RootWidget->WidgetTree->FindWidget(WidgetName); } +bool ULuaUIEventSubsystem::SetCanvasPosition(UWidget* Widget, const FVector2D& Position) +{ + if (!IsValid(Widget)) + { + return false; + } + if (UCanvasPanelSlot* CanvasSlot = Cast(Widget->Slot)) + { + CanvasSlot->SetPosition(Position); + return true; + } + return false; +} + bool ULuaUIEventSubsystem::SimulateButtonClick(UButton* Button) { if (!IsValid(Button)) @@ -103,11 +447,150 @@ bool ULuaUIEventSubsystem::SimulateButtonClick(UButton* Button) return true; } +bool ULuaUIEventSubsystem::SimulateButtonHover(UButton* Button, bool bHovered) +{ + if (!IsValid(Button)) + { + return false; + } + if (bHovered) + { + Button->OnHovered.Broadcast(); + } + else + { + Button->OnUnhovered.Broadcast(); + } + return true; +} + +bool ULuaUIEventSubsystem::SimulateCheckBoxToggle(UCheckBox* CheckBox, bool bIsChecked) +{ + if (!IsValid(CheckBox)) + { + return false; + } + CheckBox->SetIsChecked(bIsChecked); + CheckBox->OnCheckStateChanged.Broadcast(bIsChecked); + return true; +} + +bool ULuaUIEventSubsystem::SimulateSliderValue(USlider* Slider, float Value) +{ + if (!IsValid(Slider)) + { + return false; + } + Slider->SetValue(Value); + Slider->OnValueChanged.Broadcast(Value); + return true; +} + +bool ULuaUIEventSubsystem::SimulateSpinBoxValue(USpinBox* SpinBox, float Value) +{ + if (!IsValid(SpinBox)) + { + return false; + } + SpinBox->SetValue(Value); + SpinBox->OnValueChanged.Broadcast(Value); + return true; +} + +bool ULuaUIEventSubsystem::SimulateEditableTextChange(UEditableTextBox* TextBox, const FString& NewText) +{ + if (!IsValid(TextBox)) + { + return false; + } + const FText TextVal = FText::FromString(NewText); + TextBox->SetText(TextVal); + TextBox->OnTextChanged.Broadcast(TextVal); + return true; +} + +bool ULuaUIEventSubsystem::SimulateEditableTextCommit(UEditableTextBox* TextBox, const FString& NewText, int32 CommitMethod) +{ + if (!IsValid(TextBox)) + { + return false; + } + const FText TextVal = FText::FromString(NewText); + TextBox->SetText(TextVal); + TextBox->OnTextCommitted.Broadcast(TextVal, static_cast(CommitMethod)); + return true; +} + +bool ULuaUIEventSubsystem::SimulateComboBoxSelect(UComboBoxString* ComboBox, const FString& Option) +{ + if (!IsValid(ComboBox)) + { + return false; + } + ComboBox->SetSelectedOption(Option); + ComboBox->OnSelectionChanged.Broadcast(Option, ESelectInfo::OnMouseClick); + return true; +} + void ULuaUIEventSubsystem::DispatchButtonClicked(int32 BindingId) { - if (!ActiveButtonProxies.Contains(BindingId)) + if (!ActiveProxies.Contains(BindingId)) { return; } FLuaCallbackBridge::CallInt(GetGameInstance(), LuaCallbackModule, "OnNativeButtonClicked", BindingId); } + +void ULuaUIEventSubsystem::DispatchActionEvent(int32 BindingId) +{ + if (!ActiveProxies.Contains(BindingId)) + { + return; + } + FLuaCallbackBridge::CallInt(GetGameInstance(), LuaCallbackModule, "OnNativeActionEvent", BindingId); +} + +void ULuaUIEventSubsystem::DispatchBoolChanged(int32 BindingId, bool bValue) +{ + if (!ActiveProxies.Contains(BindingId)) + { + return; + } + FLuaCallbackBridge::CallIntBool(GetGameInstance(), LuaCallbackModule, "OnNativeBoolChanged", BindingId, bValue); +} + +void ULuaUIEventSubsystem::DispatchFloatChanged(int32 BindingId, float Value) +{ + if (!ActiveProxies.Contains(BindingId)) + { + return; + } + FLuaCallbackBridge::CallIntFloat(GetGameInstance(), LuaCallbackModule, "OnNativeFloatChanged", BindingId, Value); +} + +void ULuaUIEventSubsystem::DispatchTextChanged(int32 BindingId, const FString& Text) +{ + if (!ActiveProxies.Contains(BindingId)) + { + return; + } + FLuaCallbackBridge::CallIntString(GetGameInstance(), LuaCallbackModule, "OnNativeTextChanged", BindingId, Text); +} + +void ULuaUIEventSubsystem::DispatchTextCommitted(int32 BindingId, const FString& Text, int32 CommitMethod) +{ + if (!ActiveProxies.Contains(BindingId)) + { + return; + } + FLuaCallbackBridge::CallIntStringInt(GetGameInstance(), LuaCallbackModule, "OnNativeTextCommitted", BindingId, Text, CommitMethod); +} + +void ULuaUIEventSubsystem::DispatchSelectionChanged(int32 BindingId, const FString& SelectedItem, int32 SelectType) +{ + if (!ActiveProxies.Contains(BindingId)) + { + return; + } + FLuaCallbackBridge::CallIntStringInt(GetGameInstance(), LuaCallbackModule, "OnNativeSelectionChanged", BindingId, SelectedItem, SelectType); +} diff --git a/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.h b/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.h index 47badab..14b5bd0 100644 --- a/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.h +++ b/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.h @@ -4,34 +4,151 @@ #include "CoreMinimal.h" #include "Subsystems/GameInstanceSubsystem.h" +#include "Types/SlateEnums.h" #include "LuaUIEventSubsystem.generated.h" class UButton; +class UCheckBox; +class UComboBoxString; +class UEditableTextBox; +class USlider; +class USpinBox; class UUserWidget; +class UWidget; class ULuaUIEventSubsystem; -UCLASS() -class UNREALLUADEMO_API ULuaButtonClickProxy : public UObject +UCLASS(Abstract) +class UNREALLUADEMO_API ULuaWidgetEventProxyBase : public UObject { GENERATED_BODY() public: - void Init(ULuaUIEventSubsystem* InOwner, UButton* InButton, int32 InBindingId); - void Unbind(); + virtual void Unbind() {} + +protected: + TWeakObjectPtr OwnerSubsystem; + int32 BindingId = 0; +}; + +UCLASS() +class UNREALLUADEMO_API ULuaButtonClickProxy : public ULuaWidgetEventProxyBase +{ + GENERATED_BODY() + +public: + enum class EButtonEventKind : uint8 + { + Clicked, + Hovered, + Unhovered, + }; + + void Init(ULuaUIEventSubsystem* InOwner, UButton* InButton, int32 InBindingId, EButtonEventKind InKind = EButtonEventKind::Clicked); + virtual void Unbind() override; UFUNCTION() - void HandleClicked(); + void HandleEvent(); private: - TWeakObjectPtr OwnerSubsystem; TWeakObjectPtr BoundButton; - int32 BindingId = 0; + EButtonEventKind EventKind = EButtonEventKind::Clicked; +}; + +UCLASS() +class UNREALLUADEMO_API ULuaCheckBoxProxy : public ULuaWidgetEventProxyBase +{ + GENERATED_BODY() + +public: + void Init(ULuaUIEventSubsystem* InOwner, UCheckBox* InCheckBox, int32 InBindingId); + virtual void Unbind() override; + + UFUNCTION() + void HandleCheckStateChanged(bool bIsChecked); + +private: + TWeakObjectPtr BoundCheckBox; +}; + +UCLASS() +class UNREALLUADEMO_API ULuaSliderProxy : public ULuaWidgetEventProxyBase +{ + GENERATED_BODY() + +public: + void Init(ULuaUIEventSubsystem* InOwner, USlider* InSlider, int32 InBindingId); + virtual void Unbind() override; + + UFUNCTION() + void HandleValueChanged(float Value); + +private: + TWeakObjectPtr BoundSlider; +}; + +UCLASS() +class UNREALLUADEMO_API ULuaSpinBoxProxy : public ULuaWidgetEventProxyBase +{ + GENERATED_BODY() + +public: + void Init(ULuaUIEventSubsystem* InOwner, USpinBox* InSpinBox, int32 InBindingId); + virtual void Unbind() override; + + UFUNCTION() + void HandleValueChanged(float Value); + +private: + TWeakObjectPtr BoundSpinBox; +}; + +UCLASS() +class UNREALLUADEMO_API ULuaEditableTextProxy : public ULuaWidgetEventProxyBase +{ + GENERATED_BODY() + +public: + enum class ETextEventKind : uint8 + { + Changed, + Committed, + }; + + void Init(ULuaUIEventSubsystem* InOwner, UEditableTextBox* InTextBox, int32 InBindingId, ETextEventKind InKind); + virtual void Unbind() override; + + UFUNCTION() + void HandleTextChanged(const FText& Text); + + UFUNCTION() + void HandleTextCommitted(const FText& Text, ETextCommit::Type CommitMethod); + +private: + TWeakObjectPtr BoundTextBox; + ETextEventKind EventKind = ETextEventKind::Changed; +}; + +UCLASS() +class UNREALLUADEMO_API ULuaComboBoxProxy : public ULuaWidgetEventProxyBase +{ + GENERATED_BODY() + +public: + void Init(ULuaUIEventSubsystem* InOwner, UComboBoxString* InComboBox, int32 InBindingId); + virtual void Unbind() override; + + UFUNCTION() + void HandleSelectionChanged(FString SelectedItem, ESelectInfo::Type SelectionType); + +private: + TWeakObjectPtr BoundComboBox; }; /** * Per-GameInstance UMG delegate bridge for pure TS UI controllers. - * Routes UButton::OnClicked to TS `framework.ui.ui_delegate_bridge.OnNativeButtonClicked(gi, bindingId)` - * without requiring Lua UObject inheritance (@unlua), preserving 100% single-file hot-reload. + * Routes UMG widget delegates (Button, CheckBox, Slider, SpinBox, EditableTextBox, ComboBoxString) + * to TS `framework.ui.ui_delegate_bridge` without requiring Lua UObject inheritance (@unlua), + * preserving 100% single-file hot-reload. */ UCLASS() class UNREALLUADEMO_API ULuaUIEventSubsystem : public UGameInstanceSubsystem @@ -48,25 +165,83 @@ public: UFUNCTION(BlueprintCallable, Category = "Lua|UI") int32 BindButtonClicked(UButton* Button); + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + int32 BindButtonHovered(UButton* Button); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + int32 BindButtonUnhovered(UButton* Button); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + int32 BindCheckBoxChanged(UCheckBox* CheckBox); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + int32 BindSliderChanged(USlider* Slider); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + int32 BindSpinBoxChanged(USpinBox* SpinBox); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + int32 BindEditableTextChanged(UEditableTextBox* TextBox); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + int32 BindEditableTextCommitted(UEditableTextBox* TextBox); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + int32 BindComboBoxSelectionChanged(UComboBoxString* ComboBox); + UFUNCTION(BlueprintCallable, Category = "Lua|UI") bool UnbindButtonClicked(int32 BindingId); + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + bool UnbindWidgetEvent(int32 BindingId); + UFUNCTION(BlueprintPure, Category = "Lua|UI") - int32 GetActiveBindingCount() const { return ActiveButtonProxies.Num(); } + int32 GetActiveBindingCount() const { return ActiveProxies.Num(); } /** Helper: finds a named UWidget inside a UUserWidget's WidgetTree (validates designer renames cleanly). */ UFUNCTION(BlueprintPure, Category = "Lua|UI") static UWidget* FindChildWidgetByName(UUserWidget* RootWidget, const FName& WidgetName); - /** Simulates a button click for automated UE tests (invokes Button->OnClicked.Broadcast()). */ + /** Helper: sets CanvasPanelSlot position if the widget is slotted inside a UCanvasPanel. */ + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + static bool SetCanvasPosition(UWidget* Widget, const FVector2D& Position); + + /** Automated UE test simulation helpers. */ UFUNCTION(BlueprintCallable, Category = "Lua|UI|Test") static bool SimulateButtonClick(UButton* Button); + UFUNCTION(BlueprintCallable, Category = "Lua|UI|Test") + static bool SimulateButtonHover(UButton* Button, bool bHovered); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI|Test") + static bool SimulateCheckBoxToggle(UCheckBox* CheckBox, bool bIsChecked); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI|Test") + static bool SimulateSliderValue(USlider* Slider, float Value); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI|Test") + static bool SimulateSpinBoxValue(USpinBox* SpinBox, float Value); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI|Test") + static bool SimulateEditableTextChange(UEditableTextBox* TextBox, const FString& NewText); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI|Test") + static bool SimulateEditableTextCommit(UEditableTextBox* TextBox, const FString& NewText, int32 CommitMethod); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI|Test") + static bool SimulateComboBoxSelect(UComboBoxString* ComboBox, const FString& Option); + void DispatchButtonClicked(int32 BindingId); + void DispatchActionEvent(int32 BindingId); + void DispatchBoolChanged(int32 BindingId, bool bValue); + void DispatchFloatChanged(int32 BindingId, float Value); + void DispatchTextChanged(int32 BindingId, const FString& Text); + void DispatchTextCommitted(int32 BindingId, const FString& Text, int32 CommitMethod); + void DispatchSelectionChanged(int32 BindingId, const FString& SelectedItem, int32 SelectType); private: UPROPERTY(Transient) - TMap> ActiveButtonProxies; + TMap> ActiveProxies; int32 NextBindingId = 0; FString LuaCallbackModule = TEXT("framework.ui.ui_delegate_bridge"); diff --git a/Source/UnrealLuaDemoEditor/SetupDemoAssetsCommandlet.cpp b/Source/UnrealLuaDemoEditor/SetupDemoAssetsCommandlet.cpp new file mode 100644 index 0000000..ed186ee --- /dev/null +++ b/Source/UnrealLuaDemoEditor/SetupDemoAssetsCommandlet.cpp @@ -0,0 +1,1375 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "SetupDemoAssetsCommandlet.h" +#include "UnrealLuaDemoEditor.h" +#include "Core/LuaGameModeBase.h" +#include "AssetRegistry/AssetRegistryModule.h" +#include "Blueprint/WidgetTree.h" +#include "Components/Border.h" +#include "Components/Button.h" +#include "Components/CanvasPanel.h" +#include "Components/CanvasPanelSlot.h" +#include "Components/CheckBox.h" +#include "Components/ComboBoxString.h" +#include "Components/EditableTextBox.h" +#include "Components/HorizontalBox.h" +#include "Components/HorizontalBoxSlot.h" +#include "Components/Image.h" +#include "Components/Overlay.h" +#include "Components/OverlaySlot.h" +#include "Components/ProgressBar.h" +#include "Components/ScrollBox.h" +#include "Components/SizeBox.h" +#include "Components/Slider.h" +#include "Components/Spacer.h" +#include "Components/SpinBox.h" +#include "Components/TextBlock.h" +#include "Components/UniformGridPanel.h" +#include "Components/UniformGridSlot.h" +#include "Components/VerticalBox.h" +#include "Components/VerticalBoxSlot.h" +#include "Components/WidgetSwitcher.h" +#include "Engine/Font.h" +#include "Engine/FontFace.h" +#include "Engine/Texture2D.h" +#include "Engine/World.h" +#include "Fonts/CompositeFont.h" +#include "GameFramework/WorldSettings.h" +#include "HAL/FileManager.h" +#include "Kismet2/BlueprintEditorUtils.h" +#include "Kismet2/KismetEditorUtilities.h" +#include "Misc/FileHelper.h" +#include "Misc/PackageName.h" +#include "Misc/Paths.h" +#include "Styling/SlateTypes.h" +#include "UObject/Package.h" +#include "UObject/SavePackage.h" +#include "WidgetBlueprint.h" +#include "WidgetBlueprintFactory.h" + +namespace +{ + const FLinearColor ColorBgDeep(0.043f, 0.059f, 0.090f, 1.0f); + const FLinearColor ColorPanel(0.082f, 0.114f, 0.173f, 0.96f); + const FLinearColor ColorCard(0.110f, 0.153f, 0.227f, 0.98f); + const FLinearColor ColorCardDark(0.067f, 0.094f, 0.145f, 0.96f); + const FLinearColor ColorDivider(0.180f, 0.243f, 0.349f, 1.0f); + const FLinearColor ColorAccentBlue(0.149f, 0.431f, 0.855f, 1.0f); + const FLinearColor ColorAccentCyan(0.086f, 0.569f, 0.678f, 1.0f); + const FLinearColor ColorAccentGreen(0.133f, 0.588f, 0.388f, 1.0f); + const FLinearColor ColorAccentAmber(0.761f, 0.490f, 0.110f, 1.0f); + const FLinearColor ColorAccentPurple(0.478f, 0.294f, 0.784f, 1.0f); + const FLinearColor ColorAccentRed(0.745f, 0.212f, 0.255f, 1.0f); + const FLinearColor ColorBtnNeutral(0.165f, 0.224f, 0.322f, 1.0f); + const FLinearColor ColorTextPrimary(0.941f, 0.961f, 0.988f, 1.0f); + const FLinearColor ColorTextSecondary(0.659f, 0.729f, 0.824f, 1.0f); + const FLinearColor ColorTextAccent(0.451f, 0.788f, 0.980f, 1.0f); + + bool SaveAssetPackage(UPackage* Package, UObject* Asset, const FString& LongPackageName) + { + if (!Package || !Asset) + { + return false; + } + + const FString Extension = Asset->IsA() + ? FPackageName::GetMapPackageExtension() + : FPackageName::GetAssetPackageExtension(); + const FString Filename = FPackageName::LongPackageNameToFilename(LongPackageName, Extension); + + IFileManager::Get().MakeDirectory(*FPaths::GetPath(Filename), /*Tree=*/true); + + FSavePackageArgs SaveArgs; + SaveArgs.TopLevelFlags = RF_Public | RF_Standalone; + SaveArgs.Error = GError; + SaveArgs.bWarnOfLongFilename = false; + + return UPackage::SavePackage(Package, Asset, *Filename, SaveArgs); + } + + UWidgetBlueprint* BeginWidgetBlueprint(const FString& PackageName, const FString& AssetName, UPackage*& OutPackage) + { + OutPackage = CreatePackage(*PackageName); + if (!OutPackage) + { + return nullptr; + } + + UWidgetBlueprintFactory* Factory = NewObject(); + Factory->ParentClass = UUserWidget::StaticClass(); + + UWidgetBlueprint* WidgetBP = Cast( + Factory->FactoryCreateNew(UWidgetBlueprint::StaticClass(), OutPackage, *AssetName, RF_Public | RF_Standalone, nullptr, GWarn)); + if (!WidgetBP || !WidgetBP->WidgetTree) + { + return nullptr; + } + return WidgetBP; + } + + bool FinishWidgetBlueprint(UPackage* Package, UWidgetBlueprint* WidgetBP, const FString& PackageName) + { + if (!Package || !WidgetBP) + { + return false; + } + FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(WidgetBP); + FKismetEditorUtilities::CompileBlueprint(WidgetBP); + FAssetRegistryModule::AssetCreated(WidgetBP); + Package->MarkPackageDirty(); + return SaveAssetPackage(Package, WidgetBP, PackageName); + } + + FSlateFontInfo MakeDemoFont(UFont* Font, int32 Size, const FName& StyleName = TEXT("Regular")) + { + FSlateFontInfo Info; + if (Font) + { + Info = FSlateFontInfo(Font, Size, StyleName); + } + else + { + Info.Size = Size; + } + return Info; + } + + UTextBlock* MakeText( + UWidgetTree* Tree, + const FName& Name, + const FString& Text, + UFont* Font, + int32 FontSize, + const FLinearColor& Color = ColorTextPrimary, + bool bIsVariable = false, + bool bAutoWrap = false) + { + UTextBlock* TB = Tree->ConstructWidget(UTextBlock::StaticClass(), Name); + TB->bIsVariable = bIsVariable; + TB->SetText(FText::FromString(Text)); + TB->SetFont(MakeDemoFont(Font, FontSize)); + TB->SetColorAndOpacity(FSlateColor(Color)); + TB->SetAutoWrapText(bAutoWrap); + return TB; + } + + void ApplyButtonColorStyle(UButton* Button, const FLinearColor& BaseColor) + { + FButtonStyle Style = Button->GetStyle(); + + auto ConfigureBrush = [](FSlateBrush& Brush, const FLinearColor& Tint) + { + Brush.DrawAs = ESlateBrushDrawType::Box; + Brush.TintColor = FSlateColor(Tint); + Brush.Margin = FMargin(0.0f); + }; + + const FLinearColor HoverColor( + FMath::Clamp(BaseColor.R * 1.18f + 0.04f, 0.0f, 1.0f), + FMath::Clamp(BaseColor.G * 1.18f + 0.04f, 0.0f, 1.0f), + FMath::Clamp(BaseColor.B * 1.18f + 0.04f, 0.0f, 1.0f), + BaseColor.A); + const FLinearColor PressColor( + BaseColor.R * 0.80f, + BaseColor.G * 0.80f, + BaseColor.B * 0.80f, + BaseColor.A); + const FLinearColor DisabledColor(0.18f, 0.20f, 0.24f, 0.65f); + + ConfigureBrush(Style.Normal, BaseColor); + ConfigureBrush(Style.Hovered, HoverColor); + ConfigureBrush(Style.Pressed, PressColor); + ConfigureBrush(Style.Disabled, DisabledColor); + Style.NormalPadding = FMargin(12.0f, 7.0f); + Style.PressedPadding = FMargin(12.0f, 8.0f, 12.0f, 6.0f); + + Button->SetStyle(Style); + } + + UButton* MakeButton( + UWidgetTree* Tree, + const FName& BtnName, + const FName& TxtName, + const FString& Label, + UFont* Font, + int32 FontSize, + const FLinearColor& BgColor, + bool bTxtIsVariable = false) + { + UButton* Btn = Tree->ConstructWidget(UButton::StaticClass(), BtnName); + Btn->bIsVariable = true; + ApplyButtonColorStyle(Btn, BgColor); + + UTextBlock* Txt = MakeText(Tree, TxtName, Label, Font, FontSize, ColorTextPrimary, bTxtIsVariable, false); + Txt->SetJustification(ETextJustify::Center); + Btn->AddChild(Txt); + return Btn; + } + + UBorder* MakeDivider(UWidgetTree* Tree, const FName& Name) + { + UBorder* Line = Tree->ConstructWidget(UBorder::StaticClass(), Name); + Line->SetBrushColor(ColorDivider); + Line->SetPadding(FMargin(0.0f)); + USpacer* Sp = Tree->ConstructWidget(USpacer::StaticClass()); + Sp->SetSize(FVector2D(1.0f, 2.0f)); + Line->SetContent(Sp); + return Line; + } + + UBorder* MakeSectionCard(UWidgetTree* Tree, const FName& BorderName, UVerticalBox*& OutInnerBox) + { + UBorder* Card = Tree->ConstructWidget(UBorder::StaticClass(), BorderName); + Card->SetBrushColor(ColorCard); + Card->SetPadding(FMargin(14.0f, 12.0f)); + OutInnerBox = Tree->ConstructWidget(UVerticalBox::StaticClass()); + Card->SetContent(OutInnerBox); + return Card; + } + + void AddFillChild(UVerticalBox* Box, UWidget* Child, const FMargin& Padding = FMargin(0.0f)) + { + if (UVerticalBoxSlot* VSlot = Box->AddChildToVerticalBox(Child)) + { + VSlot->SetHorizontalAlignment(HAlign_Fill); + VSlot->SetPadding(Padding); + } + } + + void AddAutoHChild(UHorizontalBox* Box, UWidget* Child, const FMargin& Padding = FMargin(0.0f), EVerticalAlignment VAlign = VAlign_Center) + { + if (UHorizontalBoxSlot* HSlot = Box->AddChildToHorizontalBox(Child)) + { + HSlot->SetSize(FSlateChildSize(ESlateSizeRule::Automatic)); + HSlot->SetVerticalAlignment(VAlign); + HSlot->SetPadding(Padding); + } + } + + void AddFillHChild(UHorizontalBox* Box, UWidget* Child, const FMargin& Padding = FMargin(0.0f), EVerticalAlignment VAlign = VAlign_Center) + { + if (UHorizontalBoxSlot* HSlot = Box->AddChildToHorizontalBox(Child)) + { + HSlot->SetSize(FSlateChildSize(ESlateSizeRule::Fill)); + HSlot->SetHorizontalAlignment(HAlign_Fill); + HSlot->SetVerticalAlignment(VAlign); + HSlot->SetPadding(Padding); + } + } + + void SetupFullCanvasSlot(UCanvasPanel* Root, UWidget* Child, const FMargin& Offsets = FMargin(0.0f)) + { + if (UCanvasPanelSlot* CSlot = Root->AddChildToCanvas(Child)) + { + CSlot->SetAnchors(FAnchors(0.0f, 0.0f, 1.0f, 1.0f)); + CSlot->SetOffsets(Offsets); + } + } + + void SetupCenterCanvasSlot(UCanvasPanel* Root, UWidget* Child, const FVector2D& Size, const FVector2D& Position = FVector2D::ZeroVector) + { + if (UCanvasPanelSlot* CSlot = Root->AddChildToCanvas(Child)) + { + CSlot->SetAnchors(FAnchors(0.5f, 0.5f, 0.5f, 0.5f)); + CSlot->SetAlignment(FVector2D(0.5f, 0.5f)); + CSlot->SetPosition(Position); + CSlot->SetSize(Size); + } + } +} + +USetupDemoAssetsCommandlet::USetupDemoAssetsCommandlet() +{ + IsClient = true; + IsEditor = true; + IsServer = false; + LogToConsole = true; +} + +int32 USetupDemoAssetsCommandlet::Main(const FString& Params) +{ + UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[SetupDemoAssets] Generating Chinese font, Demo textures, L_DemoUI map, and UI Demo blueprints...")); + + UFontFace* CJKFontFace = CreateChineseFontFace(); + if (!CJKFontFace) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupDemoAssets] Failed to create /Game/UI/Fonts/FF_DemoCJK.")); + return 1; + } + + UFont* DemoFont = CreateDemoUIFont(CJKFontFace); + if (!DemoFont) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupDemoAssets] Failed to create /Game/UI/Fonts/F_DemoUI.")); + return 1; + } + + if (!CreateDemoMap(TEXT("/Game/Maps/L_DemoUI"), TEXT("L_DemoUI"))) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupDemoAssets] Failed to create /Game/Maps/L_DemoUI.")); + return 1; + } + + if (!CreateProceduralTexture(TEXT("/Game/UI/Textures/T_DemoAvatar"), TEXT("T_DemoAvatar"), 0) || + !CreateProceduralTexture(TEXT("/Game/UI/Textures/T_DemoBadgeA"), TEXT("T_DemoBadgeA"), 1) || + !CreateProceduralTexture(TEXT("/Game/UI/Textures/T_DemoBadgeB"), TEXT("T_DemoBadgeB"), 2)) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupDemoAssets] Failed to create Demo textures.")); + return 1; + } + + const bool bAllWidgetsOk = + CreateDemoHubBlueprint(DemoFont) && + CreateDemoHubItemBlueprint(DemoFont) && + CreateUIDemoMainBlueprint(DemoFont) && + CreateUIDemoListItemBlueprint(DemoFont) && + CreateUIDemoNormalBlueprint(DemoFont) && + CreateUIDemoFullscreenBlueprint(DemoFont) && + CreateUIDemoModalBlueprint(DemoFont) && + CreateUIDemoCachedBlueprint(DemoFont) && + CreateUIDemoMultiBlueprint(DemoFont) && + CreateUIDemoToastBlueprint(DemoFont) && + CreateUIDemoSystemBlueprint(DemoFont); + + if (!bAllWidgetsOk) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupDemoAssets] Failed to create one or more Demo Widget Blueprints.")); + return 1; + } + + UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[SetupDemoAssets] All Chinese font & UI Demo assets created successfully.")); + return 0; +} + +UFontFace* USetupDemoAssetsCommandlet::CreateChineseFontFace() const +{ + const FString PackageName = TEXT("/Game/UI/Fonts/FF_DemoCJK"); + const FString AssetName = TEXT("FF_DemoCJK"); + + const FString EngineFontPath = FPaths::ConvertRelativePathToFull( + FPaths::EngineContentDir() / TEXT("Slate/Fonts/DroidSansFallback.ttf")); + + TArray FontBytes; + if (!FFileHelper::LoadFileToArray(FontBytes, *EngineFontPath) || FontBytes.Num() == 0) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupDemoAssets] Could not read CJK font file: %s"), *EngineFontPath); + return nullptr; + } + + UPackage* Package = CreatePackage(*PackageName); + if (!Package) + { + return nullptr; + } + + UFontFace* FontFace = NewObject(Package, *AssetName, RF_Public | RF_Standalone); + if (!FontFace) + { + return nullptr; + } + + FontFace->SourceFilename = EngineFontPath; + FontFace->Hinting = EFontHinting::Default; + FontFace->LoadingPolicy = EFontLoadingPolicy::Inline; + FontFace->LayoutMethod = EFontLayoutMethod::Metrics; + FontFace->FontFaceData = FFontFaceData::MakeFontFaceData(MoveTemp(FontBytes)); +#if WITH_EDITORONLY_DATA + FontFace->CacheSubFaces(); +#endif + + FAssetRegistryModule::AssetCreated(FontFace); + Package->MarkPackageDirty(); + + if (!SaveAssetPackage(Package, FontFace, PackageName)) + { + return nullptr; + } + + UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[SetupDemoAssets] Imported inline CJK UFontFace from %s"), *EngineFontPath); + return FontFace; +} + +UFont* USetupDemoAssetsCommandlet::CreateDemoUIFont(UFontFace* CJKFontFace) const +{ + const FString PackageName = TEXT("/Game/UI/Fonts/F_DemoUI"); + const FString AssetName = TEXT("F_DemoUI"); + + UPackage* Package = CreatePackage(*PackageName); + if (!Package) + { + return nullptr; + } + + UFont* Font = NewObject(Package, *AssetName, RF_Public | RF_Standalone); + if (!Font) + { + return nullptr; + } + + Font->FontCacheType = EFontCacheType::Runtime; + FCompositeFont& CompositeFont = Font->GetMutableInternalCompositeFont(); + CompositeFont.DefaultTypeface.Fonts.Reset(); + { + FTypefaceEntry RegularEntry(TEXT("Regular")); + RegularEntry.Font = FFontData(CJKFontFace); + CompositeFont.DefaultTypeface.Fonts.Add(MoveTemp(RegularEntry)); + + FTypefaceEntry BoldEntry(TEXT("Bold")); + BoldEntry.Font = FFontData(CJKFontFace); + CompositeFont.DefaultTypeface.Fonts.Add(MoveTemp(BoldEntry)); + } + + CompositeFont.FallbackTypeface.Typeface.Fonts.Reset(); + { + FTypefaceEntry FallbackEntry(TEXT("Regular")); + FallbackEntry.Font = FFontData(CJKFontFace); + CompositeFont.FallbackTypeface.Typeface.Fonts.Add(MoveTemp(FallbackEntry)); + } + CompositeFont.FallbackTypeface.ScalingFactor = 1.0f; + + FAssetRegistryModule::AssetCreated(Font); + Package->MarkPackageDirty(); + + if (!SaveAssetPackage(Package, Font, PackageName)) + { + return nullptr; + } + + return Font; +} + +bool USetupDemoAssetsCommandlet::CreateDemoMap(const FString& PackageName, const FString& MapName) const +{ + UPackage* Package = CreatePackage(*PackageName); + if (!Package) + { + return false; + } + + UWorld* NewWorld = UWorld::CreateWorld(EWorldType::Inactive, false, *MapName, Package, true, ERHIFeatureLevel::Num); + if (!NewWorld) + { + return false; + } + + NewWorld->SetFlags(RF_Public | RF_Standalone); + if (AWorldSettings* WS = NewWorld->GetWorldSettings()) + { + WS->DefaultGameMode = ALuaGameModeBase::StaticClass(); + } + + FAssetRegistryModule::AssetCreated(NewWorld); + Package->MarkPackageDirty(); + + const bool bSaved = SaveAssetPackage(Package, NewWorld, PackageName); + NewWorld->DestroyWorld(false); + return bSaved; +} + +bool USetupDemoAssetsCommandlet::CreateProceduralTexture(const FString& PackageName, const FString& AssetName, int32 StyleIndex) const +{ + UPackage* Package = CreatePackage(*PackageName); + if (!Package) + { + return false; + } + + constexpr int32 Size = 128; + UTexture2D* Texture = NewObject(Package, *AssetName, RF_Public | RF_Standalone); + if (!Texture) + { + return false; + } + + TArray Pixels; + Pixels.SetNumUninitialized(Size * Size * 4); + for (int32 Y = 0; Y < Size; ++Y) + { + for (int32 X = 0; X < Size; ++X) + { + const int32 Idx = (Y * Size + X) * 4; + const float Dx = (X - Size * 0.5f) / (Size * 0.5f); + const float Dy = (Y - Size * 0.5f) / (Size * 0.5f); + const float Dist = FMath::Sqrt(Dx * Dx + Dy * Dy); + const float Diamond = FMath::Abs(Dx) + FMath::Abs(Dy); + + uint8 B = 32, G = 42, R = 58, A = 255; + + if (StyleIndex == 0) + { + // Avatar: cyan ring + bright core + head/shoulder silhouette + const bool bOuterRing = Dist >= 0.78f && Dist <= 0.94f; + const float HeadDist = FMath::Sqrt(Dx * Dx + (Dy + 0.18f) * (Dy + 0.18f)); + const float BodyDist = FMath::Sqrt((Dx * 0.85f) * (Dx * 0.85f) + (Dy - 0.58f) * (Dy - 0.58f)); + if (bOuterRing) + { + B = 245; G = 195; R = 64; + } + else if (HeadDist <= 0.25f || (BodyDist <= 0.48f && Dist <= 0.78f)) + { + B = 250; G = 235; R = 205; + } + else if (Dist <= 0.78f) + { + B = 110; G = 68; R = 32; + } + } + else if (StyleIndex == 1) + { + // Badge A: emerald diamond emblem + if (Diamond <= 0.42f) + { + B = 175; G = 250; R = 120; + } + else if (Diamond <= 0.78f) + { + B = 110; G = 195; R = 48; + } + else + { + B = 40; G = 60; R = 28; + } + } + else + { + // Badge B: crimson-gold crest + const bool bCross = (FMath::Abs(Dx) <= 0.16f && FMath::Abs(Dy) <= 0.65f) || (FMath::Abs(Dy) <= 0.16f && FMath::Abs(Dx) <= 0.65f); + if (bCross) + { + B = 72; G = 215; R = 250; + } + else if (Dist <= 0.82f) + { + B = 75; G = 48; R = 190; + } + else + { + B = 42; G = 26; R = 58; + } + } + + Pixels[Idx + 0] = B; + Pixels[Idx + 1] = G; + Pixels[Idx + 2] = R; + Pixels[Idx + 3] = A; + } + } + + Texture->Source.Init(Size, Size, 1, 1, TSF_BGRA8, Pixels.GetData()); + Texture->LODGroup = TEXTUREGROUP_UI; + Texture->CompressionSettings = TC_EditorIcon; + Texture->MipGenSettings = TMGS_NoMipmaps; + Texture->SRGB = true; + Texture->UpdateResource(); + Texture->PostEditChange(); + + FAssetRegistryModule::AssetCreated(Texture); + Package->MarkPackageDirty(); + + return SaveAssetPackage(Package, Texture, PackageName); +} + +bool USetupDemoAssetsCommandlet::CreateDemoHubBlueprint(UFont* DemoFont) const +{ + const FString PackageName = TEXT("/Game/UI/Demo/WBP_DemoHub"); + UPackage* Package = nullptr; + UWidgetBlueprint* WidgetBP = BeginWidgetBlueprint(PackageName, TEXT("WBP_DemoHub"), Package); + if (!WidgetBP) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + UCanvasPanel* Root = Tree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("RootCanvas")); + Tree->RootWidget = Root; + + UBorder* Backdrop = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("BgBackdrop")); + Backdrop->SetBrushColor(ColorBgDeep); + SetupFullCanvasSlot(Root, Backdrop); + + UBorder* HubCard = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("HubCard")); + HubCard->SetBrushColor(ColorPanel); + HubCard->SetPadding(FMargin(28.0f, 24.0f)); + SetupCenterCanvasSlot(Root, HubCard, FVector2D(820.0f, 580.0f)); + + UVerticalBox* VBox = Tree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("HubLayout")); + HubCard->SetContent(VBox); + + AddFillChild(VBox, MakeText(Tree, TEXT("TxtHubTitle"), TEXT("UnrealLuaDemo 场景启动大厅"), DemoFont, 26, ColorTextPrimary, true), FMargin(0, 0, 0, 6)); + AddFillChild(VBox, MakeText(Tree, TEXT("TxtHubSubtitle"), TEXT("在 Bootstrap 关卡中选择并切换至各个功能 Demo 场景,切图时自动验证上下文与资源清理。"), DemoFont, 13, ColorTextSecondary, true, true), FMargin(0, 0, 0, 10)); + AddFillChild(VBox, MakeText(Tree, TEXT("TxtRuntimeInfo"), TEXT("运行时信息加载中..."), DemoFont, 12, ColorTextAccent, true), FMargin(0, 0, 0, 12)); + AddFillChild(VBox, MakeDivider(Tree, TEXT("DivTop")), FMargin(0, 0, 0, 14)); + + UScrollBox* ScrollList = Tree->ConstructWidget(UScrollBox::StaticClass(), TEXT("ScrollDemoList")); + ScrollList->bIsVariable = true; + if (UVerticalBoxSlot* ListSlot = VBox->AddChildToVerticalBox(ScrollList)) + { + ListSlot->SetSize(FSlateChildSize(ESlateSizeRule::Fill)); + ListSlot->SetHorizontalAlignment(HAlign_Fill); + ListSlot->SetVerticalAlignment(VAlign_Fill); + ListSlot->SetPadding(FMargin(0, 0, 0, 14)); + } + + AddFillChild(VBox, MakeDivider(Tree, TEXT("DivBottom")), FMargin(0, 0, 0, 12)); + + UHorizontalBox* Footer = Tree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("FooterRow")); + AddFillHChild(Footer, MakeText(Tree, TEXT("TxtHubHint"), TEXT("提示:进入任意 Demo 场景后可通过右上角「返回大厅」回到 L_Bootstrap"), DemoFont, 12, ColorTextSecondary, false, true), FMargin(0, 0, 12, 0)); + AddAutoHChild(Footer, MakeButton(Tree, TEXT("BtnOpenMiniSettings"), TEXT("TxtMiniSettingsBtn"), TEXT("快捷验证:最小设置弹窗"), DemoFont, 13, ColorBtnNeutral)); + AddFillChild(VBox, Footer); + + return FinishWidgetBlueprint(Package, WidgetBP, PackageName); +} + +bool USetupDemoAssetsCommandlet::CreateDemoHubItemBlueprint(UFont* DemoFont) const +{ + const FString PackageName = TEXT("/Game/UI/Demo/WBP_DemoHubItem"); + UPackage* Package = nullptr; + UWidgetBlueprint* WidgetBP = BeginWidgetBlueprint(PackageName, TEXT("WBP_DemoHubItem"), Package); + if (!WidgetBP) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + UBorder* Card = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("CardBorder")); + Card->bIsVariable = true; + Card->SetBrushColor(ColorCard); + Card->SetPadding(FMargin(18.0f, 14.0f)); + Tree->RootWidget = Card; + + UHorizontalBox* Row = Tree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("CardRow")); + Card->SetContent(Row); + + UVerticalBox* InfoCol = Tree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("InfoCol")); + AddFillChild(InfoCol, MakeText(Tree, TEXT("TxtDemoTitle"), TEXT("Demo 标题"), DemoFont, 18, ColorTextPrimary, true), FMargin(0, 0, 0, 4)); + AddFillChild(InfoCol, MakeText(Tree, TEXT("TxtDemoDesc"), TEXT("Demo 简介说明"), DemoFont, 13, ColorTextSecondary, true, true), FMargin(0, 0, 0, 6)); + AddFillChild(InfoCol, MakeText(Tree, TEXT("TxtDemoMeta"), TEXT("关卡:/Game/Maps/L_DemoUI"), DemoFont, 11, ColorTextAccent, true)); + AddFillHChild(Row, InfoCol, FMargin(0, 0, 16, 0)); + + USizeBox* BtnWrap = Tree->ConstructWidget(USizeBox::StaticClass(), TEXT("BtnWrap")); + BtnWrap->SetWidthOverride(132.0f); + BtnWrap->SetHeightOverride(44.0f); + BtnWrap->AddChild(MakeButton(Tree, TEXT("BtnEnterDemo"), TEXT("TxtEnterLabel"), TEXT("进入场景"), DemoFont, 14, ColorAccentBlue, true)); + AddAutoHChild(Row, BtnWrap); + + return FinishWidgetBlueprint(Package, WidgetBP, PackageName); +} + +bool USetupDemoAssetsCommandlet::CreateUIDemoMainBlueprint(UFont* DemoFont) const +{ + const FString PackageName = TEXT("/Game/UI/Demo/WBP_UIDemoMain"); + UPackage* Package = nullptr; + UWidgetBlueprint* WidgetBP = BeginWidgetBlueprint(PackageName, TEXT("WBP_UIDemoMain"), Package); + if (!WidgetBP) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + UCanvasPanel* Root = Tree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("RootCanvas")); + Tree->RootWidget = Root; + + UBorder* MainBg = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("MainBg")); + MainBg->SetBrushColor(ColorBgDeep); + SetupFullCanvasSlot(Root, MainBg); + + UVerticalBox* RootVBox = Tree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("RootVBox")); + SetupFullCanvasSlot(Root, RootVBox, FMargin(16.0f)); + + // ===== Zone 1: TopBar ===== + UBorder* TopBar = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("TopBar")); + TopBar->SetBrushColor(ColorPanel); + TopBar->SetPadding(FMargin(16.0f, 10.0f)); + UHorizontalBox* TopRow = Tree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("TopRow")); + TopBar->SetContent(TopRow); + + UImage* ImgAvatar = Tree->ConstructWidget(UImage::StaticClass(), TEXT("ImgPlayerAvatar")); + ImgAvatar->bIsVariable = true; + ImgAvatar->SetDesiredSizeOverride(FVector2D(48.0f, 48.0f)); + AddAutoHChild(TopRow, ImgAvatar, FMargin(0, 0, 12, 0)); + + USizeBox* PlayerInfoWrap = Tree->ConstructWidget(USizeBox::StaticClass(), TEXT("PlayerInfoWrap")); + PlayerInfoWrap->SetWidthOverride(230.0f); + UVerticalBox* PlayerInfo = Tree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("PlayerInfoBox")); + AddFillChild(PlayerInfo, MakeText(Tree, TEXT("TxtPlayerName"), TEXT("冒险者_01 Lv.12"), DemoFont, 15, ColorTextPrimary, true), FMargin(0, 0, 0, 6)); + UProgressBar* BarExp = Tree->ConstructWidget(UProgressBar::StaticClass(), TEXT("BarPlayerExp")); + BarExp->bIsVariable = true; + BarExp->SetPercent(0.65f); + BarExp->SetFillColorAndOpacity(ColorAccentCyan); + AddFillChild(PlayerInfo, BarExp); + PlayerInfoWrap->AddChild(PlayerInfo); + AddAutoHChild(TopRow, PlayerInfoWrap, FMargin(0, 0, 16, 0)); + + UBorder* StatsBadge = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("StatsBadge")); + StatsBadge->SetBrushColor(ColorCardDark); + StatsBadge->SetPadding(FMargin(14.0f, 8.0f)); + StatsBadge->SetContent(MakeText(Tree, TEXT("TxtHudStats"), TEXT("窗口:1 | 缓存:0 | 绑定:0 | 输入:UI"), DemoFont, 13, ColorTextAccent, true)); + AddFillHChild(TopRow, StatsBadge, FMargin(0, 0, 16, 0)); + + AddAutoHChild(TopRow, MakeButton(Tree, TEXT("BtnTopSettings"), TEXT("TxtTopSettings"), TEXT("设置"), DemoFont, 13, ColorBtnNeutral), FMargin(0, 0, 8, 0)); + AddAutoHChild(TopRow, MakeButton(Tree, TEXT("BtnBackToHub"), TEXT("TxtBackToHub"), TEXT("返回大厅"), DemoFont, 13, ColorAccentRed)); + + AddFillChild(RootVBox, TopBar, FMargin(0, 0, 0, 12)); + + // ===== Zone 2: BodyRow (LeftNav | CenterStage | RightLog) ===== + UHorizontalBox* BodyRow = Tree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("BodyRow")); + if (UVerticalBoxSlot* BodySlot = RootVBox->AddChildToVerticalBox(BodyRow)) + { + BodySlot->SetSize(FSlateChildSize(ESlateSizeRule::Fill)); + BodySlot->SetHorizontalAlignment(HAlign_Fill); + BodySlot->SetVerticalAlignment(VAlign_Fill); + } + + // --- 2A. LeftNav (Window Type Showcase) --- + USizeBox* LeftWrap = Tree->ConstructWidget(USizeBox::StaticClass(), TEXT("LeftWrap")); + LeftWrap->SetWidthOverride(230.0f); + UBorder* LeftPanel = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("LeftNavPanel")); + LeftPanel->SetBrushColor(ColorPanel); + LeftPanel->SetPadding(FMargin(12.0f)); + UScrollBox* NavScroll = Tree->ConstructWidget(UScrollBox::StaticClass(), TEXT("NavScroll")); + LeftPanel->SetContent(NavScroll); + LeftWrap->AddChild(LeftPanel); + + NavScroll->AddChild(MakeText(Tree, TEXT("TxtNavTitle"), TEXT("窗口类型测试"), DemoFont, 16, ColorTextPrimary)); + USpacer* NavSp0 = Tree->ConstructWidget(USpacer::StaticClass()); + NavSp0->SetSize(FVector2D(1.0f, 10.0f)); + NavScroll->AddChild(NavSp0); + + auto AddNavBtn = [&](const FName& BtnName, const FName& TxtName, const FString& Label, const FLinearColor& Color) + { + UButton* Btn = MakeButton(Tree, BtnName, TxtName, Label, DemoFont, 13, Color); + NavScroll->AddChild(Btn); + USpacer* Sp = Tree->ConstructWidget(USpacer::StaticClass()); + Sp->SetSize(FVector2D(1.0f, 8.0f)); + NavScroll->AddChild(Sp); + }; + + AddNavBtn(TEXT("BtnWinNormal"), TEXT("TxtWinNormal"), TEXT("普通窗口 (Normal)"), ColorAccentBlue); + AddNavBtn(TEXT("BtnWinFullscreen"), TEXT("TxtWinFullscreen"), TEXT("全屏窗口 (Fullscreen)"), ColorAccentPurple); + AddNavBtn(TEXT("BtnWinModal"), TEXT("TxtWinModal"), TEXT("模态弹窗 (Modal)"), ColorAccentAmber); + AddNavBtn(TEXT("BtnWinCached"), TEXT("TxtWinCached"), TEXT("缓存窗口 (Cached)"), ColorAccentGreen); + AddNavBtn(TEXT("BtnWinMulti"), TEXT("TxtWinMulti"), TEXT("多实例窗 (Multi +1)"), ColorAccentCyan); + AddNavBtn(TEXT("BtnWinToast"), TEXT("TxtWinToast"), TEXT("飘字提示 (Toast)"), ColorBtnNeutral); + AddNavBtn(TEXT("BtnWinSystem"), TEXT("TxtWinSystem"), TEXT("系统顶层 (System)"), ColorAccentRed); + + NavScroll->AddChild(MakeDivider(Tree, TEXT("NavDiv"))); + USpacer* NavSp1 = Tree->ConstructWidget(USpacer::StaticClass()); + NavSp1->SetSize(FVector2D(1.0f, 8.0f)); + NavScroll->AddChild(NavSp1); + + AddNavBtn(TEXT("BtnEvictCache"), TEXT("TxtEvictCache"), TEXT("清空缓存池"), ColorBtnNeutral); + AddNavBtn(TEXT("BtnCloseOthers"), TEXT("TxtCloseOthers"), TEXT("关闭其他窗口"), ColorBtnNeutral); + + AddAutoHChild(BodyRow, LeftWrap, FMargin(0, 0, 12, 0), VAlign_Fill); + + // --- 2B. CenterStage (Component Lab with WidgetSwitcher) --- + UBorder* CenterPanel = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("CenterPanel")); + CenterPanel->SetBrushColor(ColorPanel); + CenterPanel->SetPadding(FMargin(14.0f)); + UVerticalBox* CenterVBox = Tree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("CenterVBox")); + CenterPanel->SetContent(CenterVBox); + + UHorizontalBox* TabBar = Tree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("TabBar")); + AddFillHChild(TabBar, MakeButton(Tree, TEXT("BtnTabBasic"), TEXT("TxtTabBasic"), TEXT("1. 基础交互"), DemoFont, 13, ColorAccentBlue), FMargin(0, 0, 6, 0)); + AddFillHChild(TabBar, MakeButton(Tree, TEXT("BtnTabInput"), TEXT("TxtTabInput"), TEXT("2. 输入与选择"), DemoFont, 13, ColorBtnNeutral), FMargin(0, 0, 6, 0)); + AddFillHChild(TabBar, MakeButton(Tree, TEXT("BtnTabMedia"), TEXT("TxtTabMedia"), TEXT("3. 图片与列表"), DemoFont, 13, ColorBtnNeutral), FMargin(0, 0, 6, 0)); + AddFillHChild(TabBar, MakeButton(Tree, TEXT("BtnTabDiag"), TEXT("TxtTabDiag"), TEXT("4. 框架诊断"), DemoFont, 13, ColorBtnNeutral)); + AddFillChild(CenterVBox, TabBar, FMargin(0, 0, 0, 12)); + + UWidgetSwitcher* TabSwitcher = Tree->ConstructWidget(UWidgetSwitcher::StaticClass(), TEXT("TabSwitcher")); + TabSwitcher->bIsVariable = true; + if (UVerticalBoxSlot* SwitchSlot = CenterVBox->AddChildToVerticalBox(TabSwitcher)) + { + SwitchSlot->SetSize(FSlateChildSize(ESlateSizeRule::Fill)); + SwitchSlot->SetHorizontalAlignment(HAlign_Fill); + SwitchSlot->SetVerticalAlignment(VAlign_Fill); + } + + // ---- Page 0: Basic Controls ---- + UScrollBox* PageBasic = Tree->ConstructWidget(UScrollBox::StaticClass(), TEXT("PageBasic")); + { + // Section 1: Button + UVerticalBox* SecBtn = nullptr; + PageBasic->AddChild(MakeSectionCard(Tree, TEXT("CardBtn"), SecBtn)); + AddFillChild(SecBtn, MakeText(Tree, TEXT("TxtSecBtnTitle"), TEXT("按钮测试(Click / Hover / Unhover / 禁用态)"), DemoFont, 15, ColorTextPrimary), FMargin(0, 0, 0, 6)); + AddFillChild(SecBtn, MakeText(Tree, TEXT("TxtBasicBtnStatus"), TEXT("按钮状态:点击 0 次 | 悬停:否 | 受控按钮:已启用"), DemoFont, 13, ColorTextAccent, true, true), FMargin(0, 0, 0, 10)); + UHorizontalBox* BtnRow = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(BtnRow, MakeButton(Tree, TEXT("BtnDemoAction"), TEXT("TxtDemoAction"), TEXT("点击 / 悬停测试"), DemoFont, 13, ColorAccentBlue), FMargin(0, 0, 8, 0)); + AddFillHChild(BtnRow, MakeButton(Tree, TEXT("BtnToggleDisable"), TEXT("TxtToggleDisable"), TEXT("切换启用 / 禁用"), DemoFont, 13, ColorBtnNeutral), FMargin(0, 0, 8, 0)); + AddFillHChild(BtnRow, MakeButton(Tree, TEXT("BtnDemoTarget"), TEXT("TxtDemoTarget"), TEXT("目标受控按钮"), DemoFont, 13, ColorAccentGreen, true)); + AddFillChild(SecBtn, BtnRow); + + USpacer* Sp1 = Tree->ConstructWidget(USpacer::StaticClass()); + Sp1->SetSize(FVector2D(1.0f, 10.0f)); + PageBasic->AddChild(Sp1); + + // Section 2: CheckBox + UVerticalBox* SecCheck = nullptr; + PageBasic->AddChild(MakeSectionCard(Tree, TEXT("CardCheck"), SecCheck)); + AddFillChild(SecCheck, MakeText(Tree, TEXT("TxtSecCheckTitle"), TEXT("复选框测试(UCheckBox)"), DemoFont, 15, ColorTextPrimary), FMargin(0, 0, 0, 8)); + UHorizontalBox* ChkRow = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + UCheckBox* ChkFeature = Tree->ConstructWidget(UCheckBox::StaticClass(), TEXT("ChkFeature")); + ChkFeature->bIsVariable = true; + AddAutoHChild(ChkRow, ChkFeature, FMargin(0, 0, 10, 0)); + AddFillHChild(ChkRow, MakeText(Tree, TEXT("TxtCheckStatus"), TEXT("复选框状态:未勾选(点击切换)"), DemoFont, 13, ColorTextSecondary, true)); + AddFillChild(SecCheck, ChkRow); + + USpacer* Sp2 = Tree->ConstructWidget(USpacer::StaticClass()); + Sp2->SetSize(FVector2D(1.0f, 10.0f)); + PageBasic->AddChild(Sp2); + + // Section 3: Slider + ProgressBar + UVerticalBox* SecSlider = nullptr; + PageBasic->AddChild(MakeSectionCard(Tree, TEXT("CardSlider"), SecSlider)); + AddFillChild(SecSlider, MakeText(Tree, TEXT("TxtSecSliderTitle"), TEXT("滑条与进度条联动(USlider + UProgressBar)"), DemoFont, 15, ColorTextPrimary), FMargin(0, 0, 0, 6)); + AddFillChild(SecSlider, MakeText(Tree, TEXT("TxtSliderStatus"), TEXT("当前进度:50%(拖动滑条或点击自动动画)"), DemoFont, 13, ColorTextAccent, true), FMargin(0, 0, 0, 8)); + USlider* SliderDemo = Tree->ConstructWidget(USlider::StaticClass(), TEXT("SliderDemo")); + SliderDemo->bIsVariable = true; + SliderDemo->SetMinValue(0.0f); + SliderDemo->SetMaxValue(1.0f); + SliderDemo->SetValue(0.5f); + AddFillChild(SecSlider, SliderDemo, FMargin(0, 0, 0, 8)); + + UProgressBar* ProgressDemo = Tree->ConstructWidget(UProgressBar::StaticClass(), TEXT("ProgressDemo")); + ProgressDemo->bIsVariable = true; + ProgressDemo->SetPercent(0.5f); + ProgressDemo->SetFillColorAndOpacity(ColorAccentGreen); + AddFillChild(SecSlider, ProgressDemo, FMargin(0, 0, 0, 10)); + + UHorizontalBox* ProgBtns = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(ProgBtns, MakeButton(Tree, TEXT("BtnProgressPlay"), TEXT("TxtProgressPlay"), TEXT("开始自动进度动画"), DemoFont, 13, ColorAccentCyan, true), FMargin(0, 0, 8, 0)); + AddFillHChild(ProgBtns, MakeButton(Tree, TEXT("BtnProgressReset"), TEXT("TxtProgressReset"), TEXT("重置为 0%"), DemoFont, 13, ColorBtnNeutral)); + AddFillChild(SecSlider, ProgBtns); + + USpacer* Sp3 = Tree->ConstructWidget(USpacer::StaticClass()); + Sp3->SetSize(FVector2D(1.0f, 10.0f)); + PageBasic->AddChild(Sp3); + + // Section 4: SpinBox + UVerticalBox* SecSpin = nullptr; + PageBasic->AddChild(MakeSectionCard(Tree, TEXT("CardSpin"), SecSpin)); + AddFillChild(SecSpin, MakeText(Tree, TEXT("TxtSecSpinTitle"), TEXT("数值微调器(USpinBox)"), DemoFont, 15, ColorTextPrimary), FMargin(0, 0, 0, 8)); + UHorizontalBox* SpinRow = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + USpinBox* SpinDemo = Tree->ConstructWidget(USpinBox::StaticClass(), TEXT("SpinDemo")); + SpinDemo->bIsVariable = true; + SpinDemo->SetMinValue(0.0f); + SpinDemo->SetMaxValue(999.0f); + SpinDemo->SetMinSliderValue(0.0f); + SpinDemo->SetMaxSliderValue(999.0f); + SpinDemo->SetValue(100.0f); + SpinDemo->SetDelta(5.0f); + SpinDemo->SetFont(MakeDemoFont(DemoFont, 14)); + USizeBox* SpinWrap = Tree->ConstructWidget(USizeBox::StaticClass()); + SpinWrap->SetWidthOverride(160.0f); + SpinWrap->AddChild(SpinDemo); + AddAutoHChild(SpinRow, SpinWrap, FMargin(0, 0, 12, 0)); + AddFillHChild(SpinRow, MakeText(Tree, TEXT("TxtSpinStatus"), TEXT("当前数值:100(范围 0 ~ 999)"), DemoFont, 13, ColorTextSecondary, true)); + AddFillChild(SecSpin, SpinRow); + } + TabSwitcher->AddChild(PageBasic); + + // ---- Page 1: Input & Selection ---- + UScrollBox* PageInput = Tree->ConstructWidget(UScrollBox::StaticClass(), TEXT("PageInput")); + { + // Section 1: EditableTextBox + UVerticalBox* SecEdit = nullptr; + PageInput->AddChild(MakeSectionCard(Tree, TEXT("CardInput"), SecEdit)); + AddFillChild(SecEdit, MakeText(Tree, TEXT("TxtSecInputTitle"), TEXT("单行输入框(UEditableTextBox)"), DemoFont, 15, ColorTextPrimary), FMargin(0, 0, 0, 6)); + AddFillChild(SecEdit, MakeText(Tree, TEXT("TxtInputDesc"), TEXT("输入中英文昵称,支持 OnTextChanged 实时字数统计,回车或点按钮应用到顶部玩家栏:"), DemoFont, 12, ColorTextSecondary, false, true), FMargin(0, 0, 0, 8)); + + UEditableTextBox* InputNick = Tree->ConstructWidget(UEditableTextBox::StaticClass(), TEXT("InputNickname")); + InputNick->bIsVariable = true; + InputNick->SetHintText(FText::FromString(TEXT("请输入新的玩家昵称(支持中文)..."))); + FEditableTextBoxStyle EditStyle = InputNick->GetWidgetStyle(); + EditStyle.SetFont(MakeDemoFont(DemoFont, 14)); + EditStyle.BackgroundColor = FSlateColor(FLinearColor(0.95f, 0.97f, 1.0f, 1.0f)); + EditStyle.ForegroundColor = FSlateColor(FLinearColor(0.08f, 0.10f, 0.14f, 1.0f)); + InputNick->SetWidgetStyle(EditStyle); + AddFillChild(SecEdit, InputNick, FMargin(0, 0, 0, 8)); + + UHorizontalBox* InputFoot = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(InputFoot, MakeText(Tree, TEXT("TxtInputStatus"), TEXT("实时内容:空(0 字符)"), DemoFont, 13, ColorTextAccent, true), FMargin(0, 0, 8, 0)); + AddAutoHChild(InputFoot, MakeButton(Tree, TEXT("BtnApplyNickname"), TEXT("TxtApplyNickname"), TEXT("应用为顶部昵称"), DemoFont, 13, ColorAccentBlue)); + AddFillChild(SecEdit, InputFoot); + + USpacer* Sp1 = Tree->ConstructWidget(USpacer::StaticClass()); + Sp1->SetSize(FVector2D(1.0f, 10.0f)); + PageInput->AddChild(Sp1); + + // Section 2: ComboBoxString + UVerticalBox* SecCombo = nullptr; + PageInput->AddChild(MakeSectionCard(Tree, TEXT("CardCombo"), SecCombo)); + AddFillChild(SecCombo, MakeText(Tree, TEXT("TxtSecComboTitle"), TEXT("下拉选择框(UComboBoxString)"), DemoFont, 15, ColorTextPrimary), FMargin(0, 0, 0, 8)); + + UComboBoxString* ComboTheme = Tree->ConstructWidget(UComboBoxString::StaticClass(), TEXT("ComboTheme")); + ComboTheme->bIsVariable = true; + PRAGMA_DISABLE_DEPRECATION_WARNINGS + ComboTheme->Font = MakeDemoFont(DemoFont, 14); + PRAGMA_ENABLE_DEPRECATION_WARNINGS + ComboTheme->AddOption(TEXT("深海蓝(普通)")); + ComboTheme->AddOption(TEXT("翡翠绿(稀有)")); + ComboTheme->AddOption(TEXT("琥珀金(传说)")); + ComboTheme->AddOption(TEXT("星云紫(史诗)")); + ComboTheme->SetSelectedOption(TEXT("深海蓝(普通)")); + AddFillChild(SecCombo, ComboTheme, FMargin(0, 0, 0, 10)); + + UBorder* ThemePreview = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("BorderThemePreview")); + ThemePreview->bIsVariable = true; + ThemePreview->SetBrushColor(ColorAccentBlue); + ThemePreview->SetPadding(FMargin(12.0f, 10.0f)); + ThemePreview->SetContent(MakeText(Tree, TEXT("TxtComboStatus"), TEXT("当前选中:深海蓝(普通)"), DemoFont, 13, ColorTextPrimary, true)); + AddFillChild(SecCombo, ThemePreview); + + USpacer* Sp2 = Tree->ConstructWidget(USpacer::StaticClass()); + Sp2->SetSize(FVector2D(1.0f, 10.0f)); + PageInput->AddChild(Sp2); + + // Section 3: TextBlock Typography + UVerticalBox* SecText = nullptr; + PageInput->AddChild(MakeSectionCard(Tree, TEXT("CardText"), SecText)); + AddFillChild(SecText, MakeText(Tree, TEXT("TxtSecTextTitle"), TEXT("中文排版与样式切换(UTextBlock)"), DemoFont, 15, ColorTextPrimary), FMargin(0, 0, 0, 8)); + AddFillChild(SecText, MakeText(Tree, TEXT("TxtRichSample"), TEXT("中英文混排示例:Unreal Engine 5.8 + UnLua + TypeScript 热更新框架,支持自动换行、动态字号与颜色切换。"), DemoFont, 14, ColorTextPrimary, true, true), FMargin(0, 0, 0, 10)); + UHorizontalBox* TextBtns = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(TextBtns, MakeButton(Tree, TEXT("BtnCycleTextColor"), TEXT("TxtCycleColor"), TEXT("切换文本颜色"), DemoFont, 13, ColorBtnNeutral), FMargin(0, 0, 8, 0)); + AddFillHChild(TextBtns, MakeButton(Tree, TEXT("BtnCycleTextSize"), TEXT("TxtCycleSize"), TEXT("切换字号(14 / 18 / 22)"), DemoFont, 13, ColorBtnNeutral)); + AddFillChild(SecText, TextBtns); + } + TabSwitcher->AddChild(PageInput); + + // ---- Page 2: Media & Containers ---- + UScrollBox* PageMedia = Tree->ConstructWidget(UScrollBox::StaticClass(), TEXT("PageMedia")); + { + // Section 1: Image async load & visibility + UVerticalBox* SecImg = nullptr; + PageMedia->AddChild(MakeSectionCard(Tree, TEXT("CardImg"), SecImg)); + AddFillChild(SecImg, MakeText(Tree, TEXT("TxtSecImgTitle"), TEXT("图片异步加载与可见性模式(UImage + ResourceService)"), DemoFont, 15, ColorTextPrimary), FMargin(0, 0, 0, 8)); + + UHorizontalBox* ImgRow = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + UImage* ImgPreview = Tree->ConstructWidget(UImage::StaticClass(), TEXT("ImgPreview")); + ImgPreview->bIsVariable = true; + ImgPreview->SetDesiredSizeOverride(FVector2D(88.0f, 88.0f)); + AddAutoHChild(ImgRow, ImgPreview, FMargin(0, 0, 14, 0)); + + UVerticalBox* ImgCtrl = Tree->ConstructWidget(UVerticalBox::StaticClass()); + AddFillChild(ImgCtrl, MakeText(Tree, TEXT("TxtImageStatus"), TEXT("当前贴图:冒险者头像 | 可见性:Visible"), DemoFont, 13, ColorTextAccent, true, true), FMargin(0, 0, 0, 8)); + UHorizontalBox* ImgBtns = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(ImgBtns, MakeButton(Tree, TEXT("BtnSwitchTex"), TEXT("TxtSwitchTex"), TEXT("异步切换贴图"), DemoFont, 12, ColorAccentBlue), FMargin(0, 0, 6, 0)); + AddFillHChild(ImgBtns, MakeButton(Tree, TEXT("BtnTintTex"), TEXT("TxtTintTex"), TEXT("切换着色"), DemoFont, 12, ColorBtnNeutral), FMargin(0, 0, 6, 0)); + AddFillHChild(ImgBtns, MakeButton(Tree, TEXT("BtnCycleVis"), TEXT("TxtCycleVis"), TEXT("切换可见性"), DemoFont, 12, ColorBtnNeutral)); + AddFillChild(ImgCtrl, ImgBtns); + AddFillHChild(ImgRow, ImgCtrl); + AddFillChild(SecImg, ImgRow); + + USpacer* Sp1 = Tree->ConstructWidget(USpacer::StaticClass()); + Sp1->SetSize(FVector2D(1.0f, 10.0f)); + PageMedia->AddChild(Sp1); + + // Section 2: Dynamic ScrollBox List + UVerticalBox* SecList = nullptr; + PageMedia->AddChild(MakeSectionCard(Tree, TEXT("CardList"), SecList)); + AddFillChild(SecList, MakeText(Tree, TEXT("TxtSecListTitle"), TEXT("动态滚动列表(UScrollBox + 子控件委托自动解绑)"), DemoFont, 15, ColorTextPrimary), FMargin(0, 0, 0, 6)); + AddFillChild(SecList, MakeText(Tree, TEXT("TxtListSummary"), TEXT("动态列表项:0 条(新增/删除时实时观察顶部绑定数变化)"), DemoFont, 12, ColorTextSecondary, true), FMargin(0, 0, 0, 8)); + + UHorizontalBox* ListBtns = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(ListBtns, MakeButton(Tree, TEXT("BtnListAddOne"), TEXT("TxtListAddOne"), TEXT("新增 1 项"), DemoFont, 12, ColorAccentGreen), FMargin(0, 0, 6, 0)); + AddFillHChild(ListBtns, MakeButton(Tree, TEXT("BtnListAddTen"), TEXT("TxtListAddTen"), TEXT("批量 +10 项"), DemoFont, 12, ColorAccentBlue), FMargin(0, 0, 6, 0)); + AddFillHChild(ListBtns, MakeButton(Tree, TEXT("BtnListClear"), TEXT("TxtListClear"), TEXT("清空列表"), DemoFont, 12, ColorAccentRed)); + AddFillChild(SecList, ListBtns, FMargin(0, 0, 0, 8)); + + USizeBox* ListWrap = Tree->ConstructWidget(USizeBox::StaticClass()); + ListWrap->SetHeightOverride(180.0f); + UBorder* ListBg = Tree->ConstructWidget(UBorder::StaticClass()); + ListBg->SetBrushColor(ColorCardDark); + ListBg->SetPadding(FMargin(6.0f)); + UScrollBox* ScrollDyn = Tree->ConstructWidget(UScrollBox::StaticClass(), TEXT("ScrollDynamicList")); + ScrollDyn->bIsVariable = true; + ListBg->SetContent(ScrollDyn); + ListWrap->AddChild(ListBg); + AddFillChild(SecList, ListWrap); + + USpacer* Sp2 = Tree->ConstructWidget(USpacer::StaticClass()); + Sp2->SetSize(FVector2D(1.0f, 10.0f)); + PageMedia->AddChild(Sp2); + + // Section 3: UniformGridPanel + Overlay Badge Showcase + UVerticalBox* SecGrid = nullptr; + PageMedia->AddChild(MakeSectionCard(Tree, TEXT("CardGrid"), SecGrid)); + AddFillChild(SecGrid, MakeText(Tree, TEXT("TxtSecGridTitle"), TEXT("网格与角标叠层布局(UUniformGridPanel + UOverlay)"), DemoFont, 15, ColorTextPrimary), FMargin(0, 0, 0, 8)); + UUniformGridPanel* Grid = Tree->ConstructWidget(UUniformGridPanel::StaticClass(), TEXT("GridBadges")); + Grid->bIsVariable = true; + Grid->SetSlotPadding(FMargin(6.0f)); + + const TArray> BadgeSpecs = { + { TEXT("武器槽"), TEXT("NEW") }, + { TEXT("防具槽"), TEXT("HOT") }, + { TEXT("饰品槽"), TEXT("LV.5") }, + { TEXT("徽章槽"), TEXT("VIP") } + }; + const TArray TagColors = { ColorAccentBlue, ColorAccentRed, ColorAccentGreen, ColorAccentAmber }; + + for (int32 i = 0; i < BadgeSpecs.Num(); ++i) + { + UOverlay* CellOverlay = Tree->ConstructWidget(UOverlay::StaticClass()); + UBorder* CellBg = Tree->ConstructWidget(UBorder::StaticClass()); + CellBg->SetBrushColor(ColorCardDark); + CellBg->SetPadding(FMargin(10.0f, 14.0f)); + UTextBlock* CellTitle = MakeText(Tree, NAME_None, BadgeSpecs[i].Key, DemoFont, 13, ColorTextPrimary); + CellTitle->SetJustification(ETextJustify::Center); + CellBg->SetContent(CellTitle); + + if (UOverlaySlot* BgSlot = CellOverlay->AddChildToOverlay(CellBg)) + { + BgSlot->SetHorizontalAlignment(HAlign_Fill); + BgSlot->SetVerticalAlignment(VAlign_Fill); + } + + UBorder* CornerTag = Tree->ConstructWidget(UBorder::StaticClass()); + CornerTag->SetBrushColor(TagColors[i]); + CornerTag->SetPadding(FMargin(6.0f, 2.0f)); + CornerTag->SetContent(MakeText(Tree, NAME_None, BadgeSpecs[i].Value, DemoFont, 10, ColorTextPrimary)); + if (UOverlaySlot* TagSlot = CellOverlay->AddChildToOverlay(CornerTag)) + { + TagSlot->SetHorizontalAlignment(HAlign_Right); + TagSlot->SetVerticalAlignment(VAlign_Top); + } + + if (UUniformGridSlot* GSlot = Grid->AddChildToUniformGrid(CellOverlay, 0, i)) + { + GSlot->SetHorizontalAlignment(HAlign_Fill); + GSlot->SetVerticalAlignment(VAlign_Fill); + } + } + AddFillChild(SecGrid, Grid); + } + TabSwitcher->AddChild(PageMedia); + + // ---- Page 3: Diagnostics ---- + UScrollBox* PageDiag = Tree->ConstructWidget(UScrollBox::StaticClass(), TEXT("PageDiag")); + { + UVerticalBox* SecDiag = nullptr; + PageDiag->AddChild(MakeSectionCard(Tree, TEXT("CardDiag"), SecDiag)); + AddFillChild(SecDiag, MakeText(Tree, TEXT("TxtSecDiagTitle"), TEXT("UI 框架与运行时实时诊断"), DemoFont, 15, ColorTextPrimary), FMargin(0, 0, 0, 8)); + AddFillChild(SecDiag, MakeText(Tree, TEXT("TxtDiagDetail"), TEXT("点击刷新查看窗口栈、资源引用与委托绑定详情..."), DemoFont, 13, ColorTextSecondary, true, true), FMargin(0, 0, 0, 12)); + + UHorizontalBox* DiagBtns = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(DiagBtns, MakeButton(Tree, TEXT("BtnDiagRefresh"), TEXT("TxtDiagRefresh"), TEXT("刷新诊断"), DemoFont, 13, ColorAccentBlue), FMargin(0, 0, 8, 0)); + AddFillHChild(DiagBtns, MakeButton(Tree, TEXT("BtnDiagConcurrent"), TEXT("TxtDiagConcurrent"), TEXT("并发双开单例测试"), DemoFont, 13, ColorAccentAmber), FMargin(0, 0, 8, 0)); + AddFillHChild(DiagBtns, MakeButton(Tree, TEXT("BtnDiagCancelLoad"), TEXT("TxtDiagCancelLoad"), TEXT("加载中取消测试"), DemoFont, 13, ColorAccentPurple)); + AddFillChild(SecDiag, DiagBtns); + } + TabSwitcher->AddChild(PageDiag); + + AddFillHChild(BodyRow, CenterPanel, FMargin(0, 0, 12, 0), VAlign_Fill); + + // --- 2C. RightLog (Live Event Inspector) --- + USizeBox* RightWrap = Tree->ConstructWidget(USizeBox::StaticClass(), TEXT("RightWrap")); + RightWrap->SetWidthOverride(290.0f); + UBorder* RightPanel = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("RightLogPanel")); + RightPanel->SetBrushColor(ColorCardDark); + RightPanel->SetPadding(FMargin(12.0f)); + UVerticalBox* LogVBox = Tree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("LogVBox")); + RightPanel->SetContent(LogVBox); + RightWrap->AddChild(RightPanel); + + UHorizontalBox* LogHeader = Tree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("LogHeader")); + AddFillHChild(LogHeader, MakeText(Tree, TEXT("TxtLogTitle"), TEXT("实时事件与生命周期日志"), DemoFont, 14, ColorTextPrimary)); + AddAutoHChild(LogHeader, MakeButton(Tree, TEXT("BtnClearLog"), TEXT("TxtClearLog"), TEXT("清空"), DemoFont, 11, ColorBtnNeutral)); + AddFillChild(LogVBox, LogHeader, FMargin(0, 0, 0, 8)); + AddFillChild(LogVBox, MakeDivider(Tree, TEXT("LogDiv")), FMargin(0, 0, 0, 8)); + + UScrollBox* ScrollLog = Tree->ConstructWidget(UScrollBox::StaticClass(), TEXT("ScrollEventLog")); + ScrollLog->bIsVariable = true; + ScrollLog->AddChild(MakeText(Tree, TEXT("TxtEventLog"), TEXT("[日志就绪]"), DemoFont, 12, ColorTextSecondary, true, true)); + if (UVerticalBoxSlot* LogSlot = LogVBox->AddChildToVerticalBox(ScrollLog)) + { + LogSlot->SetSize(FSlateChildSize(ESlateSizeRule::Fill)); + LogSlot->SetHorizontalAlignment(HAlign_Fill); + LogSlot->SetVerticalAlignment(VAlign_Fill); + } + + AddAutoHChild(BodyRow, RightWrap, FMargin(0), VAlign_Fill); + + return FinishWidgetBlueprint(Package, WidgetBP, PackageName); +} + +bool USetupDemoAssetsCommandlet::CreateUIDemoListItemBlueprint(UFont* DemoFont) const +{ + const FString PackageName = TEXT("/Game/UI/Demo/WBP_UIDemoListItem"); + UPackage* Package = nullptr; + UWidgetBlueprint* WidgetBP = BeginWidgetBlueprint(PackageName, TEXT("WBP_UIDemoListItem"), Package); + if (!WidgetBP) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + UBorder* Root = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("ItemBorder")); + Root->SetBrushColor(ColorCard); + Root->SetPadding(FMargin(10.0f, 6.0f)); + Tree->RootWidget = Root; + + UHorizontalBox* Row = Tree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("ItemRow")); + Root->SetContent(Row); + + AddFillHChild(Row, MakeText(Tree, TEXT("TxtItemTitle"), TEXT("列表项 #1"), DemoFont, 13, ColorTextPrimary, true), FMargin(0, 0, 8, 0)); + AddAutoHChild(Row, MakeButton(Tree, TEXT("BtnItemAction"), TEXT("TxtItemAction"), TEXT("触发"), DemoFont, 12, ColorAccentBlue), FMargin(0, 0, 6, 0)); + AddAutoHChild(Row, MakeButton(Tree, TEXT("BtnItemDelete"), TEXT("TxtItemDelete"), TEXT("删除"), DemoFont, 12, ColorAccentRed)); + + return FinishWidgetBlueprint(Package, WidgetBP, PackageName); +} + +bool USetupDemoAssetsCommandlet::CreateUIDemoNormalBlueprint(UFont* DemoFont) const +{ + const FString PackageName = TEXT("/Game/UI/Demo/WBP_UIDemoNormal"); + UPackage* Package = nullptr; + UWidgetBlueprint* WidgetBP = BeginWidgetBlueprint(PackageName, TEXT("WBP_UIDemoNormal"), Package); + if (!WidgetBP) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + UCanvasPanel* Root = Tree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("RootCanvas")); + Tree->RootWidget = Root; + + UBorder* Card = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("NormalCard")); + Card->SetBrushColor(ColorPanel); + Card->SetPadding(FMargin(22.0f, 18.0f)); + SetupCenterCanvasSlot(Root, Card, FVector2D(460.0f, 280.0f), FVector2D(40.0f, -20.0f)); + + UVerticalBox* VBox = Tree->ConstructWidget(UVerticalBox::StaticClass()); + Card->SetContent(VBox); + + AddFillChild(VBox, MakeText(Tree, TEXT("TxtNormalTitle"), TEXT("普通信息窗口(Normal / Singleton)"), DemoFont, 18, ColorTextPrimary, true), FMargin(0, 0, 0, 8)); + AddFillChild(VBox, MakeDivider(Tree, TEXT("NormalDiv")), FMargin(0, 0, 0, 10)); + AddFillChild(VBox, MakeText(Tree, TEXT("TxtNormalBody"), TEXT("Layer: normal | Type: normal | Singleton: true\n重复点击左侧入口不会双开,而是刷新内容并置顶。"), DemoFont, 13, ColorTextSecondary, true, true), FMargin(0, 0, 0, 16)); + + UHorizontalBox* Btns = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(Btns, MakeButton(Tree, TEXT("BtnNormalPing"), TEXT("TxtNormalPing"), TEXT("触发交互 (+1)"), DemoFont, 13, ColorAccentBlue), FMargin(0, 0, 8, 0)); + AddFillHChild(Btns, MakeButton(Tree, TEXT("BtnNormalClose"), TEXT("TxtNormalClose"), TEXT("关闭窗口"), DemoFont, 13, ColorBtnNeutral)); + AddFillChild(VBox, Btns); + + return FinishWidgetBlueprint(Package, WidgetBP, PackageName); +} + +bool USetupDemoAssetsCommandlet::CreateUIDemoFullscreenBlueprint(UFont* DemoFont) const +{ + const FString PackageName = TEXT("/Game/UI/Demo/WBP_UIDemoFullscreen"); + UPackage* Package = nullptr; + UWidgetBlueprint* WidgetBP = BeginWidgetBlueprint(PackageName, TEXT("WBP_UIDemoFullscreen"), Package); + if (!WidgetBP) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + UCanvasPanel* Root = Tree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("RootCanvas")); + Tree->RootWidget = Root; + + UBorder* FullBg = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("FullBg")); + FullBg->SetBrushColor(FLinearColor(0.063f, 0.055f, 0.118f, 1.0f)); + SetupFullCanvasSlot(Root, FullBg); + + UBorder* CenterBox = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("FullCard")); + CenterBox->SetBrushColor(ColorPanel); + CenterBox->SetPadding(FMargin(32.0f, 26.0f)); + SetupCenterCanvasSlot(Root, CenterBox, FVector2D(640.0f, 440.0f)); + + UVerticalBox* VBox = Tree->ConstructWidget(UVerticalBox::StaticClass()); + CenterBox->SetContent(VBox); + + AddFillChild(VBox, MakeText(Tree, TEXT("TxtFullTitle"), TEXT("全屏角色图鉴(Fullscreen 窗口)"), DemoFont, 24, ColorTextPrimary, true), FMargin(0, 0, 0, 10)); + AddFillChild(VBox, MakeText(Tree, TEXT("TxtFullDesc"), TEXT("Layer: normal | Type: fullscreen\n打开全屏窗口时,UIManager 会自动隐藏下层主界面与普通窗口;关闭本页时自动恢复下层显示。"), DemoFont, 14, ColorTextSecondary, true, true), FMargin(0, 0, 0, 18)); + + UImage* ImgPreview = Tree->ConstructWidget(UImage::StaticClass(), TEXT("ImgFullPreview")); + ImgPreview->bIsVariable = true; + ImgPreview->SetDesiredSizeOverride(FVector2D(128.0f, 128.0f)); + if (UVerticalBoxSlot* ImgSlot = VBox->AddChildToVerticalBox(ImgPreview)) + { + ImgSlot->SetHorizontalAlignment(HAlign_Center); + ImgSlot->SetPadding(FMargin(0, 0, 0, 18)); + } + + UHorizontalBox* Btns = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(Btns, MakeButton(Tree, TEXT("BtnFullOpenModal"), TEXT("TxtFullModal"), TEXT("在全屏页上方弹出模态框"), DemoFont, 14, ColorAccentAmber), FMargin(0, 0, 12, 0)); + AddFillHChild(Btns, MakeButton(Tree, TEXT("BtnFullClose"), TEXT("TxtFullClose"), TEXT("退出全屏(恢复主界面)"), DemoFont, 14, ColorAccentPurple)); + AddFillChild(VBox, Btns); + + return FinishWidgetBlueprint(Package, WidgetBP, PackageName); +} + +bool USetupDemoAssetsCommandlet::CreateUIDemoModalBlueprint(UFont* DemoFont) const +{ + const FString PackageName = TEXT("/Game/UI/Demo/WBP_UIDemoModal"); + UPackage* Package = nullptr; + UWidgetBlueprint* WidgetBP = BeginWidgetBlueprint(PackageName, TEXT("WBP_UIDemoModal"), Package); + if (!WidgetBP) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + UCanvasPanel* Root = Tree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("RootCanvas")); + Tree->RootWidget = Root; + + // Fullscreen semi-transparent blocker prevents clicking underlying widgets + UBorder* Mask = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("ModalMask")); + Mask->SetBrushColor(FLinearColor(0.0f, 0.0f, 0.0f, 0.68f)); + SetupFullCanvasSlot(Root, Mask); + + UBorder* Dialog = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("ModalDialog")); + Dialog->SetBrushColor(ColorPanel); + Dialog->SetPadding(FMargin(24.0f, 20.0f)); + SetupCenterCanvasSlot(Root, Dialog, FVector2D(460.0f, 250.0f)); + + UVerticalBox* VBox = Tree->ConstructWidget(UVerticalBox::StaticClass()); + Dialog->SetContent(VBox); + + AddFillChild(VBox, MakeText(Tree, TEXT("TxtModalTitle"), TEXT("二次确认模态弹窗"), DemoFont, 19, ColorTextPrimary, true), FMargin(0, 0, 0, 10)); + AddFillChild(VBox, MakeDivider(Tree, TEXT("ModalDiv")), FMargin(0, 0, 0, 12)); + AddFillChild(VBox, MakeText(Tree, TEXT("TxtModalMessage"), TEXT("半透明遮罩已拦截底层点击。请选择确认或取消以测试回调透传。"), DemoFont, 14, ColorTextSecondary, true, true), FMargin(0, 0, 0, 20)); + + UHorizontalBox* Btns = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(Btns, MakeButton(Tree, TEXT("BtnModalConfirm"), TEXT("TxtModalConfirm"), TEXT("确认"), DemoFont, 14, ColorAccentGreen), FMargin(0, 0, 12, 0)); + AddFillHChild(Btns, MakeButton(Tree, TEXT("BtnModalCancel"), TEXT("TxtModalCancel"), TEXT("取消"), DemoFont, 14, ColorBtnNeutral)); + AddFillChild(VBox, Btns); + + return FinishWidgetBlueprint(Package, WidgetBP, PackageName); +} + +bool USetupDemoAssetsCommandlet::CreateUIDemoCachedBlueprint(UFont* DemoFont) const +{ + const FString PackageName = TEXT("/Game/UI/Demo/WBP_UIDemoCached"); + UPackage* Package = nullptr; + UWidgetBlueprint* WidgetBP = BeginWidgetBlueprint(PackageName, TEXT("WBP_UIDemoCached"), Package); + if (!WidgetBP) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + UCanvasPanel* Root = Tree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("RootCanvas")); + Tree->RootWidget = Root; + + UBorder* Card = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("CachedCard")); + Card->SetBrushColor(ColorPanel); + Card->SetPadding(FMargin(24.0f, 20.0f)); + SetupCenterCanvasSlot(Root, Card, FVector2D(490.0f, 300.0f), FVector2D(-30.0f, 20.0f)); + + UVerticalBox* VBox = Tree->ConstructWidget(UVerticalBox::StaticClass()); + Card->SetContent(VBox); + + AddFillChild(VBox, MakeText(Tree, TEXT("TxtCachedTitle"), TEXT("缓存复用窗口(cacheTag = cache)"), DemoFont, 18, ColorTextPrimary, true), FMargin(0, 0, 0, 8)); + AddFillChild(VBox, MakeDivider(Tree, TEXT("CachedDiv")), FMargin(0, 0, 0, 12)); + AddFillChild(VBox, MakeText(Tree, TEXT("TxtCachedStats"), TEXT("复用次数:0 | 按钮点击:0\n关闭后进入缓存池并自动解绑委托,再次打开直接复用实例且点击不翻倍。"), DemoFont, 13, ColorTextAccent, true, true), FMargin(0, 0, 0, 18)); + + UHorizontalBox* Btns = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(Btns, MakeButton(Tree, TEXT("BtnCachedAction"), TEXT("TxtCachedAction"), TEXT("点击测试 (+1)"), DemoFont, 13, ColorAccentGreen), FMargin(0, 0, 10, 0)); + AddFillHChild(Btns, MakeButton(Tree, TEXT("BtnCachedClose"), TEXT("TxtCachedClose"), TEXT("关闭并放回缓存池"), DemoFont, 13, ColorBtnNeutral)); + AddFillChild(VBox, Btns); + + return FinishWidgetBlueprint(Package, WidgetBP, PackageName); +} + +bool USetupDemoAssetsCommandlet::CreateUIDemoMultiBlueprint(UFont* DemoFont) const +{ + const FString PackageName = TEXT("/Game/UI/Demo/WBP_UIDemoMulti"); + UPackage* Package = nullptr; + UWidgetBlueprint* WidgetBP = BeginWidgetBlueprint(PackageName, TEXT("WBP_UIDemoMulti"), Package); + if (!WidgetBP) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + UCanvasPanel* Root = Tree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("RootCanvas")); + Tree->RootWidget = Root; + + UBorder* Card = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("MultiCard")); + Card->bIsVariable = true; + Card->SetBrushColor(ColorCard); + Card->SetPadding(FMargin(18.0f, 16.0f)); + SetupCenterCanvasSlot(Root, Card, FVector2D(360.0f, 220.0f)); + + UVerticalBox* VBox = Tree->ConstructWidget(UVerticalBox::StaticClass()); + Card->SetContent(VBox); + + AddFillChild(VBox, MakeText(Tree, TEXT("TxtMultiTitle"), TEXT("多实例便签窗 #1"), DemoFont, 17, ColorTextPrimary, true), FMargin(0, 0, 0, 8)); + AddFillChild(VBox, MakeText(Tree, TEXT("TxtMultiBody"), TEXT("singleton = false\n每个实例独立偏移、独立计数、独立关闭。"), DemoFont, 13, ColorTextSecondary, true, true), FMargin(0, 0, 0, 16)); + + UHorizontalBox* Btns = Tree->ConstructWidget(UHorizontalBox::StaticClass()); + AddFillHChild(Btns, MakeButton(Tree, TEXT("BtnMultiCount"), TEXT("TxtMultiCount"), TEXT("实例计数 +1"), DemoFont, 13, ColorAccentCyan), FMargin(0, 0, 8, 0)); + AddFillHChild(Btns, MakeButton(Tree, TEXT("BtnMultiClose"), TEXT("TxtMultiClose"), TEXT("关闭本窗"), DemoFont, 13, ColorBtnNeutral)); + AddFillChild(VBox, Btns); + + return FinishWidgetBlueprint(Package, WidgetBP, PackageName); +} + +bool USetupDemoAssetsCommandlet::CreateUIDemoToastBlueprint(UFont* DemoFont) const +{ + const FString PackageName = TEXT("/Game/UI/Demo/WBP_UIDemoToast"); + UPackage* Package = nullptr; + UWidgetBlueprint* WidgetBP = BeginWidgetBlueprint(PackageName, TEXT("WBP_UIDemoToast"), Package); + if (!WidgetBP) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + UCanvasPanel* Root = Tree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("RootCanvas")); + Root->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + Tree->RootWidget = Root; + + UBorder* Pill = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("ToastPill")); + Pill->bIsVariable = true; + Pill->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + Pill->SetBrushColor(FLinearColor(0.086f, 0.310f, 0.520f, 0.94f)); + Pill->SetPadding(FMargin(22.0f, 10.0f)); + if (UCanvasPanelSlot* CSlot = Root->AddChildToCanvas(Pill)) + { + CSlot->SetAnchors(FAnchors(0.5f, 0.0f, 0.5f, 0.0f)); + CSlot->SetAlignment(FVector2D(0.5f, 0.0f)); + CSlot->SetPosition(FVector2D(0.0f, 92.0f)); + CSlot->SetAutoSize(true); + } + + UTextBlock* Msg = MakeText(Tree, TEXT("TxtToastMessage"), TEXT("飘字提示:这是一条 Tips 层自动消失通知"), DemoFont, 14, ColorTextPrimary, true); + Msg->SetJustification(ETextJustify::Center); + Pill->SetContent(Msg); + + return FinishWidgetBlueprint(Package, WidgetBP, PackageName); +} + +bool USetupDemoAssetsCommandlet::CreateUIDemoSystemBlueprint(UFont* DemoFont) const +{ + const FString PackageName = TEXT("/Game/UI/Demo/WBP_UIDemoSystem"); + UPackage* Package = nullptr; + UWidgetBlueprint* WidgetBP = BeginWidgetBlueprint(PackageName, TEXT("WBP_UIDemoSystem"), Package); + if (!WidgetBP) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + UCanvasPanel* Root = Tree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("RootCanvas")); + Tree->RootWidget = Root; + + UBorder* Mask = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("SystemMask")); + Mask->SetBrushColor(FLinearColor(0.10f, 0.03f, 0.04f, 0.76f)); + SetupFullCanvasSlot(Root, Mask); + + UBorder* Dialog = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("SystemDialog")); + Dialog->SetBrushColor(FLinearColor(0.145f, 0.075f, 0.095f, 0.98f)); + Dialog->SetPadding(FMargin(26.0f, 22.0f)); + SetupCenterCanvasSlot(Root, Dialog, FVector2D(500.0f, 250.0f)); + + UVerticalBox* VBox = Tree->ConstructWidget(UVerticalBox::StaticClass()); + Dialog->SetContent(VBox); + + AddFillChild(VBox, MakeText(Tree, TEXT("TxtSystemTitle"), TEXT("系统级顶层弹窗(Layer: system)"), DemoFont, 20, FLinearColor(1.0f, 0.62f, 0.62f, 1.0f), true), FMargin(0, 0, 0, 10)); + AddFillChild(VBox, MakeDivider(Tree, TEXT("SysDiv")), FMargin(0, 0, 0, 12)); + AddFillChild(VBox, MakeText(Tree, TEXT("TxtSystemBody"), TEXT("ZOrder 400+,优先级高于 normal / popup / tips 全部层级,常用于断线重连或强制系统公告。"), DemoFont, 14, ColorTextPrimary, true, true), FMargin(0, 0, 0, 20)); + AddFillChild(VBox, MakeButton(Tree, TEXT("BtnSystemAck"), TEXT("TxtSystemAck"), TEXT("我知道了(关闭系统弹窗)"), DemoFont, 14, ColorAccentRed)); + + return FinishWidgetBlueprint(Package, WidgetBP, PackageName); +} diff --git a/Source/UnrealLuaDemoEditor/SetupDemoAssetsCommandlet.h b/Source/UnrealLuaDemoEditor/SetupDemoAssetsCommandlet.h new file mode 100644 index 0000000..3f58df3 --- /dev/null +++ b/Source/UnrealLuaDemoEditor/SetupDemoAssetsCommandlet.h @@ -0,0 +1,46 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "Commandlets/Commandlet.h" +#include "SetupDemoAssetsCommandlet.generated.h" + +class UFont; +class UFontFace; + +/** + * Programmatically generates Chinese font assets, Demo textures, /Game/Maps/L_DemoUI, + * and all UMG Widget Blueprints for the Bootstrap Demo Hub and UI Demo scene. + * + * Run via: + * UnrealEditor-Cmd UnrealLuaDemo.uproject -run=SetupDemoAssets -unattended -nop4 -nosplash -NullRHI + */ +UCLASS() +class UNREALLUADEMOEDITOR_API USetupDemoAssetsCommandlet : public UCommandlet +{ + GENERATED_BODY() + +public: + USetupDemoAssetsCommandlet(); + + virtual int32 Main(const FString& Params) override; + +private: + UFontFace* CreateChineseFontFace() const; + UFont* CreateDemoUIFont(UFontFace* CJKFontFace) const; + bool CreateDemoMap(const FString& PackageName, const FString& MapName) const; + bool CreateProceduralTexture(const FString& PackageName, const FString& AssetName, int32 StyleIndex) const; + + bool CreateDemoHubBlueprint(UFont* DemoFont) const; + bool CreateDemoHubItemBlueprint(UFont* DemoFont) const; + bool CreateUIDemoMainBlueprint(UFont* DemoFont) const; + bool CreateUIDemoListItemBlueprint(UFont* DemoFont) const; + bool CreateUIDemoNormalBlueprint(UFont* DemoFont) const; + bool CreateUIDemoFullscreenBlueprint(UFont* DemoFont) const; + bool CreateUIDemoModalBlueprint(UFont* DemoFont) const; + bool CreateUIDemoCachedBlueprint(UFont* DemoFont) const; + bool CreateUIDemoMultiBlueprint(UFont* DemoFont) const; + bool CreateUIDemoToastBlueprint(UFont* DemoFont) const; + bool CreateUIDemoSystemBlueprint(UFont* DemoFont) const; +};