2018-08-23 07:03:28 +02:00
|
|
|
const fs = require('fs-extra')
|
|
|
|
|
2019-02-03 22:49:09 +01:00
|
|
|
const { CONSTANTS } = require('./constants')
|
2018-08-23 07:03:28 +02:00
|
|
|
|
2018-08-25 05:55:03 +02:00
|
|
|
/**
|
|
|
|
* Returns the current machine's state - either what
|
|
|
|
* we have saved or alternatively the default state.
|
|
|
|
*
|
|
|
|
* @returns {ArrayBuffer}
|
|
|
|
*/
|
2018-08-23 07:25:17 +02:00
|
|
|
function getState () {
|
2019-02-03 23:02:30 +01:00
|
|
|
const statePath = fs.existsSync(CONSTANTS.STATE_PATH)
|
|
|
|
? CONSTANTS.STATE_PATH
|
|
|
|
: CONSTANTS.DEFAULT_STATE_PATH
|
|
|
|
|
2019-02-04 00:24:29 +01:00
|
|
|
if (fs.existsSync(statePath)) {
|
|
|
|
return fs.readFileSync(statePath).buffer
|
|
|
|
}
|
2018-08-23 07:03:28 +02:00
|
|
|
}
|
|
|
|
|
2018-08-25 05:55:03 +02:00
|
|
|
/**
|
|
|
|
* Resets a saved state by simply deleting it.
|
|
|
|
*
|
|
|
|
* @returns {Promise<void>}
|
|
|
|
*/
|
|
|
|
async function resetState () {
|
2019-02-03 22:49:09 +01:00
|
|
|
if (fs.existsSync(CONSTANTS.STATE_PATH)) {
|
|
|
|
return fs.remove(CONSTANTS.STATE_PATH)
|
2018-08-25 05:55:03 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Saves the current VM's state.
|
|
|
|
*
|
|
|
|
* @returns {Promise<void>}
|
|
|
|
*/
|
|
|
|
async function saveState () {
|
|
|
|
return new Promise((resolve) => {
|
|
|
|
if (!window.emulator || !window.emulator.save_state) {
|
|
|
|
return resolve()
|
|
|
|
}
|
|
|
|
|
|
|
|
window.emulator.save_state(async (error, newState) => {
|
|
|
|
if (error) {
|
2019-02-03 22:49:09 +01:00
|
|
|
console.warn(`State: Could not save state`, error)
|
2018-08-25 05:55:03 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-02-03 22:49:09 +01:00
|
|
|
await fs.outputFile(CONSTANTS.STATE_PATH, Buffer.from(newState))
|
2018-08-25 05:55:03 +02:00
|
|
|
|
2019-02-03 22:49:09 +01:00
|
|
|
console.log(`State: Saved state to ${CONSTANTS.STATE_PATH}`)
|
2018-08-25 05:55:03 +02:00
|
|
|
|
|
|
|
resolve()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Restores the VM's state.
|
|
|
|
*/
|
|
|
|
function restoreState () {
|
2019-02-03 22:49:09 +01:00
|
|
|
const state = getState()
|
|
|
|
|
|
|
|
// Nothing to do with if we don't have a state
|
|
|
|
if (!state) {
|
|
|
|
console.log(`State: No state present, not restoring.`)
|
|
|
|
}
|
|
|
|
|
2018-08-25 05:55:03 +02:00
|
|
|
try {
|
2019-02-03 22:49:09 +01:00
|
|
|
window.emulator.restore_state(state)
|
2018-08-25 05:55:03 +02:00
|
|
|
} catch (error) {
|
2019-02-03 22:49:09 +01:00
|
|
|
console.log(`State: Could not read state file. Maybe none exists?`, error)
|
2018-08-25 05:55:03 +02:00
|
|
|
}
|
2018-08-23 07:03:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
2018-08-25 05:55:03 +02:00
|
|
|
saveState,
|
|
|
|
restoreState,
|
2018-08-23 07:03:28 +02:00
|
|
|
resetState,
|
|
|
|
getState
|
|
|
|
}
|