key-screen-framework 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/main/index.js CHANGED
@@ -1,28 +1,36 @@
1
1
  import { createReadStream } from "node:fs";
2
- import { mkdir, appendFile, readdir, rm, stat, readFile, copyFile, writeFile } from "node:fs/promises";
2
+ import { readFile, mkdir, cp, writeFile, appendFile, readdir, rm, stat, copyFile } from "node:fs/promises";
3
3
  import { createRequire } from "node:module";
4
4
  import { join, dirname, extname, relative, sep, normalize } from "node:path";
5
5
  import { Readable } from "node:stream";
6
6
  import { fileURLToPath } from "node:url";
7
- import { app, protocol, ipcMain, shell, BrowserWindow, screen } from "electron";
7
+ import { app, protocol, dialog, ipcMain, shell, BrowserWindow, screen } from "electron";
8
8
  import Store from "electron-store";
9
9
  import { validateArduinoBoardConfig, defaultArduinoBoardConfig } from "../shared/arduino-board.js";
10
10
  import { createScreenCatalog } from "../shared/screen-catalog.js";
11
11
  import { RESET_SCREEN_TARGET, buildDefaultGlobalShortcuts, mergeGlobalShortcuts, normalizeShortcutAccelerator } from "../shared/screen-shortcuts.js";
12
12
  import { b as normalizeScreenOverrides, m as mergeScreenOverrides, a as normalizeDisplayFit, n as normalizeAdminZoom, c as normalizeStoredScreenOverrides } from "../chunks/screen-overrides-0d_pEdnM.js";
13
13
  import { EventEmitter } from "node:events";
14
+ import { createHash } from "node:crypto";
14
15
  import { spawn } from "node:child_process";
15
16
  import { acceleratorToArduinoKeyboardShortcut } from "../shared/arduino-keyboard-shortcut.js";
16
17
  import { SerialPort } from "serialport";
17
18
  import { Buffer as Buffer$1 } from "node:buffer";
18
19
  const now$4 = () => (/* @__PURE__ */ new Date()).toISOString();
20
+ const ARDUINO_CLI_DATA_READY_FILE = ".key-screen-framework-arduino-data-ready";
21
+ async function getBundledArduinoDataRevision(bundledDataDir) {
22
+ const packageIndex = await readFile(join(bundledDataDir, "package_index.json"));
23
+ return createHash("sha256").update(packageIndex).digest("hex");
24
+ }
19
25
  function resolveArduinoCliPaths(app2, options = {}) {
20
26
  const platform = options.platform ?? process.platform;
21
27
  const arch = options.arch ?? process.arch;
22
28
  const resourcesRoot = app2.isPackaged ? join(options.resourcesPath ?? process.resourcesPath, "arduino") : join(app2.getAppPath(), "resources", "arduino", `${platform}-${arch}`);
29
+ const bundledDataDir = join(resourcesRoot, "data");
23
30
  return {
24
31
  cliPath: join(resourcesRoot, "bin", platform === "win32" ? "arduino-cli.exe" : "arduino-cli"),
25
- dataDir: join(resourcesRoot, "data"),
32
+ bundledDataDir,
33
+ dataDir: app2.isPackaged ? join(app2.getPath("userData"), "arduino-cli-data") : bundledDataDir,
26
34
  userDir: join(app2.getPath("userData"), "arduino-cli-user"),
27
35
  libraryPaths: [
28
36
  join(resourcesRoot, "libraries", "KeyescapeSerialProtocolBridge"),
@@ -30,6 +38,25 @@ function resolveArduinoCliPaths(app2, options = {}) {
30
38
  ]
31
39
  };
32
40
  }
41
+ async function prepareArduinoCliData(paths) {
42
+ if (paths.dataDir === paths.bundledDataDir) {
43
+ return;
44
+ }
45
+ const bundledDataRevision = await getBundledArduinoDataRevision(paths.bundledDataDir);
46
+ try {
47
+ const ready = await readFile(join(paths.dataDir, ARDUINO_CLI_DATA_READY_FILE), "utf8");
48
+ if (ready === bundledDataRevision) {
49
+ return;
50
+ }
51
+ } catch (error) {
52
+ if (error.code !== "ENOENT") {
53
+ throw error;
54
+ }
55
+ }
56
+ await mkdir(paths.dataDir, { recursive: true });
57
+ await cp(paths.bundledDataDir, paths.dataDir, { force: true, recursive: true });
58
+ await writeFile(join(paths.dataDir, ARDUINO_CLI_DATA_READY_FILE), bundledDataRevision, "utf8");
59
+ }
33
60
  function buildArduinoCompileArgs(options) {
34
61
  return [
35
62
  "compile",
@@ -71,11 +98,15 @@ class ArduinoCliRunner extends EventEmitter {
71
98
  this.cancelled = true;
72
99
  this.currentProcess?.kill("SIGTERM");
73
100
  }
74
- run(args) {
101
+ async run(args) {
75
102
  if (this.currentProcess) {
76
- return Promise.reject(new Error("Arduino CLI is already running."));
103
+ throw new Error("Arduino CLI is already running.");
77
104
  }
78
105
  this.cancelled = false;
106
+ await prepareArduinoCliData(this.paths);
107
+ if (this.currentProcess) {
108
+ throw new Error("Arduino CLI is already running.");
109
+ }
79
110
  return new Promise((resolve, reject) => {
80
111
  const child = this.spawnProcess(this.paths.cliPath, args, {
81
112
  env: {
@@ -1134,12 +1165,19 @@ class MediaManager {
1134
1165
  async ensureDirectories() {
1135
1166
  await Promise.all(MEDIA_TYPES.map((type) => mkdir(join(this.rootPath, type), { recursive: true })));
1136
1167
  }
1137
- async seedFrom(sourceRootPath) {
1168
+ async seedFrom(sourceRootPath, options = {}) {
1169
+ const sourceRoot = await stat(sourceRootPath);
1170
+ if (!sourceRoot.isDirectory()) {
1171
+ throw new Error("Media source root must be a directory.");
1172
+ }
1138
1173
  await this.ensureDirectories();
1139
1174
  await Promise.all(
1140
1175
  MEDIA_TYPES.map(async (type) => {
1141
1176
  const sourceDirectory = join(sourceRootPath, type);
1142
- const files = await readdir(sourceDirectory, { withFileTypes: true }).catch(() => []);
1177
+ const files = await readdir(sourceDirectory, { withFileTypes: true }).catch((error) => {
1178
+ if (error.code === "ENOENT") return [];
1179
+ throw error;
1180
+ });
1143
1181
  await Promise.all(
1144
1182
  files.filter((file) => file.isFile()).filter((file) => MEDIA_EXTENSION_BY_TYPE[type].has(extname(file.name).toLowerCase())).map(async (file) => {
1145
1183
  const sourcePath = join(sourceDirectory, file.name);
@@ -1151,7 +1189,7 @@ class MediaManager {
1151
1189
  return;
1152
1190
  }
1153
1191
  const existingDestination = await stat(destinationPath).catch(() => null);
1154
- if (existingDestination) {
1192
+ if (existingDestination && !options.overwrite) {
1155
1193
  return;
1156
1194
  }
1157
1195
  await mkdir(dirname(destinationPath), { recursive: true });
@@ -1162,7 +1200,6 @@ class MediaManager {
1162
1200
  );
1163
1201
  }
1164
1202
  async listLibrary() {
1165
- await this.ensureDirectories();
1166
1203
  const assets = (await Promise.all(MEDIA_TYPES.map((type) => this.listAssetsForType(type)))).flat();
1167
1204
  return {
1168
1205
  rootPath: this.rootPath,
@@ -1214,6 +1251,11 @@ class MediaManager {
1214
1251
  return assets.filter((asset) => asset !== null);
1215
1252
  }
1216
1253
  }
1254
+ function createMediaManager(options) {
1255
+ return new MediaManager(
1256
+ options.isDev ? options.sourceRootPath : options.externalRootPath
1257
+ );
1258
+ }
1217
1259
  function parseByteRange(rangeHeader, sizeBytes) {
1218
1260
  if (!rangeHeader) {
1219
1261
  return null;
@@ -1419,6 +1461,18 @@ function resolveMainRuntimePaths(overrides, context) {
1419
1461
  defaultMediaRoot: overrides?.defaultMediaRoot ?? defaultMediaRoot
1420
1462
  };
1421
1463
  }
1464
+ async function installMediaOnFirstLaunch(options) {
1465
+ if (options.platform !== "darwin" || !options.isPackaged || options.isDev || options.completed) {
1466
+ return true;
1467
+ }
1468
+ const overwrite = await options.askOverwrite();
1469
+ if (overwrite === null) {
1470
+ return false;
1471
+ }
1472
+ await options.install(overwrite);
1473
+ options.markCompleted();
1474
+ return true;
1475
+ }
1422
1476
  const requireMainDependency = createRequire(import.meta.url);
1423
1477
  function startKeyScreenMain(options) {
1424
1478
  const log = requireMainDependency("electron-log/main");
@@ -1879,9 +1933,57 @@ function startKeyScreenMain(options) {
1879
1933
  }
1880
1934
  }
1881
1935
  app.whenReady().then(async () => {
1882
- const mediaManager = new MediaManager(join(app.getPath("userData"), "media"));
1883
- await mediaManager.ensureDirectories();
1884
- await mediaManager.seedFrom(runtimePaths.defaultMediaRoot);
1936
+ if (app.isPackaged && process.argv.includes("--install-media")) {
1937
+ try {
1938
+ const installer = new MediaManager(join(app.getPath("userData"), "media"));
1939
+ await installer.seedFrom(runtimePaths.defaultMediaRoot, {
1940
+ overwrite: process.argv.includes("--overwrite-media")
1941
+ });
1942
+ app.exit(0);
1943
+ } catch (error) {
1944
+ log.error("[media] installation failed", error);
1945
+ app.exit(1);
1946
+ }
1947
+ return;
1948
+ }
1949
+ const mediaManager = createMediaManager({
1950
+ isDev,
1951
+ sourceRootPath: runtimePaths.defaultMediaRoot,
1952
+ externalRootPath: join(app.getPath("userData"), "media")
1953
+ });
1954
+ try {
1955
+ const ready = await installMediaOnFirstLaunch({
1956
+ platform: process.platform,
1957
+ isPackaged: app.isPackaged,
1958
+ isDev,
1959
+ completed: store.get("mediaInstallationCompleted", false),
1960
+ askOverwrite: async () => {
1961
+ const result = await dialog.showMessageBox({
1962
+ type: "question",
1963
+ title: "리소스 설치 옵션",
1964
+ message: "최초 실행에 필요한 media 리소스를 설치합니다.",
1965
+ detail: "기본값은 기존 파일 보존입니다. 덮어쓰기를 선택하면 같은 이름의 파일을 앱에 포함된 media 파일로 교체합니다. 사용자 추가 파일은 유지됩니다.",
1966
+ checkboxLabel: "기존 리소스 덮어쓰기",
1967
+ checkboxChecked: false,
1968
+ buttons: ["리소스 설치", "종료"],
1969
+ defaultId: 0,
1970
+ cancelId: 1
1971
+ });
1972
+ return result.response === 0 ? result.checkboxChecked : null;
1973
+ },
1974
+ install: (overwrite) => mediaManager.seedFrom(runtimePaths.defaultMediaRoot, { overwrite }),
1975
+ markCompleted: () => store.set("mediaInstallationCompleted", true)
1976
+ });
1977
+ if (!ready) {
1978
+ app.quit();
1979
+ return;
1980
+ }
1981
+ } catch (error) {
1982
+ log.error("[media] first launch installation failed", error);
1983
+ dialog.showErrorBox("리소스 설치 실패", "media 리소스를 설치하지 못했습니다. 다음 실행 시 다시 설치할 수 있습니다.");
1984
+ app.quit();
1985
+ return;
1986
+ }
1885
1987
  protocol.handle("media", async (request) => {
1886
1988
  try {
1887
1989
  return await createMediaProtocolResponse(mediaManager, request);
@@ -1934,7 +2036,6 @@ function startKeyScreenMain(options) {
1934
2036
  ipcMain.handle("media:getLibrary", async () => mediaManager.listLibrary());
1935
2037
  ipcMain.handle("media:resolveUrl", async (_event, ref) => mediaManager.resolveMediaUrl(ref));
1936
2038
  ipcMain.handle("media:openFolder", async () => {
1937
- await mediaManager.ensureDirectories();
1938
2039
  const path = mediaManager.getRootPath();
1939
2040
  const message = await shell.openPath(path);
1940
2041
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "key-screen-framework",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "description": "Screen framework for Keyescape desktop projects.",
5
5
  "repository": {
6
6
  "type": "git",
package/renderer/index.js CHANGED
@@ -1480,7 +1480,7 @@ function AdminScreen({ gameState }) {
1480
1480
  try {
1481
1481
  setMediaLibrary(await getGameApi().getMediaLibrary());
1482
1482
  } catch {
1483
- setMediaError("외부 리소스 목록을 불러오지 못했습니다.");
1483
+ setMediaError("리소스 목록을 불러오지 못했습니다.");
1484
1484
  } finally {
1485
1485
  setMediaLoading(false);
1486
1486
  }
@@ -1494,10 +1494,10 @@ function AdminScreen({ gameState }) {
1494
1494
  try {
1495
1495
  const result = await getGameApi().openMediaFolder();
1496
1496
  if (!result.ok) {
1497
- setMediaError(result.message ?? "외부 리소스 폴더를 열지 못했습니다.");
1497
+ setMediaError(result.message ?? "리소스 폴더를 열지 못했습니다.");
1498
1498
  }
1499
1499
  } catch {
1500
- setMediaError("외부 리소스 폴더를 열지 못했습니다.");
1500
+ setMediaError("리소스 폴더를 열지 못했습니다.");
1501
1501
  }
1502
1502
  };
1503
1503
  const selectArchive = async (dateKey) => {
@@ -1928,7 +1928,7 @@ function AdminScreen({ gameState }) {
1928
1928
  children: [
1929
1929
  /* @__PURE__ */ jsx("span", { className: "block text-[11px] uppercase tracking-[0.25em] text-text-dim", children: "리소스" }),
1930
1930
  /* @__PURE__ */ jsx("span", { className: "mt-2 block text-sm font-semibold text-text", children: "관리" }),
1931
- /* @__PURE__ */ jsx("span", { className: "mt-1 block text-xs text-text-subtle", children: mediaLibrary ? `${mediaLibrary.assets.length}개 파일` : "외부 파일" })
1931
+ /* @__PURE__ */ jsx("span", { className: "mt-1 block text-xs text-text-subtle", children: mediaLibrary ? `${mediaLibrary.assets.length}개 파일` : "리소스 파일" })
1932
1932
  ]
1933
1933
  }
1934
1934
  ),
@@ -2985,7 +2985,7 @@ function AdminScreen({ gameState }) {
2985
2985
  /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4 border-b border-border-soft px-5 py-4", children: [
2986
2986
  /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
2987
2987
  /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "Media Library" }),
2988
- /* @__PURE__ */ jsx("h3", { className: "mt-2 font-display text-xl text-text", children: "외부 리소스" }),
2988
+ /* @__PURE__ */ jsx("h3", { className: "mt-2 font-display text-xl text-text", children: "리소스" }),
2989
2989
  /* @__PURE__ */ jsx("p", { className: "mt-1 break-all text-sm text-text-muted", children: mediaLibrary?.rootPath ?? "리소스 폴더 확인 중" })
2990
2990
  ] }),
2991
2991
  /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [
@@ -3033,7 +3033,7 @@ function AdminScreen({ gameState }) {
3033
3033
  },
3034
3034
  type
3035
3035
  )) }),
3036
- mediaLoading ? /* @__PURE__ */ jsx("div", { className: "flex h-52 items-center justify-center rounded-lg border border-dashed border-border-soft text-sm text-text-subtle", children: "불러오는 중..." }) : !mediaLibrary || mediaLibrary.assets.length === 0 ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-border-soft px-4 py-8 text-sm text-text-subtle", children: "외부 리소스 파일이 없습니다. 폴더를 열고 `image`, `video`, `audio`, `font` 하위 폴더에 파일을 추가하세요." }) : /* @__PURE__ */ jsxs("div", { className: "overflow-hidden rounded-lg border border-border-soft", children: [
3036
+ mediaLoading ? /* @__PURE__ */ jsx("div", { className: "flex h-52 items-center justify-center rounded-lg border border-dashed border-border-soft text-sm text-text-subtle", children: "불러오는 중..." }) : !mediaLibrary || mediaLibrary.assets.length === 0 ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-border-soft px-4 py-8 text-sm text-text-subtle", children: "리소스 파일이 없습니다. 폴더를 열고 `image`, `video`, `audio`, `font` 하위 폴더에 파일을 추가하세요." }) : /* @__PURE__ */ jsxs("div", { className: "overflow-hidden rounded-lg border border-border-soft", children: [
3037
3037
  /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[120px_minmax(0,1fr)_120px_190px] gap-3 border-b border-border-soft bg-surface px-4 py-3 text-xs uppercase tracking-[0.2em] text-text-subtle", children: [
3038
3038
  /* @__PURE__ */ jsx("span", { children: "종류" }),
3039
3039
  /* @__PURE__ */ jsx("span", { children: "파일" }),
@@ -0,0 +1,51 @@
1
+ !ifndef BUILD_UNINSTALLER
2
+ !include nsDialogs.nsh
3
+ Var mediaOverwriteCheckbox
4
+ Var mediaOverwriteSelected
5
+
6
+ !macro customPageAfterChangeDir
7
+ Page custom MediaOptionsCreate MediaOptionsLeave
8
+
9
+ Function MediaOptionsCreate
10
+ !insertmacro MUI_HEADER_TEXT "리소스 설치 옵션" "기존 media 파일을 덮어쓸지 선택하세요."
11
+ nsDialogs::Create 1018
12
+ Pop $0
13
+ ${If} $0 == error
14
+ Abort
15
+ ${EndIf}
16
+
17
+ ${NSD_CreateLabel} 0 0 100% 36u "기본값은 기존 파일 보존입니다. 덮어쓰기를 선택하면 같은 이름의 파일을 인스톨러에 포함된 media 파일로 교체합니다."
18
+ Pop $0
19
+ ${NSD_CreateCheckbox} 0 44u 100% 20u "기존 리소스 덮어쓰기"
20
+ Pop $mediaOverwriteCheckbox
21
+ ${If} $mediaOverwriteSelected == ${BST_CHECKED}
22
+ ${NSD_SetState} $mediaOverwriteCheckbox ${BST_CHECKED}
23
+ ${Else}
24
+ ${NSD_SetState} $mediaOverwriteCheckbox ${BST_UNCHECKED}
25
+ ${EndIf}
26
+ nsDialogs::Show
27
+ FunctionEnd
28
+
29
+ Function MediaOptionsLeave
30
+ ${NSD_GetState} $mediaOverwriteCheckbox $mediaOverwriteSelected
31
+ FunctionEnd
32
+ !macroend
33
+ !endif
34
+
35
+ !macro customInstall
36
+ DetailPrint "Installing default media..."
37
+ ClearErrors
38
+ ${If} $mediaOverwriteSelected == ${BST_CHECKED}
39
+ ExecWait '"$INSTDIR\${APP_EXECUTABLE_FILENAME}" --install-media --overwrite-media' $0
40
+ ${Else}
41
+ ExecWait '"$INSTDIR\${APP_EXECUTABLE_FILENAME}" --install-media' $0
42
+ ${EndIf}
43
+ ${If} ${Errors}
44
+ DetailPrint "Unable to start media installation."
45
+ Abort "Media installation failed."
46
+ ${EndIf}
47
+ ${If} $0 != 0
48
+ DetailPrint "Media installation failed (exit code $0)."
49
+ Abort "Media installation failed."
50
+ ${EndIf}
51
+ !macroend
@@ -48,7 +48,8 @@
48
48
  ],
49
49
  "nsis": {
50
50
  "oneClick": false,
51
- "allowToChangeInstallationDirectory": true
51
+ "allowToChangeInstallationDirectory": true,
52
+ "include": "build/installer.nsh"
52
53
  },
53
54
  "win": {
54
55
  "icon": "build/favicon.ico",
@@ -2,6 +2,7 @@ import { EventEmitter } from 'node:events';
2
2
  import { spawn } from 'node:child_process';
3
3
  export interface ArduinoCliPaths {
4
4
  cliPath: string;
5
+ bundledDataDir: string;
5
6
  dataDir: string;
6
7
  userDir: string;
7
8
  libraryPaths: string[];
@@ -29,6 +30,7 @@ export declare function resolveArduinoCliPaths(app: AppPathLike, options?: {
29
30
  platform?: NodeJS.Platform;
30
31
  resourcesPath?: string;
31
32
  }): ArduinoCliPaths;
33
+ export declare function prepareArduinoCliData(paths: ArduinoCliPaths): Promise<void>;
32
34
  export declare function buildArduinoCompileArgs(options: {
33
35
  fqbn: string;
34
36
  libraryPaths: string[];
@@ -0,0 +1,9 @@
1
+ export declare function installMediaOnFirstLaunch(options: {
2
+ platform: string;
3
+ isPackaged: boolean;
4
+ isDev: boolean;
5
+ completed: boolean;
6
+ askOverwrite: () => Promise<boolean | null>;
7
+ install: (overwrite: boolean) => Promise<void>;
8
+ markCompleted: () => void;
9
+ }): Promise<boolean>;
@@ -5,12 +5,19 @@ export declare class MediaManager {
5
5
  constructor(rootPath: string);
6
6
  getRootPath(): string;
7
7
  ensureDirectories(): Promise<void>;
8
- seedFrom(sourceRootPath: string): Promise<void>;
8
+ seedFrom(sourceRootPath: string, options?: {
9
+ overwrite?: boolean;
10
+ }): Promise<void>;
9
11
  listLibrary(): Promise<MediaLibrary>;
10
12
  resolveMediaPath(ref: MediaRef): string;
11
13
  resolveMediaUrl(ref: MediaRef): string;
12
14
  private listAssetsForType;
13
15
  }
16
+ export declare function createMediaManager(options: {
17
+ isDev: boolean;
18
+ sourceRootPath: string;
19
+ externalRootPath: string;
20
+ }): MediaManager;
14
21
  export interface ByteRange {
15
22
  end: number;
16
23
  start: number;