|
const {app, BrowserWindow} = require('electron') |
|
const {ipcMain} = require('electron') |
|
|
|
const http = require('http') |
|
const textBody = require('body') |
|
const hat = require('hat') |
|
const minimist = require('minimist') |
|
|
|
const argv = minimist(process.argv.slice(2), { |
|
string: ['port', 'debug'], |
|
'default': { |
|
port: 8000, |
|
debug: !!process.env.DEBUG |
|
} |
|
}) |
|
|
|
const PORT = argv.port |
|
const DEBUG = argv.debug |
|
|
|
let server |
|
let win |
|
|
|
// to generate WebGL in headless environments |
|
app.commandLine.appendSwitch('ignore-gpu-blacklist') |
|
|
|
app.on('ready', () => { |
|
win = new BrowserWindow({ |
|
height: 1024, |
|
width: 1024 |
|
}) |
|
|
|
server = createServer(win) |
|
|
|
server.on('error', (err) => { |
|
console.warn(err) |
|
app.quit() |
|
}) |
|
|
|
win.loadURL(`file://${__dirname}/index.html`) |
|
|
|
if (DEBUG) { |
|
win.openDevTools() |
|
} |
|
|
|
win.on('closed', () => { |
|
win = null |
|
}) |
|
|
|
process.on('close', () => { |
|
win.close() |
|
}) |
|
|
|
win.webContents.once('did-finish-load', () => { |
|
server.listen(PORT, () => { |
|
console.log(`listening on port ${PORT}`) |
|
}) |
|
}) |
|
}) |
|
|
|
function createServer (win) { |
|
return http.createServer((req, res) => { |
|
const uid = hat() |
|
|
|
if (req.url === '/ping') { |
|
res.writeHead(200, {'Content-Type': 'text/plain'}) |
|
return res.end('pong\n') |
|
} |
|
|
|
textBody(req, {limit: 1e9}, (err, body) => { |
|
if (err) return console.warn(err) |
|
|
|
const fig = JSON.parse(body) |
|
win.webContents.send('fig', fig, uid) |
|
}) |
|
|
|
ipcMain.once(uid, (event, info) => { |
|
switch (info.code) { |
|
case 200: |
|
const buf = Buffer.from(info.imgData, 'base64') |
|
|
|
res.writeHead(200, { |
|
'Content-Type': 'image/png', |
|
'Content-Length': info.imgData.length |
|
}) |
|
|
|
if (res.write(buf)) { |
|
res.end() |
|
} else { |
|
res.once('drain', () => res.end()) |
|
} |
|
break |
|
case 525: |
|
res.writeHead(525, {'Content-Type': 'text/plain'}) |
|
res.end('plotly.js error') |
|
break |
|
} |
|
}) |
|
}) |
|
} |