UIManager.ts 14 KB

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