feat(demo): add Bootstrap Demo Hub, Chinese UI font, and UI Demo showcase scene

This commit is contained in:
szy73711 committed 2026-12-01 03:13:35 +08:00
1 parent 3572f2da43
commit 4c83c086f4
49 files changed
+7864 -131

No files matched your search

@@ -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)
+180 -17
View File
@@ -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
+161 -12
View File
@@ -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
+112 -12
View File
@@ -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
+5 -5
View File
@@ -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
+179
View File
@@ -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
+59
View File
@@ -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
+94
View File
@@ -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
@@ -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
@@ -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
+249
View File
@@ -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
@@ -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
}
}
}
@@ -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<string, string> = {
[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 {
+267 -22
View File
@@ -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<string, UIDelegateBridge | undefined> = {}
/**
* 纯 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<number, ButtonBindingRecord | undefined> = {};
private bindings: Record<number, WidgetBindingRecord | undefined> = {};
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) {
+162 -11
View File
@@ -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 {
+127 -19
View File
@@ -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<any>;
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<any>): 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>("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);
}
+3 -3
View File
@@ -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 {
+183
View File
@@ -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<string, UE.UButton | undefined> = {};
private itemScope?: ScopedObject;
private onSelectDemo?: (this: void, demo: DemoSceneDescriptor) => void;
protected override OnBindWidgets(): void {
this.txtRuntimeInfo = this.RequireWidget<UE.UTextBlock>("TxtRuntimeInfo");
this.scrollDemoList = this.RequireWidget<UE.UScrollBox>("ScrollDemoList");
this.btnOpenMiniSettings = this.RequireWidget<UE.UButton>("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<ResourceService>("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<ResourceService>("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>("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,
});
+74
View File
@@ -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;
+110
View File
@@ -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);
}
@@ -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<UE.UImage>("ImgPlayerAvatar");
this.txtPlayerName = this.RequireWidget<UE.UTextBlock>("TxtPlayerName");
this.barPlayerExp = this.RequireWidget<UE.UProgressBar>("BarPlayerExp");
this.txtHudStats = this.RequireWidget<UE.UTextBlock>("TxtHudStats");
this.btnTopSettings = this.RequireWidget<UE.UButton>("BtnTopSettings");
this.btnBackToHub = this.RequireWidget<UE.UButton>("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<UE.UButton>("BtnWinNormal");
this.btnWinFullscreen = this.RequireWidget<UE.UButton>("BtnWinFullscreen");
this.btnWinModal = this.RequireWidget<UE.UButton>("BtnWinModal");
this.btnWinCached = this.RequireWidget<UE.UButton>("BtnWinCached");
this.btnWinMulti = this.RequireWidget<UE.UButton>("BtnWinMulti");
this.btnWinToast = this.RequireWidget<UE.UButton>("BtnWinToast");
this.btnWinSystem = this.RequireWidget<UE.UButton>("BtnWinSystem");
this.btnEvictCache = this.RequireWidget<UE.UButton>("BtnEvictCache");
this.btnCloseOthers = this.RequireWidget<UE.UButton>("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<UE.UButton>("BtnTabBasic");
this.btnTabInput = this.RequireWidget<UE.UButton>("BtnTabInput");
this.btnTabMedia = this.RequireWidget<UE.UButton>("BtnTabMedia");
this.btnTabDiag = this.RequireWidget<UE.UButton>("BtnTabDiag");
this.tabSwitcher = this.RequireWidget<UE.UWidgetSwitcher>("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<UE.UTextBlock>("TxtBasicBtnStatus");
this.btnDemoAction = this.RequireWidget<UE.UButton>("BtnDemoAction");
this.btnToggleDisable = this.RequireWidget<UE.UButton>("BtnToggleDisable");
this.btnDemoTarget = this.RequireWidget<UE.UButton>("BtnDemoTarget");
this.txtDemoTarget = this.RequireWidget<UE.UTextBlock>("TxtDemoTarget");
this.chkFeature = this.RequireWidget<UE.UCheckBox>("ChkFeature");
this.txtCheckStatus = this.RequireWidget<UE.UTextBlock>("TxtCheckStatus");
this.txtSliderStatus = this.RequireWidget<UE.UTextBlock>("TxtSliderStatus");
this.sliderDemo = this.RequireWidget<UE.USlider>("SliderDemo");
this.progressDemo = this.RequireWidget<UE.UProgressBar>("ProgressDemo");
this.btnProgressPlay = this.RequireWidget<UE.UButton>("BtnProgressPlay");
this.txtProgressPlay = this.RequireWidget<UE.UTextBlock>("TxtProgressPlay");
this.btnProgressReset = this.RequireWidget<UE.UButton>("BtnProgressReset");
this.spinDemo = this.RequireWidget<UE.USpinBox>("SpinDemo");
this.txtSpinStatus = this.RequireWidget<UE.UTextBlock>("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<UE.UEditableTextBox>("InputNickname");
this.txtInputStatus = this.RequireWidget<UE.UTextBlock>("TxtInputStatus");
this.btnApplyNickname = this.RequireWidget<UE.UButton>("BtnApplyNickname");
this.comboTheme = this.RequireWidget<UE.UComboBoxString>("ComboTheme");
this.borderThemePreview = this.RequireWidget<UE.UBorder>("BorderThemePreview");
this.txtComboStatus = this.RequireWidget<UE.UTextBlock>("TxtComboStatus");
this.txtRichSample = this.RequireWidget<UE.UTextBlock>("TxtRichSample");
this.btnCycleTextColor = this.RequireWidget<UE.UButton>("BtnCycleTextColor");
this.btnCycleTextSize = this.RequireWidget<UE.UButton>("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<UE.UImage>("ImgPreview");
this.txtImageStatus = this.RequireWidget<UE.UTextBlock>("TxtImageStatus");
this.btnSwitchTex = this.RequireWidget<UE.UButton>("BtnSwitchTex");
this.btnTintTex = this.RequireWidget<UE.UButton>("BtnTintTex");
this.btnCycleVis = this.RequireWidget<UE.UButton>("BtnCycleVis");
this.txtListSummary = this.RequireWidget<UE.UTextBlock>("TxtListSummary");
this.btnListAddOne = this.RequireWidget<UE.UButton>("BtnListAddOne");
this.btnListAddTen = this.RequireWidget<UE.UButton>("BtnListAddTen");
this.btnListClear = this.RequireWidget<UE.UButton>("BtnListClear");
this.scrollDynamicList = this.RequireWidget<UE.UScrollBox>("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<UE.UTextBlock>("TxtDiagDetail");
this.btnDiagRefresh = this.RequireWidget<UE.UButton>("BtnDiagRefresh");
this.btnDiagConcurrent = this.RequireWidget<UE.UButton>("BtnDiagConcurrent");
this.btnDiagCancelLoad = this.RequireWidget<UE.UButton>("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<UE.UButton>("BtnClearLog");
this.scrollEventLog = this.RequireWidget<UE.UScrollBox>("ScrollEventLog");
this.txtEventLog = this.RequireWidget<UE.UTextBlock>("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>("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<ResourceService>("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<ResourceService>("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<ResourceService>("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>("uiDelegateBridge");
const resSvc = this.ctx.GetService<ResourceService>("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,
});
@@ -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<UE.UTextBlock>("TxtNormalTitle");
this.txtNormalBody = this.RequireWidget<UE.UTextBlock>("TxtNormalBody");
this.btnNormalPing = this.RequireWidget<UE.UButton>("BtnNormalPing");
this.btnNormalClose = this.RequireWidget<UE.UButton>("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<UE.UTextBlock>("TxtFullDesc");
this.imgFullPreview = this.RequireWidget<UE.UImage>("ImgFullPreview");
this.btnFullOpenModal = this.RequireWidget<UE.UButton>("BtnFullOpenModal");
this.btnFullClose = this.RequireWidget<UE.UButton>("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<ResourceService>("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<UE.UTextBlock>("TxtModalTitle");
this.txtModalMessage = this.RequireWidget<UE.UTextBlock>("TxtModalMessage");
this.btnModalConfirm = this.RequireWidget<UE.UButton>("BtnModalConfirm");
this.btnModalCancel = this.RequireWidget<UE.UButton>("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<UE.UTextBlock>("TxtCachedStats");
this.btnCachedAction = this.RequireWidget<UE.UButton>("BtnCachedAction");
this.btnCachedClose = this.RequireWidget<UE.UButton>("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<UE.UBorder>("MultiCard");
this.txtMultiTitle = this.RequireWidget<UE.UTextBlock>("TxtMultiTitle");
this.txtMultiBody = this.RequireWidget<UE.UTextBlock>("TxtMultiBody");
this.btnMultiCount = this.RequireWidget<UE.UButton>("BtnMultiCount");
this.btnMultiClose = this.RequireWidget<UE.UButton>("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<UE.UBorder>("ToastPill");
this.txtToastMessage = this.RequireWidget<UE.UTextBlock>("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<UE.UTextBlock>("TxtSystemBody");
this.btnSystemAck = this.RequireWidget<UE.UButton>("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,
});
+189
View File
@@ -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<ResourceService>("resource")!;
const uiBridge = ctx.GetService<UIDelegateBridge>("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<ResourceService>("resource")!;
const uiBridge = ctx.GetService<UIDelegateBridge>("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);
@@ -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();
},
},
],
};
}
+152
View File
@@ -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;
}
}
+50 -3
View File
@@ -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<number, ULuaButtonClickProxy>;
ActiveProxies: TMap<number, ULuaWidgetEventProxyBase>;
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;
}
}