xash93d/src/Instance.js
2022-10-28 02:48:42 -06:00

148 lines
3.4 KiB
JavaScript
Executable File

const Console = require('./Console')
const EmulatedIDB = require('./EmulatedIDB')
const ModPackage = require('./ModPackage')
const handleIframe = require('./util/handleIframe'),
// gzip = require('./util/gzip'),
promisify = require('./util/promisify')
const openAsync = promisify($file.open),
{ Buffer } = le._apps.abnt
class Instance {
constructor(app, modPath) {
let self = this,
bundleDir = app.bundle.for('/import/')
let width = 640 + 7 - 9,
height = 480 + 28 - 30
const options = {
title: 'Xash3D',
// url: "data:text/plain,",
url: app.bundle.openSync('./main.html', 'URL'),
// icon: app.icon,
// Windows93 adds to these to compensate for title height and such,
// but we want it to match the canvas resolution.
// We want 647 x 508 on the window element
width,
height,
minWidth: width,
minHeight: height,
bodyClass: 'xash3d_main',
menu: [
{
name: 'Game',
items: [
{
name: 'Open console',
action: function() {
self.openConsole()
self.focusConsole()
}
}
]
}
],
onready() {
const { iframe } = self.window.el
iframe.contentWindow.instance = self
handleIframe(iframe, '/import/')
},
onclose() {
self.consoleWindow?.close()
self.closed = true
app.cleanInstances()
}
}
this.consoleWindow
this.window = $window(options)
this.closed = false
this.app = app
this.assets = new Map()
this.import = new Proxy(this.assets, {
get(target, prop) {
console.log(`LOADING "${prop}"`)
if( !target.has(prop) && bundleDir.access(prop) ) {
target.set(prop, bundleDir.openSync(prop, 'URL') )
}
return target.get(prop)
}
})
this.emulatedIDB = new EmulatedIDB()
this.arguments = []
this.package = this.loadPackage(modPath)
.then(mod => {
this.window.changeTitle(mod.manifest.name)
return mod
})
.catch(console.error)
this.console = new Console(() => this.onQuit())
this.onCloseConsole
console.log('INSTANCE:', this)
}
async loadPackage(path) {
let buffer = await openAsync(path, 'ArrayBuffer'),
mod = await ModPackage.unpack(buffer)
return mod
}
openConsole() {
let self = this
if(this.consoleWindow)
// Put focus on the window instead
this.focusConsole()
const options = {
title: 'Xash Console',
bodyClass: 'ui_terminal xash3d_terminal',
onready() {
self.console.attachTo(self.consoleWindow)
self.focusConsole()
},
onclose() {
self.console.unattach()
self.onCloseConsole?.call()
}
}
this.consoleWindow = $window(options)
}
focusConsole() {
this.consoleWindow.el.header.click()
}
// Triggered when the user presses "quit" on the main menu
onQuit() {
if(this.consoleWindow) {
this.onCloseConsole = () => {
// Prevent .kill from trying to close the console
this.consoleWindow = null
this.kill()
}
} else {
this.kill()
}
}
kill() {
this.window?.close()
this.consoleWindow?.close()
delete this.assets // pls my memory
}
}
module.exports = Instance