-
Notifications
You must be signed in to change notification settings - Fork 10
/
electron-main.js
382 lines (325 loc) · 11.2 KB
/
electron-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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
const {app, ipcMain, BrowserWindow, dialog} = require('electron');
app.commandLine.appendSwitch('ignore-gpu-blacklist');
const BackendManager = require('./src/backend-manager.js');
const MenuManager = require('./src/menu-manager.js');
const UglyNotify = require('./src/ugly-notify.js');
const events = require('./src/ipc-events');
const TTC2TTF = require('./src/ttc2ttf.js');
const FontManager = require('font-manager');
const TextToSVG = require('text-to-svg');
const path = require('path');
const url = require('url');
const fs = require('fs');
const os = require('os');
let mainWindow;
let menuManager;
global.backend = {alive: false};
global.devices = {};
function createLogFile() {
var storageDir = app.getPath('userData');
function chkDir(target) {
if (fs.existsSync(target)) {
return;
} else {
chkDir(path.dirname(target));
fs.mkdirSync(target);
}
}
chkDir(storageDir);
let filename = path.join(app.getPath('userData'), 'backend.log');
let f = fs.createWriteStream(filename, {flags: 'w'});
global.backend.logfile = filename;
console._stdout = f;
console._stderr = f;
return f;
}
var DEBUG = false;
const logger = process.stderr.isTTY ? process.stderr : createLogFile();
if (process.argv.indexOf('--debug') > 0) {
DEBUG = true;
console.log('DEBUG Mode');
// require('electron-reload')(__dirname);
}
// Solve transparent window issue
if (process.platform === 'linux') {
app.disableHardwareAcceleration();
}
function onGhostUp(data) {
global.backend.alive = true;
global.backend.port = data.port;
if(mainWindow) {
mainWindow.webContents.send(events.BACKEND_UP, global.backend);
}
}
function onGhostDown() {
global.backend.alive = false;
global.backend.port = undefined;
if(mainWindow) {
mainWindow.webContents.send('backend-down');
}
}
function onDeviceUpdated(deviceInfo) {
let deviceID = `${deviceInfo.source}:${deviceInfo.uuid}`;
let origDeviceInfo = global.devices[deviceID];
if(origDeviceInfo && origDeviceInfo.st_id !== null && origDeviceInfo.st_id !== deviceInfo.st_id) {
switch(deviceInfo.st_id) {
case 48:
UglyNotify.send(deviceInfo.name, 'Is paused');
break;
case 64:
UglyNotify.send(deviceInfo.name, 'Is completed!');
break;
case 128:
UglyNotify.send(deviceInfo.name, 'Is aborted');
break;
}
}
if(mainWindow) {
mainWindow.webContents.send('device-status', deviceInfo);
}
if(deviceInfo.alive) {
menuManager.updateDevice(deviceInfo.uuid, deviceInfo);
} else {
if(global.devices[deviceID]) {
menuManager.removeDevice(deviceInfo.uuid, global.devices[deviceID]);
delete global.devices[deviceID];
}
}
global.devices[deviceID] = deviceInfo;
}
require('./src/bootstrap.js');
const backendManager = new BackendManager({
location: process.env.BACKEND,
trace_pid: process.pid,
server: process.argv.indexOf('--server') > 0,
on_ready: onGhostUp,
on_device_updated: onDeviceUpdated,
on_stderr: (data) => logger.write(`${data}`),
on_stopped: onGhostDown,
c: console
});
backendManager.start();
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1024,
height: 768,
title: `FLUX Studio - ${app.getVersion()}`,
webPreferences: {
preload: path.join(__dirname, 'src', 'main-window-entry.js'),
nodeIntegration: true
},
vibrancy: 'light'});
// mainWindow.maximize();
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'public/index.html'),
protocol: 'file:',
slashes: true,
}));
mainWindow.on('closed', function () {
mainWindow = null;
if (process.platform === 'darwin' && DEBUG) {
console.log('Main window closed.');
} else {
app.quit();
}
});
mainWindow.on('page-title-updated', function(event) {
event.preventDefault();
});
menuManager.on('DEBUG-RELOAD', () => {
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'public/index.html'),
protocol: 'file:',
slashes: true,
}));
});
menuManager.on('DEBUG-INSPECT', () => {
mainWindow.webContents.openDevTools();
});
ipcMain.on('DEBUG-INSPECT', () => {
mainWindow.webContents.openDevTools();
});
if(process.defaultApp || DEBUG) {
mainWindow.webContents.openDevTools();
}
}
ipcMain.on(events.CHECK_BACKEND_STATUS, () => {
if(mainWindow) {
mainWindow.send(events.NOTIFY_BACKEND_STATUS, {
backend: global.backend,
devices: global.devices
});
} else {
console.error('Recv async-status request but main window not exist');
}
});
var fontsListCache = [];
ipcMain.on(events.GET_AVAILABLE_FONTS , (event, arg) => {
const fonts = FontManager.getAvailableFontsSync();
fontsListCache = fonts;
event.returnValue = fonts;
});
ipcMain.on(events.FIND_FONTS , (event, arg) => {
// FontManager.findFontsSync({ family: 'Arial' });
const fonts = FontManager.findFontsSync(arg);
event.returnValue = fonts;
});
ipcMain.on(events.FIND_FONT , (event, arg) => {
// FontManager.findFontSync({ family: 'Arial', weight: 700 })
const font = FontManager.findFontSync(arg);
event.returnValue = font;
});
ipcMain.on('save-dialog', function (event, title, allFiles, extensionName, extensions, filename, file) {
const isMac = (process.platform === 'darwin');
const options = {
defaultPath: filename,
title,
filters: [
{ name: isMac ? `${extensionName} (*.${extensions[0]})` : extensionName ,extensions },
{ name: allFiles, extensions: ['*'] }
]
}
dialog.showSaveDialog(options, function (filePath) {
if (!filePath) {
return;
}
switch (typeof(file)) {
case 'string':
fs.writeFile(filePath, file, function(err) {
if (err) {
dialog.showErrorBox('Error', err);
return;
}
});
break;
case 'object':
fs.writeFileSync(filePath, file, function(err) {
if(err) {
dialog.showErrorBox('Error', err);
return;
}
});
break;
default:
dialog.showErrorBox('Error: something wrong, please contact FLUX Support');
break;
}
})
})
ipcMain.on(events.REQUEST_PATH_D_OF_TEXT , async (event, {text, x, y, fontFamily, fontSize, fontStyle, letterSpacing, key}) => {
const substitutedFamily = (function(){
//if only contain basic character (123abc!@#$...), don't substitute.
//because my Mac cannot substituteFont properly handing font like 'Windings'
//but we have to subsittue text if text contain both English and Chinese
const textOnlyContainBasicLatin = Array.from(text).every(char => {
return char.charCodeAt(0) <= 0x007F;
});
if (textOnlyContainBasicLatin) {
return fontFamily;
}
const originFont = FontManager.findFontSync({
family: fontFamily,
style: fontStyle
});
// array of used family which are in the text
const familyList = (function(){
const originPostscriptName = originFont.postscriptName;
const list = Array.from(text).map(char =>
FontManager.substituteFontSync(originPostscriptName, char).family
);
// make unique
return [...new Set(list)];
})();
if (familyList.length === 1) {
return familyList[0];
} else if (familyList.length === 2) {
// consider mixing Chinese with English. For example: '甲乙丙ABC' with font Arial.
// we choose to use Chinese font instead of English font, which make English characters differ form what it should be.
// This is not the best solution, just a quick fix.
return (familyList.filter(family => family !== fontFamily))[0];
} else {
console.log('Unexpected case in convert text to path: text contain more than 2 font-family!');
return familyList[0];
}
})();
// Font Manager won't return PingFang Semibold if input PingFang Bold
if (substitutedFamily && substitutedFamily.indexOf('PingFang') > -1) {
switch(fontStyle) {
case 'Bold':
fontStyle = 'Semibold';
break;
case 'Italic':
fontStyle = 'Regular';
break;
case 'Bold Italic':
fontStyle = 'Semibold';
break;
default:
break;
}
}
let font = FontManager.findFontSync({
family: substitutedFamily,
style: fontStyle
});
let fontPath = font.path;
if (fontFamily.indexOf("華康") >= 0 && (fontPath.toLowerCase().indexOf("arial") > 0 || fontPath.toLowerCase().indexOf("meiryo") > 0)) {
// This is a hotfix for 華康系列 fonts, because fontmanager does not support
for (var i in fontsListCache) {
const fontInfo = fontsListCache[i];
if (fontInfo.family == fontFamily) {
fontPath = fontInfo.path;
font = fontInfo;
}
}
}
console.log("New Font path ", fontPath);
if (fontPath.toLowerCase().endsWith('.ttc') || fontPath.toLowerCase().endsWith('.ttcf')) {
fontPath = await TTC2TTF(fontPath, font.postscriptName);
}
const pathD = TextToSVG.loadSync(fontPath).getD(text, {
fontSize: Number(fontSize),
anchor: 'left baseline',
x: x,
y: y,
letterSpacing: letterSpacing
});
event.sender.send(events.RESOLVE_PATH_D_OF_TEXT + key, pathD);
});
console.log('Running FLUX Studio on ', os.arch());
if (os.arch() == 'ia32' || os.arch() == 'x32') {
app.commandLine.appendSwitch('js-flags', '--max-old-space-size=2048');
} else {
app.commandLine.appendSwitch('js-flags', '--max-old-space-size=4096');
}
app.on('ready', () => {
menuManager = new MenuManager();
menuManager.on(events.MENU_CLICK, (data) => {
if(mainWindow) {
mainWindow.webContents.send(events.MENU_CLICK, data);
} else {
console.log('Menu event triggered but window does not exist.');
}
});
if (app.requestSingleInstanceLock()) {
if(!mainWindow) {
createWindow();
} else {
console.log("MainWindow instance", mainWindow);
mainWindow.focus();
}
};
});
// app.on('window-all-closed', function () {
// });
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
app.on('before-quit', function() {
backendManager.stop();
});