subWindow.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import path from 'path';
  2. import type { BrowserWindowConstructorOptions } from 'electron';
  3. import { BrowserWindow, screen } from 'electron';
  4. import { getBaseDir, isDev } from 'ee-core/ps';
  5. import { logger } from 'ee-core/log';
  6. import { getMainWindow } from 'ee-core/electron';
  7. import { localSettingsService } from '../setting/localSettings';
  8. export interface SubWindowOpenOptions {
  9. /** 完整路由(含 query),如 /workbench?newChat=1 */
  10. fullPath?: string;
  11. /** 窗口已存在时是否整窗重载(换案后需要重新读案件上下文) */
  12. reloadIfOpen?: boolean;
  13. /** 窗口已存在时是否导航到目标地址(显式导航意图) */
  14. navigateIfOpen?: boolean;
  15. }
  16. export interface SubWindowDefinition {
  17. /** 允许的路径前缀,如 /workbench、/perm-window;其余地址一律改写到该前缀 */
  18. pathPrefix: string;
  19. /** 本机设置里保存 bounds 的键名 */
  20. boundsKey: string;
  21. /** 新建窗口与恢复 bounds 时的最小尺寸 */
  22. minSize: { minWidth: number; minHeight: number };
  23. /** 创建 BrowserWindow 的选项(标题 / 尺寸 / webPreferences 等) */
  24. createWindowOptions: () => BrowserWindowConstructorOptions;
  25. /** 打开 / 关闭时通知主窗口的通道;不传则不通知 */
  26. stateChannel?: string;
  27. /**
  28. * 已存在窗口时,仅当目标带 query 才导航。
  29. *
  30. * <p>智能工作台沿用该旧规则:普通打开/聚焦不动它当前所在的视图,
  31. * 只有 ?newChat=1 / ?view=agent 这类明确意图才跳转。
  32. */
  33. navigateOnlyWhenQuery?: boolean;
  34. /**
  35. * 已保存 bounds 的使用方式。
  36. *
  37. * <ul>
  38. * <li>all(默认):位置 + 尺寸</li>
  39. * <li>position:只用上次的位置,尺寸由 createWindowOptions 决定(权限窗口跟随主窗口大小)</li>
  40. * <li>none:不恢复</li>
  41. * </ul>
  42. */
  43. restoreBoundsMode?: 'all' | 'position' | 'none';
  44. }
  45. export interface SubWindowController {
  46. getWindow(): BrowserWindow | null;
  47. isOpen(): boolean;
  48. /** 判断某个窗口是不是本控制器创建的单例窗口(IPC 解析窗口角色用) */
  49. matches(win: BrowserWindow | null | undefined): boolean;
  50. open(options?: SubWindowOpenOptions): BrowserWindow;
  51. close(): void;
  52. /** 把已打开的窗口拉到前台;没打开返回 false */
  53. focus(): boolean;
  54. }
  55. interface SavedBounds {
  56. x: number;
  57. y: number;
  58. width: number;
  59. height: number;
  60. }
  61. function escapeRegExp(value: string): string {
  62. return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  63. }
  64. /** 把任意窗口拉到前台(最小化时先还原) */
  65. export function focusWindow(win: BrowserWindow): void {
  66. if (win.isMinimized()) win.restore();
  67. win.show();
  68. win.moveTop();
  69. win.focus();
  70. }
  71. /**
  72. * 创建一个单例子窗口控制器。
  73. *
  74. * <p>把智能工作台窗口的既有行为原样抽出来(单例、聚焦、bounds 落盘、
  75. * 渲染进程崩溃自愈、dev/prod 两套加载方式),供智能工作台与权限管理窗口共用。
  76. */
  77. export function createSubWindowController(definition: SubWindowDefinition): SubWindowController {
  78. const pathPattern = new RegExp(`^${escapeRegExp(definition.pathPrefix)}(?:/|\\?|$)`);
  79. const logPrefix = `[${definition.pathPrefix}]`;
  80. let win: BrowserWindow | null = null;
  81. const getWindow = (): BrowserWindow | null => (win && !win.isDestroyed() ? win : null);
  82. function normalizeFullPath(fullPath?: string): string {
  83. const raw = typeof fullPath === 'string' ? fullPath.trim() : '';
  84. if (!raw) return definition.pathPrefix;
  85. // 只接受该窗口承载的地址,避免把业务页塞进来(如 /workbenchfoo 不算)
  86. return pathPattern.test(raw) ? raw : definition.pathPrefix;
  87. }
  88. function open(options: SubWindowOpenOptions = {}): BrowserWindow {
  89. const fullPath = normalizeFullPath(options.fullPath);
  90. const existing = getWindow();
  91. if (existing) {
  92. focusWindow(existing);
  93. if (options.reloadIfOpen) {
  94. // 刚由本次导航创建、还在加载时不用再刷一次;已加载完成的才需要按新上下文重建
  95. if (!existing.webContents.isLoading()) {
  96. existing.webContents.reload();
  97. }
  98. } else if (
  99. options.navigateIfOpen &&
  100. (!definition.navigateOnlyWhenQuery || fullPath.includes('?'))
  101. ) {
  102. loadRenderer(existing, fullPath);
  103. }
  104. return existing;
  105. }
  106. const created = new BrowserWindow({
  107. ...definition.createWindowOptions(),
  108. ...restoreBounds(),
  109. });
  110. win = created;
  111. clampToVisibleArea(created);
  112. created.once('ready-to-show', () => {
  113. if (!created.isDestroyed()) {
  114. focusWindow(created);
  115. }
  116. });
  117. created.on('close', () => saveBounds(created));
  118. created.on('closed', () => {
  119. if (win === created) win = null;
  120. notifyState(false);
  121. });
  122. // 渲染进程崩溃后留一个空壳没有意义:销毁它,下次点击重新创建
  123. created.webContents.on('render-process-gone', (_event, details) => {
  124. logger.error(`${logPrefix} render-process-gone:`, details?.reason);
  125. if (!created.isDestroyed()) {
  126. saveBounds(created);
  127. created.destroy();
  128. }
  129. });
  130. loadRenderer(created, fullPath);
  131. notifyState(true);
  132. return created;
  133. }
  134. function close(): void {
  135. getWindow()?.close();
  136. }
  137. function focus(): boolean {
  138. const current = getWindow();
  139. if (!current) return false;
  140. focusWindow(current);
  141. return true;
  142. }
  143. function loadRenderer(target: BrowserWindow, fullPath: string): void {
  144. const devServerUrl = resolveDevServerUrl();
  145. if (devServerUrl) {
  146. target.loadURL(`${devServerUrl}${fullPath}`).catch((err) => {
  147. logger.error(`${logPrefix} loadURL failed:`, err);
  148. });
  149. return;
  150. }
  151. // 生产是 file:// + hash 路由:hash 带上完整路径与 query
  152. const indexPath = path.join(getBaseDir(), 'public', 'dist', 'index.html');
  153. target.loadFile(indexPath, { hash: fullPath }).catch((err) => {
  154. logger.error(`${logPrefix} loadFile failed:`, err);
  155. });
  156. }
  157. function saveBounds(target: BrowserWindow): void {
  158. try {
  159. const { x, y, width, height } = target.getBounds();
  160. localSettingsService.set(definition.boundsKey, JSON.stringify({ x, y, width, height }));
  161. } catch (e) {
  162. logger.warn(`${logPrefix} 保存窗口位置失败:`, e instanceof Error ? e.message : String(e));
  163. }
  164. }
  165. /** 恢复上次的位置与大小;越界或尺寸不合法时交给 Electron 默认放置 */
  166. function restoreBounds(): Partial<SavedBounds> {
  167. try {
  168. const raw = localSettingsService.get(definition.boundsKey);
  169. if (!raw) return {};
  170. const parsed = JSON.parse(raw) as Partial<SavedBounds>;
  171. const { x, y, width, height } = parsed || {};
  172. if (![x, y, width, height].every((value) => typeof value === 'number' && Number.isFinite(value))) {
  173. return {};
  174. }
  175. if ((width as number) < definition.minSize.minWidth || (height as number) < definition.minSize.minHeight) {
  176. return {};
  177. }
  178. // 显示器拔掉/分辨率变化后,旧坐标可能落在屏幕外
  179. const visible = screen.getAllDisplays().some((display) => {
  180. const area = display.workArea;
  181. return (
  182. (x as number) < area.x + area.width &&
  183. (x as number) + (width as number) > area.x &&
  184. (y as number) < area.y + area.height &&
  185. (y as number) + (height as number) > area.y
  186. );
  187. });
  188. return visible ? buildRestoredBounds({ x, y, width, height }) : {};
  189. } catch (e) {
  190. logger.warn(`${logPrefix} 恢复窗口位置失败:`, e instanceof Error ? e.message : String(e));
  191. return {};
  192. }
  193. }
  194. /** 按配置决定恢复位置和/或尺寸 */
  195. function buildRestoredBounds(saved: Partial<SavedBounds>): Partial<SavedBounds> {
  196. switch (definition.restoreBoundsMode) {
  197. case 'none':
  198. return {};
  199. case 'position':
  200. // 尺寸交给 createWindowOptions(例如权限窗口跟随主窗口大小),这里只保留位置
  201. return { x: saved.x, y: saved.y };
  202. default:
  203. return saved;
  204. }
  205. }
  206. /** 位置可能配不上新的窗口尺寸(例如跟随最大化的主窗口):保证窗口完整落在最近显示器的工作区内 */
  207. function clampToVisibleArea(target: BrowserWindow): void {
  208. try {
  209. const bounds = target.getBounds();
  210. const display = screen.getDisplayMatching(bounds);
  211. const area = display.workArea;
  212. const width = Math.min(bounds.width, area.width);
  213. const height = Math.min(bounds.height, area.height);
  214. const x = Math.min(Math.max(bounds.x, area.x), Math.max(area.x, area.x + area.width - width));
  215. const y = Math.min(Math.max(bounds.y, area.y), Math.max(area.y, area.y + area.height - height));
  216. if (x !== bounds.x || y !== bounds.y || width !== bounds.width || height !== bounds.height) {
  217. target.setBounds({ x, y, width, height });
  218. }
  219. } catch (e) {
  220. logger.warn(`${logPrefix} 校正窗口位置失败:`, e instanceof Error ? e.message : String(e));
  221. }
  222. }
  223. function notifyState(open: boolean): void {
  224. const channel = definition.stateChannel;
  225. if (!channel) return;
  226. try {
  227. const main = getMainWindow();
  228. if (!main.isDestroyed() && !main.webContents.isDestroyed()) {
  229. main.webContents.send(channel, { open });
  230. }
  231. } catch {
  232. // 主窗口尚未创建或应用正在退出:忽略
  233. }
  234. }
  235. return {
  236. getWindow,
  237. isOpen: () => !!getWindow(),
  238. matches: (target) => {
  239. const current = getWindow();
  240. return !!target && !!current && target.id === current.id;
  241. },
  242. open,
  243. close,
  244. focus,
  245. };
  246. }
  247. /**
  248. * 开发环境的前端地址:与 ee-core 加载主窗口同口径,端口来自 cmd/bin.js 的 dev.frontend.port。
  249. * 生产环境(或读不到配置)返回 null,走 loadFile。
  250. */
  251. function resolveDevServerUrl(): string | null {
  252. if (!isDev()) return null;
  253. try {
  254. // eslint-disable-next-line @typescript-eslint/no-var-requires
  255. const binConfig = require(path.join(getBaseDir(), 'cmd', 'bin.js'));
  256. const frontend = binConfig?.dev?.frontend || {};
  257. const protocol = typeof frontend.protocol === 'string' ? frontend.protocol : 'http://';
  258. if (protocol === 'file://') return null;
  259. const hostname = typeof frontend.hostname === 'string' ? frontend.hostname : 'localhost';
  260. const port = Number(frontend.port) || 3100;
  261. return `${protocol}${hostname}:${port}`;
  262. } catch (e) {
  263. logger.warn('[subWindow] 读取 cmd/bin.js 失败,回退 http://localhost:3100');
  264. return 'http://localhost:3100';
  265. }
  266. }