ipc.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. import { execFile } from "node:child_process"
  2. import { BrowserWindow, Notification, app, clipboard, dialog, ipcMain, shell } from "electron"
  3. import type { IpcMainEvent, IpcMainInvokeEvent } from "electron"
  4. import type { DesktopMenuAction } from "@opencode-ai/app/desktop-menu"
  5. import type {
  6. FatalRendererError,
  7. ServerReadyData,
  8. TitlebarTheme,
  9. WindowConfig,
  10. WslConfig,
  11. } from "../preload/types"
  12. import { runDesktopMenuAction } from "./desktop-menu-actions"
  13. import { getStore } from "./store"
  14. import { getPinchZoomEnabled, setPinchZoomEnabled, setTitlebar, updateTitlebar } from "./windows"
  15. const pickerFilters = (ext?: string[]) => {
  16. if (!ext || ext.length === 0) return undefined
  17. return [{ name: "Files", extensions: ext }]
  18. }
  19. type Deps = {
  20. killSidecar: () => Promise<void> | void
  21. awaitInitialization: () => Promise<ServerReadyData>
  22. getWindowConfig: () => Promise<WindowConfig> | WindowConfig
  23. consumeInitialDeepLinks: () => Promise<string[]> | string[]
  24. getDefaultServerUrl: () => Promise<string | null> | string | null
  25. setDefaultServerUrl: (url: string | null) => Promise<void> | void
  26. getWslConfig: () => Promise<WslConfig>
  27. setWslConfig: (config: WslConfig) => Promise<void> | void
  28. getDisplayBackend: () => Promise<string | null>
  29. setDisplayBackend: (backend: string | null) => Promise<void> | void
  30. parseMarkdown: (markdown: string) => Promise<string> | string
  31. checkAppExists: (appName: string) => Promise<boolean> | boolean
  32. wslPath: (path: string, mode: "windows" | "linux" | null) => Promise<string>
  33. resolveAppPath: (appName: string) => Promise<string | null>
  34. runUpdater: (alertOnFail: boolean) => Promise<void> | void
  35. checkUpdate: () => Promise<{ updateAvailable: boolean; version?: string }>
  36. installUpdate: () => Promise<void> | void
  37. setBackgroundColor: (color: string) => void
  38. exportDebugLogs: () => Promise<string>
  39. recordFatalRendererError: (error: FatalRendererError) => Promise<void> | void
  40. }
  41. export function registerIpcHandlers(deps: Deps) {
  42. ipcMain.handle("kill-sidecar", () => deps.killSidecar())
  43. ipcMain.handle("await-initialization", () => deps.awaitInitialization())
  44. ipcMain.handle("get-window-config", () => deps.getWindowConfig())
  45. ipcMain.handle("consume-initial-deep-links", () => deps.consumeInitialDeepLinks())
  46. ipcMain.handle("get-default-server-url", () => deps.getDefaultServerUrl())
  47. ipcMain.handle("set-default-server-url", (_event: IpcMainInvokeEvent, url: string | null) =>
  48. deps.setDefaultServerUrl(url),
  49. )
  50. ipcMain.handle("get-wsl-config", () => deps.getWslConfig())
  51. ipcMain.handle("set-wsl-config", (_event: IpcMainInvokeEvent, config: WslConfig) => deps.setWslConfig(config))
  52. ipcMain.handle("get-display-backend", () => deps.getDisplayBackend())
  53. ipcMain.handle("set-display-backend", (_event: IpcMainInvokeEvent, backend: string | null) =>
  54. deps.setDisplayBackend(backend),
  55. )
  56. ipcMain.handle("parse-markdown", (_event: IpcMainInvokeEvent, markdown: string) => deps.parseMarkdown(markdown))
  57. ipcMain.handle("check-app-exists", (_event: IpcMainInvokeEvent, appName: string) => deps.checkAppExists(appName))
  58. ipcMain.handle("wsl-path", (_event: IpcMainInvokeEvent, path: string, mode: "windows" | "linux" | null) =>
  59. deps.wslPath(path, mode),
  60. )
  61. ipcMain.handle("resolve-app-path", (_event: IpcMainInvokeEvent, appName: string) => deps.resolveAppPath(appName))
  62. ipcMain.handle("run-updater", (_event: IpcMainInvokeEvent, alertOnFail: boolean) => deps.runUpdater(alertOnFail))
  63. ipcMain.handle("check-update", () => deps.checkUpdate())
  64. ipcMain.handle("install-update", () => deps.installUpdate())
  65. ipcMain.handle("set-background-color", (_event: IpcMainInvokeEvent, color: string) => deps.setBackgroundColor(color))
  66. ipcMain.handle("export-debug-logs", () => deps.exportDebugLogs())
  67. ipcMain.handle("record-fatal-renderer-error", (_event: IpcMainInvokeEvent, error: FatalRendererError) =>
  68. deps.recordFatalRendererError(error),
  69. )
  70. ipcMain.handle("store-get", (_event: IpcMainInvokeEvent, name: string, key: string) => {
  71. try {
  72. const store = getStore(name)
  73. const value = store.get(key)
  74. if (value === undefined || value === null) return null
  75. return typeof value === "string" ? value : JSON.stringify(value)
  76. } catch {
  77. return null
  78. }
  79. })
  80. ipcMain.handle("store-set", (_event: IpcMainInvokeEvent, name: string, key: string, value: string) => {
  81. getStore(name).set(key, value)
  82. })
  83. ipcMain.handle("store-delete", (_event: IpcMainInvokeEvent, name: string, key: string) => {
  84. getStore(name).delete(key)
  85. })
  86. ipcMain.handle("store-clear", (_event: IpcMainInvokeEvent, name: string) => {
  87. getStore(name).clear()
  88. })
  89. ipcMain.handle("store-keys", (_event: IpcMainInvokeEvent, name: string) => {
  90. const store = getStore(name)
  91. return Object.keys(store.store)
  92. })
  93. ipcMain.handle("store-length", (_event: IpcMainInvokeEvent, name: string) => {
  94. const store = getStore(name)
  95. return Object.keys(store.store).length
  96. })
  97. ipcMain.handle(
  98. "open-directory-picker",
  99. async (_event: IpcMainInvokeEvent, opts?: { multiple?: boolean; title?: string; defaultPath?: string }) => {
  100. const result = await dialog.showOpenDialog({
  101. properties: ["openDirectory", ...(opts?.multiple ? ["multiSelections" as const] : []), "createDirectory"],
  102. title: opts?.title ?? "Choose a folder",
  103. defaultPath: opts?.defaultPath,
  104. })
  105. if (result.canceled) return null
  106. return opts?.multiple ? result.filePaths : result.filePaths[0]
  107. },
  108. )
  109. ipcMain.handle(
  110. "open-file-picker",
  111. async (
  112. _event: IpcMainInvokeEvent,
  113. opts?: { multiple?: boolean; title?: string; defaultPath?: string; accept?: string[]; extensions?: string[] },
  114. ) => {
  115. const result = await dialog.showOpenDialog({
  116. properties: ["openFile", ...(opts?.multiple ? ["multiSelections" as const] : [])],
  117. title: opts?.title ?? "Choose a file",
  118. defaultPath: opts?.defaultPath,
  119. filters: pickerFilters(opts?.extensions),
  120. })
  121. if (result.canceled) return null
  122. return opts?.multiple ? result.filePaths : result.filePaths[0]
  123. },
  124. )
  125. ipcMain.handle(
  126. "save-file-picker",
  127. async (_event: IpcMainInvokeEvent, opts?: { title?: string; defaultPath?: string }) => {
  128. const result = await dialog.showSaveDialog({
  129. title: opts?.title ?? "Save file",
  130. defaultPath: opts?.defaultPath,
  131. })
  132. if (result.canceled) return null
  133. return result.filePath ?? null
  134. },
  135. )
  136. ipcMain.on("open-link", (_event: IpcMainEvent, url: string) => {
  137. void shell.openExternal(url)
  138. })
  139. ipcMain.handle("open-path", async (_event: IpcMainInvokeEvent, path: string, app?: string) => {
  140. if (!app) return shell.openPath(path)
  141. await new Promise<void>((resolve, reject) => {
  142. const [cmd, args] =
  143. process.platform === "darwin" ? (["open", ["-a", app, path]] as const) : ([app, [path]] as const)
  144. execFile(cmd, args, (err) => (err ? reject(err) : resolve()))
  145. })
  146. })
  147. ipcMain.handle("read-clipboard-image", () => {
  148. const image = clipboard.readImage()
  149. if (image.isEmpty()) return null
  150. const buffer = image.toPNG().buffer
  151. const size = image.getSize()
  152. return { buffer, width: size.width, height: size.height }
  153. })
  154. ipcMain.on("show-notification", (_event: IpcMainEvent, title: string, body?: string) => {
  155. new Notification({ title, body }).show()
  156. })
  157. ipcMain.handle("get-window-count", () => BrowserWindow.getAllWindows().length)
  158. ipcMain.handle("get-window-focused", (event: IpcMainInvokeEvent) => {
  159. const win = BrowserWindow.fromWebContents(event.sender)
  160. return win?.isFocused() ?? false
  161. })
  162. ipcMain.handle("set-window-focus", (event: IpcMainInvokeEvent) => {
  163. const win = BrowserWindow.fromWebContents(event.sender)
  164. win?.focus()
  165. })
  166. ipcMain.handle("show-window", (event: IpcMainInvokeEvent) => {
  167. const win = BrowserWindow.fromWebContents(event.sender)
  168. win?.show()
  169. })
  170. ipcMain.on("relaunch", () => {
  171. app.relaunch()
  172. app.exit(0)
  173. })
  174. ipcMain.handle("get-zoom-factor", (event: IpcMainInvokeEvent) => event.sender.getZoomFactor())
  175. ipcMain.handle("set-zoom-factor", (event: IpcMainInvokeEvent, factor: number) => {
  176. event.sender.setZoomFactor(factor)
  177. const win = BrowserWindow.fromWebContents(event.sender)
  178. if (!win) return
  179. updateTitlebar(win)
  180. })
  181. ipcMain.handle("get-pinch-zoom-enabled", () => getPinchZoomEnabled())
  182. ipcMain.handle("set-pinch-zoom-enabled", (_event: IpcMainInvokeEvent, enabled: boolean) => {
  183. setPinchZoomEnabled(enabled)
  184. })
  185. ipcMain.handle("set-titlebar", (event: IpcMainInvokeEvent, theme: TitlebarTheme) => {
  186. const win = BrowserWindow.fromWebContents(event.sender)
  187. if (!win) return
  188. setTitlebar(win, theme)
  189. })
  190. ipcMain.handle("run-desktop-menu-action", (event: IpcMainInvokeEvent, action: DesktopMenuAction) => {
  191. runDesktopMenuAction(BrowserWindow.fromWebContents(event.sender), action)
  192. })
  193. }
  194. export function sendMenuCommand(win: BrowserWindow, id: string) {
  195. win.webContents.send("menu-command", id)
  196. }
  197. export function sendDeepLinks(win: BrowserWindow, urls: string[]) {
  198. win.webContents.send("deep-link", urls)
  199. }