This repository has been archived by the owner on Nov 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
267 lines (235 loc) · 9.83 KB
/
main.js
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
const { app, BrowserWindow, dialog, ipcMain } = require('electron');
const fs = require('fs');
const os = require('os');
const path = require('path');
const lzma = require('lzma-native');
const yaml = require('js-yaml');
const bsdiff = require('bsdiff-node');
const childProcess = require('child_process');
const md5 = require('md5');
const SNI = require('./SNI');
// Control variable for SNI to prevent multiple rapid launches
let lastSNILaunchAttempt = 0;
// Determine user's config file path based on OS
const configDir = (process.platform === 'win32') ?
path.join(process.env.APPDATA, 'super-metroid-client-info') : // Windows
path.join(os.homedir(), '.super-metroid-client-info'); // Mac + Linux
if (!fs.existsSync(configDir)) { fs.mkdirSync(configDir, { recursive: true }); }
const configPath = path.join(configDir, 'super-metroid-client.config.json');
// Determine user's log directory based on OS
const logDir = (process.platform === 'win32') ?
path.join(process.env.APPDATA, 'super-metroid-client-info', 'logs') : // Windows
path.join(os.homedir(), '.super-metroid-client-info', 'logs'); // Mac + Linux
if (!fs.existsSync(logDir)) { fs.mkdirSync(logDir, { recursive: true }); }
// Catch and log any uncaught errors that occur in the main process
process.on('uncaughtException', (error) => {
const uncaughtLogFile = createLogFile();
fs.writeSync(uncaughtLogFile, `[${new Date().toLocaleString()}] ${JSON.stringify(error)}\n`);
fs.closeSync(uncaughtLogFile);
});
// Function to create a log file
const createLogFile = () => {
return fs.openSync(path.join(logDir, `${new Date().getTime()}.txt`), 'w');
}
// Create log file for this run
const logFile = createLogFile();
// Function to launch SNI if it is not running
const launchSNI = () => {
if (new Date().getTime() < (lastSNILaunchAttempt + 3000)) { return; }
lastSNILaunchAttempt = new Date().getTime();
const exec = require('child_process').exec;
let cmd = null;
let sniBinary = null;
switch(process.platform){
case 'win32':
cmd = 'tasklist';
sniBinary = 'sni.exe';
break;
case 'linux':
cmd = 'ps -A';
sniBinary = 'sni-linux';
break;
case 'darwin':
cmd = 'ps -ax';
sniBinary = 'sni-darwin';
break;
default:
return;
}
exec(cmd, (err, stdout, stderr) => {
if (stdout.toLowerCase().indexOf(sniBinary) === -1) {
childProcess.spawn(path.join(__dirname, 'sni', sniBinary), { detached: true });
}
});
};
// Perform certain actions during the install process
if (require('electron-squirrel-startup')) {
if (process.platform === 'win32') {
// Prepare to add registry entries for .apm3 files
const Registry = require('winreg');
const exePath = path.join(process.env.LOCALAPPDATA, 'SuperMetroidClient', 'Super Metroid Client.exe');
// Set file type description for .apm3 files
const descriptionKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Classes\\archipelago.super-metroid-client.v1',
});
descriptionKey.set(Registry.DEFAULT_VALUE, Registry.REG_SZ, 'AP Super Metroid Binary Patch',
(error) => console.error(error));
// Set icon for .apm3 files
const iconKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Classes\\archipelago.super-metroid-client.v1\\DefaultIcon',
});
iconKey.set(Registry.DEFAULT_VALUE, Registry.REG_SZ, `${exePath},0`, (error) => console.error(error));
// Set set default program for launching .apm3 files (Super Metroid Client)
const commandKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Classes\\archipelago.super-metroid-client.v1\\shell\\open\\command'
});
commandKey.set(Registry.DEFAULT_VALUE, Registry.REG_SZ, `"${exePath}" "%1"`, (error) => console.error(error));
// Set .apm3 files to launch with Super Metroid Client
const extensionKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Classes\\.apm3',
});
extensionKey.set(Registry.DEFAULT_VALUE, Registry.REG_SZ, 'archipelago.super-metroid-client.v1',
(error) => console.error(error));
}
// Do not launch the client during the install process
return app.quit();
}
// Used to transfer server data from the main process to the renderer process
const sharedData = {};
const createWindow = () => {
const win = new BrowserWindow({
width: 1280,
minWidth: 400,
height: 720,
minHeight: 100,
autoHideMenuBar: true,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
enableRemoteModule: false,
preload: path.join(__dirname, 'preload.js'),
},
});
win.loadFile('index.html').catch((error) => {
console.log(error);
fs.writeSync(logFile, `[${new Date.toLocaleString()}] ${JSON.stringify(error)}`);
});
};
app.whenReady().then(async () => {
// Create the local config file if it does not exist
if (!fs.existsSync(configPath)) {
fs.writeFileSync(configPath, JSON.stringify({}));
}
// Load the config into memory
const config = JSON.parse(fs.readFileSync(configPath).toString());
const baseRomHash = '21f3e98df4780ee1c667b84e57d88675';
// Prompt for base rom file if not present in config, missing from disk, or the hash fails
if (
!config.hasOwnProperty('baseRomPath') || // Base ROM has not been specified in the past
!fs.existsSync(config.baseRomPath) || // Base ROM no longer exists
md5(fs.readFileSync(config.baseRomPath)) !== baseRomHash // The base ROM hash is wrong (user chose the wrong file)
) {
let baseRomPath = await dialog.showOpenDialog(null, {
title: 'Select base ROM',
buttonLabel: 'Choose ROM',
message: 'Choose a base ROM to be used when patching.',
});
// Save base rom filepath back to config file
if (!baseRomPath.canceled && baseRomPath.filePaths.length > 0) {
config.baseRomPath = baseRomPath.filePaths[0];
fs.writeFileSync(configPath, JSON.stringify(Object.assign({}, config, {
baseRomPath: config.baseRomPath,
})));
}
}
// Create a new ROM from the patch file if the patch file is provided and the base rom is known
for (const arg of process.argv) {
if (arg.substr(-5).toLowerCase() === '.apm3') {
if (config.hasOwnProperty('baseRomPath') && fs.existsSync(config.baseRomPath)) {
if (md5(fs.readFileSync(config.baseRomPath)) !== baseRomHash) {
dialog.showMessageBoxSync({
type: 'info',
title: 'Invalid Base ROM',
message: 'The ROM file for your game could not be created because the base ROM is invalid.',
});
break;
}
if (!fs.existsSync(arg)) { break; }
const patchFilePath = path.join(__dirname, 'patch.bsdiff');
const romFilePath = path.join(path.dirname(arg),
`${path.basename(arg).substr(0, path.basename(arg).length - 5)}.sfc`);
const apbpBuffer = await lzma.decompress(fs.readFileSync(arg));
const apbp = yaml.load(apbpBuffer);
sharedData.apServerAddress = apbp.meta.server ? apbp.meta.server : null;
fs.writeFileSync(patchFilePath, apbp.patch);
await bsdiff.patch(config.baseRomPath, romFilePath, patchFilePath);
fs.rmSync(patchFilePath);
// If a custom launcher is specified, attempt to launch the ROM file using the specified loader
if (config.hasOwnProperty('launcherPath') && fs.existsSync(config.launcherPath)) {
childProcess.spawn(config.launcherPath, [romFilePath], { detached: true });
break;
}
// If no custom launcher is specified, launch the rom with explorer on Windows
if (process.platform === 'win32') {
childProcess.spawn('explorer', [romFilePath], { detached: true });
}
}
break;
}
}
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
}).catch((error) => {
// Write error to log
fs.writeFileSync(logFile, `[${new Date().toLocaleString()}] ${JSON.stringify(error)}\n`);
});
// Launch SNI if it is not running
launchSNI();
// Interprocess communication with the renderer process, all are asynchronous events
ipcMain.on('requestSharedData', (event, args) => {
event.sender.send('sharedData', sharedData);
});
ipcMain.on('setLauncher', async (event, args) => {
// Allow the user to specify a program to launch the ROM
const config = JSON.parse(fs.readFileSync(configPath).toString());
const launcherPath = await dialog.showOpenDialog({
title: 'Locate ROM Launcher',
buttonLabel: 'Select Launcher',
message: 'Choose an executable to be used when launching the ROM',
});
if (!launcherPath.canceled && launcherPath.filePaths.length > 0) {
fs.writeFileSync(configPath, JSON.stringify(Object.assign({}, config, {
launcherPath: launcherPath.filePaths[0],
})));
}
});
try{
// Interprocess communication with the renderer process related to SNI, all are synchronous events
const sni = new SNI();
sni.setAddressSpace(SNI.supportedAddressSpaces.FXPAKPRO); // We support communicating with FXPak devices
sni.setMemoryMap(SNI.supportedMemoryMaps.LOROM); // Super Metroid uses LOROM
ipcMain.handle('launchSNI', launchSNI);
ipcMain.handle('fetchDevices', sni.fetchDevices);
ipcMain.handle('setDevice', (event, device) => sni.setDevice.apply(sni, [device]));
ipcMain.handle('readFromAddress', (event, args) => sni.readFromAddress.apply(sni, args));
ipcMain.handle('writeToAddress', (event, args) => sni.writeToAddress.apply(sni, args));
fs.writeFileSync(logFile, `[${new Date().toLocaleString()}] Log begins.`);
ipcMain.handle('writeToLog', (event, data) =>
fs.writeFileSync(logFile, `[${new Date().toLocaleString()}] ${data}\n`));
}catch(error){
console.log(error);
fs.writeFileSync(logFile, `[${new Date().toLocaleString()}] ${JSON.stringify(error)}\n`);
}