Compare commits

..

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

11 changed files with 268 additions and 2479 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

@ -11,24 +11,22 @@ This repository includes examples of [stdio interface implementation](https://gi
### Initialization
```js
const { Dialog, GlkOte, send } =
CheapGlkOte(handlers [, { loggers, size }])
const { glkInterface, sendFn } = CheapGlkOte(handlers [, loggers])
```
### Input
```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 specify `targetWindow` by its `id` inside the `onUpdateWindows` handler.<br>
As I know, `inputType` can be `line` or `char`.
You can received `windowObject` in `onUpdateWindows` handler.<br>
You should respect input type setted by `onUpdateInputs`.
### Output and lifecycle
```js
const handlers = {
onInit: () => {
/**
* It's time to initialize the user interface.
* It's time to prepare the user interface.
*/
},
onUpdateWindows: windows => {
@ -36,11 +34,10 @@ const handlers = {
* Game wants to change the number of windows.
*/
},
onUpdateInputs: data => {
onUpdateInputs: type => {
/**
* Game wants to change input type.
* 'data' is a list with info about
* the target window and the input type.
* Supported types: 'char', 'line'.
*/
},
onUpdateContent: messages => {
@ -87,16 +84,7 @@ Default loggers:
const defaultLoggers = {
log: console.log,
warning: console.warn,
error: console.error,
}
```
### Size
Default sizes:
```js
const defaultSize = {
width: 80,
height: 25,
error: console.error
}
```

View file

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

View file

@ -2,22 +2,20 @@
* @see: https://github.com/curiousdannii/glkote-term/blob/master/src/glkote-dumb.js
*/
import { createInterface, emitKeypressEvents } from 'readline'
import MuteStream from 'mute-stream'
import ansiEsc from 'ansi-escapes'
const readline = require('readline')
const MuteStream = require('mute-stream')
const ansiEscapes = require('ansi-escapes')
const stdin = process.stdin
const stdout = new MuteStream()
stdout.pipe(process.stdout)
const rl = createInterface({
const rl = readline.createInterface({
input: stdin,
output: stdout,
prompt: ''
})
let currentWindowId = null
let currentWindow = null
let currentInputType = null
let send = _ => _
@ -29,38 +27,28 @@ const onInit = () => {
if (stdin.isTTY) {
stdin.setRawMode(true)
}
emitKeypressEvents(stdin)
readline.emitKeypressEvents(stdin)
rl.resume()
clearScreen()
}
const onUpdateWindows = windows => {
currentWindow = currentWindowId
? windows
.find(x => x.id === currentWindowId)
: windows
.filter(x => x.type === 'buffer')
.slice(-1)[0]
currentWindow = windows
.filter(x => x.type === 'buffer')
.slice(-1)[0]
}
const onUpdateInputs = data => {
if (data.length === 0) return null
const { id, type } = data[0]
currentWindowId = id
if (['char', 'line'].includes(type)) {
detach_handlers()
attach_handlers(type)
}
const onUpdateInputs = type => {
type
? attach_handlers(type)
: detach_handlers()
}
const clearScreen = () => {
stdout.write('\u001B[2J\u001B[0;0f')
}
const onUpdateContent = allMessages => {
const messages = allMessages.filter(
content => content.id === currentWindow.id
)[0]
const drawBuffer = messages => {
messages.text.forEach(({ append, content }) => {
return messages.text.forEach(({ append, content }) => {
if (!append) {
stdout.write('\n')
}
@ -71,7 +59,7 @@ const drawBuffer = messages => {
if (x.style === 'input') {
if (stdout.isTTY) {
stdout.write(ansiEsc.eraseLines(2))
stdout.write(ansiEscapes.eraseLines(2))
stdout.write('> ')
}
}
@ -85,32 +73,10 @@ const drawBuffer = messages => {
})
}
const drawGrid = messages => {
clearScreen()
messages.lines
.map(x => x.content)
.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 onDisable = disable =>
disable
? detach_handlers()
: attach_handlers()
const onExit = () => {
detach_handlers()
@ -119,8 +85,6 @@ const onExit = () => {
}
const onFileNameRequest = (tosave, usage, gameid, callback) => {
stdout.write('\n')
stdout.write(gameid, tosave)
stdout.write('\n')
rl.question(
'Please enter a file name: ',
@ -129,10 +93,10 @@ const onFileNameRequest = (tosave, usage, gameid, callback) => {
: null))
}
const onFileRead = (dirent) =>
const onFileRead = (dirent, israw) =>
void console.log('onFileRead:', dirent)
const onFileWrite = (dirent, content) =>
const onFileWrite = (dirent, content, israw) =>
void console.log('onFileWrite:', dirent, content.length)
const handle_char_input = (str, key) => {
@ -141,6 +105,8 @@ const handle_char_input = (str, key) => {
'\t': 'tab',
}
detach_handlers()
// Make sure this char isn't being remembered for the next line input
rl._line_buffer = null
rl.line = ''
@ -151,12 +117,10 @@ const handle_char_input = (str, key) => {
str ||
key.name.replace(/f(\d+)/, 'func$1')
send(res, currentInputType, currentWindow)
detach_handlers()
send(res, currentWindow)
}
const attach_handlers = type => {
currentInputType = type
if (type === 'char') {
stdout.mute()
stdin.on('keypress', handle_char_input)
@ -170,18 +134,18 @@ const detach_handlers = () => {
stdin.removeListener('keypress', handle_char_input)
rl.removeListener('line', handle_line_input)
stdout.unmute()
currentInputType = null
}
const handle_line_input = line => {
if (stdout.isTTY) {
stdout.write(ansiEsc.eraseLines(1))
stdout.write(ansiEscapes.eraseLines(1))
}
send(line, currentInputType, currentWindow)
detach_handlers()
send(line, currentWindow)
}
export const handlers = {
module.exports.handlers = {
onInit,
onUpdateWindows,
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",
"version": "0.5.1",
"version": "0.2.5",
"description": "Abstract JavaScript implementation of GlkOte",
"author": "He4eT <He4eTHb1u@gmail.com>",
"license": "MIT",
@ -10,26 +10,17 @@
"interactive fiction",
"interactive-fiction"
],
"type": "module",
"engines": {
"node": ">=14.0.0"
},
"main": "src/index.js",
"files": [
"/src"
],
"repository": "https://github.com/He4eT/cheap-glkote",
"bugs": "https://github.com/He4eT/cheap-glkote/issues",
"dependencies": {},
"devDependencies": {
"ansi-escapes": "^4.0.0",
"emglken": "^0.5.2",
"eslint": "^8.41.0",
"emglken": "^0.3.3",
"minimist": "^1.2.5",
"mute-stream": "0.0.8"
},
"scripts": {
"lint": "eslint bin/ src/",
"lint:fix": "eslint --fix bin/ src/",
"play": "node ./bin/player.stdio.js",
"test": "./tests/runtests.sh"
}

View file

@ -2,34 +2,41 @@
* @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 {
constructor(handlers, loggers, size) {
super(size)
constructor(handlers, loggers) {
super()
this.current_input_type = null
this.handlers = handlers
this.loggers = loggers
}
sendFn (message, type, window) {
sendFn(message, window) {
this.send_response(
type,
this.current_input_type,
window,
message)
this.current_input_type = null
}
init (iface) {
init(iface) {
this.handlers.onInit()
super.init(iface)
}
update_inputs (data) {
if (!data.length) return []
this.handlers.onUpdateInputs(data)
update_inputs(data) {
if (!data.length) return null
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') {
const callback = ref =>
this.send_response(
@ -46,38 +53,44 @@ class CheapGlkOte extends GlkOte {
}
}
update_content (messages) {
update_content(messages) {
this.handlers.onUpdateContent(messages)
}
exit () {
exit() {
this.handlers.onExit()
super.exit()
}
cancel_inputs (data) {
this.handlers.onUpdateInputs(data)
cancel_inputs(data) {
if (data.length === 0) {
this.current_input_type = null
this.handlers.onUpdateInputs(null)
}
}
disable (data) {
this.handlers.onDisable(data)
disable(disable) {
this.disabled = disable
this.handlers.onDisable(disable)
}
update_windows (windows) {
this.handlers.onUpdateWindows(windows)
update_windows(windows) {
if (windows.length) {
this.handlers.onUpdateWindows(windows)
}
}
log (message) {
this.loggers.log(message)
log(message) {
loggers.log(message)
}
warning (message) {
this.loggers.warn(message)
warning(message) {
loggers.warn(message)
}
error (message) {
this.loggers.error(message)
error(message) {
loggers.error(message)
}
}
export default CheapGlkOte
module.exports = CheapGlkOte

View file

@ -7,7 +7,6 @@ class FakeDialog {
constructor(handlers, loggers) {
this.streaming = false
this.handlers = handlers
this.loggers = loggers
}
file_ref_exists({ usage }) {
@ -16,11 +15,11 @@ class FakeDialog {
: false
}
file_remove_ref () {
file_remove_ref (ref) {
return true
}
file_construct_ref(filename, usage) {
file_construct_ref(filename, usage, gameid) {
return {
filename,
usage: usage || ''
@ -41,16 +40,16 @@ class FakeDialog {
}
log(message) {
this.loggers.log(message)
loggers.log(message)
}
warning(message) {
this.loggers.warn(message)
loggers.warn(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
* GlkOte Library: version 2.3.2.
* GlkOte Library: version 2.2.3.
* Glk API which this implements: version 0.7.4.
* Designed by Andrew Plotkin <erkyrath@eblong.com>
* <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.
*
* 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.
*/
/* All state is contained in GlkClass. */
var GlkClass = function() {
/* Put everything inside the Glk namespace. */
var GlkOte = null; /* imported API object */
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) */
Glk = function() {
/* Environment capabilities. (Checked at init time.) */
var has_canvas;
/* The VM interface object. */
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. */
var option_exit_warning;
@ -67,7 +70,61 @@ var event_generation = 0;
var current_partial_inputs = null;
var current_partial_outputs = null;
/* Initialize the library, initialize the VM, and set it running. (It will
// 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
run until the first glk_select() or glk_exit() call.)
The vm_options argument must have a vm_options.vm field, which must be an
@ -82,27 +139,17 @@ var current_partial_outputs = null;
library sets that up for you.)
*/
function init(vm_options) {
/* Either GlkOte was passed in or we must create one. */
if (vm_options.GlkOte) {
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);
/* Set references to external libraries */
set_references( vm_options );
VM = vm_options.vm;
GiDispa = vm_options.GiDispa; /* may be null/undefined */
if (GiDispa)
GiDispa.set_vm(VM);
vm_options.accept = accept_ui_event;
GlkOte.init(vm_options);
option_exit_warning = vm_options.exit_warning;
option_do_vm_autosave = vm_options.do_vm_autosave;
option_before_select_hook = vm_options.before_select_hook;
@ -112,16 +159,6 @@ function init(vm_options) {
if (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) {
@ -147,10 +184,12 @@ function accept_ui_event(obj) {
switch (obj.type) {
case 'init':
content_metrics = complete_metrics(obj.metrics);
/* We ignore the support array. This library is updated in sync
with GlkOte, so we know what it supports. */
VM.start();
content_metrics = obj.metrics;
/* Process the support array */
if (obj.support) {
obj.support.forEach(function(item) {support[item] = 1;});
}
VM.init();
break;
case 'external':
@ -192,7 +231,7 @@ function accept_ui_event(obj) {
break;
case 'arrange':
content_metrics = complete_metrics(obj.metrics);
content_metrics = obj.metrics;
box = {
left: content_metrics.outspacingx,
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() {
if (!gli_selectref)
return;
@ -542,8 +453,8 @@ function handle_line_input(disprock, input, termkey) {
VM.resume();
}
function update() {
var dataobj = { type: 'update', gen: event_generation };
function update(type) {
var dataobj = { type: type || 'update', gen: event_generation };
var winarray = null;
var contentarray = 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
called from Quixe.vm_autosave.
*/
function save_allstate() {
var Dialog = GlkOte.getlibrary('Dialog');
var res = {};
if (gli_rootwin)
@ -992,8 +886,6 @@ function save_allstate() {
*/
function restore_allstate(res)
{
var Dialog = GlkOte.getlibrary('Dialog');
if (gli_windowlist || gli_streamlist || gli_filereflist)
throw('restore_allstate: glkapi module has already been launched');
@ -1166,7 +1058,7 @@ function restore_allstate(res)
case strtype_Resource:
str.resfilenum = obj.resfilenum;
var el = Blorb.get_data_chunk(str.resfilenum);
var el = GiLoad.find_data_chunk(str.resfilenum);
if (el) {
str.buf = el.data;
}
@ -1251,11 +1143,6 @@ function restore_allstate(res)
function fatal_error(msg) {
has_exited = 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);
var dataobj = { type: 'update', gen: event_generation, disable: true };
dataobj.input = [];
@ -2806,10 +2693,8 @@ function UniArrayToBE32(arr) {
up in Safari, in Opera, and in Firefox if you have Firebug installed.)
*/
function qlog(msg) {
if (window.console && console.log)
if (typeof console !== 'undefined' && console.log)
console.log(msg);
else if (window.opera && opera.postError)
opera.postError(msg);
}
/* 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. */
if (win.cursorx < 0)
win.cursorx = 0;
if (win.cursorx >= win.gridwidth) {
else if (win.cursorx >= win.gridwidth) {
win.cursorx = 0;
win.cursory++;
}
if (win.cursory < 0)
win.cursory = 0;
if (win.cursory >= win.gridheight)
else if (win.cursory >= win.gridheight)
break; /* outside the window */
if (ch == "\n") {
@ -3027,7 +2912,7 @@ function gli_window_put_string(win, val) {
continue;
}
var lineobj = win.lines[win.cursory];
lineobj = win.lines[win.cursory];
lineobj.dirty = true;
lineobj.chars[win.cursorx] = ch;
lineobj.styles[win.cursorx] = win.style;
@ -3050,13 +2935,13 @@ function gli_window_put_string(win, val) {
function gli_window_grid_canonicalize(win) {
if (win.cursorx < 0)
win.cursorx = 0;
if (win.cursorx >= win.gridwidth) {
else if (win.cursorx >= win.gridwidth) {
win.cursorx = 0;
win.cursory++;
}
if (win.cursory < 0)
win.cursory = 0;
if (win.cursory >= win.gridheight)
else if (win.cursory >= win.gridheight)
return true; /* outside the window */
return false;
}
@ -3209,7 +3094,7 @@ function gli_window_close(win, recurse) {
function gli_window_rearrange(win, box) {
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;
geometry_changed = true;
@ -3495,8 +3380,6 @@ function gli_stream_dirty_file(str) {
buffer out.
*/
function gli_stream_flush_file(str) {
var Dialog = GlkOte.getlibrary('Dialog');
if (str.streaming)
GlkOte.log('### gli_stream_flush_file called for streaming file!');
if (!(str.timer_id === null)) {
@ -3507,8 +3390,6 @@ function gli_stream_flush_file(str) {
}
function gli_new_fileref(filename, usage, rock, ref) {
var Dialog = GlkOte.getlibrary('Dialog');
var fref = {};
fref.filename = filename;
fref.rock = rock;
@ -3629,7 +3510,7 @@ function gli_put_char(str, ch) {
var len = arr.length;
if (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.bufpos += len;
if (str.bufpos > str.bufeof)
@ -3932,7 +3813,6 @@ function gli_get_line(str, buf, want_unicode) {
return 0;
var len = buf.length;
var lx, ch;
var gotnewline;
switch (str.type) {
@ -4196,6 +4076,7 @@ function glk_exit() {
gli_selectref = null;
if (option_exit_warning)
GlkOte.warning(option_exit_warning);
update('exit');
return DidNotReturn;
}
@ -4252,22 +4133,20 @@ function glk_gestalt_ext(sel, val, arr) {
return 2; // gestalt_CharOutput_ExactPrint
case 4: // gestalt_MouseInput
if (val == Const.wintype_TextBuffer)
if (val == Const.wintype_TextGrid)
return 1;
if (val == Const.wintype_Graphics && has_canvas)
if (support.graphics && val == Const.wintype_Graphics)
return 1;
return 0;
case 5: // gestalt_Timer
return 1;
return support.timer || 0;
case 6: // gestalt_Graphics
return 1;
return support.graphics || 0;
case 7: // gestalt_DrawImage
if (val == Const.wintype_TextBuffer)
return 1;
if (val == Const.wintype_Graphics && has_canvas)
if (support.graphics && (val == Const.wintype_TextBuffer || val == Const.wintype_Graphics))
return 1;
return 0;
@ -4281,10 +4160,10 @@ function glk_gestalt_ext(sel, val, arr) {
return 0;
case 11: // gestalt_Hyperlinks
return 1;
return support.hyperlinks || 0;
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;
else
return 0;
@ -4293,7 +4172,7 @@ function glk_gestalt_ext(sel, val, arr) {
return 0;
case 14: // gestalt_GraphicsTransparency
return 1;
return support.graphics || 0;
case 15: // gestalt_Unicode
return 1;
@ -4432,7 +4311,7 @@ function glk_window_open(splitwin, method, size, wintype, rock) {
newwin.cursory = 0;
break;
case Const.wintype_Graphics:
if (!has_canvas) {
if (!support.graphics) {
/* Graphics windows not supported; silently return null */
gli_delete_window(newwin);
return null;
@ -4812,8 +4691,6 @@ function glk_stream_get_rock(str) {
}
function glk_stream_open_file(fref, fmode, rock) {
var Dialog = GlkOte.getlibrary('Dialog');
if (!fref)
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) {
var str;
if (!Blorb)
if (!GiLoad || !GiLoad.find_data_chunk)
return null;
var el = Blorb.get_data_chunk(filenum);
var el = GiLoad.find_data_chunk(filenum);
if (!el)
return null;
var buf = el.data;
var isbinary = (el.type == 'BINA');
str = gli_new_stream(strtype_Resource,
true,
false,
rock);
str.unicode = false;
str.isbinary = el.binary;
str.isbinary = isbinary;
str.resfilenum = filenum;
@ -4954,20 +4832,21 @@ function glk_stream_open_resource(filenum, rock) {
function glk_stream_open_resource_uni(filenum, rock) {
var str;
if (!Blorb)
if (!GiLoad || !GiLoad.find_data_chunk)
return null;
var el = Blorb.get_data_chunk(filenum);
var el = GiLoad.find_data_chunk(filenum);
if (!el)
return null;
var buf = el.data;
var isbinary = (el.type == 'BINA');
str = gli_new_stream(strtype_Resource,
true,
false,
rock);
str.unicode = true;
str.isbinary = el.binary;
str.isbinary = isbinary;
str.resfilenum = filenum;
@ -4990,8 +4869,6 @@ function glk_stream_open_resource_uni(filenum, rock) {
}
function glk_stream_close(str, result) {
var Dialog = GlkOte.getlibrary('Dialog');
if (!str)
throw('glk_stream_close: invalid stream');
@ -5072,21 +4949,18 @@ function glk_stream_get_current() {
}
function glk_fileref_create_temp(usage, rock) {
var Dialog = GlkOte.getlibrary('Dialog');
var filetype = (usage & Const.fileusage_TypeMask);
var filetypename = FileTypeMap[filetype];
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;
}
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. */
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;
}
@ -5136,19 +5010,19 @@ function glk_fileref_create_by_prompt(usage, fmode, rock) {
function gli_fileref_create_by_prompt_callback(obj) {
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 rock = ui_specialcallback.rock;
var fref = null;
if (ref && typeof(ref) == 'object') {
if (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;
@ -5189,14 +5063,12 @@ function glk_fileref_get_rock(fref) {
}
function glk_fileref_delete_file(fref) {
var Dialog = GlkOte.getlibrary('Dialog');
if (!fref)
throw('glk_fileref_delete_file: invalid fileref');
Dialog.file_remove_ref(fref.ref);
}
function glk_fileref_does_file_exist(fref) {
var Dialog = GlkOte.getlibrary('Dialog');
if (!fref)
throw('glk_fileref_does_file_exist: invalid fileref');
if (Dialog.file_ref_exists(fref.ref))
@ -5497,10 +5369,10 @@ function glk_request_timer_events(msec) {
/* Graphics functions. */
function glk_image_get_info(imgid, widthref, heightref) {
if (!Blorb || !Blorb.get_image_info)
if (!GiLoad || !GiLoad.get_image_info)
return null;
var info = Blorb.get_image_info(imgid);
var info = GiLoad.get_image_info(imgid);
if (info) {
if (widthref)
widthref.set_value(info.width);
@ -5519,9 +5391,9 @@ function glk_image_draw(win, imgid, val1, val2) {
if (!win)
throw('glk_image_draw: invalid window');
if (!Blorb || !Blorb.get_image_info)
if (!GiLoad || !GiLoad.get_image_info)
return 0;
var info = Blorb.get_image_info(imgid);
var info = GiLoad.get_image_info(imgid);
if (!info)
return 0;
@ -5569,9 +5441,9 @@ function glk_image_draw_scaled(win, imgid, val1, val2, width, height) {
if (!win)
throw('glk_image_draw_scaled: invalid window');
if (!Blorb || !Blorb.get_image_info)
if (!GiLoad || !GiLoad.get_image_info)
return 0;
var info = Blorb.get_image_info(imgid);
var info = GiLoad.get_image_info(imgid);
if (!info)
return 0;
@ -6082,8 +5954,6 @@ function glk_get_line_stream_uni(str, buf) {
}
function glk_stream_open_file_uni(fref, fmode, rock) {
var Dialog = GlkOte.getlibrary('Dialog');
if (!fref)
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
become the Glk global. */
return {
classname: 'Glk',
version: '2.3.2', /* GlkOte/GlkApi version */
var api = {
version: '2.2.3', /* GlkOte/GlkApi version */
set_references: set_references,
init : init,
inited : is_inited,
update : update,
getlibrary : get_library,
save_allstate : save_allstate,
restore_allstate : restore_allstate,
fatal_error : fatal_error,
@ -6517,12 +6385,12 @@ return {
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. */
var Glk = new GlkClass();
return api;
// 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 {
constructor({width, height}) {
this.width = width
this.height = height
constructor() {
this.current_metrics = null
this.disabled = false
this.generation = 0
this.interface = null
this.version = '0.5.1'
this.version = require('../../package.json').version
}
measure_window() {
return {
width: this.width,
height: this.height,
buffercharheight: 1,
buffercharwidth: 1,
buffermarginx: 0,
@ -28,10 +23,12 @@ class GlkOte {
gridcharwidth: 1,
gridmarginx: 0,
gridmarginy: 0,
height: 0,
inspacingx: 0,
inspacingy: 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'
import CheapGlkOte from './cheapGlkOte.js'
const FakeDialog = require('./fakeDialog')
const CheapGlkOte = require('./cheapGlkOte')
const noop = () => void null
const defaultHandlers = [
const noopHandlers = [
'onInit',
'onUpdateWindows',
'onUpdateInputs',
@ -12,36 +12,30 @@ const defaultHandlers = [
'onFileNameRequest',
'onFileRead',
'onFileWrite',
'onExit',
'onExit'
].reduce((acc, x) => ((acc[x] = noop), acc), {})
const defaultLoggers = {
log: console.log,
warning: console.warn,
error: console.error,
error: console.error
}
const defaultSize = {
width: 80,
height: 25,
}
export default (handlers_, {loggers: loggers_, size: size_ } = {}) => {
module.exports = (handlers_, loggers = defaultLoggers) => {
const handlers =
Object.assign({}, defaultHandlers, handlers_)
const loggers =
Object.assign({}, defaultLoggers, loggers_)
const size =
Object.assign({}, defaultSize, size_)
Object.assign({}, noopHandlers, handlers_)
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 {
Dialog,
GlkOte,
send,
sendFn,
glkInterface: {
Dialog,
GlkOte,
Glk: {}
}
}
}