UIManager.ts 14 KB

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