UIManager.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. import { instantiate, Node } from 'cc';
  2. import { BUNDLE_ID } from '@scripts/define/ResDefine';
  3. import { getUIViewConfig, UIViewConfig, UIViewID } from '../../define/UIDefine';
  4. import { ResourceManager } from '../resource/ResourceManager';
  5. import { UICachePolicy, UICloseReason, UILayer, UIViewState } from './UILayer';
  6. import { UIView } from './UIView';
  7. import { UIToast } from '@scripts/modules/lobby/ui/UIToast';
  8. import { IDialogConfig, UIDialog } from '@scripts/modules/lobby/ui/UIDialog';
  9. import { AppKernel } from '@scripts/app/AppKernel';
  10. interface UIViewRecord {
  11. config: UIViewConfig;
  12. state: UIViewState;
  13. view: UIView | null;
  14. ownerRoot: Node | null;
  15. generation: number;
  16. opening: Promise<UIView | null> | null;
  17. closing: Promise<boolean> | null;
  18. delayedDestroyTimer: ReturnType<typeof setTimeout> | null;
  19. }
  20. export class UIManager {
  21. private static readonly DELAYED_DESTROY_MS = 5000;
  22. private readonly records = new Map<UIViewID, UIViewRecord>();
  23. private readonly roots = new Map<UILayer, Node>();
  24. private loadingCount = 0;
  25. public get isLoading() { return this.loadingCount > 0 }
  26. constructor(private readonly resources: ResourceManager) { }
  27. bindLayer(layer: UILayer, root: Node): void {
  28. this.roots.set(layer, root);
  29. }
  30. /**
  31. * 接管当前场景各 UI Layer 中预放置的 UIView。
  32. * 注册后的 View 先进入缓存态,之后仍由 open/close 统一驱动生命周期。
  33. */
  34. async registerSceneViews(): Promise<void> {
  35. for (const [layer, root] of this.roots) {
  36. if (!root.isValid) continue;
  37. const views = root.getComponentsInChildren(UIView);
  38. for (const view of views) {
  39. const viewId = view.getViewID();
  40. if (!viewId) {
  41. console.warn(`[UIManager] Scene UIView has no viewId: ${view.node.name}`);
  42. continue;
  43. }
  44. const config = getUIViewConfig(viewId);
  45. if (!config) {
  46. console.warn(`[UIManager] Scene UIView is not configured: ${viewId}`);
  47. continue;
  48. }
  49. if (config.layer !== layer) {
  50. console.warn(
  51. `[UIManager] Scene UIView is under the wrong layer: ${viewId}, expected=${config.layer}, actual=${layer}`,
  52. );
  53. continue;
  54. }
  55. const existing = this.records.get(viewId);
  56. if (existing?.view === view) continue;
  57. if (existing?.view?.node?.isValid) {
  58. console.warn(`[UIManager] Duplicate scene UIView ignored: ${viewId}`);
  59. continue;
  60. }
  61. if (existing) this.forgetRecord(existing);
  62. const record: UIViewRecord = {
  63. config,
  64. state: UIViewState.Creating,
  65. view,
  66. ownerRoot: root,
  67. generation: 1,
  68. opening: null,
  69. closing: null,
  70. delayedDestroyTimer: null,
  71. };
  72. this.records.set(viewId, record);
  73. view.node.active = false;
  74. try {
  75. await view.internalCreate();
  76. if (!view.node.isValid || this.records.get(viewId) !== record) {
  77. this.forgetRecord(record);
  78. continue;
  79. }
  80. record.state = UIViewState.Cached;
  81. } catch (error) {
  82. this.forgetRecord(record);
  83. throw error;
  84. }
  85. }
  86. }
  87. }
  88. clearSceneLayers(): void {
  89. const sceneRoots = new Set(this.roots.values());
  90. this.roots.clear();
  91. for (const record of [...this.records.values()]) {
  92. const node = record.view?.node;
  93. const belongsToSceneLayer = node?.isValid
  94. ? [...sceneRoots].some((root) => root.isValid && (node === root || node.isChildOf(root)))
  95. : record.ownerRoot !== null && sceneRoots.has(record.ownerRoot);
  96. if (!node?.isValid || belongsToSceneLayer) {
  97. this.forgetRecord(record);
  98. }
  99. }
  100. }
  101. get<TView extends UIView>(viewId: UIViewID): TView | null {
  102. const record = this.records.get(viewId);
  103. if (
  104. !record
  105. || !record.view?.node?.isValid
  106. || (record.state !== UIViewState.Opening && record.state !== UIViewState.Opened)
  107. ) {
  108. return null;
  109. }
  110. return record.view as TView | null;
  111. }
  112. isOpen(viewId: UIViewID): boolean {
  113. return this.get(viewId) !== null;
  114. }
  115. async open<TView extends UIView, TParams = unknown>(viewId: UIViewID, params?: TParams): Promise<TView | null> {
  116. const config = getUIViewConfig(viewId);
  117. const currentRecord = this.records.get(viewId);
  118. const shouldShowLoading = config.ignoreLoading !== true
  119. && currentRecord?.state !== UIViewState.Opened
  120. && !currentRecord?.opening;
  121. if (!shouldShowLoading) {
  122. return this.openView<TView, TParams>(viewId, params);
  123. }
  124. await this.loading(true, 0.5);
  125. try {
  126. return await this.openView<TView, TParams>(viewId, params);
  127. } finally {
  128. await this.loading(false);
  129. }
  130. }
  131. private async openView<TView extends UIView, TParams = unknown>(
  132. viewId: UIViewID,
  133. params?: TParams,
  134. ): Promise<TView | null> {
  135. let record = this.records.get(viewId);
  136. if (record?.closing) {
  137. await record.closing;
  138. record = this.records.get(viewId);
  139. }
  140. if (record?.view && !record.view.node.isValid) {
  141. this.forgetRecord(record);
  142. record = undefined;
  143. }
  144. if (record?.state === UIViewState.Opened) return record.view as TView;
  145. if (record?.opening) return record.opening as Promise<TView | null>;
  146. if (record) this.cancelDelayedDestroy(record);
  147. if (record?.state === UIViewState.Cached && record.view?.node.isValid) {
  148. const generation = ++record.generation;
  149. const opening = this.performCachedOpen(record, params, generation);
  150. record.opening = opening;
  151. try {
  152. return await opening as TView | null;
  153. } finally {
  154. if (record.opening === opening) record.opening = null;
  155. }
  156. }
  157. const config = getUIViewConfig(viewId);
  158. const root = this.roots.get(config.layer);
  159. if (!root?.isValid) {
  160. console.error(`[UIManager] UILayer is not bound: ${config.layer}`);
  161. return null;
  162. }
  163. record = record ?? {
  164. config,
  165. state: UIViewState.None,
  166. view: null,
  167. ownerRoot: root,
  168. generation: 0,
  169. opening: null,
  170. closing: null,
  171. delayedDestroyTimer: null,
  172. };
  173. record.ownerRoot = root;
  174. this.records.set(viewId, record);
  175. const generation = ++record.generation;
  176. const opening = this.performOpen(record, root, params, generation);
  177. record.opening = opening;
  178. try {
  179. await opening as TView | null;
  180. AppKernel.events.emit("open:ui-view", viewId);
  181. return;
  182. } finally {
  183. if (record.opening === opening) record.opening = null;
  184. }
  185. }
  186. async close(viewIdOrInstance: UIViewID, reason = UICloseReason.User): Promise<boolean> {
  187. const record = typeof viewIdOrInstance === 'string'
  188. ? this.records.get(viewIdOrInstance)
  189. : [...this.records.values()].find((item) => item.view === viewIdOrInstance);
  190. if (!record) return false;
  191. if (record.closing) return record.closing;
  192. if (record.state === UIViewState.Cached) {
  193. if (record.opening) {
  194. ++record.generation;
  195. if ((record.config.cache || UICachePolicy.None) === UICachePolicy.Delayed) {
  196. this.scheduleDelayedDestroy(record);
  197. }
  198. }
  199. return true;
  200. }
  201. ++record.generation;
  202. record.closing = this.performClose(record, reason);
  203. try {
  204. await record.closing;
  205. AppKernel.events.emit("close:ui-view", viewIdOrInstance);
  206. return;
  207. } finally {
  208. record.closing = null;
  209. }
  210. }
  211. /**
  212. * 关闭全部已登记界面;ignoreViewIds 中的界面会保持当前状态。
  213. */
  214. async closeAll(ignoreViewIds: readonly UIViewID[] = [], reason = UICloseReason.SceneChanged): Promise<void> {
  215. const ignoredViews = new Set(ignoreViewIds);
  216. const handles: Promise<boolean>[] = [];
  217. this.records.forEach(record => {
  218. if (ignoredViews.has(record.config.id)) return;
  219. handles.push(this.close(record.config.id, reason));
  220. })
  221. await Promise.all(handles);
  222. }
  223. private async performOpen(
  224. record: UIViewRecord,
  225. root: Node,
  226. params: unknown,
  227. generation: number,
  228. ): Promise<UIView | null> {
  229. record.state = UIViewState.Loading;
  230. const bundleName = record.config.bundle || BUNDLE_ID.Lobby;
  231. const prefab = await this.resources.loadPrefab(bundleName, record.config.prefabPath);
  232. if (generation !== record.generation) return null;
  233. const prefabView = prefab.data?.getComponent?.(UIView) as UIView | null;
  234. if (!prefabView) {
  235. record.state = UIViewState.None;
  236. console.error(`[UIManager] Prefab has no UIView component: ${record.config.id}`);
  237. return null;
  238. }
  239. record.state = UIViewState.Creating;
  240. const node = instantiate(prefab);
  241. node.active = false;
  242. root.addChild(node);
  243. const view = node.getComponent(UIView);
  244. if (!view) {
  245. node.destroy();
  246. console.error(`[UIManager] Prefab has no UIView component: ${record.config.id}`);
  247. return null;
  248. }
  249. record.view = view;
  250. view.internalCreate();
  251. if (generation !== record.generation || !node.isValid) {
  252. node.destroy();
  253. record.view = null;
  254. return null;
  255. }
  256. const loadingCountBeforeOpen = this.loadingCount;
  257. let allowOpen: boolean;
  258. try {
  259. allowOpen = await view.internalOpenBefore(params);
  260. } catch (error) {
  261. console.error(error, record.config.id)
  262. node.destroy();
  263. record.view = null;
  264. if (generation === record.generation) record.state = UIViewState.None;
  265. return null;
  266. }
  267. if (generation !== record.generation || !node.isValid) {
  268. node.destroy();
  269. record.view = null;
  270. return null;
  271. }
  272. if (!allowOpen) {
  273. await this.closeLoadingOpenedDuring(loadingCountBeforeOpen);
  274. node.destroy();
  275. record.view = null;
  276. record.state = UIViewState.None;
  277. return null;
  278. }
  279. await this.closeMutexViews(record.config);
  280. record.state = UIViewState.Opening;
  281. node.active = true;
  282. await view.internalOpen(params);
  283. if (generation !== record.generation || !node.isValid) return null;
  284. record.state = UIViewState.Opened;
  285. return view;
  286. }
  287. private async performCachedOpen(
  288. record: UIViewRecord,
  289. params: unknown,
  290. generation: number,
  291. ): Promise<UIView | null> {
  292. const view = record.view;
  293. if (!view?.node?.isValid) return null;
  294. const loadingCountBeforeOpen = this.loadingCount;
  295. let allowOpen: boolean;
  296. try {
  297. allowOpen = await view.internalOpenBefore(params);
  298. } catch (error) {
  299. if (generation === record.generation) this.restoreCachedRecord(record);
  300. throw error;
  301. }
  302. if (generation !== record.generation || !view.node.isValid) return null;
  303. if (!allowOpen) {
  304. await this.closeLoadingOpenedDuring(loadingCountBeforeOpen);
  305. this.restoreCachedRecord(record);
  306. return null;
  307. }
  308. await this.closeMutexViews(record.config);
  309. if (generation !== record.generation || !view.node.isValid) return null;
  310. record.state = UIViewState.Opening;
  311. view.node.active = true;
  312. await view.internalOpen(params);
  313. if (generation !== record.generation || !view.node.isValid) return null;
  314. record.state = UIViewState.Opened;
  315. return view;
  316. }
  317. private restoreCachedRecord(record: UIViewRecord): void {
  318. if (!record.view?.node?.isValid || this.records.get(record.config.id) !== record) return;
  319. record.view.node.active = false;
  320. record.state = UIViewState.Cached;
  321. if ((record.config.cache || UICachePolicy.None) === UICachePolicy.Delayed) {
  322. this.scheduleDelayedDestroy(record);
  323. }
  324. }
  325. /** 仅回收 onBeforeOpen 阶段额外开启的 Loading,不影响本次 open 的自动 Loading。 */
  326. private closeLoadingOpenedDuring(loadingCountBeforeOpen: number) {
  327. while (this.loadingCount > loadingCountBeforeOpen) {
  328. this.loading(false);
  329. }
  330. }
  331. private async performClose(record: UIViewRecord, reason: UICloseReason): Promise<boolean> {
  332. if (!record.view?.node?.isValid) {
  333. this.cancelDelayedDestroy(record);
  334. record.state = UIViewState.Disposed;
  335. record.view = null;
  336. this.records.delete(record.config.id);
  337. return false;
  338. }
  339. const allow = reason === UICloseReason.ForceDispose
  340. ? true
  341. : await record.view.internalBeforeClose(reason);
  342. if (!allow) return false;
  343. record.state = UIViewState.Closing;
  344. await record.view.internalClose(reason);
  345. const uiCache = record.config.cache || UICachePolicy.None;
  346. if (reason === UICloseReason.ForceDispose || uiCache === UICachePolicy.None) {
  347. this.disposeRecord(record);
  348. return true;
  349. }
  350. record.view.node.active = false;
  351. record.state = UIViewState.Cached;
  352. if (uiCache === UICachePolicy.Delayed) {
  353. this.scheduleDelayedDestroy(record);
  354. }
  355. return true;
  356. }
  357. private scheduleDelayedDestroy(record: UIViewRecord): void {
  358. this.cancelDelayedDestroy(record);
  359. const generation = record.generation;
  360. record.delayedDestroyTimer = setTimeout(() => {
  361. record.delayedDestroyTimer = null;
  362. if (
  363. record.generation === generation
  364. && record.state === UIViewState.Cached
  365. ) {
  366. this.disposeRecord(record);
  367. }
  368. }, UIManager.DELAYED_DESTROY_MS);
  369. }
  370. private cancelDelayedDestroy(record: UIViewRecord): void {
  371. if (record.delayedDestroyTimer === null) return;
  372. clearTimeout(record.delayedDestroyTimer);
  373. record.delayedDestroyTimer = null;
  374. }
  375. private disposeRecord(record: UIViewRecord): void {
  376. this.cancelDelayedDestroy(record);
  377. if (record.view?.node?.isValid) {
  378. record.view.internalDispose();
  379. record.view.node.destroy();
  380. }
  381. record.view = null;
  382. record.ownerRoot = null;
  383. record.state = UIViewState.Disposed;
  384. this.records.delete(record.config.id);
  385. }
  386. /** 从管理器中同步移除记录,不主动销毁正由场景释放的节点。 */
  387. private forgetRecord(record: UIViewRecord): void {
  388. ++record.generation;
  389. this.cancelDelayedDestroy(record);
  390. if (record.view?.node?.isValid) {
  391. record.view.internalDispose();
  392. }
  393. record.view = null;
  394. record.ownerRoot = null;
  395. record.opening = null;
  396. record.closing = null;
  397. record.state = UIViewState.Disposed;
  398. if (this.records.get(record.config.id) === record) {
  399. this.records.delete(record.config.id);
  400. }
  401. }
  402. private async closeMutexViews(config: UIViewConfig): Promise<void> {
  403. const tasks: Promise<boolean>[] = [];
  404. for (const record of this.records.values()) {
  405. if (!record.config.mutexGroup) continue;
  406. if (record.config.id !== config.id && record.config.mutexGroup === config.mutexGroup) {
  407. tasks.push(this.close(record.config.id, UICloseReason.Navigation));
  408. }
  409. }
  410. await Promise.all(tasks);
  411. }
  412. async loading(active: boolean, delay = 0): Promise<void> {
  413. if (active) {
  414. ++this.loadingCount;
  415. try {
  416. await this.open(UIViewID.LoadingView, { delay });
  417. if (this.loadingCount === 0) {
  418. await this.close(UIViewID.LoadingView);
  419. }
  420. } catch (error) {
  421. this.loadingCount = Math.max(0, this.loadingCount - 1);
  422. throw error;
  423. }
  424. return;
  425. }
  426. if (this.loadingCount > 0) --this.loadingCount;
  427. if (this.loadingCount > 0) return;
  428. await this.close(UIViewID.LoadingView);
  429. // close 等待期间可能又有新的加载任务,需重新显示 LoadingView。
  430. if (this.loadingCount > 0) {
  431. await this.open(UIViewID.LoadingView);
  432. }
  433. }
  434. async toast(msg: string) {
  435. let uiToast = this.get<UIToast>(UIViewID.UIToast);
  436. if (!uiToast) {
  437. uiToast = await this.open(UIViewID.UIToast);
  438. }
  439. uiToast.show(msg);
  440. }
  441. async dialog(config: IDialogConfig) {
  442. this.loadingCount = 0;
  443. this.close(UIViewID.LoadingView);
  444. const panel = this.get<UIDialog>(UIViewID.UIDialog);
  445. if (panel && panel.node.active) {
  446. panel.internalOpen(config);
  447. return;
  448. }
  449. await AppKernel.ui.open<UIDialog>(UIViewID.UIDialog, config);
  450. }
  451. }