Repository navigation
Expand file tree
/
Copy pathelectron-deeplink.mjs
More file actions
210 lines (188 loc) · 6.61 KB
/
Copy pathelectron-deeplink.mjs
File metadata and controls
210 lines (188 loc) · 6.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import electron from 'electron';
import fs from 'node:fs';
import path from 'path';
import { fileURLToPath } from 'url';
import {
configurePortableAppPaths,
resolvePortableRuntime,
} from './utils/portableRuntime.mjs';
const { app, BrowserWindow, dialog } = electron;
const SCHEME = 'imagemetahub';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const portableRuntime = resolvePortableRuntime();
const packagedProvenanceSmokeEnabled = app.isPackaged
&& process.env.IMH_PACKAGED_PROVENANCE_FILE_OPERATIONS_SMOKE === '1';
const packagedSavedPromptSmokeEnabled = app.isPackaged
&& process.env.IMH_PACKAGED_SAVED_PROMPT_SMOKE === '1';
const packagedCanvasSmokeEnabled = app.isPackaged && process.env.IMH_PACKAGED_CANVAS_SMOKE === '1';
let portableStartupError = null;
try {
configurePortableAppPaths(app, portableRuntime);
} catch (error) {
portableStartupError = error;
const detail = error?.cause?.message || error?.message || String(error);
console.error('[Portable] Failed to initialize the portable profile:', error);
dialog.showErrorBox(
'Image MetaHub Portable could not start',
[
`Image MetaHub could not write to:\n${portableRuntime.userDataPath}`,
'',
'Move the portable app to a writable folder or allow write access, then try again.',
'',
detail,
].join('\n'),
);
app.exit(1);
}
function isDeepLink(value) {
return typeof value === 'string' && value.toLowerCase().startsWith(`${SCHEME}://`);
}
function findDeepLink(args) {
return Array.from(args || []).find(isDeepLink) || null;
}
function normalizeCliArgs(args) {
return Array.from(args || []).slice(app.isPackaged ? 1 : 2);
}
function getTargetFromLink(value) {
if (!isDeepLink(value)) return null;
try {
const url = new URL(value);
const rawFile = url.searchParams.get('file');
if (rawFile) {
return { type: 'file', path: path.resolve(rawFile) };
}
const rawPath = url.searchParams.get('path') || url.searchParams.get('dir') || url.searchParams.get('directory');
return rawPath ? { type: 'directory', path: path.resolve(rawPath) } : null;
} catch (error) {
console.warn('[ImageMetaHub protocol] Invalid URL:', error);
return null;
}
}
function getDirectoryFromCliArgs(args) {
const argv = normalizeCliArgs(args);
const dirFlagIndex = argv.indexOf('--dir');
if (dirFlagIndex !== -1 && argv[dirFlagIndex + 1]) {
return path.resolve(argv[dirFlagIndex + 1]);
}
const directPath = argv.find((arg) => {
if (typeof arg !== 'string' || !arg.trim() || arg.startsWith('--')) return false;
if (isDeepLink(arg)) return false;
if (arg === process.execPath) return false;
if (arg.endsWith('.exe') || arg.endsWith('.mjs') || arg.endsWith('.js')) return false;
return true;
});
return directPath ? path.resolve(directPath) : null;
}
function getDirectoryFromArgs(args) {
const linkTarget = getTargetFromLink(findDeepLink(args));
if (linkTarget?.type === 'directory') {
return linkTarget.path;
}
return getDirectoryFromCliArgs(args);
}
function focusMainWindow() {
const target = BrowserWindow.getAllWindows().find((window) => !window.isDestroyed());
if (!target) return null;
if (target.isMinimized()) target.restore();
target.show();
target.focus();
return target;
}
function sendDirectoryToRenderer(directoryPath, attempt = 0) {
if (!directoryPath) return;
const target = focusMainWindow();
if (!target || target.webContents.isLoading()) {
if (attempt < 120) {
setTimeout(() => sendDirectoryToRenderer(directoryPath, attempt + 1), 250);
}
return;
}
target.webContents.send('load-directory-from-cli', directoryPath);
}
function sendFileToRenderer(filePath, attempt = 0) {
if (!filePath) return;
const target = focusMainWindow();
if (!target || target.webContents.isLoading()) {
if (attempt < 120) {
setTimeout(() => sendFileToRenderer(filePath, attempt + 1), 250);
}
return;
}
target.webContents.send('open-file-from-deep-link', filePath);
}
function dispatchTarget(target) {
if (target?.type === 'file') {
sendFileToRenderer(target.path);
} else if (target?.type === 'directory') {
sendDirectoryToRenderer(target.path);
}
}
function registerProtocol() {
try {
if (process.defaultApp) {
const entry = process.argv[1] ? path.resolve(process.argv[1]) : path.join(__dirname, 'electron-deeplink.mjs');
return app.setAsDefaultProtocolClient(SCHEME, process.execPath, [entry]);
}
return app.setAsDefaultProtocolClient(SCHEME);
} catch (error) {
console.warn('[ImageMetaHub protocol] Registration failed:', error);
return false;
}
}
if (!portableStartupError) {
const lock = packagedProvenanceSmokeEnabled || packagedSavedPromptSmokeEnabled || packagedCanvasSmokeEnabled || app.requestSingleInstanceLock();
if (!lock) {
app.quit();
} else {
if (!portableRuntime.isPortable) {
registerProtocol();
}
const startupTarget = getTargetFromLink(findDeepLink(process.argv));
const startupDirectory = startupTarget?.type === 'file' ? null : getDirectoryFromArgs(process.argv);
if (startupDirectory) {
process.argv.push('--dir', startupDirectory);
}
app.on('second-instance', (_event, argv) => {
const target = getTargetFromLink(findDeepLink(argv));
if (target) {
dispatchTarget(target);
return;
}
focusMainWindow();
sendDirectoryToRenderer(getDirectoryFromArgs(argv));
});
app.on('open-url', (event, url) => {
event.preventDefault();
dispatchTarget(getTargetFromLink(url));
});
try {
await import('./electron.mjs');
} catch (error) {
console.error('[Electron bootstrap] Failed to import the main process:', error);
if (packagedProvenanceSmokeEnabled || packagedSavedPromptSmokeEnabled || packagedCanvasSmokeEnabled) {
const resultPath = (
process.env.IMH_PACKAGED_PROVENANCE_FILE_OPERATIONS_SMOKE_RESULT
|| process.env.IMH_PACKAGED_SAVED_PROMPT_SMOKE_RESULT
|| process.env.IMH_PACKAGED_CANVAS_SMOKE_RESULT
)?.trim();
if (resultPath) {
try {
fs.mkdirSync(path.dirname(resultPath), { recursive: true });
fs.writeFileSync(resultPath, JSON.stringify({
success: false,
error: error?.message || String(error),
stack: error?.stack || null,
}, null, 2), 'utf8');
} catch { /* stderr remains the fallback */ }
}
app.exit(1);
} else {
throw error;
}
}
if (startupTarget?.type === 'file') {
sendFileToRenderer(startupTarget.path);
}
}
}