-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
80 lines (64 loc) · 2.62 KB
/
index.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
import { readFileSync, unlinkSync } from 'fs'
import { join } from 'path'
import { format } from 'url'
import { exec } from 'child_process'
import { promisify } from 'util'
import { BrowserWindow, app, screen } from 'electron'
import { runLinuxSCROT } from './linux-scrot'
const execAsync = promisify(exec)
const formatFileUrl = (...args) => format({
pathname: join(...args),
protocol: 'file',
slashes: true
})
const tryCreateScreenshotFile = async (tempOutputFile) => {
try { return await execAsync(`gnome-screenshot --file ${tempOutputFile}`, { shell: true }) } catch (error) {}
try { return await execAsync(`import -window root ${tempOutputFile}`, { shell: true }) } catch (error) {}
await runLinuxSCROT(tempOutputFile)
}
// get screenshot
const createDataUrlFromBuffer = (buffer, MIME) => `data:${MIME};base64,${buffer.toString('base64')}`
const loadImageFileAsDataUrl = (imagePath, MIME = 'image/png') => createDataUrlFromBuffer(readFileSync(imagePath), MIME)
const getScreenshotDataUrl = async () => {
const tempOutputFile = join(app.getPath('temp'), 'temp-screenshot.png')
await tryCreateScreenshotFile(tempOutputFile)
const imageDataUrl = await loadImageFileAsDataUrl(tempOutputFile)
unlinkSync(tempOutputFile)
return imageDataUrl
}
// pick color
const pickColorWithBrowserWindow = async ({ imageDataUrl }) => {
const { width, height } = screen.getPrimaryDisplay().bounds
if (!width || !height) throw new Error(`[pickColorWithBrowserWindow] invalid display bounds: ${JSON.stringify({ width, height })}`)
const browserWindow = new BrowserWindow({
width,
height,
frame: false,
resizable: false,
scrollable: false,
fullscreen: true,
alwaysOnTop: true,
enableLargerThanScreen: true,
titleBarStyle: 'hidden'
})
browserWindow.webContents.loadURL(formatFileUrl(__dirname, 'pick-color.html'))
const colorHex = await new Promise((resolve) => {
browserWindow.on('closed', () => { resolve('') })
browserWindow.webContents.on('before-input-event', (event, input) => {
if (input.key !== 'Escape') return
event.preventDefault()
resolve('')
})
browserWindow.webContents.executeJavaScript(`window.PICK_COLOR({ IMAGE_DATA_URL: ${JSON.stringify(imageDataUrl)}, ZOOM: 10, GRID_COUNT: 17 })`)
.then(resolve)
})
__DEV__ && console.log('[pickColorWithBrowserWindow] PICK_COLOR:', { colorHex })
browserWindow.close()
return colorHex
}
const runColorPicker = async () => {
const imageDataUrl = await getScreenshotDataUrl()
const possibleColorString = await pickColorWithBrowserWindow({ imageDataUrl })
return { possibleColorString }
}
export { runColorPicker }