Rebase to master when repo went private
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
const adb = require('adbkit');
|
||||
const fs = require('fs');
|
||||
const request = require('request');
|
||||
const progress = require('request-progress');
|
||||
const Readable = require('stream').Readable;
|
||||
import { SetPropertiesCommand } from './setproperties';
|
||||
|
||||
export class ADB {
|
||||
client;
|
||||
_logcat;
|
||||
setupAdb(adbPath, cb, ecb) {
|
||||
if (this.client) return;
|
||||
this.client = adb.createClient({
|
||||
bin: adbPath,
|
||||
});
|
||||
cb();
|
||||
}
|
||||
endLogcat() {
|
||||
if (this._logcat) {
|
||||
this._logcat.end();
|
||||
this._logcat = null;
|
||||
}
|
||||
}
|
||||
logcat(serial, tag, priority, cb, scb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
if (!this._logcat) this.endLogcat();
|
||||
this.client
|
||||
.openLogcat(serial, { clear: true })
|
||||
.then(logcat => {
|
||||
this._logcat = logcat;
|
||||
logcat.include(tag, priority).on('entry', entry => scb(entry));
|
||||
})
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
installRemote(serial, path, cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.installRemote(serial, path)
|
||||
.then(cb)
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
install(serial, path, isLocal, cb, scb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
let stream;
|
||||
try {
|
||||
stream = isLocal
|
||||
? fs.createReadStream(path)
|
||||
: new Readable().wrap(
|
||||
progress(request(path), {
|
||||
throttle: 60,
|
||||
})
|
||||
.on('progress', state => {
|
||||
scb(state);
|
||||
})
|
||||
.on('end', () => {
|
||||
scb({
|
||||
percent: 1,
|
||||
});
|
||||
})
|
||||
);
|
||||
} catch (e) {
|
||||
const isInvalidURI = e && typeof e.message === 'string' && e.message.startsWith('Invalid URI "');
|
||||
if (isInvalidURI) {
|
||||
return ecb("Can't download file. Invalid URL:");
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
this.client
|
||||
.install(serial, stream)
|
||||
.then(cb)
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
uninstall(serial, packageName, cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.uninstall(serial, packageName)
|
||||
.then(cb)
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
clear(serial, packageName, cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.clear(serial, packageName)
|
||||
.then(cb)
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
disconnect(cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.disconnect()
|
||||
.then(cb)
|
||||
.then(() => this.client.kill())
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
connect(deviceIp, cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.connect(deviceIp + ':5555')
|
||||
.then(cb)
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
tcpip(serial, cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.tcpip(serial, 5555)
|
||||
.then(r => {
|
||||
console.log(r);
|
||||
cb(r);
|
||||
})
|
||||
.catch(e => {
|
||||
console.log(serial, e);
|
||||
ecb(e);
|
||||
});
|
||||
}
|
||||
usb(serial, cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.usb(serial)
|
||||
.then(cb)
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
listDevices(cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.listDevices()
|
||||
.then(cb)
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
setProperties(serial, command, cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.transport(serial)
|
||||
.then(function(transport) {
|
||||
return new SetPropertiesCommand(transport).execute(command);
|
||||
})
|
||||
// this.client
|
||||
// .setProperties(serial, command)
|
||||
.then(res => cb(res))
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
getPackages(serial, cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.getPackages(serial)
|
||||
.then(res => cb(res))
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
shell(serial, command, cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.shell(serial, command)
|
||||
.then(adb.util.readAll)
|
||||
.then(res => cb(res.toString()))
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
readdir(serial, path, cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.readdir(serial, path)
|
||||
.then(res =>
|
||||
res
|
||||
.map(r => {
|
||||
r.__isFile = r.isFile();
|
||||
return r;
|
||||
})
|
||||
.filter(r => !(r.__isFile && r.name.lastIndexOf('\\') > -1))
|
||||
)
|
||||
.then(res => cb(res))
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
push(serial, path, savePath, cb, scb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.push(serial, fs.createReadStream(path), savePath)
|
||||
.then(transfer => {
|
||||
let _stats, autocancel;
|
||||
const interval = setInterval(() => {
|
||||
scb(_stats);
|
||||
}, 1000);
|
||||
transfer.on('progress', stats => {
|
||||
clearTimeout(autocancel);
|
||||
_stats = stats;
|
||||
autocancel = setTimeout(() => {
|
||||
clearInterval(interval);
|
||||
cb();
|
||||
}, 90000);
|
||||
});
|
||||
transfer.on('end', () => {
|
||||
clearTimeout(autocancel);
|
||||
clearInterval(interval);
|
||||
cb();
|
||||
});
|
||||
transfer.on('error', e => {
|
||||
ecb(e);
|
||||
});
|
||||
})
|
||||
.catch(e => {
|
||||
ecb(e);
|
||||
});
|
||||
}
|
||||
pull(serial, path, savePath, cb, scb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.pull(serial, path)
|
||||
.then(transfer => {
|
||||
transfer.on('progress', stats => {
|
||||
scb(stats);
|
||||
});
|
||||
transfer.on('end', () => {
|
||||
cb();
|
||||
});
|
||||
transfer.on('error', e => {
|
||||
ecb(e);
|
||||
});
|
||||
transfer.pipe(fs.createWriteStream(savePath));
|
||||
})
|
||||
.catch(e => {
|
||||
ecb(e);
|
||||
});
|
||||
}
|
||||
stat(serial, path, cb, ecb) {
|
||||
if (!this.client) return ecb('Not connected.');
|
||||
this.client
|
||||
.stat(serial, path)
|
||||
.then(res => cb(res))
|
||||
.catch(e => ecb(e));
|
||||
}
|
||||
}
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
import { app, protocol, ipcMain, Menu, MenuItemConstructorOptions, BrowserWindow } from 'electron';
|
||||
import { ADB } from './adbkit';
|
||||
import { StateStorage, EnvironmentConfig } from './state-storage';
|
||||
import { AppWindow } from './window';
|
||||
const path = require('path');
|
||||
const { autoUpdater } = require('electron-updater');
|
||||
const download = require('./download');
|
||||
const extract = require('extract-zip');
|
||||
|
||||
let config: StateStorage;
|
||||
let appWindow: AppWindow;
|
||||
let mainWindow: BrowserWindow;
|
||||
let popupWindow: BrowserWindow;
|
||||
let hasUpdate = false;
|
||||
|
||||
if (app.requestSingleInstanceLock()) {
|
||||
const environment: EnvironmentConfig = { userDataPath: app.getPath('userData') };
|
||||
config = new StateStorage(environment, console);
|
||||
setupApp();
|
||||
} else {
|
||||
app.quit();
|
||||
}
|
||||
|
||||
function parseOpenUrl(argv: string[]) {
|
||||
//fs.writeFileSync(path.join(app.getPath('appData'), 'SideQuest', 'test_output_loaded.txt'), JSON.stringify(argv));
|
||||
if (argv[1] && argv[1].length && argv[1].substr(0, 12) === 'sidequest://') {
|
||||
setTimeout(() => mainWindow.webContents.send('open-url', argv[1].toString()), 5000);
|
||||
}
|
||||
}
|
||||
|
||||
function createWindow() {
|
||||
appWindow = new AppWindow(config);
|
||||
mainWindow = appWindow.window;
|
||||
|
||||
if (process.env.NODE_ENV === 'dev') {
|
||||
mainWindow.loadURL('http://localhost:4205');
|
||||
mainWindow.webContents.openDevTools();
|
||||
} else {
|
||||
mainWindow.loadFile('build/app/index.html');
|
||||
}
|
||||
mainWindow.on('closed', function() {
|
||||
mainWindow = undefined;
|
||||
});
|
||||
|
||||
setupMenu();
|
||||
mainWindow.webContents.once('dom-ready', async _e => {
|
||||
parseOpenUrl(process.argv);
|
||||
autoUpdater.autoDownload = false;
|
||||
if (process.platform !== 'linux') autoUpdater.checkForUpdates();
|
||||
});
|
||||
|
||||
protocol.registerBufferProtocol(
|
||||
'beatsaver',
|
||||
(request, _callback) => {
|
||||
mainWindow.webContents.send(
|
||||
'open-url',
|
||||
'sidequest://bsaber/#https://beatsaver.com/api/download/key/' + request.url.replace('beatsaver://', '')
|
||||
);
|
||||
},
|
||||
error => {
|
||||
if (error) console.error('Failed to register protocol');
|
||||
}
|
||||
);
|
||||
|
||||
protocol.registerStringProtocol(
|
||||
'sidequest',
|
||||
(request, _callback) => {
|
||||
mainWindow.webContents.send('open-url', request.url);
|
||||
},
|
||||
error => {
|
||||
if (error) console.error('Failed to register protocol');
|
||||
}
|
||||
);
|
||||
|
||||
mainWindow.webContents.session.on('will-download', (_evt, item, _webContents) => {
|
||||
let url = item.getURL();
|
||||
let etx = path.extname(url.split('?')[0]).toLowerCase();
|
||||
if (~url.indexOf('https://beatsaver.com/cdn')) {
|
||||
// beat saber mods /songs
|
||||
mainWindow.webContents.send('open-url', 'sidequest://bsaber/#' + url);
|
||||
} else if (~url.indexOf('http://songbeater.com/')) {
|
||||
// songbeater mods /songs
|
||||
mainWindow.webContents.send('open-url', 'sidequest://songbeater/#' + url);
|
||||
} else if (~url.indexOf('https://synthriderz.com/')) {
|
||||
// synthriderz mods /songs
|
||||
mainWindow.webContents.send('open-url', 'sidequest://synthriders/#' + url);
|
||||
} else if (etx === '.audica') {
|
||||
// audica custom song format
|
||||
mainWindow.webContents.send('open-url', 'sidequest://audica/#' + url);
|
||||
} else if (etx === '.apk') {
|
||||
// any file ending with apk.
|
||||
mainWindow.webContents.send('pre-open-url', url);
|
||||
} else if (~url.indexOf('ssl.hwcdn.net/') || ~url.indexOf('patreonusercontent.com/')) {
|
||||
//itch.io & patreon
|
||||
let name = item.getFilename();
|
||||
mainWindow.webContents.send('pre-open-url', { url, name });
|
||||
BrowserWindow.getAllWindows()
|
||||
.filter(b => b !== mainWindow)
|
||||
.forEach(b => b.close());
|
||||
}
|
||||
item.cancel();
|
||||
});
|
||||
}
|
||||
|
||||
function setupMenu() {
|
||||
// const template: MenuItemConstructorOptions[] = [
|
||||
// {
|
||||
// label: 'SideQuest',
|
||||
// submenu: [
|
||||
// {
|
||||
// label: 'Quit',
|
||||
// accelerator: 'Command+Q',
|
||||
// click: function() {
|
||||
// app.quit();
|
||||
// },
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// label: 'Edit',
|
||||
// submenu: [
|
||||
// {
|
||||
// label: 'Undo',
|
||||
// accelerator: 'CmdOrCtrl+Z',
|
||||
// // selector: 'undo:',
|
||||
// },
|
||||
// {
|
||||
// label: 'Redo',
|
||||
// accelerator: 'Shift+CmdOrCtrl+Z',
|
||||
// // selector: 'redo:',
|
||||
// },
|
||||
// { type: 'separator' },
|
||||
// {
|
||||
// label: 'Cut',
|
||||
// accelerator: 'CmdOrCtrl+X',
|
||||
// // selector: 'cut:'
|
||||
// },
|
||||
// {
|
||||
// label: 'Copy',
|
||||
// accelerator: 'CmdOrCtrl+C',
|
||||
// // selector: 'copy:',
|
||||
// },
|
||||
// {
|
||||
// label: 'Paste',
|
||||
// accelerator: 'CmdOrCtrl+V',
|
||||
// // selector: 'paste:',
|
||||
// },
|
||||
// {
|
||||
// label: 'Select All',
|
||||
// accelerator: 'CmdOrCtrl+A',
|
||||
// // selector: 'selectAll:',
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// ];
|
||||
//
|
||||
// Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||
Menu.setApplicationMenu(null);
|
||||
}
|
||||
|
||||
function setupApp() {
|
||||
app.on('second-instance', (_event, commandLine, _workingDirectory) => {
|
||||
parseOpenUrl(commandLine);
|
||||
if (mainWindow) {
|
||||
if (mainWindow.isMinimized()) mainWindow.restore();
|
||||
mainWindow.focus();
|
||||
}
|
||||
});
|
||||
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
|
||||
if (process.env.NODE_ENV === 'dev') {
|
||||
// Verification logic.
|
||||
event.preventDefault();
|
||||
callback(true);
|
||||
} else {
|
||||
callback(false);
|
||||
}
|
||||
});
|
||||
app.on('ready', createWindow);
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function() {
|
||||
if (process.platform !== 'darwin') app.quit();
|
||||
if (adb.client) adb.client.kill();
|
||||
});
|
||||
|
||||
app.on('activate', function() {
|
||||
if (mainWindow === null) createWindow();
|
||||
});
|
||||
app.setAsDefaultProtocolClient('sidequest');
|
||||
app.on('open-url', function(event, url) {
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
app.on('web-contents-created', (e, contents) => {
|
||||
if (contents.getType() === 'webview') {
|
||||
// contents.on('new-window', (e : any, url) => {
|
||||
// popupWindow = new BrowserWindow({show: false})
|
||||
// popupWindow.once('ready-to-show', () => popupWindow.show())
|
||||
// popupWindow.loadURL(url);
|
||||
// e.newGuest = popupWindow;
|
||||
// e.preventDefault();
|
||||
// });
|
||||
}
|
||||
});
|
||||
|
||||
app.on('browser-window-blur', () => {
|
||||
if (appWindow) {
|
||||
appWindow.saveWindowState();
|
||||
}
|
||||
});
|
||||
|
||||
autoUpdater.on('checking-for-update', () => {
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send('update-status', { status: 'checking-for-update' });
|
||||
}
|
||||
});
|
||||
autoUpdater.on('update-available', info => {
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send('update-status', { status: 'update-available', info });
|
||||
hasUpdate = true;
|
||||
}
|
||||
});
|
||||
autoUpdater.on('update-not-available', info => {
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send('update-status', { status: 'no-update', info });
|
||||
}
|
||||
});
|
||||
autoUpdater.on('error', err => {
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send('update-status', { status: 'error', err });
|
||||
} else {
|
||||
console.log(err);
|
||||
}
|
||||
});
|
||||
autoUpdater.on('download-progress', progressObj => {
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send('update-status', { status: 'downloading', progressObj });
|
||||
}
|
||||
});
|
||||
autoUpdater.on('update-downloaded', info => {
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send('update-status', { status: 'update-downloaded', info });
|
||||
}
|
||||
});
|
||||
(global as any).receiveMessage = function(text) {
|
||||
mainWindow.webContents.send('info', text);
|
||||
};
|
||||
|
||||
const adb = new ADB();
|
||||
|
||||
ipcMain.on('download-url', async (event, { url, token, directory, filename }) => {
|
||||
await download(url, path.join(directory, filename), stats => {
|
||||
return event.sender.send('download-progress', { stats, token });
|
||||
}).catch(e => console.log(e));
|
||||
event.sender.send('download-url', { token });
|
||||
});
|
||||
ipcMain.on('extract-file', async (event, { token, directory, filename }) => {
|
||||
extract(
|
||||
filename,
|
||||
{
|
||||
dir: directory,
|
||||
onEntry: entry => {
|
||||
let stats = entry.fileName;
|
||||
event.sender.send('extract-progress', { stats, token });
|
||||
},
|
||||
},
|
||||
err => {
|
||||
event.sender.send('extract-file', { token });
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
ipcMain.on('automatic-update', (event, arg) => {
|
||||
if (process.platform !== 'darwin' && hasUpdate) {
|
||||
setTimeout(() => {
|
||||
autoUpdater.downloadUpdate().then(() => autoUpdater.quitAndInstall(false, false));
|
||||
}, 5000);
|
||||
}
|
||||
});
|
||||
ipcMain.on('adb-command', (event, arg) => {
|
||||
const success = d => {
|
||||
if (!event.sender.isDestroyed()) {
|
||||
event.sender.send('adb-command', { command: arg.command, resp: d, uuid: arg.uuid });
|
||||
}
|
||||
};
|
||||
const reject = e => {
|
||||
if (!event.sender.isDestroyed()) {
|
||||
event.sender.send('adb-command', { command: arg.command, error: e, uuid: arg.uuid });
|
||||
}
|
||||
};
|
||||
const status = d => {
|
||||
if (!event.sender.isDestroyed()) {
|
||||
event.sender.send('adb-command', { command: arg.command, status: d, uuid: arg.uuid });
|
||||
}
|
||||
};
|
||||
switch (arg.command) {
|
||||
case 'setupAdb':
|
||||
adb.setupAdb(arg.settings.adbPath, success, reject);
|
||||
break;
|
||||
case 'endLogcat':
|
||||
adb.endLogcat();
|
||||
success('Done.');
|
||||
break;
|
||||
case 'logcat':
|
||||
adb.logcat(arg.settings.serial, arg.settings.tag, arg.settings.priority, success, status, reject);
|
||||
break;
|
||||
case 'listDevices':
|
||||
adb.listDevices(success, reject);
|
||||
break;
|
||||
case 'getPackages':
|
||||
adb.getPackages(arg.settings.serial, success, reject);
|
||||
break;
|
||||
case 'shell':
|
||||
adb.shell(arg.settings.serial, arg.settings.command, success, reject);
|
||||
break;
|
||||
case 'readdir':
|
||||
adb.readdir(arg.settings.serial, arg.settings.path, success, reject);
|
||||
break;
|
||||
case 'push':
|
||||
adb.push(arg.settings.serial, arg.settings.path, arg.settings.savePath, success, status, reject);
|
||||
break;
|
||||
case 'pull':
|
||||
adb.pull(arg.settings.serial, arg.settings.path, arg.settings.savePath, success, status, reject);
|
||||
break;
|
||||
case 'stat':
|
||||
adb.stat(arg.settings.serial, arg.settings.path, success, reject);
|
||||
break;
|
||||
case 'install':
|
||||
adb.install(arg.settings.serial, arg.settings.path, arg.settings.isLocal, success, status, reject);
|
||||
break;
|
||||
case 'uninstall':
|
||||
adb.uninstall(arg.settings.serial, arg.settings.packageName, success, reject);
|
||||
break;
|
||||
case 'installRemote':
|
||||
adb.installRemote(arg.settings.serial, arg.settings.path, success, reject);
|
||||
break;
|
||||
case 'clear':
|
||||
adb.clear(arg.settings.serial, arg.settings.packageName, success, reject);
|
||||
break;
|
||||
case 'connect':
|
||||
adb.connect(arg.settings.deviceIp, success, reject);
|
||||
break;
|
||||
case 'disconnect':
|
||||
adb.disconnect(success, reject);
|
||||
break;
|
||||
case 'usb':
|
||||
adb.usb(arg.settings.serial, success, reject);
|
||||
break;
|
||||
case 'tcpip':
|
||||
adb.tcpip(arg.settings.serial, success, reject);
|
||||
break;
|
||||
case 'setProperties':
|
||||
adb.setProperties(arg.settings.serial, arg.settings.command, success, reject);
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
const https = require('https');
|
||||
const http = require('http');
|
||||
const fs = require('fs');
|
||||
const { basename } = require('path');
|
||||
const Url = require('url');
|
||||
|
||||
const TIMEOUT = 60000;
|
||||
|
||||
module.exports = function(url, path, progress) {
|
||||
const uri = Url.parse(url);
|
||||
if (!path) {
|
||||
path = basename(uri.path);
|
||||
}
|
||||
const file = fs.createWriteStream(path);
|
||||
|
||||
function get(url, callback) {
|
||||
let request = (uri.protocol === 'https:' ? https : http).get(url, function(response) {
|
||||
if (response.headers.location) {
|
||||
get(response.headers.location, callback);
|
||||
} else {
|
||||
callback(null, response);
|
||||
}
|
||||
});
|
||||
|
||||
request.setTimeout(TIMEOUT, function() {
|
||||
request.abort();
|
||||
callback(new Error(`request timeout after ${TIMEOUT / 1000.0}s`));
|
||||
});
|
||||
}
|
||||
|
||||
return new Promise(function(resolve, reject) {
|
||||
get(uri.href, (err, res) => {
|
||||
if (err) {
|
||||
return console.log(err);
|
||||
}
|
||||
const len = parseInt(res.headers['content-length'], 10);
|
||||
let downloaded = 0;
|
||||
let percent = 0;
|
||||
res.on('data', function(chunk) {
|
||||
file.write(chunk);
|
||||
downloaded += chunk.length;
|
||||
percent = Math.round((10000 * downloaded) / len) / 100;
|
||||
progress(percent);
|
||||
})
|
||||
.on('end', function() {
|
||||
file.end();
|
||||
resolve();
|
||||
})
|
||||
.on('error', function(err) {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
const Command = require('adbkit/lib/adb/command');
|
||||
const Protocol = require('adbkit/lib/adb/protocol');
|
||||
|
||||
const RE_KEYVAL = /^\[([\s\S]*?)\]: \[([\s\S]*?)\]\r?$/gm;
|
||||
|
||||
export class SetPropertiesCommand extends Command {
|
||||
constructor(arg) {
|
||||
super(arg);
|
||||
}
|
||||
|
||||
execute(command) {
|
||||
this._send('shell:setprop ' + command);
|
||||
return this.parser.readAscii(4).then(
|
||||
(function(_this) {
|
||||
return function(reply) {
|
||||
switch (reply) {
|
||||
case Protocol.OKAY:
|
||||
return _this.parser.readAll().then(function(data) {
|
||||
return _this._parseProperties(data.toString());
|
||||
});
|
||||
case Protocol.FAIL:
|
||||
return _this.parser.readError();
|
||||
default:
|
||||
return _this.parser.unexpected(reply, 'OKAY or FAIL');
|
||||
}
|
||||
};
|
||||
})(this)
|
||||
);
|
||||
}
|
||||
|
||||
_parseProperties(value) {
|
||||
var match, properties;
|
||||
properties = {};
|
||||
while ((match = RE_KEYVAL.exec(value))) {
|
||||
properties[match[1]] = match[2];
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import { promisify } from 'util';
|
||||
|
||||
export interface EnvironmentConfig {
|
||||
userDataPath: string;
|
||||
}
|
||||
|
||||
interface LogService {
|
||||
error(error: any);
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns whether the provided parameter is undefined.
|
||||
*/
|
||||
export function isUndefined(obj: any): obj is undefined {
|
||||
return typeof obj === 'undefined';
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns whether the provided parameter is undefined or null.
|
||||
*/
|
||||
export function isUndefinedOrNull(obj: any): obj is undefined | null {
|
||||
return isUndefined(obj) || obj === null;
|
||||
}
|
||||
|
||||
type StorageDatabase = { [key: string]: any };
|
||||
|
||||
export class FileStorage {
|
||||
private _database: StorageDatabase | null = null;
|
||||
private lastFlushedSerializedDatabase: string | null = null;
|
||||
|
||||
constructor(private dbPath: string, private onError: (error: Error) => void) {}
|
||||
|
||||
private get database(): StorageDatabase {
|
||||
if (!this._database) {
|
||||
this._database = this.loadSync();
|
||||
}
|
||||
|
||||
return this._database;
|
||||
}
|
||||
|
||||
async init(): Promise<void> {
|
||||
if (this._database) {
|
||||
return;
|
||||
}
|
||||
|
||||
const database = await this.loadAsync();
|
||||
|
||||
if (this._database) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._database = database;
|
||||
}
|
||||
|
||||
private loadSync(): StorageDatabase {
|
||||
try {
|
||||
this.lastFlushedSerializedDatabase = fs.readFileSync(this.dbPath).toString();
|
||||
|
||||
return JSON.parse(this.lastFlushedSerializedDatabase);
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
this.onError(error);
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
private async loadAsync(): Promise<StorageDatabase> {
|
||||
try {
|
||||
const readFile = promisify(fs.readFile);
|
||||
this.lastFlushedSerializedDatabase = (await readFile(this.dbPath)).toString();
|
||||
|
||||
return JSON.parse(this.lastFlushedSerializedDatabase);
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
this.onError(error);
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
getItem<T>(key: string, defaultValue: T): T;
|
||||
getItem<T>(key: string, defaultValue?: T): T | undefined;
|
||||
getItem<T>(key: string, defaultValue?: T): T | undefined {
|
||||
const res = this.database[key];
|
||||
if (isUndefinedOrNull(res)) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
setItem(key: string, data?: object | string | number | boolean | undefined | null): void {
|
||||
if (isUndefinedOrNull(data)) {
|
||||
return this.removeItem(key);
|
||||
}
|
||||
|
||||
const isPrimitive = typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean';
|
||||
const noUpdateNeeded = isPrimitive && this.database[key] === data;
|
||||
if (noUpdateNeeded) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.database[key] = data;
|
||||
this.saveSync();
|
||||
}
|
||||
|
||||
removeItem(key: string): void {
|
||||
if (!isUndefined(this.database[key])) {
|
||||
this.database[key] = undefined;
|
||||
this.saveSync();
|
||||
}
|
||||
}
|
||||
|
||||
private saveSync(): void {
|
||||
const serializedDatabase = JSON.stringify(this.database, null, 4);
|
||||
const hasNotChanged = serializedDatabase === this.lastFlushedSerializedDatabase;
|
||||
if (hasNotChanged) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
fs.writeFileSync(this.dbPath, serializedDatabase);
|
||||
this.lastFlushedSerializedDatabase = serializedDatabase;
|
||||
} catch (error) {
|
||||
this.onError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class StateStorage {
|
||||
private static readonly STATE_FILE = 'state-storage.json';
|
||||
|
||||
private fileStorage: FileStorage;
|
||||
|
||||
constructor(environment: EnvironmentConfig, logService: LogService) {
|
||||
const storagePath = path.join(environment.userDataPath, StateStorage.STATE_FILE);
|
||||
this.fileStorage = new FileStorage(storagePath, error => logService.error(error));
|
||||
}
|
||||
|
||||
init(): Promise<void> {
|
||||
return this.fileStorage.init();
|
||||
}
|
||||
|
||||
getItem<T>(key: string, defaultValue: T): T;
|
||||
getItem<T>(key: string, defaultValue: T | undefined): T | undefined;
|
||||
getItem<T>(key: string, defaultValue?: T): T | undefined {
|
||||
return this.fileStorage.getItem(key, defaultValue);
|
||||
}
|
||||
|
||||
setItem(key: string, data?: object | string | number | boolean | undefined | null): void {
|
||||
this.fileStorage.setItem(key, data);
|
||||
}
|
||||
|
||||
removeItem(key: string): void {
|
||||
this.fileStorage.removeItem(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import { screen, BrowserWindow, BrowserWindowConstructorOptions, Display, Rectangle } from 'electron';
|
||||
import { StateStorage } from './state-storage';
|
||||
|
||||
type WindowMode = 'normal' | 'maximized';
|
||||
|
||||
interface WorkingArea {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface WindowState {
|
||||
width?: number;
|
||||
height?: number;
|
||||
x?: number;
|
||||
y?: number;
|
||||
mode?: WindowMode;
|
||||
display?: number;
|
||||
}
|
||||
|
||||
function defaultWindowState(): WindowState {
|
||||
return {
|
||||
width: 1024,
|
||||
height: 768,
|
||||
mode: 'normal',
|
||||
};
|
||||
}
|
||||
|
||||
export class AppWindow {
|
||||
private static WINDOW_STATE_ITEM_KEY = 'windowState';
|
||||
|
||||
private _window: BrowserWindow;
|
||||
private isClosing = false;
|
||||
|
||||
public get window(): BrowserWindow {
|
||||
return this._window;
|
||||
}
|
||||
|
||||
constructor(private stateStorage: StateStorage) {
|
||||
const state = this.stateStorage.getItem<WindowState>(AppWindow.WINDOW_STATE_ITEM_KEY, undefined);
|
||||
this.createWindow(state);
|
||||
this.registerListeners();
|
||||
}
|
||||
|
||||
private createWindow(state?: WindowState) {
|
||||
const [windowState, hasMultipleDisplays] = this.restoreWindowState(state);
|
||||
|
||||
const isMaximized = windowState.mode === 'maximized';
|
||||
const showAfterSetup = isMaximized;
|
||||
|
||||
const options: BrowserWindowConstructorOptions = {
|
||||
width: windowState.width,
|
||||
height: windowState.height,
|
||||
x: windowState.x,
|
||||
y: windowState.y,
|
||||
minWidth: 800,
|
||||
minHeight: 480,
|
||||
show: !showAfterSetup,
|
||||
frame: false,
|
||||
webPreferences: {
|
||||
nodeIntegration: true,
|
||||
},
|
||||
};
|
||||
this._window = new BrowserWindow(options);
|
||||
|
||||
// (Electron 4 regression): when running on multiple displays where the target display
|
||||
// to open the window has a larger resolution than the primary display, the window will not size
|
||||
// correctly unless we set the bounds again
|
||||
const isMacintosh = process.platform === 'darwin';
|
||||
if (isMacintosh && hasMultipleDisplays) {
|
||||
const hasAllBoundsValues = [windowState.width, windowState.height, windowState.x, windowState.y].every(
|
||||
value => typeof value === 'number'
|
||||
);
|
||||
if (hasAllBoundsValues) {
|
||||
this._window.setBounds({
|
||||
width: windowState.width,
|
||||
height: windowState.height,
|
||||
x: windowState.x,
|
||||
y: windowState.y,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (isMaximized) {
|
||||
this._window.maximize();
|
||||
|
||||
if (!this._window.isVisible()) {
|
||||
this._window.show();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private registerListeners() {
|
||||
this._window.on('close', e => {
|
||||
if (!this.isClosing) {
|
||||
e.preventDefault();
|
||||
this.isClosing = true;
|
||||
this.saveWindowState();
|
||||
this._window.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public saveWindowState() {
|
||||
this.stateStorage.setItem(AppWindow.WINDOW_STATE_ITEM_KEY, this.serializeWindowState());
|
||||
}
|
||||
|
||||
private getWorkingArea(display: Display): WorkingArea | undefined {
|
||||
if (display.workArea.width > 0 && display.workArea.height > 0) {
|
||||
return display.workArea;
|
||||
}
|
||||
|
||||
if (display.bounds.width > 0 && display.bounds.height > 0) {
|
||||
return display.bounds;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private validateWindowState(state: WindowState, displays: Display[]): WindowState {
|
||||
if (
|
||||
typeof state.x !== 'number' ||
|
||||
typeof state.y !== 'number' ||
|
||||
typeof state.width !== 'number' ||
|
||||
typeof state.height !== 'number'
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (state.width <= 0 || state.height <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (displays.length === 1) {
|
||||
const displayWorkingArea = this.getWorkingArea(displays[0]);
|
||||
if (displayWorkingArea) {
|
||||
const ensureStateInDisplayWorkingArea = () => {
|
||||
const isTooFarLeft = state.x < displayWorkingArea.x;
|
||||
if (isTooFarLeft) {
|
||||
state.x = displayWorkingArea.x;
|
||||
}
|
||||
const isTooFarUp = state.y < displayWorkingArea.y;
|
||||
if (isTooFarUp) {
|
||||
state.y = displayWorkingArea.y;
|
||||
}
|
||||
};
|
||||
ensureStateInDisplayWorkingArea();
|
||||
const isTooWide = state.width > displayWorkingArea.width;
|
||||
if (isTooWide) {
|
||||
state.width = displayWorkingArea.width;
|
||||
}
|
||||
const isTooTall = state.height > displayWorkingArea.height;
|
||||
if (isTooTall) {
|
||||
state.height = displayWorkingArea.height;
|
||||
}
|
||||
const isTooFarRight = state.x > displayWorkingArea.x + displayWorkingArea.width - 128;
|
||||
if (isTooFarRight) {
|
||||
state.x = displayWorkingArea.x + displayWorkingArea.width - 128;
|
||||
}
|
||||
const isTooFarDown = state.y > displayWorkingArea.y + displayWorkingArea.height - 128;
|
||||
if (isTooFarDown) {
|
||||
state.y = displayWorkingArea.y + displayWorkingArea.height - 128;
|
||||
}
|
||||
ensureStateInDisplayWorkingArea();
|
||||
}
|
||||
return state;
|
||||
} else {
|
||||
const display = screen.getDisplayMatching({ x: state.x, y: state.y, width: state.width, height: state.height });
|
||||
const displayWorkingArea = this.getWorkingArea(display);
|
||||
if (
|
||||
display &&
|
||||
displayWorkingArea &&
|
||||
state.x + state.width > displayWorkingArea.x &&
|
||||
state.y + state.height > displayWorkingArea.y &&
|
||||
state.x < displayWorkingArea.x + displayWorkingArea.width &&
|
||||
state.y < displayWorkingArea.y + displayWorkingArea.height
|
||||
) {
|
||||
return state;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getBounds(): Rectangle {
|
||||
const pos = this._window.getPosition();
|
||||
const dimension = this._window.getSize();
|
||||
return { x: pos[0], y: pos[1], width: dimension[0], height: dimension[1] };
|
||||
}
|
||||
|
||||
serializeWindowState(): WindowState {
|
||||
if (!this._window) {
|
||||
return defaultWindowState();
|
||||
}
|
||||
|
||||
const display = screen.getDisplayMatching(this.getBounds());
|
||||
const mode: WindowMode = this._window.isMaximized() ? 'maximized' : 'normal';
|
||||
const bounds = mode === 'normal' ? this.getBounds() : this._window.getNormalBounds();
|
||||
const state: WindowState = {
|
||||
mode,
|
||||
x: bounds.x,
|
||||
y: bounds.y,
|
||||
width: bounds.width,
|
||||
height: bounds.height,
|
||||
display: display ? display.id : undefined,
|
||||
};
|
||||
return state;
|
||||
}
|
||||
|
||||
private restoreWindowState(state?: WindowState): [WindowState, boolean] {
|
||||
const displays = screen.getAllDisplays();
|
||||
const hasMultipleDisplays = displays.length > 1;
|
||||
if (state) {
|
||||
state = this.validateWindowState(state, displays);
|
||||
}
|
||||
return [state || defaultWindowState(), hasMultipleDisplays];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user