Compare commits

..

No commits in common. "master" and "0.2.3" have entirely different histories.

11 changed files with 268 additions and 2488 deletions

View file

@ -1,35 +0,0 @@
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": "eslint:recommended",
"overrides": [
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"ignorePatterns": [
"src/glkOte/*.js"
],
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"never"
]
}
}

View file

@ -1,5 +1,4 @@
# cheap-glkote # cheap-glkote
[![NPM Version](https://img.shields.io/npm/v/cheap-glkote.svg?style=flat-square)](https://www.npmjs.org/package/cheap-glkote)
This is an abstract implementation of the [GlkOte](https://github.com/erkyrath/glkote) library interface designed to be used with [Emglken](https://github.com/curiousdannii/emglken).<br> This is an abstract implementation of the [GlkOte](https://github.com/erkyrath/glkote) library interface designed to be used with [Emglken](https://github.com/curiousdannii/emglken).<br>
Can be used in Node.js or in a web browser. Can be used in Node.js or in a web browser.
@ -11,24 +10,22 @@ This repository includes examples of [stdio interface implementation](https://gi
### Initialization ### Initialization
```js ```js
const { Dialog, GlkOte, send } = const { glkInterface, sendFn } = CheapGlkOte(handlers [, loggers])
CheapGlkOte(handlers [, { loggers, size }])
``` ```
### Input ### Input
```js ```js
send('open door', inputType, targetWindow) sendFn('open door', windowObject)
``` ```
You can obtain `inputType` and `id` of `targetWindow` inside the `onUpdateInputs` handler.<br> You can received `windowObject` in `onUpdateWindows` handler.<br>
You can specify `targetWindow` by its `id` inside the `onUpdateWindows` handler.<br> You should respect input type setted by `onUpdateInputs`.
As I know, `inputType` can be `line` or `char`.
### Output and lifecycle ### Output and lifecycle
```js ```js
const handlers = { const handlers = {
onInit: () => { onInit: () => {
/** /**
* It's time to initialize the user interface. * It's time to prepare the user interface.
*/ */
}, },
onUpdateWindows: windows => { onUpdateWindows: windows => {
@ -36,11 +33,10 @@ const handlers = {
* Game wants to change the number of windows. * Game wants to change the number of windows.
*/ */
}, },
onUpdateInputs: data => { onUpdateInputs: type => {
/** /**
* Game wants to change input type. * Game wants to change input type.
* 'data' is a list with info about * Supported types: 'char', 'line'.
* the target window and the input type.
*/ */
}, },
onUpdateContent: messages => { onUpdateContent: messages => {
@ -87,16 +83,7 @@ Default loggers:
const defaultLoggers = { const defaultLoggers = {
log: console.log, log: console.log,
warning: console.warn, warning: console.warn,
error: console.error, error: console.error
}
```
### Size
Default sizes:
```js
const defaultSize = {
width: 80,
height: 25,
} }
``` ```

View file

@ -4,12 +4,11 @@
* @see: https://github.com/curiousdannii/emglken/blob/master/bin/emglken.js * @see: https://github.com/curiousdannii/emglken/blob/master/bin/emglken.js
*/ */
import { readFileSync } from 'fs' const fs = require('fs')
import minimist from 'minimist' const minimist = require('minimist')
import CheapGlkOte from '../src/index.js' const CheapGlkOte = require('../src/')
const { handlers } = require('./stdio')
import { handlers } from './stdio.js'
const formats = [ const formats = [
{ {
@ -51,19 +50,13 @@ if (!format) {
process.exit(0) process.exit(0)
} }
import(`emglken/src/${format.id}.js`) const { glkInterface, sendFn } = CheapGlkOte(handlers)
.then(({default: engine}) => engine) handlers.setSend(sendFn)
.then((engine) => new engine())
.then((vm) => {
const cheapGlkOte = CheapGlkOte(handlers)
handlers.setSend(cheapGlkOte.send) const engine = require('emglken/src/' + format.engine)
const vm = new engine()
vm.init(readFileSync(storyfile), { vm.prepare(
Dialog: cheapGlkOte.Dialog, fs.readFileSync(storyfile),
GlkOte: cheapGlkOte.GlkOte, glkInterface)
Glk: {}, vm.start()
wasmBinary: readFileSync(new URL(`../node_modules/emglken/build/${format.id}-core.wasm`, import.meta.url))
})
vm.start()
})

View file

@ -2,22 +2,20 @@
* @see: https://github.com/curiousdannii/glkote-term/blob/master/src/glkote-dumb.js * @see: https://github.com/curiousdannii/glkote-term/blob/master/src/glkote-dumb.js
*/ */
import { createInterface, emitKeypressEvents } from 'readline' const readline = require('readline')
import MuteStream from 'mute-stream' const MuteStream = require('mute-stream')
import ansiEsc from 'ansi-escapes' const ansiEscapes = require('ansi-escapes')
const stdin = process.stdin const stdin = process.stdin
const stdout = new MuteStream() const stdout = new MuteStream()
stdout.pipe(process.stdout) stdout.pipe(process.stdout)
const rl = createInterface({ const rl = readline.createInterface({
input: stdin, input: stdin,
output: stdout, output: stdout,
prompt: '' prompt: ''
}) })
let currentWindowId = null
let currentWindow = null let currentWindow = null
let currentInputType = null
let send = _ => _ let send = _ => _
@ -29,38 +27,28 @@ const onInit = () => {
if (stdin.isTTY) { if (stdin.isTTY) {
stdin.setRawMode(true) stdin.setRawMode(true)
} }
emitKeypressEvents(stdin) readline.emitKeypressEvents(stdin)
rl.resume() rl.resume()
clearScreen()
} }
const onUpdateWindows = windows => { const onUpdateWindows = windows => {
currentWindow = currentWindowId currentWindow = windows
? windows .filter(x => x.type === 'buffer')
.find(x => x.id === currentWindowId) .slice(-1)[0]
: windows
.filter(x => x.type === 'buffer')
.slice(-1)[0]
} }
const onUpdateInputs = data => { const onUpdateInputs = type => {
if (data.length === 0) return null type
const { id, type } = data[0] ? attach_handlers(type)
: detach_handlers()
currentWindowId = id
if (['char', 'line'].includes(type)) {
detach_handlers()
attach_handlers(type)
}
} }
const clearScreen = () => { const onUpdateContent = allMessages => {
stdout.write('\u001B[2J\u001B[0;0f') const messages = allMessages.filter(
} content => content.id === currentWindow.id
)[0]
const drawBuffer = messages => { return messages.text.forEach(({ append, content }) => {
messages.text.forEach(({ append, content }) => {
if (!append) { if (!append) {
stdout.write('\n') stdout.write('\n')
} }
@ -71,7 +59,7 @@ const drawBuffer = messages => {
if (x.style === 'input') { if (x.style === 'input') {
if (stdout.isTTY) { if (stdout.isTTY) {
stdout.write(ansiEsc.eraseLines(2)) stdout.write(ansiEscapes.eraseLines(2))
stdout.write('> ') stdout.write('> ')
} }
} }
@ -85,32 +73,10 @@ const drawBuffer = messages => {
}) })
} }
const drawGrid = messages => { const onDisable = disable =>
clearScreen() disable
messages.lines ? detach_handlers()
.map(x => x.content) : attach_handlers()
.map(([x]) => x)
.map(({text}) => text)
.map(x => x.trim())
.forEach(x => stdout.write(`${x}\n`))
}
const onUpdateContent = allMessages => {
detach_handlers()
const messages = allMessages.find(
content => content.id === currentWindow.id
)
;({
'buffer': drawBuffer,
'grid': drawGrid
})[currentWindow.type](messages)
}
const onDisable = disable => {
if (disable) detach_handlers()
}
const onExit = () => { const onExit = () => {
detach_handlers() detach_handlers()
@ -119,8 +85,6 @@ const onExit = () => {
} }
const onFileNameRequest = (tosave, usage, gameid, callback) => { const onFileNameRequest = (tosave, usage, gameid, callback) => {
stdout.write('\n')
stdout.write(gameid, tosave)
stdout.write('\n') stdout.write('\n')
rl.question( rl.question(
'Please enter a file name: ', 'Please enter a file name: ',
@ -129,10 +93,10 @@ const onFileNameRequest = (tosave, usage, gameid, callback) => {
: null)) : null))
} }
const onFileRead = (dirent) => const onFileRead = (dirent, israw) =>
void console.log('onFileRead:', dirent) void console.log('onFileRead:', dirent)
const onFileWrite = (dirent, content) => const onFileWrite = (dirent, content, israw) =>
void console.log('onFileWrite:', dirent, content.length) void console.log('onFileWrite:', dirent, content.length)
const handle_char_input = (str, key) => { const handle_char_input = (str, key) => {
@ -141,6 +105,8 @@ const handle_char_input = (str, key) => {
'\t': 'tab', '\t': 'tab',
} }
detach_handlers()
// Make sure this char isn't being remembered for the next line input // Make sure this char isn't being remembered for the next line input
rl._line_buffer = null rl._line_buffer = null
rl.line = '' rl.line = ''
@ -151,12 +117,10 @@ const handle_char_input = (str, key) => {
str || str ||
key.name.replace(/f(\d+)/, 'func$1') key.name.replace(/f(\d+)/, 'func$1')
send(res, currentInputType, currentWindow) send(res, currentWindow)
detach_handlers()
} }
const attach_handlers = type => { const attach_handlers = type => {
currentInputType = type
if (type === 'char') { if (type === 'char') {
stdout.mute() stdout.mute()
stdin.on('keypress', handle_char_input) stdin.on('keypress', handle_char_input)
@ -170,18 +134,18 @@ const detach_handlers = () => {
stdin.removeListener('keypress', handle_char_input) stdin.removeListener('keypress', handle_char_input)
rl.removeListener('line', handle_line_input) rl.removeListener('line', handle_line_input)
stdout.unmute() stdout.unmute()
currentInputType = null
} }
const handle_line_input = line => { const handle_line_input = line => {
if (stdout.isTTY) { if (stdout.isTTY) {
stdout.write(ansiEsc.eraseLines(1)) stdout.write(ansiEscapes.eraseLines(1))
} }
send(line, currentInputType, currentWindow)
detach_handlers() detach_handlers()
send(line, currentWindow)
} }
export const handlers = { module.exports.handlers = {
onInit, onInit,
onUpdateWindows, onUpdateWindows,
onUpdateInputs, onUpdateInputs,

2003
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{ {
"name": "cheap-glkote", "name": "cheap-glkote",
"version": "0.5.1", "version": "0.2.3",
"description": "Abstract JavaScript implementation of GlkOte", "description": "Abstract JavaScript implementation of GlkOte",
"author": "He4eT <He4eTHb1u@gmail.com>", "author": "He4eT <He4eTHb1u@gmail.com>",
"license": "MIT", "license": "MIT",
@ -10,26 +10,17 @@
"interactive fiction", "interactive fiction",
"interactive-fiction" "interactive-fiction"
], ],
"type": "module",
"engines": {
"node": ">=14.0.0"
},
"main": "src/index.js", "main": "src/index.js",
"files": [
"/src"
],
"repository": "https://github.com/He4eT/cheap-glkote", "repository": "https://github.com/He4eT/cheap-glkote",
"bugs": "https://github.com/He4eT/cheap-glkote/issues", "bugs": "https://github.com/He4eT/cheap-glkote/issues",
"dependencies": {},
"devDependencies": { "devDependencies": {
"ansi-escapes": "^4.0.0", "ansi-escapes": "^4.0.0",
"emglken": "^0.5.2", "emglken": "^0.3.3",
"eslint": "^8.41.0",
"minimist": "^1.2.5", "minimist": "^1.2.5",
"mute-stream": "0.0.8" "mute-stream": "0.0.8"
}, },
"scripts": { "scripts": {
"lint": "eslint bin/ src/",
"lint:fix": "eslint --fix bin/ src/",
"play": "node ./bin/player.stdio.js", "play": "node ./bin/player.stdio.js",
"test": "./tests/runtests.sh" "test": "./tests/runtests.sh"
} }

View file

@ -2,34 +2,41 @@
* @see: https://github.com/curiousdannii/glkote-term/blob/master/src/glkote-dumb.js * @see: https://github.com/curiousdannii/glkote-term/blob/master/src/glkote-dumb.js
*/ */
import GlkOte from './glkOte/glkote-term.js' const GlkOte = require('./glkOte/glkote-term')
class CheapGlkOte extends GlkOte { class CheapGlkOte extends GlkOte {
constructor(handlers, loggers, size) { constructor(handlers, loggers) {
super(size) super()
this.current_input_type = null
this.handlers = handlers this.handlers = handlers
this.loggers = loggers
} }
sendFn (message, type, window) { sendFn(message, window) {
this.send_response( this.send_response(
type, this.current_input_type,
window, window,
message) message)
this.current_input_type = null
} }
init (iface) { init(iface) {
this.handlers.onInit() this.handlers.onInit()
super.init(iface) super.init(iface)
} }
update_inputs (data) { update_inputs(data) {
if (!data.length) return [] if (!data.length) return null
this.handlers.onUpdateInputs(data)
const { type } = data[0]
if (['char', 'line'].includes(type)) {
this.current_input_type = type
this.handlers.onUpdateInputs(type)
}
} }
accept_specialinput (data) { accept_specialinput(data) {
if (data.type === 'fileref_prompt') { if (data.type === 'fileref_prompt') {
const callback = ref => const callback = ref =>
this.send_response( this.send_response(
@ -46,38 +53,44 @@ class CheapGlkOte extends GlkOte {
} }
} }
update_content (messages) { update_content(messages) {
this.handlers.onUpdateContent(messages) this.handlers.onUpdateContent(messages)
} }
exit () { exit() {
this.handlers.onExit() this.handlers.onExit()
super.exit() super.exit()
} }
cancel_inputs (data) { cancel_inputs(data) {
this.handlers.onUpdateInputs(data) if (data.length === 0) {
this.current_input_type = null
this.handlers.onUpdateInputs(null)
}
} }
disable (data) { disable(disable) {
this.handlers.onDisable(data) this.disabled = disable
this.handlers.onDisable(disable)
} }
update_windows (windows) { update_windows(windows) {
this.handlers.onUpdateWindows(windows) if (windows.length) {
this.handlers.onUpdateWindows(windows)
}
} }
log (message) { log(message) {
this.loggers.log(message) loggers.log(message)
} }
warning (message) { warning(message) {
this.loggers.warn(message) loggers.warn(message)
} }
error (message) { error(message) {
this.loggers.error(message) loggers.error(message)
} }
} }
export default CheapGlkOte module.exports = CheapGlkOte

View file

@ -7,20 +7,11 @@ class FakeDialog {
constructor(handlers, loggers) { constructor(handlers, loggers) {
this.streaming = false this.streaming = false
this.handlers = handlers this.handlers = handlers
this.loggers = loggers
} }
file_ref_exists({ usage }) { file_ref_exists = ref => false
return usage === 'save'
? true
: false
}
file_remove_ref () { file_construct_ref(filename, usage, gameid) {
return true
}
file_construct_ref(filename, usage) {
return { return {
filename, filename,
usage: usage || '' usage: usage || ''
@ -41,16 +32,16 @@ class FakeDialog {
} }
log(message) { log(message) {
this.loggers.log(message) loggers.log(message)
} }
warning(message) { warning(message) {
this.loggers.warn(message) loggers.warn(message)
} }
error(message) { error(message) {
this.loggers.error(message) loggers.error(message)
} }
} }
export default FakeDialog module.exports = FakeDialog

View file

@ -1,12 +1,10 @@
'use strict';
/* GlkAPI -- a Javascript Glk API for IF interfaces /* GlkAPI -- a Javascript Glk API for IF interfaces
* GlkOte Library: version 2.3.2. * GlkOte Library: version 2.2.3.
* Glk API which this implements: version 0.7.4. * Glk API which this implements: version 0.7.4.
* Designed by Andrew Plotkin <erkyrath@eblong.com> * Designed by Andrew Plotkin <erkyrath@eblong.com>
* <http://eblong.com/zarf/glk/glkote.html> * <http://eblong.com/zarf/glk/glkote.html>
* *
* This Javascript library is copyright 2010-20 by Andrew Plotkin. * This Javascript library is copyright 2010-16 by Andrew Plotkin.
* It is distributed under the MIT license; see the "LICENSE" file. * It is distributed under the MIT license; see the "LICENSE" file.
* *
* This file is a Glk API compatibility layer for glkote.js. It offers a * This file is a Glk API compatibility layer for glkote.js. It offers a
@ -40,16 +38,21 @@
and will also double the write-count in a stream. and will also double the write-count in a stream.
*/ */
/* All state is contained in GlkClass. */ /* Put everything inside the Glk namespace. */
var GlkClass = function() {
var GlkOte = null; /* imported API object */ Glk = function() {
var VM = null; /* imported API object (the VM interface) */
var GiDispa = null; /* imported API object (the dispatch layer) */
var Blorb = null; /* imported API object (the resource layer) */
/* Environment capabilities. (Checked at init time.) */ /* The VM interface object. */
var has_canvas; var VM = null;
/* References to external libraries */
var Dialog;
var GiDispa;
var GiLoad;
var GlkOte;
/* Environment capabilities */
var support = {};
/* Options from the vm_options object. */ /* Options from the vm_options object. */
var option_exit_warning; var option_exit_warning;
@ -67,6 +70,60 @@ var event_generation = 0;
var current_partial_inputs = null; var current_partial_inputs = null;
var current_partial_outputs = null; var current_partial_outputs = null;
// Set external variable references
function set_references( vm_options )
{
if ( vm_options.Dialog )
{
Dialog = vm_options.Dialog;
}
if ( !Dialog )
{
if ( typeof window !== 'undefined' && window.Dialog )
{
Dialog = window.Dialog;
}
else
{
throw new Error( 'No reference to Dialog' );
}
}
if ( vm_options.GiDispa )
{
GiDispa = vm_options.GiDispa;
}
else if ( !GiDispa && typeof window !== 'undefined' && window.GiDispa )
{
GiDispa = window.GiDispa;
}
if ( vm_options.GiLoad )
{
GiLoad = vm_options.GiLoad;
}
else if ( !GiLoad && typeof window !== 'undefined' && window.GiLoad )
{
GiLoad = window.GiLoad;
}
if ( vm_options.GlkOte )
{
GlkOte = vm_options.GlkOte;
}
if ( !GlkOte )
{
if ( typeof window !== 'undefined' && window.GlkOte )
{
GlkOte = window.GlkOte;
}
else
{
throw new Error('No reference to GlkOte');
}
}
}
/* Initialize the library, initialize the VM, and set it running. (It will /* Initialize the library, initialize the VM, and set it running. (It will
run until the first glk_select() or glk_exit() call.) run until the first glk_select() or glk_exit() call.)
@ -82,27 +139,17 @@ var current_partial_outputs = null;
library sets that up for you.) library sets that up for you.)
*/ */
function init(vm_options) { function init(vm_options) {
/* Either GlkOte was passed in or we must create one. */ /* Set references to external libraries */
if (vm_options.GlkOte) { set_references( vm_options );
GlkOte = vm_options.GlkOte;
}
else if (window.GlkOteClass) {
GlkOte = new window.GlkOteClass();
}
/* Either Blorb was passed in or we don't have one. */
if (vm_options.Blorb) {
Blorb = vm_options.Blorb;
}
/* Check for canvas support. We don't rely on jquery here. */
has_canvas = (document.createElement('canvas').getContext != undefined);
VM = vm_options.vm; VM = vm_options.vm;
GiDispa = vm_options.GiDispa; /* may be null/undefined */ if (GiDispa)
GiDispa.set_vm(VM);
vm_options.accept = accept_ui_event; vm_options.accept = accept_ui_event;
GlkOte.init(vm_options);
option_exit_warning = vm_options.exit_warning; option_exit_warning = vm_options.exit_warning;
option_do_vm_autosave = vm_options.do_vm_autosave; option_do_vm_autosave = vm_options.do_vm_autosave;
option_before_select_hook = vm_options.before_select_hook; option_before_select_hook = vm_options.before_select_hook;
@ -112,16 +159,6 @@ function init(vm_options) {
if (option_before_select_hook) { if (option_before_select_hook) {
option_before_select_hook(); option_before_select_hook();
} }
/* Initialize the lower levels. */
if (GiDispa)
GiDispa.init({ io:vm_options.io, vm:vm_options.vm });
GlkOte.init(vm_options);
}
function is_inited() {
return (VM != null && GlkOte != null);
} }
function accept_ui_event(obj) { function accept_ui_event(obj) {
@ -147,10 +184,12 @@ function accept_ui_event(obj) {
switch (obj.type) { switch (obj.type) {
case 'init': case 'init':
content_metrics = complete_metrics(obj.metrics); content_metrics = obj.metrics;
/* We ignore the support array. This library is updated in sync /* Process the support array */
with GlkOte, so we know what it supports. */ if (obj.support) {
VM.start(); obj.support.forEach(function(item) {support[item] = 1;});
}
VM.init();
break; break;
case 'external': case 'external':
@ -192,7 +231,7 @@ function accept_ui_event(obj) {
break; break;
case 'arrange': case 'arrange':
content_metrics = complete_metrics(obj.metrics); content_metrics = obj.metrics;
box = { box = {
left: content_metrics.outspacingx, left: content_metrics.outspacingx,
top: content_metrics.outspacingy, top: content_metrics.outspacingy,
@ -216,134 +255,6 @@ function accept_ui_event(obj) {
} }
} }
/* Given a partial metrics object, return one with all the required
values. Missing values will default to 0 or the standard inherited
terms. (E.g., if "inspacingx" is missing it will default to
"inspacing", then "spacing", then 0. See measure_window() in
glkote.js or data_metrics_parse() in RemGlk.)
All values in the given object will be copied over; defaulting only
applies to missing values from the required set.
*/
function complete_metrics(metrics) {
// Default values if absolutely nothing is specified.
var res = {
width: 80,
height: 50,
gridcharwidth: 1,
gridcharheight: 1,
buffercharwidth: 1,
buffercharheight: 1,
gridmarginx: 0,
gridmarginy: 0,
buffermarginx: 0,
buffermarginy: 0,
graphicsmarginx: 0,
graphicsmarginy: 0,
outspacingx: 0,
outspacingy: 0,
inspacingx: 0,
inspacingy: 0,
};
// Various ways of specifying defaults.
var val;
val = metrics.charwidth;
if (val !== undefined) {
res.gridcharwidth = val;
res.buffercharwidth = val;
}
val = metrics.charheight;
if (val !== undefined) {
res.gridcharheight = val;
res.buffercharheight = val;
}
val = metrics.margin;
if (val !== undefined) {
res.gridmarginx = val;
res.gridmarginy = val;
res.buffermarginx = val;
res.buffermarginy = val;
res.graphicsmarginx = val;
res.graphicsmarginy = val;
}
val = metrics.gridmargin;
if (val !== undefined) {
res.gridmarginx = val;
res.gridmarginy = val;
}
val = metrics.buffermargin;
if (val !== undefined) {
res.buffermarginx = val;
res.buffermarginy = val;
}
val = metrics.graphicsmargin;
if (val !== undefined) {
res.graphicsmarginx = val;
res.graphicsmarginy = val;
}
val = metrics.marginx;
if (val !== undefined) {
res.gridmarginx = val;
res.buffermarginx = val;
res.graphicsmarginx = val;
}
val = metrics.marginy;
if (val !== undefined) {
res.gridmarginy = val;
res.buffermarginy = val;
res.graphicsmarginy = val;
}
val = metrics.spacing;
if (val !== undefined) {
res.inspacingx = val;
res.inspacingy = val;
res.outspacingx = val;
res.outspacingy = val;
}
val = metrics.inspacing;
if (val !== undefined) {
res.inspacingx = val;
res.inspacingy = val;
}
val = metrics.outspacing;
if (val !== undefined) {
res.outspacingx = val;
res.outspacingy = val;
}
val = metrics.spacingx;
if (val !== undefined) {
res.inspacingx = val;
res.outspacingx = val;
}
val = metrics.spacingy;
if (val !== undefined) {
res.inspacingy = val;
res.outspacingy = val;
}
// Copy over all the supplied fields. These override the defaults above.
res = Object.assign(res, metrics);
return res;
}
function handle_arrange_input() { function handle_arrange_input() {
if (!gli_selectref) if (!gli_selectref)
return; return;
@ -542,8 +453,8 @@ function handle_line_input(disprock, input, termkey) {
VM.resume(); VM.resume();
} }
function update() { function update(type) {
var dataobj = { type: 'update', gen: event_generation }; var dataobj = { type: type || 'update', gen: event_generation };
var winarray = null; var winarray = null;
var contentarray = null; var contentarray = null;
var inputarray = null; var inputarray = null;
@ -794,27 +705,10 @@ function update() {
} }
} }
/* Return the library interface object that we were passed or created.
Call this if you want to use, e.g., the same Dialog object that GlkOte
is using.
*/
function get_library(val) {
switch (val) {
case 'VM': return VM;
case 'GlkOte': return GlkOte;
case 'GiDispa': return GiDispa;
case 'Blorb': return Blorb;
case 'Dialog': return GlkOte.getlibrary('Dialog');
}
/* Unrecognized library name. */
return null;
}
/* Wrap up the current display state as a (JSONable) object. This is /* Wrap up the current display state as a (JSONable) object. This is
called from Quixe.vm_autosave. called from Quixe.vm_autosave.
*/ */
function save_allstate() { function save_allstate() {
var Dialog = GlkOte.getlibrary('Dialog');
var res = {}; var res = {};
if (gli_rootwin) if (gli_rootwin)
@ -992,8 +886,6 @@ function save_allstate() {
*/ */
function restore_allstate(res) function restore_allstate(res)
{ {
var Dialog = GlkOte.getlibrary('Dialog');
if (gli_windowlist || gli_streamlist || gli_filereflist) if (gli_windowlist || gli_streamlist || gli_filereflist)
throw('restore_allstate: glkapi module has already been launched'); throw('restore_allstate: glkapi module has already been launched');
@ -1166,7 +1058,7 @@ function restore_allstate(res)
case strtype_Resource: case strtype_Resource:
str.resfilenum = obj.resfilenum; str.resfilenum = obj.resfilenum;
var el = Blorb.get_data_chunk(str.resfilenum); var el = GiLoad.find_data_chunk(str.resfilenum);
if (el) { if (el) {
str.buf = el.data; str.buf = el.data;
} }
@ -1251,11 +1143,6 @@ function restore_allstate(res)
function fatal_error(msg) { function fatal_error(msg) {
has_exited = true; has_exited = true;
ui_disabled = true; ui_disabled = true;
if (!GlkOte) {
// We haven't been initialized yet, so we can only try to log the error and hope someone sees it.
console.log('Fatal error:', msg);
return;
}
GlkOte.error(msg); GlkOte.error(msg);
var dataobj = { type: 'update', gen: event_generation, disable: true }; var dataobj = { type: 'update', gen: event_generation, disable: true };
dataobj.input = []; dataobj.input = [];
@ -2806,10 +2693,8 @@ function UniArrayToBE32(arr) {
up in Safari, in Opera, and in Firefox if you have Firebug installed.) up in Safari, in Opera, and in Firefox if you have Firebug installed.)
*/ */
function qlog(msg) { function qlog(msg) {
if (window.console && console.log) if (typeof console !== 'undefined' && console.log)
console.log(msg); console.log(msg);
else if (window.opera && opera.postError)
opera.postError(msg);
} }
/* RefBox: Simple class used for "call-by-reference" Glk arguments. The object /* RefBox: Simple class used for "call-by-reference" Glk arguments. The object
@ -3011,13 +2896,13 @@ function gli_window_put_string(win, val) {
gli_window_grid_canonicalize(), but I've inlined it. */ gli_window_grid_canonicalize(), but I've inlined it. */
if (win.cursorx < 0) if (win.cursorx < 0)
win.cursorx = 0; win.cursorx = 0;
if (win.cursorx >= win.gridwidth) { else if (win.cursorx >= win.gridwidth) {
win.cursorx = 0; win.cursorx = 0;
win.cursory++; win.cursory++;
} }
if (win.cursory < 0) if (win.cursory < 0)
win.cursory = 0; win.cursory = 0;
if (win.cursory >= win.gridheight) else if (win.cursory >= win.gridheight)
break; /* outside the window */ break; /* outside the window */
if (ch == "\n") { if (ch == "\n") {
@ -3027,7 +2912,7 @@ function gli_window_put_string(win, val) {
continue; continue;
} }
var lineobj = win.lines[win.cursory]; lineobj = win.lines[win.cursory];
lineobj.dirty = true; lineobj.dirty = true;
lineobj.chars[win.cursorx] = ch; lineobj.chars[win.cursorx] = ch;
lineobj.styles[win.cursorx] = win.style; lineobj.styles[win.cursorx] = win.style;
@ -3050,13 +2935,13 @@ function gli_window_put_string(win, val) {
function gli_window_grid_canonicalize(win) { function gli_window_grid_canonicalize(win) {
if (win.cursorx < 0) if (win.cursorx < 0)
win.cursorx = 0; win.cursorx = 0;
if (win.cursorx >= win.gridwidth) { else if (win.cursorx >= win.gridwidth) {
win.cursorx = 0; win.cursorx = 0;
win.cursory++; win.cursory++;
} }
if (win.cursory < 0) if (win.cursory < 0)
win.cursory = 0; win.cursory = 0;
if (win.cursory >= win.gridheight) else if (win.cursory >= win.gridheight)
return true; /* outside the window */ return true; /* outside the window */
return false; return false;
} }
@ -3209,7 +3094,7 @@ function gli_window_close(win, recurse) {
function gli_window_rearrange(win, box) { function gli_window_rearrange(win, box) {
var width, height, oldwidth, oldheight; var width, height, oldwidth, oldheight;
var min, max, diff, split, splitwid, ix, cx, lineobj; var min, max, diff, splitwid, ix, cx, lineobj;
var box1, box2, ch1, ch2; var box1, box2, ch1, ch2;
geometry_changed = true; geometry_changed = true;
@ -3495,8 +3380,6 @@ function gli_stream_dirty_file(str) {
buffer out. buffer out.
*/ */
function gli_stream_flush_file(str) { function gli_stream_flush_file(str) {
var Dialog = GlkOte.getlibrary('Dialog');
if (str.streaming) if (str.streaming)
GlkOte.log('### gli_stream_flush_file called for streaming file!'); GlkOte.log('### gli_stream_flush_file called for streaming file!');
if (!(str.timer_id === null)) { if (!(str.timer_id === null)) {
@ -3507,8 +3390,6 @@ function gli_stream_flush_file(str) {
} }
function gli_new_fileref(filename, usage, rock, ref) { function gli_new_fileref(filename, usage, rock, ref) {
var Dialog = GlkOte.getlibrary('Dialog');
var fref = {}; var fref = {};
fref.filename = filename; fref.filename = filename;
fref.rock = rock; fref.rock = rock;
@ -3629,7 +3510,7 @@ function gli_put_char(str, ch) {
var len = arr.length; var len = arr.length;
if (len > str.buflen-str.bufpos) if (len > str.buflen-str.bufpos)
len = str.buflen-str.bufpos; len = str.buflen-str.bufpos;
for (var ix=0; ix<len; ix++) for (ix=0; ix<len; ix++)
str.buf[str.bufpos+ix] = arr[ix]; str.buf[str.bufpos+ix] = arr[ix];
str.bufpos += len; str.bufpos += len;
if (str.bufpos > str.bufeof) if (str.bufpos > str.bufeof)
@ -3932,7 +3813,6 @@ function gli_get_line(str, buf, want_unicode) {
return 0; return 0;
var len = buf.length; var len = buf.length;
var lx, ch;
var gotnewline; var gotnewline;
switch (str.type) { switch (str.type) {
@ -4196,6 +4076,7 @@ function glk_exit() {
gli_selectref = null; gli_selectref = null;
if (option_exit_warning) if (option_exit_warning)
GlkOte.warning(option_exit_warning); GlkOte.warning(option_exit_warning);
update('exit');
return DidNotReturn; return DidNotReturn;
} }
@ -4252,22 +4133,20 @@ function glk_gestalt_ext(sel, val, arr) {
return 2; // gestalt_CharOutput_ExactPrint return 2; // gestalt_CharOutput_ExactPrint
case 4: // gestalt_MouseInput case 4: // gestalt_MouseInput
if (val == Const.wintype_TextBuffer) if (val == Const.wintype_TextGrid)
return 1; return 1;
if (val == Const.wintype_Graphics && has_canvas) if (support.graphics && val == Const.wintype_Graphics)
return 1; return 1;
return 0; return 0;
case 5: // gestalt_Timer case 5: // gestalt_Timer
return 1; return support.timer || 0;
case 6: // gestalt_Graphics case 6: // gestalt_Graphics
return 1; return support.graphics || 0;
case 7: // gestalt_DrawImage case 7: // gestalt_DrawImage
if (val == Const.wintype_TextBuffer) if (support.graphics && (val == Const.wintype_TextBuffer || val == Const.wintype_Graphics))
return 1;
if (val == Const.wintype_Graphics && has_canvas)
return 1; return 1;
return 0; return 0;
@ -4281,10 +4160,10 @@ function glk_gestalt_ext(sel, val, arr) {
return 0; return 0;
case 11: // gestalt_Hyperlinks case 11: // gestalt_Hyperlinks
return 1; return support.hyperlinks || 0;
case 12: // gestalt_HyperlinkInput case 12: // gestalt_HyperlinkInput
if (val == 3 || val == 4) // TextBuffer or TextGrid if (support.hyperlinks && (val == Const.wintype_TextBuffer || val == Const.wintype_TextGrid))
return 1; return 1;
else else
return 0; return 0;
@ -4293,7 +4172,7 @@ function glk_gestalt_ext(sel, val, arr) {
return 0; return 0;
case 14: // gestalt_GraphicsTransparency case 14: // gestalt_GraphicsTransparency
return 1; return support.graphics || 0;
case 15: // gestalt_Unicode case 15: // gestalt_Unicode
return 1; return 1;
@ -4432,7 +4311,7 @@ function glk_window_open(splitwin, method, size, wintype, rock) {
newwin.cursory = 0; newwin.cursory = 0;
break; break;
case Const.wintype_Graphics: case Const.wintype_Graphics:
if (!has_canvas) { if (!support.graphics) {
/* Graphics windows not supported; silently return null */ /* Graphics windows not supported; silently return null */
gli_delete_window(newwin); gli_delete_window(newwin);
return null; return null;
@ -4812,8 +4691,6 @@ function glk_stream_get_rock(str) {
} }
function glk_stream_open_file(fref, fmode, rock) { function glk_stream_open_file(fref, fmode, rock) {
var Dialog = GlkOte.getlibrary('Dialog');
if (!fref) if (!fref)
throw('glk_stream_open_file: invalid fileref'); throw('glk_stream_open_file: invalid fileref');
@ -4916,20 +4793,21 @@ function glk_stream_open_memory(buf, fmode, rock) {
function glk_stream_open_resource(filenum, rock) { function glk_stream_open_resource(filenum, rock) {
var str; var str;
if (!Blorb) if (!GiLoad || !GiLoad.find_data_chunk)
return null; return null;
var el = Blorb.get_data_chunk(filenum); var el = GiLoad.find_data_chunk(filenum);
if (!el) if (!el)
return null; return null;
var buf = el.data; var buf = el.data;
var isbinary = (el.type == 'BINA');
str = gli_new_stream(strtype_Resource, str = gli_new_stream(strtype_Resource,
true, true,
false, false,
rock); rock);
str.unicode = false; str.unicode = false;
str.isbinary = el.binary; str.isbinary = isbinary;
str.resfilenum = filenum; str.resfilenum = filenum;
@ -4954,20 +4832,21 @@ function glk_stream_open_resource(filenum, rock) {
function glk_stream_open_resource_uni(filenum, rock) { function glk_stream_open_resource_uni(filenum, rock) {
var str; var str;
if (!Blorb) if (!GiLoad || !GiLoad.find_data_chunk)
return null; return null;
var el = Blorb.get_data_chunk(filenum); var el = GiLoad.find_data_chunk(filenum);
if (!el) if (!el)
return null; return null;
var buf = el.data; var buf = el.data;
var isbinary = (el.type == 'BINA');
str = gli_new_stream(strtype_Resource, str = gli_new_stream(strtype_Resource,
true, true,
false, false,
rock); rock);
str.unicode = true; str.unicode = true;
str.isbinary = el.binary; str.isbinary = isbinary;
str.resfilenum = filenum; str.resfilenum = filenum;
@ -4990,8 +4869,6 @@ function glk_stream_open_resource_uni(filenum, rock) {
} }
function glk_stream_close(str, result) { function glk_stream_close(str, result) {
var Dialog = GlkOte.getlibrary('Dialog');
if (!str) if (!str)
throw('glk_stream_close: invalid stream'); throw('glk_stream_close: invalid stream');
@ -5072,21 +4949,18 @@ function glk_stream_get_current() {
} }
function glk_fileref_create_temp(usage, rock) { function glk_fileref_create_temp(usage, rock) {
var Dialog = GlkOte.getlibrary('Dialog');
var filetype = (usage & Const.fileusage_TypeMask); var filetype = (usage & Const.fileusage_TypeMask);
var filetypename = FileTypeMap[filetype]; var filetypename = FileTypeMap[filetype];
var ref = Dialog.file_construct_temp_ref(filetypename); var ref = Dialog.file_construct_temp_ref(filetypename);
var fref = gli_new_fileref(ref.filename, usage, rock, ref); fref = gli_new_fileref(ref.filename, usage, rock, ref);
return fref; return fref;
} }
function glk_fileref_create_by_name(usage, filename, rock) { function glk_fileref_create_by_name(usage, filename, rock) {
var Dialog = GlkOte.getlibrary('Dialog');
/* Filenames that do not come from the user must be cleaned up. */ /* Filenames that do not come from the user must be cleaned up. */
filename = Dialog.file_clean_fixed_name(filename, (usage & Const.fileusage_TypeMask)); filename = Dialog.file_clean_fixed_name(filename, (usage & Const.fileusage_TypeMask));
var fref = gli_new_fileref(filename, usage, rock, null); fref = gli_new_fileref(filename, usage, rock, null);
return fref; return fref;
} }
@ -5136,19 +5010,19 @@ function glk_fileref_create_by_prompt(usage, fmode, rock) {
function gli_fileref_create_by_prompt_callback(obj) { function gli_fileref_create_by_prompt_callback(obj) {
var ref = obj.value; var ref = obj.value;
/* This "value" field will be a dialog.js fileref object if we are
connected to GlkOte. However, if we are connected to RegTest,
it will be a plain string. We attempt to handle both cases. */
var usage = ui_specialcallback.usage; var usage = ui_specialcallback.usage;
var rock = ui_specialcallback.rock; var rock = ui_specialcallback.rock;
var fref = null; var fref = null;
if (ref && typeof(ref) == 'object') { if (ref) {
fref = gli_new_fileref(ref.filename, usage, rock, ref); fref = gli_new_fileref(ref.filename, usage, rock, ref);
} }
else if (ref && typeof(ref) == 'string') {
fref = gli_new_fileref(ref, usage, rock, null); // If reading a file which doesn't exist, return null
if ( ui_specialinput.filemode === 'read' && !Dialog.file_ref_exists( fref.ref ) )
{
glk_fileref_destroy( fref );
fref = null;
} }
ui_specialinput = null; ui_specialinput = null;
@ -5189,14 +5063,12 @@ function glk_fileref_get_rock(fref) {
} }
function glk_fileref_delete_file(fref) { function glk_fileref_delete_file(fref) {
var Dialog = GlkOte.getlibrary('Dialog');
if (!fref) if (!fref)
throw('glk_fileref_delete_file: invalid fileref'); throw('glk_fileref_delete_file: invalid fileref');
Dialog.file_remove_ref(fref.ref); Dialog.file_remove_ref(fref.ref);
} }
function glk_fileref_does_file_exist(fref) { function glk_fileref_does_file_exist(fref) {
var Dialog = GlkOte.getlibrary('Dialog');
if (!fref) if (!fref)
throw('glk_fileref_does_file_exist: invalid fileref'); throw('glk_fileref_does_file_exist: invalid fileref');
if (Dialog.file_ref_exists(fref.ref)) if (Dialog.file_ref_exists(fref.ref))
@ -5497,10 +5369,10 @@ function glk_request_timer_events(msec) {
/* Graphics functions. */ /* Graphics functions. */
function glk_image_get_info(imgid, widthref, heightref) { function glk_image_get_info(imgid, widthref, heightref) {
if (!Blorb || !Blorb.get_image_info) if (!GiLoad || !GiLoad.get_image_info)
return null; return null;
var info = Blorb.get_image_info(imgid); var info = GiLoad.get_image_info(imgid);
if (info) { if (info) {
if (widthref) if (widthref)
widthref.set_value(info.width); widthref.set_value(info.width);
@ -5519,9 +5391,9 @@ function glk_image_draw(win, imgid, val1, val2) {
if (!win) if (!win)
throw('glk_image_draw: invalid window'); throw('glk_image_draw: invalid window');
if (!Blorb || !Blorb.get_image_info) if (!GiLoad || !GiLoad.get_image_info)
return 0; return 0;
var info = Blorb.get_image_info(imgid); var info = GiLoad.get_image_info(imgid);
if (!info) if (!info)
return 0; return 0;
@ -5569,9 +5441,9 @@ function glk_image_draw_scaled(win, imgid, val1, val2, width, height) {
if (!win) if (!win)
throw('glk_image_draw_scaled: invalid window'); throw('glk_image_draw_scaled: invalid window');
if (!Blorb || !Blorb.get_image_info) if (!GiLoad || !GiLoad.get_image_info)
return 0; return 0;
var info = Blorb.get_image_info(imgid); var info = GiLoad.get_image_info(imgid);
if (!info) if (!info)
return 0; return 0;
@ -6082,8 +5954,6 @@ function glk_get_line_stream_uni(str, buf) {
} }
function glk_stream_open_file_uni(fref, fmode, rock) { function glk_stream_open_file_uni(fref, fmode, rock) {
var Dialog = GlkOte.getlibrary('Dialog');
if (!fref) if (!fref)
throw('glk_stream_open_file_uni: invalid fileref'); throw('glk_stream_open_file_uni: invalid fileref');
@ -6371,13 +6241,11 @@ function glk_date_to_simple_time_local(dateref, factor) {
/* End of Glk namespace function. Return the object which will /* End of Glk namespace function. Return the object which will
become the Glk global. */ become the Glk global. */
return { var api = {
classname: 'Glk', version: '2.2.3', /* GlkOte/GlkApi version */
version: '2.3.2', /* GlkOte/GlkApi version */ set_references: set_references,
init : init, init : init,
inited : is_inited,
update : update, update : update,
getlibrary : get_library,
save_allstate : save_allstate, save_allstate : save_allstate,
restore_allstate : restore_allstate, restore_allstate : restore_allstate,
fatal_error : fatal_error, fatal_error : fatal_error,
@ -6517,12 +6385,12 @@ return {
glk_stream_open_resource_uni : glk_stream_open_resource_uni glk_stream_open_resource_uni : glk_stream_open_resource_uni
}; };
}; if (typeof module !== 'undefined' && module.exports) {
module.exports = api;
}
/* Glk is an instance of GlkClass, ready to init. */ return api;
var Glk = new GlkClass();
// Node-compatible behavior }();
try { exports.Glk = Glk; exports.GlkClass = GlkClass; } catch (ex) {};
/* End of Glk library. */ /* End of Glk library. */

View file

@ -3,21 +3,16 @@
*/ */
class GlkOte { class GlkOte {
constructor({width, height}) { constructor() {
this.width = width
this.height = height
this.current_metrics = null this.current_metrics = null
this.disabled = false this.disabled = false
this.generation = 0 this.generation = 0
this.interface = null this.interface = null
this.version = '0.5.1' this.version = require('../../package.json').version
} }
measure_window() { measure_window() {
return { return {
width: this.width,
height: this.height,
buffercharheight: 1, buffercharheight: 1,
buffercharwidth: 1, buffercharwidth: 1,
buffermarginx: 0, buffermarginx: 0,
@ -28,10 +23,12 @@ class GlkOte {
gridcharwidth: 1, gridcharwidth: 1,
gridmarginx: 0, gridmarginx: 0,
gridmarginy: 0, gridmarginy: 0,
height: 0,
inspacingx: 0, inspacingx: 0,
inspacingy: 0, inspacingy: 0,
outspacingx: 0, outspacingx: 0,
outspacingy: 0 outspacingy: 0,
width: 0,
} }
} }
@ -149,4 +146,4 @@ class GlkOte {
} }
} }
export default GlkOte module.exports = GlkOte

View file

@ -1,9 +1,9 @@
import FakeDialog from './fakeDialog.js' const FakeDialog = require('./fakeDialog')
import CheapGlkOte from './cheapGlkOte.js' const CheapGlkOte = require('./cheapGlkOte')
const noop = () => void null const noop = () => void null
const defaultHandlers = [ const noopHandlers = [
'onInit', 'onInit',
'onUpdateWindows', 'onUpdateWindows',
'onUpdateInputs', 'onUpdateInputs',
@ -12,36 +12,30 @@ const defaultHandlers = [
'onFileNameRequest', 'onFileNameRequest',
'onFileRead', 'onFileRead',
'onFileWrite', 'onFileWrite',
'onExit', 'onExit'
].reduce((acc, x) => ((acc[x] = noop), acc), {}) ].reduce((acc, x) => ((acc[x] = noop), acc), {})
const defaultLoggers = { const defaultLoggers = {
log: console.log, log: console.log,
warning: console.warn, warning: console.warn,
error: console.error, error: console.error
} }
const defaultSize = { module.exports = (handlers_, loggers = defaultLoggers) => {
width: 80,
height: 25,
}
export default (handlers_, {loggers: loggers_, size: size_ } = {}) => {
const handlers = const handlers =
Object.assign({}, defaultHandlers, handlers_) Object.assign({}, noopHandlers, handlers_)
const loggers =
Object.assign({}, defaultLoggers, loggers_)
const size =
Object.assign({}, defaultSize, size_)
const Dialog = new FakeDialog(handlers, loggers) const Dialog = new FakeDialog(handlers, loggers)
const GlkOte = new CheapGlkOte(handlers, loggers, size) const GlkOte = new CheapGlkOte(handlers, loggers)
const send = GlkOte.sendFn.bind(GlkOte) const sendFn = GlkOte.sendFn.bind(GlkOte)
return { return {
Dialog, sendFn,
GlkOte, glkInterface: {
send, Dialog,
GlkOte,
Glk: {}
}
} }
} }