2022-09-20 19:35:01 +08:00

63 lines
1.9 KiB
JavaScript

const { chmodSync, existsSync, mkdirSync, copyFileSync } = require('fs')
const { EventEmitter } = require('events');
const path = require('path');
const { execFile } = require('child_process');
const homeDir = require('os').homedir();
class ClipboardEventListener extends EventEmitter {
constructor() {
super();
this.child = null;
this.listening = false;
}
startListening() {
const { platform } = process;
if (platform === 'win32') {
this.child = execFile(path.join(__dirname, 'platform/clipboard-event-handler-win32.exe'));
}
else if (platform === 'linux') {
// linux: cant execFile without chmod, and cant chmod in app.asar
// so we need to copy the file to /usr/bin
const targetPath = path.resolve(homeDir, '.local', 'bin')
const target = path.resolve(targetPath, 'clipboard-event-handler-linux')
const p = path.join(__dirname, 'platform/clipboard-event-handler-linux')
if(!existsSync(target)) {
try {
mkdirSync(targetPath)
copyFileSync(p, target)
chmodSync(target, 0o755)
} catch (error) {
this.emit('error', error)
}
}
this.child = execFile(target);
}
else if (platform === 'darwin') {
this.child = execFile(path.join(__dirname, 'platform/clipboard-event-handler-mac'));
}
else {
throw 'Not yet supported';
}
this.child.stdout.on('data', (data) => {
if (data.trim() === 'CLIPBOARD_CHANGE') {
this.emit('change');
}
});
this.child.stdout.on('close', () => {
this.emit('close');
this.listening = false;
});
this.child.stdout.on('exit', () => {
this.emit('exit');
this.listening = false;
});
this.listening = true;
}
stopListening() {
const res = this.child.kill();
this.listening = false;
return res;
}
}
module.exports = new ClipboardEventListener();